2 * This file is part of cparser.
3 * Copyright (C) 2012 Matthias Braun <matze@braunis.de>
12 #include "adt/strutil.h"
14 #include "diagnostic.h"
15 #include "format_check.h"
16 #include "preprocessor.h"
21 #include "type_hash.h"
24 #include "attribute_t.h"
25 #include "lang_features.h"
30 #include "adt/bitfiddle.h"
31 #include "adt/error.h"
32 #include "adt/array.h"
34 //#define PRINT_TOKENS
35 #define MAX_LOOKAHEAD 1
40 entity_namespace_t namespc;
43 typedef struct declaration_specifiers_t declaration_specifiers_t;
44 struct declaration_specifiers_t {
46 storage_class_t storage_class;
47 unsigned char alignment; /**< Alignment, 0 if not set. */
49 bool thread_local : 1;
50 attribute_t *attributes; /**< list of attributes */
55 * An environment for parsing initializers (and compound literals).
57 typedef struct parse_initializer_env_t {
58 type_t *type; /**< the type of the initializer. In case of an
59 array type with unspecified size this gets
60 adjusted to the actual size. */
61 entity_t *entity; /**< the variable that is initialized if any */
62 bool must_be_constant;
63 } parse_initializer_env_t;
65 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
67 /** The current token. */
69 /** The lookahead ring-buffer. */
70 static token_t lookahead_buffer[MAX_LOOKAHEAD];
71 /** Position of the next token in the lookahead buffer. */
72 static size_t lookahead_bufpos;
73 static stack_entry_t *environment_stack = NULL;
74 static stack_entry_t *label_stack = NULL;
75 static scope_t *file_scope = NULL;
76 static scope_t *current_scope = NULL;
77 /** Point to the current function declaration if inside a function. */
78 static function_t *current_function = NULL;
79 static entity_t *current_entity = NULL;
80 static switch_statement_t *current_switch = NULL;
81 static statement_t *current_loop = NULL;
82 static statement_t *current_parent = NULL;
83 static ms_try_statement_t *current_try = NULL;
84 static linkage_kind_t current_linkage;
85 static goto_statement_t *goto_first = NULL;
86 static goto_statement_t **goto_anchor = NULL;
87 static label_statement_t *label_first = NULL;
88 static label_statement_t **label_anchor = NULL;
89 /** current translation unit. */
90 static translation_unit_t *unit = NULL;
91 /** true if we are in an __extension__ context. */
92 static bool in_gcc_extension = false;
93 static struct obstack temp_obst;
94 static entity_t *anonymous_entity;
95 static declaration_t **incomplete_arrays;
96 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
99 #define PUSH_CURRENT_ENTITY(entity) \
100 entity_t *const new_current_entity = (entity); \
101 entity_t *const old_current_entity = current_entity; \
102 ((void)(current_entity = new_current_entity))
103 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
105 #define PUSH_PARENT(stmt) \
106 statement_t *const new_parent = (stmt); \
107 statement_t *const old_parent = current_parent; \
108 ((void)(current_parent = new_parent))
109 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
111 #define PUSH_SCOPE(scope) \
112 size_t const top = environment_top(); \
113 scope_t *const new_scope = (scope); \
114 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
115 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
116 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
118 #define PUSH_EXTENSION() \
120 bool const old_gcc_extension = in_gcc_extension; \
121 while (accept(T___extension__)) { \
122 in_gcc_extension = true; \
125 #define POP_EXTENSION() \
126 ((void)(in_gcc_extension = old_gcc_extension))
128 /** The token anchor set */
129 static unsigned short token_anchor_set[T_LAST_TOKEN];
131 /** The current source position. */
132 #define HERE (&token.base.pos)
134 /** true if we are in GCC mode. */
135 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
137 static statement_t *parse_compound_statement(bool inside_expression_statement);
138 static statement_t *parse_statement(void);
140 static expression_t *parse_subexpression(precedence_t);
141 static expression_t *parse_expression(void);
142 static type_t *parse_typename(void);
143 static void parse_externals(void);
144 static void parse_external(void);
146 static void parse_compound_type_entries(compound_t *compound_declaration);
148 static void check_call_argument(type_t *expected_type,
149 call_argument_t *argument, unsigned pos);
151 typedef enum declarator_flags_t {
153 DECL_MAY_BE_ABSTRACT = 1U << 0,
154 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
155 DECL_IS_PARAMETER = 1U << 2
156 } declarator_flags_t;
158 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
159 declarator_flags_t flags);
161 static void semantic_comparison(binary_expression_t *expression,
164 #define STORAGE_CLASSES \
165 STORAGE_CLASSES_NO_EXTERN \
168 #define STORAGE_CLASSES_NO_EXTERN \
173 case T__Thread_local:
175 #define TYPE_QUALIFIERS \
180 case T__forceinline: \
181 case T___attribute__:
183 #define COMPLEX_SPECIFIERS \
185 #define IMAGINARY_SPECIFIERS \
188 #define TYPE_SPECIFIERS \
190 case T___builtin_va_list: \
215 #define DECLARATION_START \
220 #define DECLARATION_START_NO_EXTERN \
221 STORAGE_CLASSES_NO_EXTERN \
225 #define EXPRESSION_START \
234 case T_CHARACTER_CONSTANT: \
238 case T_STRING_LITERAL: \
240 case T___FUNCDNAME__: \
241 case T___FUNCSIG__: \
242 case T___PRETTY_FUNCTION__: \
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_copy: \
254 case T___builtin_va_start: \
267 * Returns the size of a statement node.
269 * @param kind the statement kind
271 static size_t get_statement_struct_size(statement_kind_t kind)
273 static const size_t sizes[] = {
274 [STATEMENT_ERROR] = sizeof(statement_base_t),
275 [STATEMENT_EMPTY] = sizeof(statement_base_t),
276 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
277 [STATEMENT_RETURN] = sizeof(return_statement_t),
278 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
279 [STATEMENT_IF] = sizeof(if_statement_t),
280 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
281 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
282 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
283 [STATEMENT_BREAK] = sizeof(statement_base_t),
284 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
285 [STATEMENT_GOTO] = sizeof(goto_statement_t),
286 [STATEMENT_LABEL] = sizeof(label_statement_t),
287 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
288 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
289 [STATEMENT_FOR] = sizeof(for_statement_t),
290 [STATEMENT_ASM] = sizeof(asm_statement_t),
291 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
292 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
294 assert((size_t)kind < lengthof(sizes));
295 assert(sizes[kind] != 0);
300 * Returns the size of an expression node.
302 * @param kind the expression kind
304 static size_t get_expression_struct_size(expression_kind_t kind)
306 static const size_t sizes[] = {
307 [EXPR_ERROR] = sizeof(expression_base_t),
308 [EXPR_REFERENCE] = sizeof(reference_expression_t),
309 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
310 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
311 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
312 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_CHARACTER] = sizeof(string_literal_expression_t),
314 [EXPR_LITERAL_MS_NOOP] = sizeof(literal_expression_t),
315 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
316 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
317 [EXPR_CALL] = sizeof(call_expression_t),
318 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
319 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
320 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
321 [EXPR_SELECT] = sizeof(select_expression_t),
322 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
323 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
324 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
325 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
326 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
327 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
328 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
329 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
330 [EXPR_VA_START] = sizeof(va_start_expression_t),
331 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
332 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
333 [EXPR_STATEMENT] = sizeof(statement_expression_t),
334 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
336 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
337 return sizes[EXPR_UNARY_FIRST];
339 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
340 return sizes[EXPR_BINARY_FIRST];
342 assert((size_t)kind < lengthof(sizes));
343 assert(sizes[kind] != 0);
348 * Allocate a statement node of given kind and initialize all
349 * fields with zero. Sets its source position to the position
350 * of the current token.
352 static statement_t *allocate_statement_zero(statement_kind_t kind)
354 size_t size = get_statement_struct_size(kind);
355 statement_t *res = allocate_ast_zero(size);
357 res->base.kind = kind;
358 res->base.parent = current_parent;
359 res->base.pos = *HERE;
364 * Allocate an expression node of given kind and initialize all
367 * @param kind the kind of the expression to allocate
369 static expression_t *allocate_expression_zero(expression_kind_t kind)
371 size_t size = get_expression_struct_size(kind);
372 expression_t *res = allocate_ast_zero(size);
374 res->base.kind = kind;
375 res->base.type = type_error_type;
376 res->base.pos = *HERE;
381 * Creates a new invalid expression at the source position
382 * of the current token.
384 static expression_t *create_error_expression(void)
386 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
387 expression->base.type = type_error_type;
392 * Creates a new invalid statement.
394 static statement_t *create_error_statement(void)
396 return allocate_statement_zero(STATEMENT_ERROR);
400 * Allocate a new empty statement.
402 static statement_t *create_empty_statement(void)
404 return allocate_statement_zero(STATEMENT_EMPTY);
408 * Returns the size of an initializer node.
410 * @param kind the initializer kind
412 static size_t get_initializer_size(initializer_kind_t kind)
414 static const size_t sizes[] = {
415 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
416 [INITIALIZER_STRING] = sizeof(initializer_value_t),
417 [INITIALIZER_LIST] = sizeof(initializer_list_t),
418 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
420 assert((size_t)kind < lengthof(sizes));
421 assert(sizes[kind] != 0);
426 * Allocate an initializer node of given kind and initialize all
429 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
431 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
438 * Returns the index of the top element of the environment stack.
440 static size_t environment_top(void)
442 return ARR_LEN(environment_stack);
446 * Returns the index of the top element of the global label stack.
448 static size_t label_top(void)
450 return ARR_LEN(label_stack);
454 * Return the next token.
456 static inline void next_token(void)
458 token = lookahead_buffer[lookahead_bufpos];
459 lookahead_buffer[lookahead_bufpos] = pp_token;
460 next_preprocessing_token();
462 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
465 print_token(stderr, &token);
466 fprintf(stderr, "\n");
470 static inline void eat(token_kind_t const kind)
472 assert(token.kind == kind);
478 * Consume the current token, if it is of the expected kind.
480 * @param kind The kind of token to consume.
481 * @return Whether the token was consumed.
483 static inline bool accept(token_kind_t const kind)
485 if (token.kind == kind) {
494 * Return the next token with a given lookahead.
496 static inline const token_t *look_ahead(size_t num)
498 assert(0 < num && num <= MAX_LOOKAHEAD);
499 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
500 return &lookahead_buffer[pos];
504 * Adds a token type to the token type anchor set (a multi-set).
506 static void add_anchor_token(token_kind_t const token_kind)
508 assert(token_kind < T_LAST_TOKEN);
509 ++token_anchor_set[token_kind];
513 * Remove a token type from the token type anchor set (a multi-set).
515 static void rem_anchor_token(token_kind_t const token_kind)
517 assert(token_kind < T_LAST_TOKEN);
518 assert(token_anchor_set[token_kind] != 0);
519 --token_anchor_set[token_kind];
523 * Eat tokens until a matching token type is found.
525 static void eat_until_matching_token(token_kind_t const type)
527 token_kind_t end_token;
529 case '(': end_token = ')'; break;
530 case '{': end_token = '}'; break;
531 case '[': end_token = ']'; break;
532 default: end_token = type; break;
535 unsigned parenthesis_count = 0;
536 unsigned brace_count = 0;
537 unsigned bracket_count = 0;
538 while (token.kind != end_token ||
539 parenthesis_count != 0 ||
541 bracket_count != 0) {
542 switch (token.kind) {
544 case '(': ++parenthesis_count; break;
545 case '{': ++brace_count; break;
546 case '[': ++bracket_count; break;
549 if (parenthesis_count > 0)
559 if (bracket_count > 0)
562 if (token.kind == end_token &&
563 parenthesis_count == 0 &&
577 * Eat input tokens until an anchor is found.
579 static void eat_until_anchor(void)
581 while (token_anchor_set[token.kind] == 0) {
582 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
583 eat_until_matching_token(token.kind);
589 * Eat a whole block from input tokens.
591 static void eat_block(void)
593 eat_until_matching_token('{');
598 * Report a parse error because an expected token was not found.
601 #if defined __GNUC__ && __GNUC__ >= 4
602 __attribute__((sentinel))
604 void parse_error_expected(const char *message, ...)
606 if (message != NULL) {
607 errorf(HERE, "%s", message);
610 va_start(ap, message);
611 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
616 * Report an incompatible type.
618 static void type_error_incompatible(const char *msg,
619 const position_t *pos, type_t *type1, type_t *type2)
621 errorf(pos, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
624 static bool skip_till(token_kind_t const expected, char const *const context)
626 if (UNLIKELY(token.kind != expected)) {
627 parse_error_expected(context, expected, NULL);
628 add_anchor_token(expected);
630 rem_anchor_token(expected);
631 if (token.kind != expected)
638 * Expect the current token is the expected token.
639 * If not, generate an error and skip until the next anchor.
641 static void expect(token_kind_t const expected)
643 if (skip_till(expected, NULL))
647 static symbol_t *expect_identifier(char const *const context,
648 position_t *const pos)
650 if (!skip_till(T_IDENTIFIER, context))
652 symbol_t *const sym = token.base.symbol;
660 * Push a given scope on the scope stack and make it the
663 static scope_t *scope_push(scope_t *new_scope)
665 if (current_scope != NULL) {
666 new_scope->depth = current_scope->depth + 1;
669 scope_t *old_scope = current_scope;
670 current_scope = new_scope;
675 * Pop the current scope from the scope stack.
677 static void scope_pop(scope_t *old_scope)
679 current_scope = old_scope;
683 * Search an entity by its symbol in a given namespace.
685 static entity_t *get_entity(const symbol_t *const symbol,
686 namespace_tag_t namespc)
688 entity_t *entity = symbol->entity;
689 for (; entity != NULL; entity = entity->base.symbol_next) {
690 if ((namespace_tag_t)entity->base.namespc == namespc)
697 /* §6.2.3:1 24) There is only one name space for tags even though three are
699 static entity_t *get_tag(symbol_t const *const symbol,
700 entity_kind_tag_t const kind)
702 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
703 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
705 "'%Y' defined as wrong kind of tag (previous definition %P)",
706 symbol, &entity->base.pos);
713 * pushs an entity on the environment stack and links the corresponding symbol
716 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
718 symbol_t *symbol = entity->base.symbol;
719 entity_namespace_t namespc = entity->base.namespc;
720 assert(namespc != 0);
722 /* replace/add entity into entity list of the symbol */
725 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
730 /* replace an entry? */
731 if (iter->base.namespc == namespc) {
732 entity->base.symbol_next = iter->base.symbol_next;
738 /* remember old declaration */
740 entry.symbol = symbol;
741 entry.old_entity = iter;
742 entry.namespc = namespc;
743 ARR_APP1(stack_entry_t, *stack_ptr, entry);
747 * Push an entity on the environment stack.
749 static void environment_push(entity_t *entity)
751 assert(entity->base.pos.input_name != NULL);
752 assert(entity->base.parent_scope != NULL);
753 stack_push(&environment_stack, entity);
757 * Push a declaration on the global label stack.
759 * @param declaration the declaration
761 static void label_push(entity_t *label)
763 /* we abuse the parameters scope as parent for the labels */
764 label->base.parent_scope = ¤t_function->parameters;
765 stack_push(&label_stack, label);
769 * pops symbols from the environment stack until @p new_top is the top element
771 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
773 stack_entry_t *stack = *stack_ptr;
774 size_t top = ARR_LEN(stack);
777 assert(new_top <= top);
781 for (i = top; i > new_top; --i) {
782 stack_entry_t *entry = &stack[i - 1];
784 entity_t *old_entity = entry->old_entity;
785 symbol_t *symbol = entry->symbol;
786 entity_namespace_t namespc = entry->namespc;
788 /* replace with old_entity/remove */
791 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
793 assert(iter != NULL);
794 /* replace an entry? */
795 if (iter->base.namespc == namespc)
799 /* restore definition from outer scopes (if there was one) */
800 if (old_entity != NULL) {
801 old_entity->base.symbol_next = iter->base.symbol_next;
802 *anchor = old_entity;
804 /* remove entry from list */
805 *anchor = iter->base.symbol_next;
809 ARR_SHRINKLEN(*stack_ptr, new_top);
813 * Pop all entries from the environment stack until the new_top
816 * @param new_top the new stack top
818 static void environment_pop_to(size_t new_top)
820 stack_pop_to(&environment_stack, new_top);
824 * Pop all entries from the global label stack until the new_top
827 * @param new_top the new stack top
829 static void label_pop_to(size_t new_top)
831 stack_pop_to(&label_stack, new_top);
835 * §6.3.1.1:2 Do integer promotion for a given type.
837 * @param type the type to promote
838 * @return the promoted type
840 static type_t *promote_integer(type_t *type)
842 atomic_type_kind_t akind = get_arithmetic_akind(type);
843 if (get_akind_rank(akind) < get_akind_rank(ATOMIC_TYPE_INT))
850 * Check if a given expression represents a null pointer constant.
852 * @param expression the expression to check
854 static bool is_null_pointer_constant(const expression_t *expression)
856 /* skip void* cast */
857 if (expression->kind == EXPR_UNARY_CAST) {
858 type_t *const type = skip_typeref(expression->base.type);
859 if (types_compatible(type, type_void_ptr))
860 expression = expression->unary.value;
863 type_t *const type = skip_typeref(expression->base.type);
864 if (!is_type_integer(type))
866 switch (is_constant_expression(expression)) {
867 case EXPR_CLASS_ERROR: return true;
868 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
869 default: return false;
874 * Create an implicit cast expression.
876 * @param expression the expression to cast
877 * @param dest_type the destination type
879 static expression_t *create_implicit_cast(expression_t *expression,
882 type_t *const source_type = skip_typeref(expression->base.type);
883 if (source_type == skip_typeref(dest_type))
886 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
887 cast->unary.value = expression;
888 cast->base.type = dest_type;
889 cast->base.implicit = true;
894 typedef enum assign_error_t {
896 ASSIGN_ERROR_INCOMPATIBLE,
897 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
898 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
899 ASSIGN_WARNING_POINTER_FROM_INT,
900 ASSIGN_WARNING_INT_FROM_POINTER
903 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, position_t const *const pos)
905 type_t *const orig_type_right = right->base.type;
906 type_t *const type_left = skip_typeref(orig_type_left);
907 type_t *const type_right = skip_typeref(orig_type_right);
912 case ASSIGN_ERROR_INCOMPATIBLE:
913 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
916 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
917 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
918 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
920 /* the left type has all qualifiers from the right type */
921 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
922 warningf(WARN_OTHER, pos, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type", orig_type_left, context, orig_type_right, missing_qualifiers);
926 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
927 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
930 case ASSIGN_WARNING_POINTER_FROM_INT:
931 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
934 case ASSIGN_WARNING_INT_FROM_POINTER:
935 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
939 panic("invalid error value");
943 /** Implements the rules from §6.5.16.1 */
944 static assign_error_t semantic_assign(type_t *orig_type_left,
945 const expression_t *const right)
947 type_t *const orig_type_right = right->base.type;
948 type_t *const type_left = skip_typeref(orig_type_left);
949 type_t *const type_right = skip_typeref(orig_type_right);
951 if (is_type_pointer(type_left)) {
952 if (is_null_pointer_constant(right)) {
953 return ASSIGN_SUCCESS;
954 } else if (is_type_pointer(type_right)) {
955 type_t *points_to_left
956 = skip_typeref(type_left->pointer.points_to);
957 type_t *points_to_right
958 = skip_typeref(type_right->pointer.points_to);
959 assign_error_t res = ASSIGN_SUCCESS;
961 /* the left type has all qualifiers from the right type */
962 unsigned missing_qualifiers
963 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
964 if (missing_qualifiers != 0) {
965 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
968 points_to_left = get_unqualified_type(points_to_left);
969 points_to_right = get_unqualified_type(points_to_right);
971 if (is_type_void(points_to_left))
974 if (is_type_void(points_to_right)) {
975 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
976 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
979 if (!types_compatible(points_to_left, points_to_right)) {
980 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
984 } else if (is_type_integer(type_right)) {
985 return ASSIGN_WARNING_POINTER_FROM_INT;
987 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
988 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
989 && is_type_pointer(type_right))) {
990 return ASSIGN_SUCCESS;
991 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
992 type_t *const unqual_type_left = get_unqualified_type(type_left);
993 type_t *const unqual_type_right = get_unqualified_type(type_right);
994 if (types_compatible(unqual_type_left, unqual_type_right)) {
995 return ASSIGN_SUCCESS;
997 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
998 return ASSIGN_WARNING_INT_FROM_POINTER;
1001 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1002 return ASSIGN_SUCCESS;
1004 return ASSIGN_ERROR_INCOMPATIBLE;
1007 static expression_t *parse_constant_expression(void)
1009 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1011 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1012 errorf(&result->base.pos, "expression '%E' is not constant", result);
1018 static expression_t *parse_assignment_expression(void)
1020 return parse_subexpression(PREC_ASSIGNMENT);
1023 static void append_string(string_t const *const s)
1025 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1026 * possible, because other tokens are grown there alongside. */
1027 obstack_grow(&ast_obstack, s->begin, s->size);
1030 static string_t finish_string(string_encoding_t const enc)
1032 obstack_1grow(&ast_obstack, '\0');
1033 size_t const size = obstack_object_size(&ast_obstack) - 1;
1034 char const *const string = obstack_finish(&ast_obstack);
1035 return (string_t){ string, size, enc };
1038 static string_t concat_string_literals(void)
1040 assert(token.kind == T_STRING_LITERAL);
1043 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1044 append_string(&token.literal.string);
1045 eat(T_STRING_LITERAL);
1046 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1047 string_encoding_t enc = token.literal.string.encoding;
1049 string_encoding_t const new_enc = token.literal.string.encoding;
1050 if (new_enc != enc && new_enc != STRING_ENCODING_CHAR) {
1051 if (enc == STRING_ENCODING_CHAR) {
1054 errorf(HERE, "concatenating string literals with encodings %s and %s", get_string_encoding_prefix(enc), get_string_encoding_prefix(new_enc));
1057 append_string(&token.literal.string);
1058 eat(T_STRING_LITERAL);
1059 } while (token.kind == T_STRING_LITERAL);
1060 result = finish_string(enc);
1062 result = token.literal.string;
1063 eat(T_STRING_LITERAL);
1069 static string_t parse_string_literals(char const *const context)
1071 if (!skip_till(T_STRING_LITERAL, context))
1072 return (string_t){ "", 0, STRING_ENCODING_CHAR };
1074 position_t const pos = *HERE;
1075 string_t const res = concat_string_literals();
1077 if (res.encoding != STRING_ENCODING_CHAR) {
1078 errorf(&pos, "expected plain string literal, got %s string literal", get_string_encoding_prefix(res.encoding));
1084 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1086 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1087 attribute->kind = kind;
1088 attribute->pos = *HERE;
1093 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1096 * __attribute__ ( ( attribute-list ) )
1100 * attribute_list , attrib
1105 * any-word ( identifier )
1106 * any-word ( identifier , nonempty-expr-list )
1107 * any-word ( expr-list )
1109 * where the "identifier" must not be declared as a type, and
1110 * "any-word" may be any identifier (including one declared as a
1111 * type), a reserved word storage class specifier, type specifier or
1112 * type qualifier. ??? This still leaves out most reserved keywords
1113 * (following the old parser), shouldn't we include them, and why not
1114 * allow identifiers declared as types to start the arguments?
1116 * Matze: this all looks confusing and little systematic, so we're even less
1117 * strict and parse any list of things which are identifiers or
1118 * (assignment-)expressions.
1120 static attribute_argument_t *parse_attribute_arguments(void)
1122 attribute_argument_t *first = NULL;
1123 attribute_argument_t **anchor = &first;
1124 if (token.kind != ')') do {
1125 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1127 /* is it an identifier */
1128 if (token.kind == T_IDENTIFIER
1129 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1130 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1131 argument->v.symbol = token.base.symbol;
1134 /* must be an expression */
1135 expression_t *expression = parse_assignment_expression();
1137 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1138 argument->v.expression = expression;
1141 /* append argument */
1143 anchor = &argument->next;
1144 } while (accept(','));
1149 static attribute_t *parse_attribute_asm(void)
1151 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1154 attribute->a.arguments = parse_attribute_arguments();
1158 static attribute_t *parse_attribute_gnu_single(void)
1160 /* parse "any-word" */
1161 symbol_t *const symbol = token.base.symbol;
1162 if (symbol == NULL) {
1163 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1167 attribute_kind_t kind;
1168 char const *const name = symbol->string;
1169 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1170 if (kind > ATTRIBUTE_GNU_LAST) {
1171 /* special case for "__const" */
1172 if (token.kind == T_const) {
1173 kind = ATTRIBUTE_GNU_CONST;
1177 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1178 /* TODO: we should still save the attribute in the list... */
1179 kind = ATTRIBUTE_UNKNOWN;
1183 const char *attribute_name = get_attribute_name(kind);
1184 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1188 attribute_t *attribute = allocate_attribute_zero(kind);
1191 /* parse arguments */
1193 attribute->a.arguments = parse_attribute_arguments();
1198 static attribute_t *parse_attribute_gnu(void)
1200 attribute_t *first = NULL;
1201 attribute_t **anchor = &first;
1203 eat(T___attribute__);
1204 add_anchor_token(')');
1205 add_anchor_token(',');
1209 if (token.kind != ')') do {
1210 attribute_t *attribute = parse_attribute_gnu_single();
1212 *anchor = attribute;
1213 anchor = &attribute->next;
1215 } while (accept(','));
1216 rem_anchor_token(',');
1217 rem_anchor_token(')');
1224 /** Parse attributes. */
1225 static attribute_t *parse_attributes(attribute_t *first)
1227 attribute_t **anchor = &first;
1229 while (*anchor != NULL)
1230 anchor = &(*anchor)->next;
1232 attribute_t *attribute;
1233 switch (token.kind) {
1234 case T___attribute__:
1235 attribute = parse_attribute_gnu();
1236 if (attribute == NULL)
1241 attribute = parse_attribute_asm();
1245 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1250 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1254 case T__forceinline:
1255 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1256 eat(T__forceinline);
1260 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1265 /* TODO record modifier */
1266 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1267 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1275 *anchor = attribute;
1276 anchor = &attribute->next;
1280 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1282 static entity_t *determine_lhs_ent(expression_t *const expr,
1285 switch (expr->kind) {
1286 case EXPR_REFERENCE: {
1287 entity_t *const entity = expr->reference.entity;
1288 /* we should only find variables as lvalues... */
1289 if (entity->base.kind != ENTITY_VARIABLE
1290 && entity->base.kind != ENTITY_PARAMETER)
1296 case EXPR_ARRAY_ACCESS: {
1297 expression_t *const ref = expr->array_access.array_ref;
1298 entity_t * ent = NULL;
1299 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1300 ent = determine_lhs_ent(ref, lhs_ent);
1303 mark_vars_read(ref, lhs_ent);
1305 mark_vars_read(expr->array_access.index, lhs_ent);
1310 mark_vars_read(expr->select.compound, lhs_ent);
1311 if (is_type_compound(skip_typeref(expr->base.type)))
1312 return determine_lhs_ent(expr->select.compound, lhs_ent);
1316 case EXPR_UNARY_DEREFERENCE: {
1317 expression_t *const val = expr->unary.value;
1318 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1320 return determine_lhs_ent(val->unary.value, lhs_ent);
1322 mark_vars_read(val, NULL);
1328 mark_vars_read(expr, NULL);
1333 #define ENT_ANY ((entity_t*)-1)
1336 * Mark declarations, which are read. This is used to detect variables, which
1340 * x is not marked as "read", because it is only read to calculate its own new
1344 * x and y are not detected as "not read", because multiple variables are
1347 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1349 switch (expr->kind) {
1350 case EXPR_REFERENCE: {
1351 entity_t *const entity = expr->reference.entity;
1352 if (entity->kind != ENTITY_VARIABLE
1353 && entity->kind != ENTITY_PARAMETER)
1356 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1357 entity->variable.read = true;
1363 // TODO respect pure/const
1364 mark_vars_read(expr->call.function, NULL);
1365 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1366 mark_vars_read(arg->expression, NULL);
1370 case EXPR_CONDITIONAL:
1371 // TODO lhs_decl should depend on whether true/false have an effect
1372 mark_vars_read(expr->conditional.condition, NULL);
1373 if (expr->conditional.true_expression != NULL)
1374 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1375 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1379 if (lhs_ent == ENT_ANY
1380 && !is_type_compound(skip_typeref(expr->base.type)))
1382 mark_vars_read(expr->select.compound, lhs_ent);
1385 case EXPR_ARRAY_ACCESS: {
1386 mark_vars_read(expr->array_access.index, lhs_ent);
1387 expression_t *const ref = expr->array_access.array_ref;
1388 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1389 if (lhs_ent == ENT_ANY)
1392 mark_vars_read(ref, lhs_ent);
1397 mark_vars_read(expr->va_arge.ap, lhs_ent);
1401 mark_vars_read(expr->va_copye.src, lhs_ent);
1404 case EXPR_UNARY_CAST:
1405 /* Special case: Use void cast to mark a variable as "read" */
1406 if (is_type_void(skip_typeref(expr->base.type)))
1411 case EXPR_UNARY_THROW:
1412 if (expr->unary.value == NULL)
1415 case EXPR_UNARY_DEREFERENCE:
1416 case EXPR_UNARY_DELETE:
1417 case EXPR_UNARY_DELETE_ARRAY:
1418 if (lhs_ent == ENT_ANY)
1422 case EXPR_UNARY_NEGATE:
1423 case EXPR_UNARY_PLUS:
1424 case EXPR_UNARY_COMPLEMENT:
1425 case EXPR_UNARY_NOT:
1426 case EXPR_UNARY_TAKE_ADDRESS:
1427 case EXPR_UNARY_POSTFIX_INCREMENT:
1428 case EXPR_UNARY_POSTFIX_DECREMENT:
1429 case EXPR_UNARY_PREFIX_INCREMENT:
1430 case EXPR_UNARY_PREFIX_DECREMENT:
1431 case EXPR_UNARY_ASSUME:
1432 case EXPR_UNARY_IMAG:
1433 case EXPR_UNARY_REAL:
1435 mark_vars_read(expr->unary.value, lhs_ent);
1438 case EXPR_BINARY_ADD:
1439 case EXPR_BINARY_SUB:
1440 case EXPR_BINARY_MUL:
1441 case EXPR_BINARY_DIV:
1442 case EXPR_BINARY_MOD:
1443 case EXPR_BINARY_EQUAL:
1444 case EXPR_BINARY_NOTEQUAL:
1445 case EXPR_BINARY_LESS:
1446 case EXPR_BINARY_LESSEQUAL:
1447 case EXPR_BINARY_GREATER:
1448 case EXPR_BINARY_GREATEREQUAL:
1449 case EXPR_BINARY_BITWISE_AND:
1450 case EXPR_BINARY_BITWISE_OR:
1451 case EXPR_BINARY_BITWISE_XOR:
1452 case EXPR_BINARY_LOGICAL_AND:
1453 case EXPR_BINARY_LOGICAL_OR:
1454 case EXPR_BINARY_SHIFTLEFT:
1455 case EXPR_BINARY_SHIFTRIGHT:
1456 case EXPR_BINARY_COMMA:
1457 case EXPR_BINARY_ISGREATER:
1458 case EXPR_BINARY_ISGREATEREQUAL:
1459 case EXPR_BINARY_ISLESS:
1460 case EXPR_BINARY_ISLESSEQUAL:
1461 case EXPR_BINARY_ISLESSGREATER:
1462 case EXPR_BINARY_ISUNORDERED:
1463 mark_vars_read(expr->binary.left, lhs_ent);
1464 mark_vars_read(expr->binary.right, lhs_ent);
1467 case EXPR_BINARY_ASSIGN:
1468 case EXPR_BINARY_MUL_ASSIGN:
1469 case EXPR_BINARY_DIV_ASSIGN:
1470 case EXPR_BINARY_MOD_ASSIGN:
1471 case EXPR_BINARY_ADD_ASSIGN:
1472 case EXPR_BINARY_SUB_ASSIGN:
1473 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1474 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1475 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1476 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1477 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1478 if (lhs_ent == ENT_ANY)
1480 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1481 mark_vars_read(expr->binary.right, lhs_ent);
1486 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1489 case EXPR_LITERAL_CASES:
1490 case EXPR_LITERAL_CHARACTER:
1492 case EXPR_STRING_LITERAL:
1493 case EXPR_COMPOUND_LITERAL: // TODO init?
1495 case EXPR_CLASSIFY_TYPE:
1498 case EXPR_BUILTIN_CONSTANT_P:
1499 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1501 case EXPR_STATEMENT: // TODO
1502 case EXPR_LABEL_ADDRESS:
1503 case EXPR_ENUM_CONSTANT:
1507 panic("unhandled expression");
1510 static designator_t *parse_designation(void)
1512 designator_t *result = NULL;
1513 designator_t **anchor = &result;
1516 designator_t *designator;
1517 switch (token.kind) {
1519 designator = allocate_ast_zero(sizeof(designator[0]));
1520 designator->pos = *HERE;
1522 add_anchor_token(']');
1523 add_anchor_token(T_DOTDOTDOT);
1524 designator->array_index = parse_constant_expression();
1525 if (accept(T_DOTDOTDOT)) {
1526 designator->range_last = parse_constant_expression();
1527 errorf(&designator->pos, "range initializer not supported");
1529 rem_anchor_token(T_DOTDOTDOT);
1530 rem_anchor_token(']');
1534 designator = allocate_ast_zero(sizeof(designator[0]));
1535 designator->pos = *HERE;
1537 designator->symbol = expect_identifier("while parsing designator", NULL);
1538 if (!designator->symbol)
1546 assert(designator != NULL);
1547 *anchor = designator;
1548 anchor = &designator->next;
1553 * Build an initializer from a given expression.
1555 static initializer_t *initializer_from_expression(type_t *orig_type,
1556 expression_t *expression)
1558 /* TODO check that expression is a constant expression */
1560 type_t *const type = skip_typeref(orig_type);
1562 /* §6.7.8.14/15 char array may be initialized by string literals */
1563 if (expression->kind == EXPR_STRING_LITERAL && is_type_array(type)) {
1564 array_type_t *const array_type = &type->array;
1565 type_t *const element_type = skip_typeref(array_type->element_type);
1566 switch (expression->string_literal.value.encoding) {
1567 case STRING_ENCODING_CHAR:
1568 case STRING_ENCODING_UTF8: {
1569 if (is_type_atomic(element_type, ATOMIC_TYPE_CHAR) ||
1570 is_type_atomic(element_type, ATOMIC_TYPE_SCHAR) ||
1571 is_type_atomic(element_type, ATOMIC_TYPE_UCHAR)) {
1572 goto make_string_init;
1577 case STRING_ENCODING_CHAR16:
1578 case STRING_ENCODING_CHAR32:
1579 case STRING_ENCODING_WIDE: {
1580 assert(is_type_pointer(expression->base.type));
1581 type_t *const init_type = get_unqualified_type(expression->base.type->pointer.points_to);
1582 if (types_compatible(get_unqualified_type(element_type), init_type)) {
1584 initializer_t *const init = allocate_initializer_zero(INITIALIZER_STRING);
1585 init->value.value = expression;
1593 assign_error_t error = semantic_assign(type, expression);
1594 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1596 report_assign_error(error, type, expression, "initializer",
1597 &expression->base.pos);
1599 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1600 result->value.value = create_implicit_cast(expression, type);
1606 * Parses an scalar initializer.
1608 * §6.7.8.11; eat {} without warning
1610 static initializer_t *parse_scalar_initializer(type_t *type,
1611 bool must_be_constant)
1613 /* there might be extra {} hierarchies */
1615 if (token.kind == '{') {
1616 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1620 } while (token.kind == '{');
1623 expression_t *expression = parse_assignment_expression();
1624 mark_vars_read(expression, NULL);
1625 if (must_be_constant && !is_linker_constant(expression)) {
1626 errorf(&expression->base.pos,
1627 "initialisation expression '%E' is not constant",
1631 initializer_t *initializer = initializer_from_expression(type, expression);
1633 if (initializer == NULL) {
1634 errorf(&expression->base.pos,
1635 "expression '%E' (type '%T') doesn't match expected type '%T'",
1636 expression, expression->base.type, type);
1641 bool additional_warning_displayed = false;
1642 while (braces > 0) {
1644 if (token.kind != '}') {
1645 if (!additional_warning_displayed) {
1646 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1647 additional_warning_displayed = true;
1658 * An entry in the type path.
1660 typedef struct type_path_entry_t type_path_entry_t;
1661 struct type_path_entry_t {
1662 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1664 size_t index; /**< For array types: the current index. */
1665 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1670 * A type path expression a position inside compound or array types.
1672 typedef struct type_path_t type_path_t;
1673 struct type_path_t {
1674 type_path_entry_t *path; /**< An flexible array containing the current path. */
1675 type_t *top_type; /**< type of the element the path points */
1676 size_t max_index; /**< largest index in outermost array */
1680 * Prints a type path for debugging.
1682 static __attribute__((unused)) void debug_print_type_path(
1683 const type_path_t *path)
1685 size_t len = ARR_LEN(path->path);
1687 for (size_t i = 0; i < len; ++i) {
1688 const type_path_entry_t *entry = & path->path[i];
1690 type_t *type = skip_typeref(entry->type);
1691 if (is_type_compound(type)) {
1692 /* in gcc mode structs can have no members */
1693 if (entry->v.compound_entry == NULL) {
1697 fprintf(stderr, ".%s",
1698 entry->v.compound_entry->base.symbol->string);
1699 } else if (is_type_array(type)) {
1700 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1702 fprintf(stderr, "-INVALID-");
1705 if (path->top_type != NULL) {
1706 fprintf(stderr, " (");
1707 print_type(path->top_type);
1708 fprintf(stderr, ")");
1713 * Return the top type path entry, i.e. in a path
1714 * (type).a.b returns the b.
1716 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1718 size_t len = ARR_LEN(path->path);
1720 return &path->path[len-1];
1724 * Enlarge the type path by an (empty) element.
1726 static type_path_entry_t *append_to_type_path(type_path_t *path)
1728 size_t len = ARR_LEN(path->path);
1729 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1731 type_path_entry_t *result = & path->path[len];
1732 memset(result, 0, sizeof(result[0]));
1737 * Descending into a sub-type. Enter the scope of the current top_type.
1739 static void descend_into_subtype(type_path_t *path)
1741 type_t *orig_top_type = path->top_type;
1742 type_t *top_type = skip_typeref(orig_top_type);
1744 type_path_entry_t *top = append_to_type_path(path);
1745 top->type = top_type;
1747 if (is_type_compound(top_type)) {
1748 compound_t *const compound = top_type->compound.compound;
1749 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1751 if (entry != NULL) {
1752 top->v.compound_entry = &entry->declaration;
1753 path->top_type = entry->declaration.type;
1755 path->top_type = NULL;
1757 } else if (is_type_array(top_type)) {
1759 path->top_type = top_type->array.element_type;
1761 assert(!is_type_valid(top_type));
1766 * Pop an entry from the given type path, i.e. returning from
1767 * (type).a.b to (type).a
1769 static void ascend_from_subtype(type_path_t *path)
1771 type_path_entry_t *top = get_type_path_top(path);
1773 path->top_type = top->type;
1775 size_t len = ARR_LEN(path->path);
1776 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1780 * Pop entries from the given type path until the given
1781 * path level is reached.
1783 static void ascend_to(type_path_t *path, size_t top_path_level)
1785 size_t len = ARR_LEN(path->path);
1787 while (len > top_path_level) {
1788 ascend_from_subtype(path);
1789 len = ARR_LEN(path->path);
1793 static bool walk_designator(type_path_t *path, const designator_t *designator,
1794 bool used_in_offsetof)
1796 for (; designator != NULL; designator = designator->next) {
1797 type_path_entry_t *top = get_type_path_top(path);
1798 type_t *orig_type = top->type;
1800 type_t *type = skip_typeref(orig_type);
1802 if (designator->symbol != NULL) {
1803 symbol_t *symbol = designator->symbol;
1804 if (!is_type_compound(type)) {
1805 if (is_type_valid(type)) {
1806 errorf(&designator->pos,
1807 "'.%Y' designator used for non-compound type '%T'",
1811 top->type = type_error_type;
1812 top->v.compound_entry = NULL;
1813 orig_type = type_error_type;
1815 compound_t *compound = type->compound.compound;
1816 entity_t *iter = compound->members.entities;
1817 for (; iter != NULL; iter = iter->base.next) {
1818 if (iter->base.symbol == symbol) {
1823 errorf(&designator->pos,
1824 "'%T' has no member named '%Y'", orig_type, symbol);
1827 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1828 if (used_in_offsetof && iter->compound_member.bitfield) {
1829 errorf(&designator->pos,
1830 "offsetof designator '%Y' must not specify bitfield",
1835 top->type = orig_type;
1836 top->v.compound_entry = &iter->declaration;
1837 orig_type = iter->declaration.type;
1840 expression_t *array_index = designator->array_index;
1841 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1844 if (!is_type_array(type)) {
1845 if (is_type_valid(type)) {
1846 errorf(&designator->pos,
1847 "[%E] designator used for non-array type '%T'",
1848 array_index, orig_type);
1853 long index = fold_constant_to_int(array_index);
1854 if (!used_in_offsetof) {
1856 errorf(&designator->pos,
1857 "array index [%E] must be positive", array_index);
1858 } else if (type->array.size_constant) {
1859 long array_size = type->array.size;
1860 if (index >= array_size) {
1861 errorf(&designator->pos,
1862 "designator [%E] (%d) exceeds array size %d",
1863 array_index, index, array_size);
1868 top->type = orig_type;
1869 top->v.index = (size_t) index;
1870 orig_type = type->array.element_type;
1872 path->top_type = orig_type;
1874 if (designator->next != NULL) {
1875 descend_into_subtype(path);
1881 static void advance_current_object(type_path_t *path, size_t top_path_level)
1883 type_path_entry_t *top = get_type_path_top(path);
1885 type_t *type = skip_typeref(top->type);
1886 if (is_type_union(type)) {
1887 /* in unions only the first element is initialized */
1888 top->v.compound_entry = NULL;
1889 } else if (is_type_struct(type)) {
1890 declaration_t *entry = top->v.compound_entry;
1892 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1893 if (next_entity != NULL) {
1894 assert(is_declaration(next_entity));
1895 entry = &next_entity->declaration;
1900 top->v.compound_entry = entry;
1901 if (entry != NULL) {
1902 path->top_type = entry->type;
1905 } else if (is_type_array(type)) {
1906 assert(is_type_array(type));
1910 if (!type->array.size_constant || top->v.index < type->array.size) {
1914 assert(!is_type_valid(type));
1918 /* we're past the last member of the current sub-aggregate, try if we
1919 * can ascend in the type hierarchy and continue with another subobject */
1920 size_t len = ARR_LEN(path->path);
1922 if (len > top_path_level) {
1923 ascend_from_subtype(path);
1924 advance_current_object(path, top_path_level);
1926 path->top_type = NULL;
1931 * skip any {...} blocks until a closing bracket is reached.
1933 static void skip_initializers(void)
1937 while (token.kind != '}') {
1938 if (token.kind == T_EOF)
1940 if (token.kind == '{') {
1948 static initializer_t *create_empty_initializer(void)
1950 static initializer_t empty_initializer
1951 = { .list = { { INITIALIZER_LIST }, 0 } };
1952 return &empty_initializer;
1956 * Parse a part of an initialiser for a struct or union,
1958 static initializer_t *parse_sub_initializer(type_path_t *path,
1959 type_t *outer_type, size_t top_path_level,
1960 parse_initializer_env_t *env)
1962 if (token.kind == '}') {
1963 /* empty initializer */
1964 return create_empty_initializer();
1967 initializer_t *result = NULL;
1969 type_t *orig_type = path->top_type;
1970 type_t *type = NULL;
1972 if (orig_type == NULL) {
1973 /* We are initializing an empty compound. */
1975 type = skip_typeref(orig_type);
1978 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1981 designator_t *designator = NULL;
1982 if (token.kind == '.' || token.kind == '[') {
1983 designator = parse_designation();
1984 goto finish_designator;
1985 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1986 /* GNU-style designator ("identifier: value") */
1987 designator = allocate_ast_zero(sizeof(designator[0]));
1988 designator->pos = *HERE;
1989 designator->symbol = token.base.symbol;
1994 /* reset path to toplevel, evaluate designator from there */
1995 ascend_to(path, top_path_level);
1996 if (!walk_designator(path, designator, false)) {
1997 /* can't continue after designation error */
2001 initializer_t *designator_initializer
2002 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2003 designator_initializer->designator.designator = designator;
2004 ARR_APP1(initializer_t*, initializers, designator_initializer);
2006 orig_type = path->top_type;
2007 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2012 if (token.kind == '{') {
2013 if (type != NULL && is_type_scalar(type)) {
2014 sub = parse_scalar_initializer(type, env->must_be_constant);
2017 if (env->entity != NULL) {
2018 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2020 errorf(HERE, "extra brace group at end of initializer");
2025 descend_into_subtype(path);
2028 add_anchor_token('}');
2029 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2031 rem_anchor_token('}');
2036 goto error_parse_next;
2038 ascend_from_subtype(path);
2041 /* must be an expression */
2042 expression_t *expression = parse_assignment_expression();
2043 mark_vars_read(expression, NULL);
2045 if (env->must_be_constant && !is_linker_constant(expression)) {
2046 errorf(&expression->base.pos,
2047 "Initialisation expression '%E' is not constant",
2052 /* we are already outside, ... */
2053 if (outer_type == NULL)
2054 goto error_parse_next;
2055 type_t *const outer_type_skip = skip_typeref(outer_type);
2056 if (is_type_compound(outer_type_skip) &&
2057 !outer_type_skip->compound.compound->complete) {
2058 goto error_parse_next;
2061 position_t const* const pos = &expression->base.pos;
2062 if (env->entity != NULL) {
2063 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2065 warningf(WARN_OTHER, pos, "excess elements in initializer");
2067 goto error_parse_next;
2070 /* handle { "string" } special case */
2071 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2072 result = initializer_from_expression(outer_type, expression);
2073 if (result != NULL) {
2075 if (token.kind != '}') {
2076 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", outer_type);
2078 /* TODO: eat , ... */
2083 /* descend into subtypes until expression matches type */
2085 orig_type = path->top_type;
2086 type = skip_typeref(orig_type);
2088 sub = initializer_from_expression(orig_type, expression);
2092 if (!is_type_valid(type)) {
2095 if (is_type_scalar(type)) {
2096 errorf(&expression->base.pos,
2097 "expression '%E' doesn't match expected type '%T'",
2098 expression, orig_type);
2102 descend_into_subtype(path);
2106 /* update largest index of top array */
2107 const type_path_entry_t *first = &path->path[0];
2108 type_t *first_type = first->type;
2109 first_type = skip_typeref(first_type);
2110 if (is_type_array(first_type)) {
2111 size_t index = first->v.index;
2112 if (index > path->max_index)
2113 path->max_index = index;
2116 /* append to initializers list */
2117 ARR_APP1(initializer_t*, initializers, sub);
2122 if (token.kind == '}') {
2127 /* advance to the next declaration if we are not at the end */
2128 advance_current_object(path, top_path_level);
2129 orig_type = path->top_type;
2130 if (orig_type != NULL)
2131 type = skip_typeref(orig_type);
2137 size_t len = ARR_LEN(initializers);
2138 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2139 result = allocate_ast_zero(size);
2140 result->kind = INITIALIZER_LIST;
2141 result->list.len = len;
2142 memcpy(&result->list.initializers, initializers,
2143 len * sizeof(initializers[0]));
2147 skip_initializers();
2149 DEL_ARR_F(initializers);
2150 ascend_to(path, top_path_level+1);
2154 static expression_t *make_size_literal(size_t value)
2156 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2157 literal->base.type = type_size_t;
2160 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2161 literal->literal.value = make_string(buf);
2167 * Parses an initializer. Parsers either a compound literal
2168 * (env->declaration == NULL) or an initializer of a declaration.
2170 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2172 type_t *type = skip_typeref(env->type);
2173 size_t max_index = 0;
2174 initializer_t *result;
2176 if (is_type_scalar(type)) {
2177 result = parse_scalar_initializer(type, env->must_be_constant);
2178 } else if (token.kind == '{') {
2182 memset(&path, 0, sizeof(path));
2183 path.top_type = env->type;
2184 path.path = NEW_ARR_F(type_path_entry_t, 0);
2186 descend_into_subtype(&path);
2188 add_anchor_token('}');
2189 result = parse_sub_initializer(&path, env->type, 1, env);
2190 rem_anchor_token('}');
2192 max_index = path.max_index;
2193 DEL_ARR_F(path.path);
2197 /* parse_scalar_initializer() also works in this case: we simply
2198 * have an expression without {} around it */
2199 result = parse_scalar_initializer(type, env->must_be_constant);
2202 /* §6.7.8:22 array initializers for arrays with unknown size determine
2203 * the array type size */
2204 if (is_type_array(type) && type->array.size_expression == NULL
2205 && result != NULL) {
2207 switch (result->kind) {
2208 case INITIALIZER_LIST:
2209 assert(max_index != 0xdeadbeaf);
2210 size = max_index + 1;
2213 case INITIALIZER_STRING: {
2214 size = get_string_len(&get_init_string(result)->value) + 1;
2218 case INITIALIZER_DESIGNATOR:
2219 case INITIALIZER_VALUE:
2220 /* can happen for parse errors */
2225 internal_errorf(HERE, "invalid initializer type");
2228 type_t *new_type = duplicate_type(type);
2230 new_type->array.size_expression = make_size_literal(size);
2231 new_type->array.size_constant = true;
2232 new_type->array.has_implicit_size = true;
2233 new_type->array.size = size;
2234 env->type = new_type;
2240 static void append_entity(scope_t *scope, entity_t *entity)
2242 if (scope->last_entity != NULL) {
2243 scope->last_entity->base.next = entity;
2245 scope->entities = entity;
2247 entity->base.parent_entity = current_entity;
2248 scope->last_entity = entity;
2252 static compound_t *parse_compound_type_specifier(bool is_struct)
2254 position_t const pos = *HERE;
2255 eat(is_struct ? T_struct : T_union);
2257 symbol_t *symbol = NULL;
2258 entity_t *entity = NULL;
2259 attribute_t *attributes = NULL;
2261 if (token.kind == T___attribute__) {
2262 attributes = parse_attributes(NULL);
2265 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2266 if (token.kind == T_IDENTIFIER) {
2267 /* the compound has a name, check if we have seen it already */
2268 symbol = token.base.symbol;
2269 entity = get_tag(symbol, kind);
2272 if (entity != NULL) {
2273 if (entity->base.parent_scope != current_scope &&
2274 (token.kind == '{' || token.kind == ';')) {
2275 /* we're in an inner scope and have a definition. Shadow
2276 * existing definition in outer scope */
2278 } else if (entity->compound.complete && token.kind == '{') {
2279 position_t const *const ppos = &entity->base.pos;
2280 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2281 /* clear members in the hope to avoid further errors */
2282 entity->compound.members.entities = NULL;
2285 } else if (token.kind != '{') {
2286 char const *const msg =
2287 is_struct ? "while parsing struct type specifier" :
2288 "while parsing union type specifier";
2289 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2294 if (entity == NULL) {
2295 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2296 entity->compound.alignment = 1;
2297 entity->base.parent_scope = current_scope;
2298 if (symbol != NULL) {
2299 environment_push(entity);
2301 append_entity(current_scope, entity);
2304 if (token.kind == '{') {
2305 parse_compound_type_entries(&entity->compound);
2307 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2308 if (symbol == NULL) {
2309 assert(anonymous_entity == NULL);
2310 anonymous_entity = entity;
2314 if (attributes != NULL) {
2315 entity->compound.attributes = attributes;
2316 handle_entity_attributes(attributes, entity);
2319 return &entity->compound;
2322 static void parse_enum_entries(type_t *const enum_type)
2326 if (token.kind == '}') {
2327 errorf(HERE, "empty enum not allowed");
2332 add_anchor_token('}');
2333 add_anchor_token(',');
2335 add_anchor_token('=');
2337 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2338 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2339 entity->enum_value.enum_type = enum_type;
2340 rem_anchor_token('=');
2343 expression_t *value = parse_constant_expression();
2345 value = create_implicit_cast(value, enum_type);
2346 entity->enum_value.value = value;
2351 record_entity(entity, false);
2352 } while (accept(',') && token.kind != '}');
2353 rem_anchor_token(',');
2354 rem_anchor_token('}');
2359 static type_t *parse_enum_specifier(void)
2361 position_t const pos = *HERE;
2366 switch (token.kind) {
2368 symbol = token.base.symbol;
2369 entity = get_tag(symbol, ENTITY_ENUM);
2372 if (entity != NULL) {
2373 if (entity->base.parent_scope != current_scope &&
2374 (token.kind == '{' || token.kind == ';')) {
2375 /* we're in an inner scope and have a definition. Shadow
2376 * existing definition in outer scope */
2378 } else if (entity->enume.complete && token.kind == '{') {
2379 position_t const *const ppos = &entity->base.pos;
2380 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2391 parse_error_expected("while parsing enum type specifier",
2392 T_IDENTIFIER, '{', NULL);
2396 if (entity == NULL) {
2397 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2398 entity->base.parent_scope = current_scope;
2401 type_t *const type = allocate_type_zero(TYPE_ENUM);
2402 type->enumt.enume = &entity->enume;
2403 type->enumt.base.akind = ATOMIC_TYPE_INT;
2405 if (token.kind == '{') {
2406 if (symbol != NULL) {
2407 environment_push(entity);
2409 append_entity(current_scope, entity);
2410 entity->enume.complete = true;
2412 parse_enum_entries(type);
2413 parse_attributes(NULL);
2415 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2416 if (symbol == NULL) {
2417 assert(anonymous_entity == NULL);
2418 anonymous_entity = entity;
2420 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2421 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2428 * if a symbol is a typedef to another type, return true
2430 static bool is_typedef_symbol(symbol_t *symbol)
2432 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2433 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2436 static type_t *parse_typeof(void)
2442 add_anchor_token(')');
2445 expression_t *expression = NULL;
2447 switch (token.kind) {
2449 if (is_typedef_symbol(token.base.symbol)) {
2451 type = parse_typename();
2454 expression = parse_expression();
2455 type = revert_automatic_type_conversion(expression);
2460 rem_anchor_token(')');
2463 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2464 typeof_type->typeoft.expression = expression;
2465 typeof_type->typeoft.typeof_type = type;
2470 typedef enum specifiers_t {
2472 SPECIFIER_SIGNED = 1 << 0,
2473 SPECIFIER_UNSIGNED = 1 << 1,
2474 SPECIFIER_LONG = 1 << 2,
2475 SPECIFIER_INT = 1 << 3,
2476 SPECIFIER_DOUBLE = 1 << 4,
2477 SPECIFIER_CHAR = 1 << 5,
2478 SPECIFIER_WCHAR_T = 1 << 6,
2479 SPECIFIER_SHORT = 1 << 7,
2480 SPECIFIER_LONG_LONG = 1 << 8,
2481 SPECIFIER_FLOAT = 1 << 9,
2482 SPECIFIER_BOOL = 1 << 10,
2483 SPECIFIER_VOID = 1 << 11,
2484 SPECIFIER_INT8 = 1 << 12,
2485 SPECIFIER_INT16 = 1 << 13,
2486 SPECIFIER_INT32 = 1 << 14,
2487 SPECIFIER_INT64 = 1 << 15,
2488 SPECIFIER_INT128 = 1 << 16,
2489 SPECIFIER_COMPLEX = 1 << 17,
2490 SPECIFIER_IMAGINARY = 1 << 18,
2493 static type_t *get_typedef_type(symbol_t *symbol)
2495 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2496 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2499 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2500 type->typedeft.typedefe = &entity->typedefe;
2505 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2507 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2509 add_anchor_token(')');
2510 add_anchor_token(',');
2514 add_anchor_token('=');
2516 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2517 rem_anchor_token('=');
2519 symbol_t **prop = NULL;
2521 if (streq(prop_sym->string, "put")) {
2522 prop = &property->put_symbol;
2523 } else if (streq(prop_sym->string, "get")) {
2524 prop = &property->get_symbol;
2526 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2530 add_anchor_token(T_IDENTIFIER);
2532 rem_anchor_token(T_IDENTIFIER);
2534 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2536 *prop = sym ? sym : sym_anonymous;
2537 } while (accept(','));
2538 rem_anchor_token(',');
2539 rem_anchor_token(')');
2541 attribute->a.property = property;
2547 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2549 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2550 if (accept(T_restrict)) {
2551 kind = ATTRIBUTE_MS_RESTRICT;
2552 } else if (token.kind == T_IDENTIFIER) {
2553 char const *const name = token.base.symbol->string;
2554 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2556 const char *attribute_name = get_attribute_name(k);
2557 if (attribute_name != NULL && streq(attribute_name, name)) {
2563 if (kind == ATTRIBUTE_UNKNOWN) {
2564 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2567 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2571 attribute_t *attribute = allocate_attribute_zero(kind);
2574 if (kind == ATTRIBUTE_MS_PROPERTY) {
2575 return parse_attribute_ms_property(attribute);
2578 /* parse arguments */
2580 attribute->a.arguments = parse_attribute_arguments();
2585 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2589 add_anchor_token(')');
2591 if (token.kind != ')') {
2592 attribute_t **anchor = &first;
2594 while (*anchor != NULL)
2595 anchor = &(*anchor)->next;
2597 attribute_t *attribute
2598 = parse_microsoft_extended_decl_modifier_single();
2599 if (attribute == NULL)
2602 *anchor = attribute;
2603 anchor = &attribute->next;
2604 } while (accept(','));
2606 rem_anchor_token(')');
2611 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2613 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2614 if (is_declaration(entity)) {
2615 entity->declaration.type = type_error_type;
2616 entity->declaration.implicit = true;
2617 } else if (kind == ENTITY_TYPEDEF) {
2618 entity->typedefe.type = type_error_type;
2619 entity->typedefe.builtin = true;
2621 if (kind != ENTITY_COMPOUND_MEMBER)
2622 record_entity(entity, false);
2626 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2628 type_t *type = NULL;
2629 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2630 unsigned type_specifiers = 0;
2631 bool newtype = false;
2632 bool saw_error = false;
2634 memset(specifiers, 0, sizeof(*specifiers));
2635 specifiers->pos = *HERE;
2638 specifiers->attributes = parse_attributes(specifiers->attributes);
2640 switch (token.kind) {
2642 #define MATCH_STORAGE_CLASS(token, class) \
2644 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2645 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2647 specifiers->storage_class = class; \
2648 if (specifiers->thread_local) \
2649 goto check_thread_storage_class; \
2653 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2654 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2655 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2656 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2657 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2660 specifiers->attributes
2661 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2664 case T__Thread_local:
2665 if (specifiers->thread_local) {
2666 errorf(HERE, "duplicate %K", &token);
2668 specifiers->thread_local = true;
2669 check_thread_storage_class:
2670 switch (specifiers->storage_class) {
2671 case STORAGE_CLASS_EXTERN:
2672 case STORAGE_CLASS_NONE:
2673 case STORAGE_CLASS_STATIC:
2677 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2678 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2679 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2680 wrong_thread_storage_class:
2681 errorf(HERE, "%K used with '%s'", &token, wrong);
2688 /* type qualifiers */
2689 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2691 qualifiers |= qualifier; \
2695 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2696 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2697 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2698 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2699 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2700 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2701 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2702 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2704 /* type specifiers */
2705 #define MATCH_SPECIFIER(token, specifier, name) \
2707 if (type_specifiers & specifier) { \
2708 errorf(HERE, "multiple " name " type specifiers given"); \
2710 type_specifiers |= specifier; \
2715 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2716 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2717 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2718 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2719 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2720 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2721 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2722 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2723 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2724 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2725 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2726 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2727 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2728 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2729 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2730 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2731 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2732 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2736 specifiers->is_inline = true;
2740 case T__forceinline:
2741 eat(T__forceinline);
2742 specifiers->modifiers |= DM_FORCEINLINE;
2747 if (type_specifiers & SPECIFIER_LONG_LONG) {
2748 errorf(HERE, "too many long type specifiers given");
2749 } else if (type_specifiers & SPECIFIER_LONG) {
2750 type_specifiers |= SPECIFIER_LONG_LONG;
2752 type_specifiers |= SPECIFIER_LONG;
2757 #define CHECK_DOUBLE_TYPE() \
2758 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2761 CHECK_DOUBLE_TYPE();
2762 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2764 type->compound.compound = parse_compound_type_specifier(true);
2767 CHECK_DOUBLE_TYPE();
2768 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2769 type->compound.compound = parse_compound_type_specifier(false);
2772 CHECK_DOUBLE_TYPE();
2773 type = parse_enum_specifier();
2776 CHECK_DOUBLE_TYPE();
2777 type = parse_typeof();
2779 case T___builtin_va_list:
2780 CHECK_DOUBLE_TYPE();
2781 type = duplicate_type(type_valist);
2782 eat(T___builtin_va_list);
2785 case T_IDENTIFIER: {
2786 /* only parse identifier if we haven't found a type yet */
2787 if (type != NULL || type_specifiers != 0) {
2788 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2789 * declaration, so it doesn't generate errors about expecting '(' or
2791 switch (look_ahead(1)->kind) {
2798 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2802 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2807 goto finish_specifiers;
2811 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2812 if (typedef_type == NULL) {
2813 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2814 * declaration, so it doesn't generate 'implicit int' followed by more
2815 * errors later on. */
2816 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2822 errorf(HERE, "%K does not name a type", &token);
2824 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2826 type = allocate_type_zero(TYPE_TYPEDEF);
2827 type->typedeft.typedefe = &entity->typedefe;
2835 goto finish_specifiers;
2840 type = typedef_type;
2844 /* function specifier */
2846 goto finish_specifiers;
2851 specifiers->attributes = parse_attributes(specifiers->attributes);
2853 if (type == NULL || (saw_error && type_specifiers != 0)) {
2854 position_t const* const pos = &specifiers->pos;
2855 atomic_type_kind_t atomic_type;
2857 /* match valid basic types */
2858 switch (type_specifiers & ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2859 case SPECIFIER_VOID:
2860 if (type_specifiers & (SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2861 if (type_specifiers & SPECIFIER_COMPLEX)
2862 errorf(pos, "_Complex specifier is invalid for void");
2863 if (type_specifiers & SPECIFIER_IMAGINARY)
2864 errorf(pos, "_Imaginary specifier is invalid for void");
2865 type_specifiers &= ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY);
2867 atomic_type = ATOMIC_TYPE_VOID;
2869 case SPECIFIER_WCHAR_T:
2870 atomic_type = ATOMIC_TYPE_WCHAR_T;
2872 case SPECIFIER_CHAR:
2873 atomic_type = ATOMIC_TYPE_CHAR;
2875 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2876 atomic_type = ATOMIC_TYPE_SCHAR;
2878 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2879 atomic_type = ATOMIC_TYPE_UCHAR;
2881 case SPECIFIER_SHORT:
2882 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2883 case SPECIFIER_SHORT | SPECIFIER_INT:
2884 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2885 atomic_type = ATOMIC_TYPE_SHORT;
2887 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2888 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2889 atomic_type = ATOMIC_TYPE_USHORT;
2892 case SPECIFIER_SIGNED:
2893 case SPECIFIER_SIGNED | SPECIFIER_INT:
2894 atomic_type = ATOMIC_TYPE_INT;
2896 case SPECIFIER_UNSIGNED:
2897 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2898 atomic_type = ATOMIC_TYPE_UINT;
2900 case SPECIFIER_LONG:
2901 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2902 case SPECIFIER_LONG | SPECIFIER_INT:
2903 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2904 atomic_type = ATOMIC_TYPE_LONG;
2906 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2907 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2908 atomic_type = ATOMIC_TYPE_ULONG;
2911 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2912 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2913 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2914 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2916 atomic_type = ATOMIC_TYPE_LONGLONG;
2917 goto warn_about_long_long;
2919 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2920 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2922 atomic_type = ATOMIC_TYPE_ULONGLONG;
2923 warn_about_long_long:
2924 warningf(WARN_LONG_LONG, &specifiers->pos, "ISO C90 does not support 'long long'");
2927 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2928 atomic_type = unsigned_int8_type_kind;
2931 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2932 atomic_type = unsigned_int16_type_kind;
2935 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2936 atomic_type = unsigned_int32_type_kind;
2939 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2940 atomic_type = unsigned_int64_type_kind;
2943 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2944 atomic_type = unsigned_int128_type_kind;
2947 case SPECIFIER_INT8:
2948 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2949 atomic_type = int8_type_kind;
2952 case SPECIFIER_INT16:
2953 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2954 atomic_type = int16_type_kind;
2957 case SPECIFIER_INT32:
2958 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2959 atomic_type = int32_type_kind;
2962 case SPECIFIER_INT64:
2963 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2964 atomic_type = int64_type_kind;
2967 case SPECIFIER_INT128:
2968 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2969 atomic_type = int128_type_kind;
2972 case SPECIFIER_FLOAT:
2973 atomic_type = ATOMIC_TYPE_FLOAT;
2975 case SPECIFIER_DOUBLE:
2976 atomic_type = ATOMIC_TYPE_DOUBLE;
2978 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2979 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2981 case SPECIFIER_BOOL:
2982 if (type_specifiers & (SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2983 if (type_specifiers & SPECIFIER_COMPLEX)
2984 errorf(pos, "_Complex specifier is invalid for _Bool");
2985 if (type_specifiers & SPECIFIER_IMAGINARY)
2986 errorf(pos, "_Imaginary specifier is invalid for _Bool");
2987 type_specifiers &= ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY);
2989 atomic_type = ATOMIC_TYPE_BOOL;
2992 /* invalid specifier combination, give an error message */
2993 if (type_specifiers == 0) {
2995 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
2996 if (!(c_mode & _CXX) && !strict_mode) {
2997 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
2998 atomic_type = ATOMIC_TYPE_INT;
3001 errorf(pos, "no type specifiers given in declaration");
3004 } else if (type_specifiers == SPECIFIER_COMPLEX) {
3005 warningf(WARN_OTHER, pos, "_Complex requires a type specifier; assuming '_Complex double'");
3006 atomic_type = ATOMIC_TYPE_DOUBLE;
3008 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3009 (type_specifiers & SPECIFIER_UNSIGNED)) {
3010 errorf(pos, "signed and unsigned specifiers given");
3011 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3012 errorf(pos, "only integer types can be signed or unsigned");
3014 errorf(pos, "multiple datatypes in declaration");
3016 specifiers->type = type_error_type;
3021 if (type_specifiers & SPECIFIER_COMPLEX) {
3022 type = allocate_type_zero(TYPE_COMPLEX);
3023 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3024 type = allocate_type_zero(TYPE_IMAGINARY);
3026 type = allocate_type_zero(TYPE_ATOMIC);
3028 type->atomic.akind = atomic_type;
3030 } else if (type_specifiers != 0) {
3031 errorf(&specifiers->pos, "multiple datatypes in declaration");
3034 /* FIXME: check type qualifiers here */
3035 type->base.qualifiers = qualifiers;
3038 type = identify_new_type(type);
3040 type = typehash_insert(type);
3043 if (specifiers->attributes != NULL)
3044 type = handle_type_attributes(specifiers->attributes, type);
3045 specifiers->type = type;
3048 static type_qualifiers_t parse_type_qualifiers(void)
3050 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3053 switch (token.kind) {
3054 /* type qualifiers */
3055 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3056 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3057 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3058 /* microsoft extended type modifiers */
3059 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3060 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3061 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3062 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3063 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3072 * Parses an K&R identifier list
3074 static void parse_identifier_list(scope_t *scope)
3076 assert(token.kind == T_IDENTIFIER);
3078 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3079 /* a K&R parameter has no type, yet */
3083 append_entity(scope, entity);
3084 } while (accept(',') && token.kind == T_IDENTIFIER);
3087 static entity_t *parse_parameter(void)
3089 declaration_specifiers_t specifiers;
3090 parse_declaration_specifiers(&specifiers);
3092 entity_t *entity = parse_declarator(&specifiers,
3093 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3094 anonymous_entity = NULL;
3098 static void semantic_parameter_incomplete(const entity_t *entity)
3100 assert(entity->kind == ENTITY_PARAMETER);
3102 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3103 * list in a function declarator that is part of a
3104 * definition of that function shall not have
3105 * incomplete type. */
3106 type_t *type = skip_typeref(entity->declaration.type);
3107 if (is_type_incomplete(type)) {
3108 errorf(&entity->base.pos, "'%N' has incomplete type", entity);
3112 static bool has_parameters(void)
3114 /* func(void) is not a parameter */
3115 if (look_ahead(1)->kind != ')')
3117 if (token.kind == T_IDENTIFIER) {
3118 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3121 if (entity->kind != ENTITY_TYPEDEF)
3123 type_t const *const type = skip_typeref(entity->typedefe.type);
3124 if (!is_type_void(type))
3126 if (c_mode & _CXX) {
3127 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3128 * is not allowed. */
3129 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3130 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3131 /* §6.7.5.3:10 Qualification is not allowed here. */
3132 errorf(HERE, "'void' as parameter must not have type qualifiers");
3134 } else if (token.kind != T_void) {
3142 * Parses function type parameters (and optionally creates variable_t entities
3143 * for them in a scope)
3145 static void parse_parameters(function_type_t *type, scope_t *scope)
3147 add_anchor_token(')');
3150 if (token.kind == T_IDENTIFIER &&
3151 !is_typedef_symbol(token.base.symbol) &&
3152 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3153 type->kr_style_parameters = true;
3154 parse_identifier_list(scope);
3155 } else if (token.kind == ')') {
3156 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3157 if (!(c_mode & _CXX))
3158 type->unspecified_parameters = true;
3159 } else if (has_parameters()) {
3160 function_parameter_t **anchor = &type->parameters;
3161 add_anchor_token(',');
3163 switch (token.kind) {
3166 type->variadic = true;
3167 goto parameters_finished;
3172 entity_t *entity = parse_parameter();
3173 if (entity->kind == ENTITY_TYPEDEF) {
3174 errorf(&entity->base.pos,
3175 "typedef not allowed as function parameter");
3178 assert(is_declaration(entity));
3180 semantic_parameter_incomplete(entity);
3182 function_parameter_t *const parameter =
3183 allocate_parameter(entity->declaration.type);
3185 if (scope != NULL) {
3186 append_entity(scope, entity);
3189 *anchor = parameter;
3190 anchor = ¶meter->next;
3195 goto parameters_finished;
3197 } while (accept(','));
3198 parameters_finished:
3199 rem_anchor_token(',');
3202 rem_anchor_token(')');
3206 typedef enum construct_type_kind_t {
3207 CONSTRUCT_POINTER = 1,
3208 CONSTRUCT_REFERENCE,
3211 } construct_type_kind_t;
3213 typedef union construct_type_t construct_type_t;
3215 typedef struct construct_type_base_t {
3216 construct_type_kind_t kind;
3218 construct_type_t *next;
3219 } construct_type_base_t;
3221 typedef struct parsed_pointer_t {
3222 construct_type_base_t base;
3223 type_qualifiers_t type_qualifiers;
3224 variable_t *base_variable; /**< MS __based extension. */
3227 typedef struct parsed_reference_t {
3228 construct_type_base_t base;
3229 } parsed_reference_t;
3231 typedef struct construct_function_type_t {
3232 construct_type_base_t base;
3233 type_t *function_type;
3234 } construct_function_type_t;
3236 typedef struct parsed_array_t {
3237 construct_type_base_t base;
3238 type_qualifiers_t type_qualifiers;
3244 union construct_type_t {
3245 construct_type_kind_t kind;
3246 construct_type_base_t base;
3247 parsed_pointer_t pointer;
3248 parsed_reference_t reference;
3249 construct_function_type_t function;
3250 parsed_array_t array;
3253 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3255 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3256 memset(cons, 0, size);
3258 cons->base.pos = *HERE;
3263 static construct_type_t *parse_pointer_declarator(void)
3265 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3267 cons->pointer.type_qualifiers = parse_type_qualifiers();
3268 //cons->pointer.base_variable = base_variable;
3273 /* ISO/IEC 14882:1998(E) §8.3.2 */
3274 static construct_type_t *parse_reference_declarator(void)
3276 if (!(c_mode & _CXX))
3277 errorf(HERE, "references are only available for C++");
3279 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3286 static construct_type_t *parse_array_declarator(void)
3288 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3289 parsed_array_t *const array = &cons->array;
3292 add_anchor_token(']');
3294 bool is_static = accept(T_static);
3296 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3299 is_static = accept(T_static);
3301 array->type_qualifiers = type_qualifiers;
3302 array->is_static = is_static;
3304 expression_t *size = NULL;
3305 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3306 array->is_variable = true;
3308 } else if (token.kind != ']') {
3309 size = parse_assignment_expression();
3311 /* §6.7.5.2:1 Array size must have integer type */
3312 type_t *const orig_type = size->base.type;
3313 type_t *const type = skip_typeref(orig_type);
3314 if (!is_type_integer(type) && is_type_valid(type)) {
3315 errorf(&size->base.pos,
3316 "array size '%E' must have integer type but has type '%T'",
3321 mark_vars_read(size, NULL);
3324 if (is_static && size == NULL)
3325 errorf(&array->base.pos, "static array parameters require a size");
3327 rem_anchor_token(']');
3333 static construct_type_t *parse_function_declarator(scope_t *scope)
3335 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3337 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3338 function_type_t *ftype = &type->function;
3340 ftype->linkage = current_linkage;
3341 ftype->calling_convention = CC_DEFAULT;
3343 parse_parameters(ftype, scope);
3345 cons->function.function_type = type;
3350 typedef struct parse_declarator_env_t {
3351 bool may_be_abstract : 1;
3352 bool must_be_abstract : 1;
3353 decl_modifiers_t modifiers;
3357 attribute_t *attributes;
3358 } parse_declarator_env_t;
3361 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3363 /* construct a single linked list of construct_type_t's which describe
3364 * how to construct the final declarator type */
3365 construct_type_t *first = NULL;
3366 construct_type_t **anchor = &first;
3368 env->attributes = parse_attributes(env->attributes);
3371 construct_type_t *type;
3372 //variable_t *based = NULL; /* MS __based extension */
3373 switch (token.kind) {
3375 type = parse_reference_declarator();
3379 panic("based not supported anymore");
3384 type = parse_pointer_declarator();
3388 goto ptr_operator_end;
3392 anchor = &type->base.next;
3394 /* TODO: find out if this is correct */
3395 env->attributes = parse_attributes(env->attributes);
3399 construct_type_t *inner_types = NULL;
3401 switch (token.kind) {
3403 if (env->must_be_abstract) {
3404 errorf(HERE, "no identifier expected in typename");
3406 env->symbol = token.base.symbol;
3413 /* Parenthesized declarator or function declarator? */
3414 token_t const *const la1 = look_ahead(1);
3415 switch (la1->kind) {
3417 if (is_typedef_symbol(la1->base.symbol)) {
3419 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3420 * interpreted as ``function with no parameter specification'', rather
3421 * than redundant parentheses around the omitted identifier. */
3423 /* Function declarator. */
3424 if (!env->may_be_abstract) {
3425 errorf(HERE, "function declarator must have a name");
3432 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3433 /* Paranthesized declarator. */
3435 add_anchor_token(')');
3436 inner_types = parse_inner_declarator(env);
3437 if (inner_types != NULL) {
3438 /* All later declarators only modify the return type */
3439 env->must_be_abstract = true;
3441 rem_anchor_token(')');
3450 if (env->may_be_abstract)
3452 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3457 construct_type_t **const p = anchor;
3460 construct_type_t *type;
3461 switch (token.kind) {
3463 scope_t *scope = NULL;
3464 if (!env->must_be_abstract) {
3465 scope = &env->parameters;
3468 type = parse_function_declarator(scope);
3472 type = parse_array_declarator();
3475 goto declarator_finished;
3478 /* insert in the middle of the list (at p) */
3479 type->base.next = *p;
3482 anchor = &type->base.next;
3485 declarator_finished:
3486 /* append inner_types at the end of the list, we don't to set anchor anymore
3487 * as it's not needed anymore */
3488 *anchor = inner_types;
3493 static type_t *construct_declarator_type(construct_type_t *construct_list,
3496 construct_type_t *iter = construct_list;
3497 for (; iter != NULL; iter = iter->base.next) {
3498 position_t const* const pos = &iter->base.pos;
3499 switch (iter->kind) {
3500 case CONSTRUCT_FUNCTION: {
3501 construct_function_type_t *function = &iter->function;
3502 type_t *function_type = function->function_type;
3504 function_type->function.return_type = type;
3506 type_t *skipped_return_type = skip_typeref(type);
3508 if (is_type_function(skipped_return_type)) {
3509 errorf(pos, "function returning function is not allowed");
3510 } else if (is_type_array(skipped_return_type)) {
3511 errorf(pos, "function returning array is not allowed");
3513 if (skipped_return_type->base.qualifiers != 0) {
3514 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3518 /* The function type was constructed earlier. Freeing it here will
3519 * destroy other types. */
3520 type = typehash_insert(function_type);
3524 case CONSTRUCT_POINTER: {
3525 if (is_type_reference(skip_typeref(type)))
3526 errorf(pos, "cannot declare a pointer to reference");
3528 parsed_pointer_t *pointer = &iter->pointer;
3529 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3533 case CONSTRUCT_REFERENCE:
3534 if (is_type_reference(skip_typeref(type)))
3535 errorf(pos, "cannot declare a reference to reference");
3537 type = make_reference_type(type);
3540 case CONSTRUCT_ARRAY: {
3541 if (is_type_reference(skip_typeref(type)))
3542 errorf(pos, "cannot declare an array of references");
3544 parsed_array_t *array = &iter->array;
3545 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3547 expression_t *size_expression = array->size;
3548 if (size_expression != NULL) {
3550 = create_implicit_cast(size_expression, type_size_t);
3553 array_type->base.qualifiers = array->type_qualifiers;
3554 array_type->array.element_type = type;
3555 array_type->array.is_static = array->is_static;
3556 array_type->array.is_variable = array->is_variable;
3557 array_type->array.size_expression = size_expression;
3559 if (size_expression != NULL) {
3560 switch (is_constant_expression(size_expression)) {
3561 case EXPR_CLASS_CONSTANT: {
3562 long const size = fold_constant_to_int(size_expression);
3563 array_type->array.size = size;
3564 array_type->array.size_constant = true;
3565 /* §6.7.5.2:1 If the expression is a constant expression,
3566 * it shall have a value greater than zero. */
3568 errorf(&size_expression->base.pos,
3569 "size of array must be greater than zero");
3570 } else if (size == 0 && !GNU_MODE) {
3571 errorf(&size_expression->base.pos,
3572 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3577 case EXPR_CLASS_VARIABLE:
3578 array_type->array.is_vla = true;
3581 case EXPR_CLASS_ERROR:
3586 type_t *skipped_type = skip_typeref(type);
3588 if (is_type_incomplete(skipped_type)) {
3589 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3590 } else if (is_type_function(skipped_type)) {
3591 errorf(pos, "array of functions is not allowed");
3593 type = identify_new_type(array_type);
3597 internal_errorf(pos, "invalid type construction found");
3603 static type_t *automatic_type_conversion(type_t *orig_type);
3605 static type_t *semantic_parameter(const position_t *pos, type_t *type,
3606 const declaration_specifiers_t *specifiers,
3607 entity_t const *const param)
3609 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3610 * shall be adjusted to ``qualified pointer to type'',
3612 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3613 * type'' shall be adjusted to ``pointer to function
3614 * returning type'', as in 6.3.2.1. */
3615 type = automatic_type_conversion(type);
3617 if (specifiers->is_inline && is_type_valid(type)) {
3618 errorf(pos, "'%N' declared 'inline'", param);
3621 /* §6.9.1:6 The declarations in the declaration list shall contain
3622 * no storage-class specifier other than register and no
3623 * initializations. */
3624 if (specifiers->thread_local || (
3625 specifiers->storage_class != STORAGE_CLASS_NONE &&
3626 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3628 errorf(pos, "invalid storage class for '%N'", param);
3631 /* delay test for incomplete type, because we might have (void)
3632 * which is legal but incomplete... */
3637 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3638 declarator_flags_t flags)
3640 parse_declarator_env_t env;
3641 memset(&env, 0, sizeof(env));
3642 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3644 construct_type_t *construct_type = parse_inner_declarator(&env);
3646 construct_declarator_type(construct_type, specifiers->type);
3647 type_t *type = skip_typeref(orig_type);
3649 if (construct_type != NULL) {
3650 obstack_free(&temp_obst, construct_type);
3653 attribute_t *attributes = parse_attributes(env.attributes);
3654 /* append (shared) specifier attribute behind attributes of this
3656 attribute_t **anchor = &attributes;
3657 while (*anchor != NULL)
3658 anchor = &(*anchor)->next;
3659 *anchor = specifiers->attributes;
3662 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3663 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.pos);
3664 entity->typedefe.type = orig_type;
3666 if (anonymous_entity != NULL) {
3667 if (is_type_compound(type)) {
3668 assert(anonymous_entity->compound.alias == NULL);
3669 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3670 anonymous_entity->kind == ENTITY_UNION);
3671 anonymous_entity->compound.alias = entity;
3672 anonymous_entity = NULL;
3673 } else if (is_type_enum(type)) {
3674 assert(anonymous_entity->enume.alias == NULL);
3675 assert(anonymous_entity->kind == ENTITY_ENUM);
3676 anonymous_entity->enume.alias = entity;
3677 anonymous_entity = NULL;
3681 /* create a declaration type entity */
3682 position_t const *const pos = env.symbol ? &env.pos : &specifiers->pos;
3683 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3684 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3686 if (env.symbol != NULL) {
3687 if (specifiers->is_inline && is_type_valid(type)) {
3688 errorf(&env.pos, "'%N' declared 'inline'", entity);
3691 if (specifiers->thread_local ||
3692 specifiers->storage_class != STORAGE_CLASS_NONE) {
3693 errorf(&env.pos, "'%N' must have no storage class", entity);
3696 } else if (flags & DECL_IS_PARAMETER) {
3697 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3698 orig_type = semantic_parameter(&env.pos, orig_type, specifiers, entity);
3699 } else if (is_type_function(type)) {
3700 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3701 entity->function.is_inline = specifiers->is_inline;
3702 entity->function.elf_visibility = default_visibility;
3703 entity->function.parameters = env.parameters;
3705 if (env.symbol != NULL) {
3706 /* this needs fixes for C++ */
3707 bool in_function_scope = current_function != NULL;
3709 if (specifiers->thread_local || (
3710 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3711 specifiers->storage_class != STORAGE_CLASS_NONE &&
3712 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3714 errorf(&env.pos, "invalid storage class for '%N'", entity);
3718 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3719 entity->variable.elf_visibility = default_visibility;
3720 entity->variable.thread_local = specifiers->thread_local;
3722 if (env.symbol != NULL) {
3723 if (specifiers->is_inline && is_type_valid(type)) {
3724 errorf(&env.pos, "'%N' declared 'inline'", entity);
3727 bool invalid_storage_class = false;
3728 if (current_scope == file_scope) {
3729 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3730 specifiers->storage_class != STORAGE_CLASS_NONE &&
3731 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3732 invalid_storage_class = true;
3735 if (specifiers->thread_local &&
3736 specifiers->storage_class == STORAGE_CLASS_NONE) {
3737 invalid_storage_class = true;
3740 if (invalid_storage_class) {
3741 errorf(&env.pos, "invalid storage class for '%N'", entity);
3746 entity->declaration.type = orig_type;
3747 entity->declaration.alignment = get_type_alignment(orig_type);
3748 entity->declaration.modifiers = env.modifiers;
3749 entity->declaration.attributes = attributes;
3751 storage_class_t storage_class = specifiers->storage_class;
3752 entity->declaration.declared_storage_class = storage_class;
3754 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3755 storage_class = STORAGE_CLASS_AUTO;
3756 entity->declaration.storage_class = storage_class;
3759 if (attributes != NULL) {
3760 handle_entity_attributes(attributes, entity);
3763 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3764 adapt_special_functions(&entity->function);
3770 static type_t *parse_abstract_declarator(type_t *base_type)
3772 parse_declarator_env_t env;
3773 memset(&env, 0, sizeof(env));
3774 env.may_be_abstract = true;
3775 env.must_be_abstract = true;
3777 construct_type_t *construct_type = parse_inner_declarator(&env);
3779 type_t *result = construct_declarator_type(construct_type, base_type);
3780 if (construct_type != NULL) {
3781 obstack_free(&temp_obst, construct_type);
3783 result = handle_type_attributes(env.attributes, result);
3789 * Check if the declaration of main is suspicious. main should be a
3790 * function with external linkage, returning int, taking either zero
3791 * arguments, two, or three arguments of appropriate types, ie.
3793 * int main([ int argc, char **argv [, char **env ] ]).
3795 * @param decl the declaration to check
3796 * @param type the function type of the declaration
3798 static void check_main(const entity_t *entity)
3800 const position_t *pos = &entity->base.pos;
3801 if (entity->kind != ENTITY_FUNCTION) {
3802 warningf(WARN_MAIN, pos, "'main' is not a function");
3806 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3807 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3810 type_t *type = skip_typeref(entity->declaration.type);
3811 assert(is_type_function(type));
3813 function_type_t const *const func_type = &type->function;
3814 type_t *const ret_type = func_type->return_type;
3815 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3816 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3818 const function_parameter_t *parm = func_type->parameters;
3820 type_t *const first_type = skip_typeref(parm->type);
3821 type_t *const first_type_unqual = get_unqualified_type(first_type);
3822 if (!types_compatible(first_type_unqual, type_int)) {
3823 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3827 type_t *const second_type = skip_typeref(parm->type);
3828 type_t *const second_type_unqual
3829 = get_unqualified_type(second_type);
3830 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3831 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3835 type_t *const third_type = skip_typeref(parm->type);
3836 type_t *const third_type_unqual
3837 = get_unqualified_type(third_type);
3838 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3839 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3843 goto warn_arg_count;
3847 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3852 static void error_redefined_as_different_kind(const position_t *pos,
3853 const entity_t *old, entity_kind_t new_kind)
3855 char const *const what = get_entity_kind_name(new_kind);
3856 position_t const *const ppos = &old->base.pos;
3857 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3860 static bool is_entity_valid(entity_t *const ent)
3862 if (is_declaration(ent)) {
3863 return is_type_valid(skip_typeref(ent->declaration.type));
3864 } else if (ent->kind == ENTITY_TYPEDEF) {
3865 return is_type_valid(skip_typeref(ent->typedefe.type));
3870 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3872 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3873 if (attributes_equal(tattr, attr))
3880 * Tests whether new_list contains any attributes not included in old_list
3882 static bool has_new_attributes(const attribute_t *old_list,
3883 const attribute_t *new_list)
3885 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3886 if (!contains_attribute(old_list, attr))
3893 * Merge in attributes from an attribute list (probably from a previous
3894 * declaration with the same name). Warning: destroys the old structure
3895 * of the attribute list - don't reuse attributes after this call.
3897 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3900 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3902 if (contains_attribute(decl->attributes, attr))
3905 /* move attribute to new declarations attributes list */
3906 attr->next = decl->attributes;
3907 decl->attributes = attr;
3911 static bool is_main(entity_t*);
3914 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3915 * for various problems that occur for multiple definitions
3917 entity_t *record_entity(entity_t *entity, const bool is_definition)
3919 const symbol_t *const symbol = entity->base.symbol;
3920 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3921 const position_t *pos = &entity->base.pos;
3923 /* can happen in error cases */
3927 assert(!entity->base.parent_scope);
3928 assert(current_scope);
3929 entity->base.parent_scope = current_scope;
3931 entity_t *const previous_entity = get_entity(symbol, namespc);
3932 /* pushing the same entity twice will break the stack structure */
3933 assert(previous_entity != entity);
3935 if (entity->kind == ENTITY_FUNCTION) {
3936 type_t *const orig_type = entity->declaration.type;
3937 type_t *const type = skip_typeref(orig_type);
3939 assert(is_type_function(type));
3940 if (type->function.unspecified_parameters &&
3941 previous_entity == NULL &&
3942 !entity->declaration.implicit) {
3943 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3946 if (is_main(entity)) {
3951 if (is_declaration(entity) &&
3952 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3953 current_scope != file_scope &&
3954 !entity->declaration.implicit) {
3955 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3958 if (previous_entity != NULL) {
3959 position_t const *const ppos = &previous_entity->base.pos;
3961 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3962 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3963 assert(previous_entity->kind == ENTITY_PARAMETER);
3964 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3968 if (previous_entity->base.parent_scope == current_scope) {
3969 if (previous_entity->kind != entity->kind) {
3970 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3971 error_redefined_as_different_kind(pos, previous_entity,
3976 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3977 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3980 if (previous_entity->kind == ENTITY_TYPEDEF) {
3981 type_t *const type = skip_typeref(entity->typedefe.type);
3982 type_t *const prev_type
3983 = skip_typeref(previous_entity->typedefe.type);
3984 if (c_mode & _CXX) {
3985 /* C++ allows double typedef if they are identical
3986 * (after skipping typedefs) */
3987 if (type == prev_type)
3990 /* GCC extension: redef in system headers is allowed */
3991 if ((pos->is_system_header || ppos->is_system_header) &&
3992 types_compatible(type, prev_type))
3995 errorf(pos, "redefinition of '%N' (declared %P)",
4000 /* at this point we should have only VARIABLES or FUNCTIONS */
4001 assert(is_declaration(previous_entity) && is_declaration(entity));
4003 declaration_t *const prev_decl = &previous_entity->declaration;
4004 declaration_t *const decl = &entity->declaration;
4006 /* can happen for K&R style declarations */
4007 if (prev_decl->type == NULL &&
4008 previous_entity->kind == ENTITY_PARAMETER &&
4009 entity->kind == ENTITY_PARAMETER) {
4010 prev_decl->type = decl->type;
4011 prev_decl->storage_class = decl->storage_class;
4012 prev_decl->declared_storage_class = decl->declared_storage_class;
4013 prev_decl->modifiers = decl->modifiers;
4014 return previous_entity;
4017 type_t *const type = skip_typeref(decl->type);
4018 type_t *const prev_type = skip_typeref(prev_decl->type);
4020 if (!types_compatible(type, prev_type)) {
4021 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4023 unsigned old_storage_class = prev_decl->storage_class;
4025 if (is_definition &&
4027 !(prev_decl->modifiers & DM_USED) &&
4028 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4029 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4032 storage_class_t new_storage_class = decl->storage_class;
4034 /* pretend no storage class means extern for function
4035 * declarations (except if the previous declaration is neither
4036 * none nor extern) */
4037 if (entity->kind == ENTITY_FUNCTION) {
4038 /* the previous declaration could have unspecified parameters or
4039 * be a typedef, so use the new type */
4040 if (prev_type->function.unspecified_parameters || is_definition)
4041 prev_decl->type = type;
4043 switch (old_storage_class) {
4044 case STORAGE_CLASS_NONE:
4045 old_storage_class = STORAGE_CLASS_EXTERN;
4048 case STORAGE_CLASS_EXTERN:
4049 if (is_definition) {
4050 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4051 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4053 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4054 new_storage_class = STORAGE_CLASS_EXTERN;
4061 } else if (is_type_incomplete(prev_type)) {
4062 prev_decl->type = type;
4065 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4066 new_storage_class == STORAGE_CLASS_EXTERN) {
4068 warn_redundant_declaration: ;
4070 = has_new_attributes(prev_decl->attributes,
4072 if (has_new_attrs) {
4073 merge_in_attributes(decl, prev_decl->attributes);
4074 } else if (!is_definition &&
4075 is_type_valid(prev_type) &&
4076 !pos->is_system_header) {
4077 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4079 } else if (current_function == NULL) {
4080 if (old_storage_class != STORAGE_CLASS_STATIC &&
4081 new_storage_class == STORAGE_CLASS_STATIC) {
4082 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4083 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4084 prev_decl->storage_class = STORAGE_CLASS_NONE;
4085 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4087 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4089 goto error_redeclaration;
4090 goto warn_redundant_declaration;
4092 } else if (is_type_valid(prev_type)) {
4093 if (old_storage_class == new_storage_class) {
4094 error_redeclaration:
4095 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4097 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4102 prev_decl->modifiers |= decl->modifiers;
4103 if (entity->kind == ENTITY_FUNCTION) {
4104 previous_entity->function.is_inline |= entity->function.is_inline;
4106 return previous_entity;
4110 if (is_warn_on(why = WARN_SHADOW) ||
4111 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4112 char const *const what = get_entity_kind_name(previous_entity->kind);
4113 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4117 if (entity->kind == ENTITY_FUNCTION) {
4118 if (is_definition &&
4119 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4121 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4122 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4124 goto warn_missing_declaration;
4127 } else if (entity->kind == ENTITY_VARIABLE) {
4128 if (current_scope == file_scope &&
4129 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4130 !entity->declaration.implicit) {
4131 warn_missing_declaration:
4132 if (is_type_valid(skip_typeref(entity->declaration.type)))
4133 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4138 environment_push(entity);
4139 append_entity(current_scope, entity);
4144 static void parser_error_multiple_definition(entity_t *entity,
4145 const position_t *pos)
4147 errorf(pos, "redefinition of '%N' (declared %P)", entity, &entity->base.pos);
4150 static bool is_declaration_specifier(const token_t *token)
4152 switch (token->kind) {
4156 return is_typedef_symbol(token->base.symbol);
4163 static void parse_init_declarator_rest(entity_t *entity)
4165 type_t *orig_type = type_error_type;
4167 if (entity->base.kind == ENTITY_TYPEDEF) {
4168 position_t const *const pos = &entity->base.pos;
4169 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4171 assert(is_declaration(entity));
4172 orig_type = entity->declaration.type;
4175 type_t *type = skip_typeref(orig_type);
4177 if (entity->kind == ENTITY_VARIABLE
4178 && entity->variable.initializer != NULL) {
4179 parser_error_multiple_definition(entity, HERE);
4183 declaration_t *const declaration = &entity->declaration;
4184 bool must_be_constant = false;
4185 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4186 entity->base.parent_scope == file_scope) {
4187 must_be_constant = true;
4190 if (is_type_function(type)) {
4191 position_t const *const pos = &entity->base.pos;
4192 errorf(pos, "'%N' is initialized like a variable", entity);
4193 orig_type = type_error_type;
4196 parse_initializer_env_t env;
4197 env.type = orig_type;
4198 env.must_be_constant = must_be_constant;
4199 env.entity = entity;
4201 initializer_t *initializer = parse_initializer(&env);
4203 if (entity->kind == ENTITY_VARIABLE) {
4204 /* §6.7.5:22 array initializers for arrays with unknown size
4205 * determine the array type size */
4206 declaration->type = env.type;
4207 entity->variable.initializer = initializer;
4211 /* parse rest of a declaration without any declarator */
4212 static void parse_anonymous_declaration_rest(
4213 const declaration_specifiers_t *specifiers)
4216 anonymous_entity = NULL;
4218 position_t const *const pos = &specifiers->pos;
4219 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4220 specifiers->thread_local) {
4221 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4224 type_t *type = specifiers->type;
4225 switch (type->kind) {
4226 case TYPE_COMPOUND_STRUCT:
4227 case TYPE_COMPOUND_UNION: {
4228 if (type->compound.compound->base.symbol == NULL) {
4229 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4238 warningf(WARN_OTHER, pos, "empty declaration");
4243 static void check_variable_type_complete(entity_t *ent)
4245 if (ent->kind != ENTITY_VARIABLE)
4248 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4249 * type for the object shall be complete [...] */
4250 declaration_t *decl = &ent->declaration;
4251 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4252 decl->storage_class == STORAGE_CLASS_STATIC)
4255 type_t *const type = skip_typeref(decl->type);
4256 if (!is_type_incomplete(type))
4259 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4260 * are given length one. */
4261 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4262 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4266 errorf(&ent->base.pos, "variable '%#N' has incomplete type", ent);
4270 static void parse_declaration_rest(entity_t *ndeclaration,
4271 const declaration_specifiers_t *specifiers,
4272 parsed_declaration_func finished_declaration,
4273 declarator_flags_t flags)
4275 add_anchor_token(';');
4276 add_anchor_token(',');
4278 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4280 if (token.kind == '=') {
4281 parse_init_declarator_rest(entity);
4282 } else if (entity->kind == ENTITY_VARIABLE) {
4283 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4284 * [...] where the extern specifier is explicitly used. */
4285 declaration_t *decl = &entity->declaration;
4286 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4287 is_type_reference(skip_typeref(decl->type))) {
4288 position_t const *const pos = &entity->base.pos;
4289 errorf(pos, "reference '%#N' must be initialized", entity);
4293 check_variable_type_complete(entity);
4298 add_anchor_token('=');
4299 ndeclaration = parse_declarator(specifiers, flags);
4300 rem_anchor_token('=');
4302 rem_anchor_token(',');
4303 rem_anchor_token(';');
4306 anonymous_entity = NULL;
4309 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4311 symbol_t *symbol = entity->base.symbol;
4315 assert(entity->base.namespc == NAMESPACE_NORMAL);
4316 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4317 if (previous_entity == NULL
4318 || previous_entity->base.parent_scope != current_scope) {
4319 errorf(&entity->base.pos, "expected declaration of a function parameter, found '%Y'",
4324 if (is_definition) {
4325 errorf(HERE, "'%N' is initialised", entity);
4328 return record_entity(entity, false);
4331 static void parse_declaration(parsed_declaration_func finished_declaration,
4332 declarator_flags_t flags)
4334 add_anchor_token(';');
4335 declaration_specifiers_t specifiers;
4336 parse_declaration_specifiers(&specifiers);
4337 rem_anchor_token(';');
4339 if (token.kind == ';') {
4340 parse_anonymous_declaration_rest(&specifiers);
4342 entity_t *entity = parse_declarator(&specifiers, flags);
4343 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4348 static type_t *get_default_promoted_type(type_t *orig_type)
4350 type_t *result = orig_type;
4352 type_t *type = skip_typeref(orig_type);
4353 if (is_type_integer(type)) {
4354 result = promote_integer(type);
4355 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4356 result = type_double;
4362 static void parse_kr_declaration_list(entity_t *entity)
4364 if (entity->kind != ENTITY_FUNCTION)
4367 type_t *type = skip_typeref(entity->declaration.type);
4368 assert(is_type_function(type));
4369 if (!type->function.kr_style_parameters)
4372 add_anchor_token('{');
4374 PUSH_SCOPE(&entity->function.parameters);
4376 entity_t *parameter = entity->function.parameters.entities;
4377 for ( ; parameter != NULL; parameter = parameter->base.next) {
4378 assert(parameter->base.parent_scope == NULL);
4379 parameter->base.parent_scope = current_scope;
4380 environment_push(parameter);
4383 /* parse declaration list */
4385 switch (token.kind) {
4387 /* This covers symbols, which are no type, too, and results in
4388 * better error messages. The typical cases are misspelled type
4389 * names and missing includes. */
4391 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4401 /* update function type */
4402 type_t *new_type = duplicate_type(type);
4404 function_parameter_t *parameters = NULL;
4405 function_parameter_t **anchor = ¶meters;
4407 /* did we have an earlier prototype? */
4408 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4409 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4412 function_parameter_t *proto_parameter = NULL;
4413 if (proto_type != NULL) {
4414 type_t *proto_type_type = proto_type->declaration.type;
4415 proto_parameter = proto_type_type->function.parameters;
4416 /* If a K&R function definition has a variadic prototype earlier, then
4417 * make the function definition variadic, too. This should conform to
4418 * §6.7.5.3:15 and §6.9.1:8. */
4419 new_type->function.variadic = proto_type_type->function.variadic;
4421 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4423 new_type->function.unspecified_parameters = true;
4426 bool need_incompatible_warning = false;
4427 parameter = entity->function.parameters.entities;
4428 for (; parameter != NULL; parameter = parameter->base.next,
4430 proto_parameter == NULL ? NULL : proto_parameter->next) {
4431 if (parameter->kind != ENTITY_PARAMETER)
4434 type_t *parameter_type = parameter->declaration.type;
4435 if (parameter_type == NULL) {
4436 position_t const* const pos = ¶meter->base.pos;
4438 errorf(pos, "no type specified for function '%N'", parameter);
4439 parameter_type = type_error_type;
4441 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4442 parameter_type = type_int;
4444 parameter->declaration.type = parameter_type;
4447 semantic_parameter_incomplete(parameter);
4449 /* we need the default promoted types for the function type */
4450 type_t *not_promoted = parameter_type;
4451 parameter_type = get_default_promoted_type(parameter_type);
4453 /* gcc special: if the type of the prototype matches the unpromoted
4454 * type don't promote */
4455 if (!strict_mode && proto_parameter != NULL) {
4456 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4457 type_t *promo_skip = skip_typeref(parameter_type);
4458 type_t *param_skip = skip_typeref(not_promoted);
4459 if (!types_compatible(proto_p_type, promo_skip)
4460 && types_compatible(proto_p_type, param_skip)) {
4462 need_incompatible_warning = true;
4463 parameter_type = not_promoted;
4466 function_parameter_t *const function_parameter
4467 = allocate_parameter(parameter_type);
4469 *anchor = function_parameter;
4470 anchor = &function_parameter->next;
4473 new_type->function.parameters = parameters;
4474 new_type = identify_new_type(new_type);
4476 if (need_incompatible_warning) {
4477 symbol_t const *const sym = entity->base.symbol;
4478 position_t const *const pos = &entity->base.pos;
4479 position_t const *const ppos = &proto_type->base.pos;
4480 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4482 entity->declaration.type = new_type;
4484 rem_anchor_token('{');
4487 static bool first_err = true;
4490 * When called with first_err set, prints the name of the current function,
4493 static void print_in_function(void)
4497 char const *const file = current_function->base.base.pos.input_name;
4498 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4503 * Check if all labels are defined in the current function.
4504 * Check if all labels are used in the current function.
4506 static void check_labels(void)
4508 for (const goto_statement_t *goto_statement = goto_first;
4509 goto_statement != NULL;
4510 goto_statement = goto_statement->next) {
4511 label_t *label = goto_statement->label;
4512 if (label->base.pos.input_name == NULL) {
4513 print_in_function();
4514 position_t const *const pos = &goto_statement->base.pos;
4515 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4519 if (is_warn_on(WARN_UNUSED_LABEL)) {
4520 for (const label_statement_t *label_statement = label_first;
4521 label_statement != NULL;
4522 label_statement = label_statement->next) {
4523 label_t *label = label_statement->label;
4525 if (! label->used) {
4526 print_in_function();
4527 position_t const *const pos = &label_statement->base.pos;
4528 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4534 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4536 entity_t const *const end = last != NULL ? last->base.next : NULL;
4537 for (; entity != end; entity = entity->base.next) {
4538 if (!is_declaration(entity))
4541 declaration_t *declaration = &entity->declaration;
4542 if (declaration->implicit)
4545 if (!declaration->used) {
4546 print_in_function();
4547 warningf(why, &entity->base.pos, "'%N' is unused", entity);
4548 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4549 print_in_function();
4550 warningf(why, &entity->base.pos, "'%N' is never read", entity);
4555 static void check_unused_variables(statement_t *const stmt, void *const env)
4559 switch (stmt->kind) {
4560 case STATEMENT_DECLARATION: {
4561 declaration_statement_t const *const decls = &stmt->declaration;
4562 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4567 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4576 * Check declarations of current_function for unused entities.
4578 static void check_declarations(void)
4580 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4581 const scope_t *scope = ¤t_function->parameters;
4582 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4584 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4585 walk_statements(current_function->body, check_unused_variables, NULL);
4589 static int determine_truth(expression_t const* const cond)
4592 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4593 fold_constant_to_bool(cond) ? 1 :
4597 static void check_reachable(statement_t *);
4598 static bool reaches_end;
4600 static bool expression_returns(expression_t const *const expr)
4602 switch (expr->kind) {
4604 expression_t const *const func = expr->call.function;
4605 type_t const *const type = skip_typeref(func->base.type);
4606 if (type->kind == TYPE_POINTER) {
4607 type_t const *const points_to
4608 = skip_typeref(type->pointer.points_to);
4609 if (points_to->kind == TYPE_FUNCTION
4610 && points_to->function.modifiers & DM_NORETURN)
4614 if (!expression_returns(func))
4617 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4618 if (!expression_returns(arg->expression))
4625 case EXPR_REFERENCE:
4626 case EXPR_ENUM_CONSTANT:
4627 case EXPR_LITERAL_CASES:
4628 case EXPR_LITERAL_CHARACTER:
4629 case EXPR_STRING_LITERAL:
4630 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4631 case EXPR_LABEL_ADDRESS:
4632 case EXPR_CLASSIFY_TYPE:
4633 case EXPR_SIZEOF: // TODO handle obscure VLA case
4636 case EXPR_BUILTIN_CONSTANT_P:
4637 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4642 case EXPR_STATEMENT: {
4643 bool old_reaches_end = reaches_end;
4644 reaches_end = false;
4645 check_reachable(expr->statement.statement);
4646 bool returns = reaches_end;
4647 reaches_end = old_reaches_end;
4651 case EXPR_CONDITIONAL:
4652 // TODO handle constant expression
4654 if (!expression_returns(expr->conditional.condition))
4657 if (expr->conditional.true_expression != NULL
4658 && expression_returns(expr->conditional.true_expression))
4661 return expression_returns(expr->conditional.false_expression);
4664 return expression_returns(expr->select.compound);
4666 case EXPR_ARRAY_ACCESS:
4668 expression_returns(expr->array_access.array_ref) &&
4669 expression_returns(expr->array_access.index);
4672 return expression_returns(expr->va_starte.ap);
4675 return expression_returns(expr->va_arge.ap);
4678 return expression_returns(expr->va_copye.src);
4680 case EXPR_UNARY_CASES_MANDATORY:
4681 return expression_returns(expr->unary.value);
4683 case EXPR_UNARY_THROW:
4686 case EXPR_BINARY_CASES:
4687 // TODO handle constant lhs of && and ||
4689 expression_returns(expr->binary.left) &&
4690 expression_returns(expr->binary.right);
4693 panic("unhandled expression");
4696 static bool initializer_returns(initializer_t const *const init)
4698 switch (init->kind) {
4699 case INITIALIZER_VALUE:
4700 return expression_returns(init->value.value);
4702 case INITIALIZER_LIST: {
4703 initializer_t * const* i = init->list.initializers;
4704 initializer_t * const* const end = i + init->list.len;
4705 bool returns = true;
4706 for (; i != end; ++i) {
4707 if (!initializer_returns(*i))
4713 case INITIALIZER_STRING:
4714 case INITIALIZER_DESIGNATOR: // designators have no payload
4717 panic("unhandled initializer");
4720 static bool noreturn_candidate;
4722 static void check_reachable(statement_t *const stmt)
4724 if (stmt->base.reachable)
4726 if (stmt->kind != STATEMENT_DO_WHILE)
4727 stmt->base.reachable = true;
4729 statement_t *last = stmt;
4731 switch (stmt->kind) {
4732 case STATEMENT_ERROR:
4733 case STATEMENT_EMPTY:
4735 next = stmt->base.next;
4738 case STATEMENT_DECLARATION: {
4739 declaration_statement_t const *const decl = &stmt->declaration;
4740 entity_t const * ent = decl->declarations_begin;
4741 entity_t const *const last_decl = decl->declarations_end;
4743 for (;; ent = ent->base.next) {
4744 if (ent->kind == ENTITY_VARIABLE &&
4745 ent->variable.initializer != NULL &&
4746 !initializer_returns(ent->variable.initializer)) {
4749 if (ent == last_decl)
4753 next = stmt->base.next;
4757 case STATEMENT_COMPOUND:
4758 next = stmt->compound.statements;
4760 next = stmt->base.next;
4763 case STATEMENT_RETURN: {
4764 expression_t const *const val = stmt->returns.value;
4765 if (val == NULL || expression_returns(val))
4766 noreturn_candidate = false;
4770 case STATEMENT_IF: {
4771 if_statement_t const *const ifs = &stmt->ifs;
4772 expression_t const *const cond = ifs->condition;
4774 if (!expression_returns(cond))
4777 int const val = determine_truth(cond);
4780 check_reachable(ifs->true_statement);
4785 if (ifs->false_statement != NULL) {
4786 check_reachable(ifs->false_statement);
4790 next = stmt->base.next;
4794 case STATEMENT_SWITCH: {
4795 switch_statement_t const *const switchs = &stmt->switchs;
4796 expression_t const *const expr = switchs->expression;
4798 if (!expression_returns(expr))
4801 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4802 ir_tarval *const val = fold_constant_to_tarval(expr);
4803 case_label_statement_t * defaults = NULL;
4804 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4805 if (i->expression == NULL) {
4810 if (i->first_case == val || i->last_case == val ||
4811 ((tarval_cmp(i->first_case, val) & ir_relation_less_equal)
4812 && (tarval_cmp(val, i->last_case) & ir_relation_less_equal))) {
4813 check_reachable((statement_t*)i);
4818 if (defaults != NULL) {
4819 check_reachable((statement_t*)defaults);
4823 bool has_default = false;
4824 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4825 if (i->expression == NULL)
4828 check_reachable((statement_t*)i);
4835 next = stmt->base.next;
4839 case STATEMENT_EXPRESSION: {
4840 /* Check for noreturn function call */
4841 expression_t const *const expr = stmt->expression.expression;
4842 if (!expression_returns(expr))
4845 next = stmt->base.next;
4849 case STATEMENT_CONTINUE:
4850 for (statement_t *parent = stmt;;) {
4851 parent = parent->base.parent;
4852 if (parent == NULL) /* continue not within loop */
4856 switch (parent->kind) {
4857 case STATEMENT_DO_WHILE: goto continue_do_while;
4858 case STATEMENT_FOR: goto continue_for;
4864 case STATEMENT_BREAK:
4865 for (statement_t *parent = stmt;;) {
4866 parent = parent->base.parent;
4867 if (parent == NULL) /* break not within loop/switch */
4870 switch (parent->kind) {
4871 case STATEMENT_SWITCH:
4872 case STATEMENT_DO_WHILE:
4875 next = parent->base.next;
4876 goto found_break_parent;
4884 case STATEMENT_COMPUTED_GOTO: {
4885 if (!expression_returns(stmt->computed_goto.expression))
4888 statement_t *parent = stmt->base.parent;
4889 if (parent == NULL) /* top level goto */
4895 case STATEMENT_GOTO:
4896 next = stmt->gotos.label->statement;
4897 if (next == NULL) /* missing label */
4901 case STATEMENT_LABEL:
4902 next = stmt->label.statement;
4905 case STATEMENT_CASE_LABEL:
4906 next = stmt->case_label.statement;
4909 case STATEMENT_DO_WHILE:
4910 next = stmt->do_while.body;
4913 case STATEMENT_FOR: {
4914 for_statement_t *const fors = &stmt->fors;
4916 if (fors->condition_reachable)
4918 fors->condition_reachable = true;
4920 expression_t const *const cond = fors->condition;
4925 } else if (expression_returns(cond)) {
4926 val = determine_truth(cond);
4932 check_reachable(fors->body);
4937 next = stmt->base.next;
4941 case STATEMENT_MS_TRY: {
4942 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4943 check_reachable(ms_try->try_statement);
4944 next = ms_try->final_statement;
4948 case STATEMENT_LEAVE: {
4949 statement_t *parent = stmt;
4951 parent = parent->base.parent;
4952 if (parent == NULL) /* __leave not within __try */
4955 if (parent->kind == STATEMENT_MS_TRY) {
4957 next = parent->ms_try.final_statement;
4965 panic("invalid statement kind");
4968 while (next == NULL) {
4969 next = last->base.parent;
4971 noreturn_candidate = false;
4973 type_t *const type = skip_typeref(current_function->base.type);
4974 assert(is_type_function(type));
4975 type_t *const ret = skip_typeref(type->function.return_type);
4976 if (!is_type_void(ret) &&
4977 is_type_valid(ret) &&
4978 !is_main(current_entity)) {
4979 position_t const *const pos = &stmt->base.pos;
4980 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4985 switch (next->kind) {
4986 case STATEMENT_ERROR:
4987 case STATEMENT_EMPTY:
4988 case STATEMENT_DECLARATION:
4989 case STATEMENT_EXPRESSION:
4991 case STATEMENT_RETURN:
4992 case STATEMENT_CONTINUE:
4993 case STATEMENT_BREAK:
4994 case STATEMENT_COMPUTED_GOTO:
4995 case STATEMENT_GOTO:
4996 case STATEMENT_LEAVE:
4997 panic("invalid control flow in function");
4999 case STATEMENT_COMPOUND:
5000 if (next->compound.stmt_expr) {
5006 case STATEMENT_SWITCH:
5007 case STATEMENT_LABEL:
5008 case STATEMENT_CASE_LABEL:
5010 next = next->base.next;
5013 case STATEMENT_DO_WHILE: {
5015 if (next->base.reachable)
5017 next->base.reachable = true;
5019 do_while_statement_t const *const dw = &next->do_while;
5020 expression_t const *const cond = dw->condition;
5022 if (!expression_returns(cond))
5025 int const val = determine_truth(cond);
5028 check_reachable(dw->body);
5034 next = next->base.next;
5038 case STATEMENT_FOR: {
5040 for_statement_t *const fors = &next->fors;
5042 fors->step_reachable = true;
5044 if (fors->condition_reachable)
5046 fors->condition_reachable = true;
5048 expression_t const *const cond = fors->condition;
5053 } else if (expression_returns(cond)) {
5054 val = determine_truth(cond);
5060 check_reachable(fors->body);
5066 next = next->base.next;
5070 case STATEMENT_MS_TRY:
5072 next = next->ms_try.final_statement;
5077 check_reachable(next);
5080 static void check_unreachable(statement_t* const stmt, void *const env)
5084 switch (stmt->kind) {
5085 case STATEMENT_DO_WHILE:
5086 if (!stmt->base.reachable) {
5087 expression_t const *const cond = stmt->do_while.condition;
5088 if (determine_truth(cond) >= 0) {
5089 position_t const *const pos = &cond->base.pos;
5090 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5095 case STATEMENT_FOR: {
5096 for_statement_t const* const fors = &stmt->fors;
5098 // if init and step are unreachable, cond is unreachable, too
5099 if (!stmt->base.reachable && !fors->step_reachable) {
5100 goto warn_unreachable;
5102 if (!stmt->base.reachable && fors->initialisation != NULL) {
5103 position_t const *const pos = &fors->initialisation->base.pos;
5104 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5107 if (!fors->condition_reachable && fors->condition != NULL) {
5108 position_t const *const pos = &fors->condition->base.pos;
5109 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5112 if (!fors->step_reachable && fors->step != NULL) {
5113 position_t const *const pos = &fors->step->base.pos;
5114 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5120 case STATEMENT_COMPOUND:
5121 if (stmt->compound.statements != NULL)
5123 goto warn_unreachable;
5125 case STATEMENT_DECLARATION: {
5126 /* Only warn if there is at least one declarator with an initializer.
5127 * This typically occurs in switch statements. */
5128 declaration_statement_t const *const decl = &stmt->declaration;
5129 entity_t const * ent = decl->declarations_begin;
5130 entity_t const *const last = decl->declarations_end;
5132 for (;; ent = ent->base.next) {
5133 if (ent->kind == ENTITY_VARIABLE &&
5134 ent->variable.initializer != NULL) {
5135 goto warn_unreachable;
5145 if (!stmt->base.reachable) {
5146 position_t const *const pos = &stmt->base.pos;
5147 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5153 static bool is_main(entity_t *entity)
5155 static symbol_t *sym_main = NULL;
5156 if (sym_main == NULL) {
5157 sym_main = symbol_table_insert("main");
5160 if (entity->base.symbol != sym_main)
5162 /* must be in outermost scope */
5163 if (entity->base.parent_scope != file_scope)
5169 static void prepare_main_collect2(entity_t*);
5171 static void parse_external_declaration(void)
5173 /* function-definitions and declarations both start with declaration
5175 add_anchor_token(';');
5176 declaration_specifiers_t specifiers;
5177 parse_declaration_specifiers(&specifiers);
5178 rem_anchor_token(';');
5180 /* must be a declaration */
5181 if (token.kind == ';') {
5182 parse_anonymous_declaration_rest(&specifiers);
5186 add_anchor_token(',');
5187 add_anchor_token('=');
5188 add_anchor_token(';');
5189 add_anchor_token('{');
5191 /* declarator is common to both function-definitions and declarations */
5192 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5194 rem_anchor_token('{');
5195 rem_anchor_token(';');
5196 rem_anchor_token('=');
5197 rem_anchor_token(',');
5199 /* must be a declaration */
5200 switch (token.kind) {
5204 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5209 /* must be a function definition */
5210 parse_kr_declaration_list(ndeclaration);
5212 if (token.kind != '{') {
5213 parse_error_expected("while parsing function definition", '{', NULL);
5214 eat_until_matching_token(';');
5218 assert(is_declaration(ndeclaration));
5219 type_t *const orig_type = ndeclaration->declaration.type;
5220 type_t * type = skip_typeref(orig_type);
5222 if (!is_type_function(type)) {
5223 if (is_type_valid(type)) {
5224 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5230 position_t const *const pos = &ndeclaration->base.pos;
5231 if (is_typeref(orig_type)) {
5233 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5236 if (is_type_compound(skip_typeref(type->function.return_type))) {
5237 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5239 if (type->function.unspecified_parameters) {
5240 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5242 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5245 /* §6.7.5.3:14 a function definition with () means no
5246 * parameters (and not unspecified parameters) */
5247 if (type->function.unspecified_parameters &&
5248 type->function.parameters == NULL) {
5249 type_t *copy = duplicate_type(type);
5250 copy->function.unspecified_parameters = false;
5251 type = identify_new_type(copy);
5253 ndeclaration->declaration.type = type;
5256 entity_t *const entity = record_entity(ndeclaration, true);
5257 assert(entity->kind == ENTITY_FUNCTION);
5258 assert(ndeclaration->kind == ENTITY_FUNCTION);
5260 function_t *const function = &entity->function;
5261 if (ndeclaration != entity) {
5262 function->parameters = ndeclaration->function.parameters;
5265 PUSH_SCOPE(&function->parameters);
5267 entity_t *parameter = function->parameters.entities;
5268 for (; parameter != NULL; parameter = parameter->base.next) {
5269 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5270 parameter->base.parent_scope = current_scope;
5272 assert(parameter->base.parent_scope == NULL
5273 || parameter->base.parent_scope == current_scope);
5274 parameter->base.parent_scope = current_scope;
5275 if (parameter->base.symbol == NULL) {
5276 errorf(¶meter->base.pos, "parameter name omitted");
5279 environment_push(parameter);
5282 if (function->body != NULL) {
5283 parser_error_multiple_definition(entity, HERE);
5286 /* parse function body */
5287 int label_stack_top = label_top();
5288 function_t *old_current_function = current_function;
5289 current_function = function;
5290 PUSH_CURRENT_ENTITY(entity);
5294 goto_anchor = &goto_first;
5296 label_anchor = &label_first;
5298 statement_t *const body = parse_compound_statement(false);
5299 function->body = body;
5302 check_declarations();
5303 if (is_warn_on(WARN_RETURN_TYPE) ||
5304 is_warn_on(WARN_UNREACHABLE_CODE) ||
5305 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5306 noreturn_candidate = true;
5307 check_reachable(body);
5308 if (is_warn_on(WARN_UNREACHABLE_CODE))
5309 walk_statements(body, check_unreachable, NULL);
5310 if (noreturn_candidate &&
5311 !(function->base.modifiers & DM_NORETURN)) {
5312 position_t const *const pos = &body->base.pos;
5313 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5317 if (is_main(entity)) {
5318 /* Force main to C linkage. */
5319 type_t *const type = entity->declaration.type;
5320 assert(is_type_function(type));
5321 if (type->function.linkage != LINKAGE_C) {
5322 type_t *new_type = duplicate_type(type);
5323 new_type->function.linkage = LINKAGE_C;
5324 entity->declaration.type = identify_new_type(new_type);
5327 if (enable_main_collect2_hack)
5328 prepare_main_collect2(entity);
5331 POP_CURRENT_ENTITY();
5333 assert(current_function == function);
5334 current_function = old_current_function;
5335 label_pop_to(label_stack_top);
5341 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5343 entity_t *iter = compound->members.entities;
5344 for (; iter != NULL; iter = iter->base.next) {
5345 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5348 if (iter->base.symbol == symbol) {
5350 } else if (iter->base.symbol == NULL) {
5351 /* search in anonymous structs and unions */
5352 type_t *type = skip_typeref(iter->declaration.type);
5353 if (is_type_compound(type)) {
5354 if (find_compound_entry(type->compound.compound, symbol)
5365 static void check_deprecated(const position_t *pos, const entity_t *entity)
5367 if (!is_declaration(entity))
5369 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5372 position_t const *const epos = &entity->base.pos;
5373 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5375 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5377 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P)", entity, epos);
5382 static expression_t *create_select(const position_t *pos, expression_t *addr,
5383 type_qualifiers_t qualifiers,
5386 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5388 check_deprecated(pos, entry);
5390 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5391 select->select.compound = addr;
5392 select->select.compound_entry = entry;
5394 type_t *entry_type = entry->declaration.type;
5395 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5397 /* bitfields need special treatment */
5398 if (entry->compound_member.bitfield) {
5399 unsigned bit_size = entry->compound_member.bit_size;
5400 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5401 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5402 res_type = type_int;
5406 /* we always do the auto-type conversions; the & and sizeof parser contains
5407 * code to revert this! */
5408 select->base.type = automatic_type_conversion(res_type);
5415 * Find entry with symbol in compound. Search anonymous structs and unions and
5416 * creates implicit select expressions for them.
5417 * Returns the adress for the innermost compound.
5419 static expression_t *find_create_select(const position_t *pos,
5421 type_qualifiers_t qualifiers,
5422 compound_t *compound, symbol_t *symbol)
5424 entity_t *iter = compound->members.entities;
5425 for (; iter != NULL; iter = iter->base.next) {
5426 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5429 symbol_t *iter_symbol = iter->base.symbol;
5430 if (iter_symbol == NULL) {
5431 type_t *type = iter->declaration.type;
5432 if (!is_type_compound(type))
5435 compound_t *sub_compound = type->compound.compound;
5437 if (find_compound_entry(sub_compound, symbol) == NULL)
5440 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5441 sub_addr->base.pos = *pos;
5442 sub_addr->base.implicit = true;
5443 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5447 if (iter_symbol == symbol) {
5448 return create_select(pos, addr, qualifiers, iter);
5455 static void parse_bitfield_member(entity_t *entity)
5459 expression_t *size = parse_constant_expression();
5462 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5463 type_t *type = entity->declaration.type;
5464 if (!is_type_integer(skip_typeref(type))) {
5465 errorf(HERE, "bitfield base type '%T' is not an integer type",
5469 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5470 /* error already reported by parse_constant_expression */
5471 size_long = get_type_size(type) * 8;
5473 size_long = fold_constant_to_int(size);
5475 const symbol_t *symbol = entity->base.symbol;
5476 const symbol_t *user_symbol
5477 = symbol == NULL ? sym_anonymous : symbol;
5478 unsigned bit_size = get_type_size(type) * 8;
5479 if (size_long < 0) {
5480 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5481 } else if (size_long == 0 && symbol != NULL) {
5482 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5483 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5484 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5487 /* hope that people don't invent crazy types with more bits
5488 * than our struct can hold */
5490 (1 << sizeof(entity->compound_member.bit_size)*8));
5494 entity->compound_member.bitfield = true;
5495 entity->compound_member.bit_size = (unsigned char)size_long;
5498 static void parse_compound_declarators(compound_t *compound,
5499 const declaration_specifiers_t *specifiers)
5501 add_anchor_token(';');
5502 add_anchor_token(',');
5506 if (token.kind == ':') {
5507 /* anonymous bitfield */
5508 type_t *type = specifiers->type;
5509 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5510 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5511 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5512 entity->declaration.type = type;
5514 parse_bitfield_member(entity);
5516 attribute_t *attributes = parse_attributes(NULL);
5517 attribute_t **anchor = &attributes;
5518 while (*anchor != NULL)
5519 anchor = &(*anchor)->next;
5520 *anchor = specifiers->attributes;
5521 if (attributes != NULL) {
5522 handle_entity_attributes(attributes, entity);
5524 entity->declaration.attributes = attributes;
5526 append_entity(&compound->members, entity);
5528 entity = parse_declarator(specifiers,
5529 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5530 position_t const *const pos = &entity->base.pos;
5531 if (entity->kind == ENTITY_TYPEDEF) {
5532 errorf(pos, "typedef not allowed as compound member");
5534 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5536 /* make sure we don't define a symbol multiple times */
5537 symbol_t *symbol = entity->base.symbol;
5538 if (symbol != NULL) {
5539 entity_t *prev = find_compound_entry(compound, symbol);
5541 position_t const *const ppos = &prev->base.pos;
5542 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5546 if (token.kind == ':') {
5547 parse_bitfield_member(entity);
5549 attribute_t *attributes = parse_attributes(NULL);
5550 handle_entity_attributes(attributes, entity);
5552 type_t *orig_type = entity->declaration.type;
5553 type_t *type = skip_typeref(orig_type);
5554 if (is_type_function(type)) {
5555 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5556 } else if (is_type_incomplete(type)) {
5557 /* §6.7.2.1:16 flexible array member */
5558 if (!is_type_array(type) ||
5559 token.kind != ';' ||
5560 look_ahead(1)->kind != '}') {
5561 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5562 } else if (compound->members.entities == NULL) {
5563 errorf(pos, "flexible array member in otherwise empty struct");
5568 append_entity(&compound->members, entity);
5571 } while (accept(','));
5572 rem_anchor_token(',');
5573 rem_anchor_token(';');
5576 anonymous_entity = NULL;
5579 static void parse_compound_type_entries(compound_t *compound)
5582 add_anchor_token('}');
5585 switch (token.kind) {
5587 case T___extension__:
5588 case T_IDENTIFIER: {
5590 declaration_specifiers_t specifiers;
5591 parse_declaration_specifiers(&specifiers);
5592 parse_compound_declarators(compound, &specifiers);
5598 rem_anchor_token('}');
5601 compound->complete = true;
5607 static type_t *parse_typename(void)
5609 declaration_specifiers_t specifiers;
5610 parse_declaration_specifiers(&specifiers);
5611 if (specifiers.storage_class != STORAGE_CLASS_NONE
5612 || specifiers.thread_local) {
5613 /* TODO: improve error message, user does probably not know what a
5614 * storage class is...
5616 errorf(&specifiers.pos, "typename must not have a storage class");
5619 type_t *result = parse_abstract_declarator(specifiers.type);
5627 typedef expression_t* (*parse_expression_function)(void);
5628 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5630 typedef struct expression_parser_function_t expression_parser_function_t;
5631 struct expression_parser_function_t {
5632 parse_expression_function parser;
5633 precedence_t infix_precedence;
5634 parse_expression_infix_function infix_parser;
5637 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5639 static type_t *get_string_type(string_encoding_t const enc)
5641 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5643 case STRING_ENCODING_CHAR:
5644 case STRING_ENCODING_UTF8: return warn ? type_const_char_ptr : type_char_ptr;
5645 case STRING_ENCODING_CHAR16: return warn ? type_char16_t_const_ptr : type_char16_t_ptr;
5646 case STRING_ENCODING_CHAR32: return warn ? type_char32_t_const_ptr : type_char32_t_ptr;
5647 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5649 panic("invalid string encoding");
5653 * Parse a string constant.
5655 static expression_t *parse_string_literal(void)
5657 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5658 expr->string_literal.value = concat_string_literals();
5659 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5664 * Parse a boolean constant.
5666 static expression_t *parse_boolean_literal(bool value)
5668 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5669 literal->base.type = type_bool;
5670 literal->literal.value.begin = value ? "true" : "false";
5671 literal->literal.value.size = value ? 4 : 5;
5673 eat(value ? T_true : T_false);
5677 static void warn_traditional_suffix(char const *const suffix)
5679 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5682 static void check_integer_suffix(expression_t *const expr, char const *const suffix)
5684 unsigned spec = SPECIFIER_NONE;
5685 char const *c = suffix;
5686 while (*c != '\0') {
5691 add = SPECIFIER_LONG;
5693 add |= SPECIFIER_LONG_LONG;
5699 add = SPECIFIER_UNSIGNED;
5707 add = SPECIFIER_COMPLEX;
5721 switch (spec & ~SPECIFIER_COMPLEX) {
5722 case SPECIFIER_NONE: type = type_int; break;
5723 case SPECIFIER_LONG: type = type_long; break;
5724 case SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long; break;
5725 case SPECIFIER_UNSIGNED: type = type_unsigned_int; break;
5726 case SPECIFIER_UNSIGNED | SPECIFIER_LONG: type = type_unsigned_long; break;
5727 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5728 default: panic("inconsistent suffix");
5730 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG) {
5731 warn_traditional_suffix(suffix);
5733 if (spec & SPECIFIER_COMPLEX) {
5734 assert(type->kind == TYPE_ATOMIC);
5735 type = make_complex_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
5737 expr->base.type = type;
5738 /* Integer type depends on the size of the number and the size
5739 * representable by the types. The backend/codegeneration has to
5740 * determine that. */
5741 determine_literal_type(&expr->literal);
5744 errorf(HERE, "invalid suffix '%s' on integer constant", suffix);
5748 static void check_floatingpoint_suffix(expression_t *const expr, char const *const suffix)
5751 char const *c = suffix;
5752 bool is_complex = false;
5756 case 'f': type = type_float; ++c; break;
5758 case 'l': type = type_long_double; ++c; break;
5768 default: type = type_double; break;
5773 assert(type->kind == TYPE_ATOMIC);
5774 type = make_complex_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
5777 expr->base.type = type;
5778 if (suffix[0] != '\0') {
5779 warn_traditional_suffix(suffix);
5782 errorf(HERE, "invalid suffix '%s' on floatingpoint constant", suffix);
5786 static expression_t *parse_number_literal(void)
5788 string_t const *const str = &token.literal.string;
5789 char const * i = str->begin;
5790 unsigned digits = 0;
5791 bool is_float = false;
5793 /* Parse base prefix. */
5797 case 'B': case 'b': base = 2; ++i; break;
5798 case 'X': case 'x': base = 16; ++i; break;
5799 default: base = 8; digits |= 1U << 0; break;
5805 /* Parse mantissa. */
5811 errorf(HERE, "multiple decimal points in %K", &token);
5820 case '0': digit = 0; break;
5821 case '1': digit = 1; break;
5822 case '2': digit = 2; break;
5823 case '3': digit = 3; break;
5824 case '4': digit = 4; break;
5825 case '5': digit = 5; break;
5826 case '6': digit = 6; break;
5827 case '7': digit = 7; break;
5828 case '8': digit = 8; break;
5829 case '9': digit = 9; break;
5830 case 'A': case 'a': digit = 10; break;
5831 case 'B': case 'b': digit = 11; break;
5832 case 'C': case 'c': digit = 12; break;
5833 case 'D': case 'd': digit = 13; break;
5834 case 'E': case 'e': digit = 14; break;
5835 case 'F': case 'f': digit = 15; break;
5837 default: goto done_mantissa;
5840 if (digit >= 10 && base != 16)
5843 digits |= 1U << digit;
5847 /* Parse exponent. */
5851 errorf(HERE, "binary floating %K not allowed", &token);
5856 if (*i == 'E' || *i == 'e') {
5858 goto parse_exponent;
5863 if (*i == 'P' || *i == 'p') {
5868 if (*i == '-' || *i == '+')
5874 } while (isdigit(*i));
5876 errorf(HERE, "exponent of %K has no digits", &token);
5878 } else if (is_float) {
5879 errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5885 panic("invalid base");
5889 expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5890 expr->literal.value = *str;
5894 errorf(HERE, "%K has no digits", &token);
5895 } else if (digits & ~((1U << base) - 1)) {
5896 errorf(HERE, "invalid digit in %K", &token);
5898 expr->literal.suffix = i;
5900 check_floatingpoint_suffix(expr, i);
5902 check_integer_suffix(expr, i);
5912 * Parse a character constant.
5914 static expression_t *parse_character_constant(void)
5916 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5917 literal->string_literal.value = token.literal.string;
5919 size_t const size = get_string_len(&token.literal.string);
5920 switch (token.literal.string.encoding) {
5921 case STRING_ENCODING_CHAR:
5922 case STRING_ENCODING_UTF8:
5923 literal->base.type = c_mode & _CXX ? type_char : type_int;
5925 if (!GNU_MODE && !(c_mode & _C99)) {
5926 errorf(HERE, "more than 1 character in character constant");
5928 literal->base.type = type_int;
5929 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5934 case STRING_ENCODING_CHAR16: literal->base.type = type_char16_t; goto warn_multi;
5935 case STRING_ENCODING_CHAR32: literal->base.type = type_char32_t; goto warn_multi;
5936 case STRING_ENCODING_WIDE: literal->base.type = type_wchar_t; goto warn_multi;
5939 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5944 eat(T_CHARACTER_CONSTANT);
5948 static entity_t *create_implicit_function(symbol_t *symbol, position_t const *const pos)
5950 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5951 ntype->function.return_type = type_int;
5952 ntype->function.unspecified_parameters = true;
5953 ntype->function.linkage = LINKAGE_C;
5954 type_t *type = identify_new_type(ntype);
5956 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5957 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5958 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5959 entity->declaration.type = type;
5960 entity->declaration.implicit = true;
5962 if (current_scope != NULL)
5963 record_entity(entity, false);
5969 * Performs automatic type cast as described in §6.3.2.1.
5971 * @param orig_type the original type
5973 static type_t *automatic_type_conversion(type_t *orig_type)
5975 type_t *type = skip_typeref(orig_type);
5976 if (is_type_array(type)) {
5977 array_type_t *array_type = &type->array;
5978 type_t *element_type = array_type->element_type;
5979 unsigned qualifiers = array_type->base.qualifiers;
5981 return make_pointer_type(element_type, qualifiers);
5984 if (is_type_function(type)) {
5985 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5992 * reverts the automatic casts of array to pointer types and function
5993 * to function-pointer types as defined §6.3.2.1
5995 type_t *revert_automatic_type_conversion(const expression_t *expression)
5997 switch (expression->kind) {
5998 case EXPR_REFERENCE: {
5999 entity_t *entity = expression->reference.entity;
6000 if (is_declaration(entity)) {
6001 return entity->declaration.type;
6002 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6003 return entity->enum_value.enum_type;
6005 panic("no declaration or enum in reference");
6010 entity_t *entity = expression->select.compound_entry;
6011 assert(is_declaration(entity));
6012 type_t *type = entity->declaration.type;
6013 return get_qualified_type(type, expression->base.type->base.qualifiers);
6016 case EXPR_UNARY_DEREFERENCE: {
6017 const expression_t *const value = expression->unary.value;
6018 type_t *const type = skip_typeref(value->base.type);
6019 if (!is_type_pointer(type))
6020 return type_error_type;
6021 return type->pointer.points_to;
6024 case EXPR_ARRAY_ACCESS: {
6025 const expression_t *array_ref = expression->array_access.array_ref;
6026 type_t *type_left = skip_typeref(array_ref->base.type);
6027 if (!is_type_pointer(type_left))
6028 return type_error_type;
6029 return type_left->pointer.points_to;
6032 case EXPR_STRING_LITERAL: {
6033 size_t const size = get_string_len(&expression->string_literal.value) + 1;
6034 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
6035 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
6038 case EXPR_COMPOUND_LITERAL:
6039 return expression->compound_literal.type;
6044 return expression->base.type;
6048 * Find an entity matching a symbol in a scope.
6049 * Uses current scope if scope is NULL
6051 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6052 namespace_tag_t namespc)
6054 if (scope == NULL) {
6055 return get_entity(symbol, namespc);
6058 /* we should optimize here, if scope grows above a certain size we should
6059 construct a hashmap here... */
6060 entity_t *entity = scope->entities;
6061 for ( ; entity != NULL; entity = entity->base.next) {
6062 if (entity->base.symbol == symbol
6063 && (namespace_tag_t)entity->base.namespc == namespc)
6070 static entity_t *parse_qualified_identifier(void)
6072 /* namespace containing the symbol */
6075 const scope_t *lookup_scope = NULL;
6077 if (accept(T_COLONCOLON))
6078 lookup_scope = &unit->scope;
6082 symbol = expect_identifier("while parsing identifier", &pos);
6084 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6087 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6089 if (!accept(T_COLONCOLON))
6092 switch (entity->kind) {
6093 case ENTITY_NAMESPACE:
6094 lookup_scope = &entity->namespacee.members;
6099 lookup_scope = &entity->compound.members;
6102 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6103 symbol, get_entity_kind_name(entity->kind));
6105 /* skip further qualifications */
6106 while (accept(T_IDENTIFIER) && accept(T_COLONCOLON)) {}
6108 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6112 if (entity == NULL) {
6113 if (!strict_mode && token.kind == '(') {
6114 /* an implicitly declared function */
6115 entity = create_implicit_function(symbol, &pos);
6116 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6118 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6119 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6126 static expression_t *parse_reference(void)
6128 position_t const pos = *HERE;
6129 entity_t *const entity = parse_qualified_identifier();
6132 if (is_declaration(entity)) {
6133 orig_type = entity->declaration.type;
6134 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6135 orig_type = entity->enum_value.enum_type;
6137 panic("expected declaration or enum value in reference");
6140 /* we always do the auto-type conversions; the & and sizeof parser contains
6141 * code to revert this! */
6142 type_t *type = automatic_type_conversion(orig_type);
6144 expression_kind_t kind = EXPR_REFERENCE;
6145 if (entity->kind == ENTITY_ENUM_VALUE)
6146 kind = EXPR_ENUM_CONSTANT;
6148 expression_t *expression = allocate_expression_zero(kind);
6149 expression->base.pos = pos;
6150 expression->base.type = type;
6151 expression->reference.entity = entity;
6153 /* this declaration is used */
6154 if (is_declaration(entity)) {
6155 entity->declaration.used = true;
6158 if (entity->base.parent_scope != file_scope
6159 && (current_function != NULL
6160 && entity->base.parent_scope->depth < current_function->parameters.depth)
6161 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6162 /* access of a variable from an outer function */
6163 entity->variable.address_taken = true;
6164 current_function->need_closure = true;
6167 check_deprecated(&pos, entity);
6172 static bool semantic_cast(expression_t *cast)
6174 expression_t *expression = cast->unary.value;
6175 type_t *orig_dest_type = cast->base.type;
6176 type_t *orig_type_right = expression->base.type;
6177 type_t const *dst_type = skip_typeref(orig_dest_type);
6178 type_t const *src_type = skip_typeref(orig_type_right);
6179 position_t const *pos = &cast->base.pos;
6181 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation
6182 * than for utility. */
6183 if (is_type_void(dst_type))
6186 /* only integer and pointer can be casted to pointer */
6187 if (is_type_pointer(dst_type) &&
6188 !is_type_pointer(src_type) &&
6189 !is_type_integer(src_type) &&
6190 is_type_valid(src_type)) {
6191 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6195 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6196 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6200 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6201 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6205 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6206 type_t *src = skip_typeref(src_type->pointer.points_to);
6207 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6208 unsigned missing_qualifiers =
6209 src->base.qualifiers & ~dst->base.qualifiers;
6210 if (missing_qualifiers != 0) {
6211 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6217 static void semantic_complex_extract(unary_expression_t *extract)
6219 type_t *orig_value_type = extract->value->base.type;
6220 type_t *value_type = skip_typeref(orig_value_type);
6221 if (!is_type_valid(value_type)) {
6222 extract->base.type = type_error_type;
6226 type_t *type = value_type;
6227 if (!is_type_complex(type)) {
6228 if (!is_type_arithmetic(type)) {
6229 errorf(&extract->base.pos,
6230 "%s requires an argument with complex or arithmetic type, got '%T'",
6231 extract->base.kind == EXPR_UNARY_IMAG ? "__imag__" : "__real__",
6233 extract->base.type = type_error_type;
6236 atomic_type_kind_t const akind = get_arithmetic_akind(type);
6237 type = make_complex_type(akind, TYPE_QUALIFIER_NONE);
6238 extract->value = create_implicit_cast(extract->value, type);
6240 assert(type->kind == TYPE_COMPLEX);
6241 type = make_atomic_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
6242 extract->base.type = type;
6245 static expression_t *parse_compound_literal(position_t const *const pos,
6248 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6249 expression->base.pos = *pos;
6250 bool global_scope = current_scope == file_scope;
6252 parse_initializer_env_t env;
6255 env.must_be_constant = global_scope;
6256 initializer_t *initializer = parse_initializer(&env);
6259 expression->base.type = automatic_type_conversion(type);
6260 expression->compound_literal.initializer = initializer;
6261 expression->compound_literal.type = type;
6262 expression->compound_literal.global_scope = global_scope;
6268 * Parse a cast expression.
6270 static expression_t *parse_cast(void)
6272 position_t const pos = *HERE;
6275 add_anchor_token(')');
6277 type_t *type = parse_typename();
6279 rem_anchor_token(')');
6282 if (token.kind == '{') {
6283 return parse_compound_literal(&pos, type);
6286 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6287 cast->base.pos = pos;
6289 expression_t *value = parse_subexpression(PREC_CAST);
6290 cast->base.type = type;
6291 cast->unary.value = value;
6293 if (!semantic_cast(cast)) {
6294 cast->base.type = type_error_type;
6300 static expression_t *parse_complex_extract_expression(expression_kind_t const kind)
6302 expression_t *extract = allocate_expression_zero(kind);
6305 extract->unary.value = parse_subexpression(PREC_CAST);
6306 semantic_complex_extract(&extract->unary);
6311 * Parse a statement expression.
6313 static expression_t *parse_statement_expression(void)
6315 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6318 add_anchor_token(')');
6320 statement_t *statement = parse_compound_statement(true);
6321 statement->compound.stmt_expr = true;
6322 expression->statement.statement = statement;
6324 /* find last statement and use its type */
6325 type_t *type = type_void;
6326 const statement_t *stmt = statement->compound.statements;
6328 while (stmt->base.next != NULL)
6329 stmt = stmt->base.next;
6331 if (stmt->kind == STATEMENT_EXPRESSION) {
6332 type = stmt->expression.expression->base.type;
6335 position_t const *const pos = &expression->base.pos;
6336 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6338 expression->base.type = type;
6340 rem_anchor_token(')');
6346 * Parse a parenthesized expression.
6348 static expression_t *parse_parenthesized_expression(void)
6350 token_t const* const la1 = look_ahead(1);
6351 switch (la1->kind) {
6353 /* gcc extension: a statement expression */
6354 return parse_statement_expression();
6357 if (is_typedef_symbol(la1->base.symbol)) {
6359 return parse_cast();
6364 add_anchor_token(')');
6365 expression_t *result = parse_expression();
6366 result->base.parenthesized = true;
6367 rem_anchor_token(')');
6373 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6375 if (current_function == NULL) {
6376 errorf(HERE, "%K used outside of a function", &token);
6379 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6380 expression->base.type = type_char_ptr;
6381 expression->funcname.kind = kind;
6388 static designator_t *parse_designator(void)
6390 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6391 result->symbol = expect_identifier("while parsing member designator", &result->pos);
6392 if (!result->symbol)
6395 designator_t *last_designator = result;
6398 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6399 designator->symbol = expect_identifier("while parsing member designator", &designator->pos);
6400 if (!designator->symbol)
6403 last_designator->next = designator;
6404 last_designator = designator;
6408 add_anchor_token(']');
6409 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6410 designator->pos = *HERE;
6411 designator->array_index = parse_expression();
6412 rem_anchor_token(']');
6415 last_designator->next = designator;
6416 last_designator = designator;
6426 * Parse the __builtin_offsetof() expression.
6428 static expression_t *parse_offsetof(void)
6430 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6431 expression->base.type = type_size_t;
6433 eat(T___builtin_offsetof);
6435 add_anchor_token(')');
6436 add_anchor_token(',');
6438 type_t *type = parse_typename();
6439 rem_anchor_token(',');
6441 designator_t *designator = parse_designator();
6442 rem_anchor_token(')');
6445 expression->offsetofe.type = type;
6446 expression->offsetofe.designator = designator;
6449 memset(&path, 0, sizeof(path));
6450 path.top_type = type;
6451 path.path = NEW_ARR_F(type_path_entry_t, 0);
6453 descend_into_subtype(&path);
6455 if (!walk_designator(&path, designator, true)) {
6456 return create_error_expression();
6459 DEL_ARR_F(path.path);
6464 static bool is_last_parameter(expression_t *const param)
6466 if (param->kind == EXPR_REFERENCE) {
6467 entity_t *const entity = param->reference.entity;
6468 if (entity->kind == ENTITY_PARAMETER &&
6469 !entity->base.next &&
6470 entity->base.parent_scope == ¤t_function->parameters) {
6475 if (!is_type_valid(skip_typeref(param->base.type)))
6482 * Parses a __builtin_va_start() expression.
6484 static expression_t *parse_va_start(void)
6486 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6488 eat(T___builtin_va_start);
6490 add_anchor_token(')');
6491 add_anchor_token(',');
6493 expression->va_starte.ap = parse_assignment_expression();
6494 rem_anchor_token(',');
6496 expression_t *const param = parse_assignment_expression();
6497 expression->va_starte.parameter = param;
6498 rem_anchor_token(')');
6501 if (!current_function) {
6502 errorf(&expression->base.pos, "'va_start' used outside of function");
6503 } else if (!current_function->base.type->function.variadic) {
6504 errorf(&expression->base.pos, "'va_start' used in non-variadic function");
6505 } else if (!is_last_parameter(param)) {
6506 errorf(¶m->base.pos, "second argument of 'va_start' must be last parameter of the current function");
6513 * Parses a __builtin_va_arg() expression.
6515 static expression_t *parse_va_arg(void)
6517 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6519 eat(T___builtin_va_arg);
6521 add_anchor_token(')');
6522 add_anchor_token(',');
6525 ap.expression = parse_assignment_expression();
6526 expression->va_arge.ap = ap.expression;
6527 check_call_argument(type_valist, &ap, 1);
6529 rem_anchor_token(',');
6531 expression->base.type = parse_typename();
6532 rem_anchor_token(')');
6539 * Parses a __builtin_va_copy() expression.
6541 static expression_t *parse_va_copy(void)
6543 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6545 eat(T___builtin_va_copy);
6547 add_anchor_token(')');
6548 add_anchor_token(',');
6550 expression_t *dst = parse_assignment_expression();
6551 assign_error_t error = semantic_assign(type_valist, dst);
6552 report_assign_error(error, type_valist, dst, "call argument 1",
6554 expression->va_copye.dst = dst;
6556 rem_anchor_token(',');
6559 call_argument_t src;
6560 src.expression = parse_assignment_expression();
6561 check_call_argument(type_valist, &src, 2);
6562 expression->va_copye.src = src.expression;
6563 rem_anchor_token(')');
6570 * Parses a __builtin_constant_p() expression.
6572 static expression_t *parse_builtin_constant(void)
6574 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6576 eat(T___builtin_constant_p);
6578 add_anchor_token(')');
6580 expression->builtin_constant.value = parse_expression();
6581 rem_anchor_token(')');
6583 expression->base.type = type_int;
6589 * Parses a __builtin_types_compatible_p() expression.
6591 static expression_t *parse_builtin_types_compatible(void)
6593 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6595 eat(T___builtin_types_compatible_p);
6597 add_anchor_token(')');
6598 add_anchor_token(',');
6600 expression->builtin_types_compatible.left = parse_typename();
6601 rem_anchor_token(',');
6603 expression->builtin_types_compatible.right = parse_typename();
6604 rem_anchor_token(')');
6606 expression->base.type = type_int;
6612 * Parses a __builtin_is_*() compare expression.
6614 static expression_t *parse_compare_builtin(void)
6616 expression_kind_t kind;
6617 switch (token.kind) {
6618 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6619 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6620 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6621 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6622 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6623 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6624 default: internal_errorf(HERE, "invalid compare builtin found");
6626 expression_t *const expression = allocate_expression_zero(kind);
6629 add_anchor_token(')');
6630 add_anchor_token(',');
6632 expression->binary.left = parse_assignment_expression();
6633 rem_anchor_token(',');
6635 expression->binary.right = parse_assignment_expression();
6636 rem_anchor_token(')');
6639 type_t *const orig_type_left = expression->binary.left->base.type;
6640 type_t *const orig_type_right = expression->binary.right->base.type;
6642 type_t *const type_left = skip_typeref(orig_type_left);
6643 type_t *const type_right = skip_typeref(orig_type_right);
6644 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6645 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6646 type_error_incompatible("invalid operands in comparison",
6647 &expression->base.pos, orig_type_left, orig_type_right);
6650 semantic_comparison(&expression->binary, true);
6657 * Parses a MS assume() expression.
6659 static expression_t *parse_assume(void)
6661 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6665 add_anchor_token(')');
6667 expression->unary.value = parse_expression();
6668 rem_anchor_token(')');
6671 expression->base.type = type_void;
6676 * Return the label for the current symbol or create a new one.
6678 static label_t *get_label(char const *const context)
6680 assert(current_function != NULL);
6682 symbol_t *const sym = expect_identifier(context, NULL);
6686 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6687 /* If we find a local label, we already created the declaration. */
6688 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6689 if (label->base.parent_scope != current_scope) {
6690 assert(label->base.parent_scope->depth < current_scope->depth);
6691 current_function->goto_to_outer = true;
6693 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6694 /* There is no matching label in the same function, so create a new one. */
6695 position_t const nowhere = { NULL, 0, 0, false };
6696 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6700 return &label->label;
6704 * Parses a GNU && label address expression.
6706 static expression_t *parse_label_address(void)
6708 position_t const pos = *HERE;
6711 label_t *const label = get_label("while parsing label address");
6713 return create_error_expression();
6716 label->address_taken = true;
6718 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6719 expression->base.pos = pos;
6721 /* label address is treated as a void pointer */
6722 expression->base.type = type_void_ptr;
6723 expression->label_address.label = label;
6728 * Parse a microsoft __noop expression.
6730 static expression_t *parse_noop_expression(void)
6732 /* the result is a (int)0 */
6733 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6734 literal->base.type = type_int;
6735 literal->literal.value.begin = "__noop";
6736 literal->literal.value.size = 6;
6740 if (token.kind == '(') {
6741 /* parse arguments */
6743 add_anchor_token(')');
6744 add_anchor_token(',');
6746 if (token.kind != ')') do {
6747 (void)parse_assignment_expression();
6748 } while (accept(','));
6750 rem_anchor_token(',');
6751 rem_anchor_token(')');
6759 * Parses a primary expression.
6761 static expression_t *parse_primary_expression(void)
6763 switch (token.kind) {
6764 case T_false: return parse_boolean_literal(false);
6765 case T_true: return parse_boolean_literal(true);
6766 case T_NUMBER: return parse_number_literal();
6767 case T_CHARACTER_CONSTANT: return parse_character_constant();
6768 case T_STRING_LITERAL: return parse_string_literal();
6769 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6770 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6771 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6772 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6773 case T___builtin_offsetof: return parse_offsetof();
6774 case T___builtin_va_start: return parse_va_start();
6775 case T___builtin_va_arg: return parse_va_arg();
6776 case T___builtin_va_copy: return parse_va_copy();
6777 case T___builtin_isgreater:
6778 case T___builtin_isgreaterequal:
6779 case T___builtin_isless:
6780 case T___builtin_islessequal:
6781 case T___builtin_islessgreater:
6782 case T___builtin_isunordered: return parse_compare_builtin();
6783 case T___builtin_constant_p: return parse_builtin_constant();
6784 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6785 case T__assume: return parse_assume();
6788 return parse_label_address();
6791 case '(': return parse_parenthesized_expression();
6792 case T___noop: return parse_noop_expression();
6793 case T___imag__: return parse_complex_extract_expression(EXPR_UNARY_IMAG);
6794 case T___real__: return parse_complex_extract_expression(EXPR_UNARY_REAL);
6796 /* Gracefully handle type names while parsing expressions. */
6798 return parse_reference();
6800 if (!is_typedef_symbol(token.base.symbol)) {
6801 return parse_reference();
6805 position_t const pos = *HERE;
6806 declaration_specifiers_t specifiers;
6807 parse_declaration_specifiers(&specifiers);
6808 type_t const *const type = parse_abstract_declarator(specifiers.type);
6809 errorf(&pos, "encountered type '%T' while parsing expression", type);
6810 return create_error_expression();
6814 errorf(HERE, "unexpected token %K, expected an expression", &token);
6816 return create_error_expression();
6819 static expression_t *parse_array_expression(expression_t *left)
6821 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6822 array_access_expression_t *const arr = &expr->array_access;
6825 add_anchor_token(']');
6827 expression_t *const inside = parse_expression();
6829 type_t *const orig_type_left = left->base.type;
6830 type_t *const orig_type_inside = inside->base.type;
6832 type_t *const type_left = skip_typeref(orig_type_left);
6833 type_t *const type_inside = skip_typeref(orig_type_inside);
6839 if (is_type_pointer(type_left)) {
6842 idx_type = type_inside;
6843 res_type = type_left->pointer.points_to;
6845 } else if (is_type_pointer(type_inside)) {
6846 arr->flipped = true;
6849 idx_type = type_left;
6850 res_type = type_inside->pointer.points_to;
6852 res_type = automatic_type_conversion(res_type);
6853 if (!is_type_integer(idx_type)) {
6854 if (is_type_valid(idx_type))
6855 errorf(&idx->base.pos, "array subscript must have integer type");
6856 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6857 position_t const *const pos = &idx->base.pos;
6858 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6861 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6862 errorf(&expr->base.pos, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6864 res_type = type_error_type;
6869 arr->array_ref = ref;
6871 arr->base.type = res_type;
6873 rem_anchor_token(']');
6878 static bool is_bitfield(const expression_t *expression)
6880 return expression->kind == EXPR_SELECT
6881 && expression->select.compound_entry->compound_member.bitfield;
6884 static expression_t *parse_typeprop(expression_kind_t const kind)
6886 expression_t *tp_expression = allocate_expression_zero(kind);
6887 tp_expression->base.type = type_size_t;
6889 eat(kind == EXPR_SIZEOF ? T_sizeof : T__Alignof);
6892 expression_t *expression;
6893 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6894 position_t const pos = *HERE;
6896 add_anchor_token(')');
6897 orig_type = parse_typename();
6898 rem_anchor_token(')');
6901 if (token.kind == '{') {
6902 /* It was not sizeof(type) after all. It is sizeof of an expression
6903 * starting with a compound literal */
6904 expression = parse_compound_literal(&pos, orig_type);
6905 goto typeprop_expression;
6908 expression = parse_subexpression(PREC_UNARY);
6910 typeprop_expression:
6911 if (is_bitfield(expression)) {
6912 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6913 errorf(&tp_expression->base.pos,
6914 "operand of %s expression must not be a bitfield", what);
6917 tp_expression->typeprop.tp_expression = expression;
6919 orig_type = revert_automatic_type_conversion(expression);
6920 expression->base.type = orig_type;
6923 tp_expression->typeprop.type = orig_type;
6924 type_t const* const type = skip_typeref(orig_type);
6925 char const* wrong_type = NULL;
6926 if (is_type_incomplete(type)) {
6927 if (!is_type_void(type) || !GNU_MODE)
6928 wrong_type = "incomplete";
6929 } else if (type->kind == TYPE_FUNCTION) {
6931 /* function types are allowed (and return 1) */
6932 position_t const *const pos = &tp_expression->base.pos;
6933 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6934 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6936 wrong_type = "function";
6940 if (wrong_type != NULL) {
6941 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6942 errorf(&tp_expression->base.pos,
6943 "operand of %s expression must not be of %s type '%T'",
6944 what, wrong_type, orig_type);
6947 return tp_expression;
6950 static expression_t *parse_sizeof(void)
6952 return parse_typeprop(EXPR_SIZEOF);
6955 static expression_t *parse_alignof(void)
6957 return parse_typeprop(EXPR_ALIGNOF);
6960 static expression_t *parse_select_expression(expression_t *addr)
6962 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6963 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6964 position_t const pos = *HERE;
6967 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6969 return create_error_expression();
6971 type_t *const orig_type = addr->base.type;
6972 type_t *const type = skip_typeref(orig_type);
6975 bool saw_error = false;
6976 if (is_type_pointer(type)) {
6977 if (!select_left_arrow) {
6979 "request for member '%Y' in something not a struct or union, but '%T'",
6983 type_left = skip_typeref(type->pointer.points_to);
6985 if (select_left_arrow && is_type_valid(type)) {
6986 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6992 if (!is_type_compound(type_left)) {
6993 if (is_type_valid(type_left) && !saw_error) {
6995 "request for member '%Y' in something not a struct or union, but '%T'",
6998 return create_error_expression();
7001 compound_t *compound = type_left->compound.compound;
7002 if (!compound->complete) {
7003 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7005 return create_error_expression();
7008 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7009 expression_t *result =
7010 find_create_select(&pos, addr, qualifiers, compound, symbol);
7012 if (result == NULL) {
7013 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7014 return create_error_expression();
7020 static void check_call_argument(type_t *expected_type,
7021 call_argument_t *argument, unsigned pos)
7023 type_t *expected_type_skip = skip_typeref(expected_type);
7024 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7025 expression_t *arg_expr = argument->expression;
7026 type_t *arg_type = skip_typeref(arg_expr->base.type);
7028 /* handle transparent union gnu extension */
7029 if (is_type_union(expected_type_skip)
7030 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7031 compound_t *union_decl = expected_type_skip->compound.compound;
7032 type_t *best_type = NULL;
7033 entity_t *entry = union_decl->members.entities;
7034 for ( ; entry != NULL; entry = entry->base.next) {
7035 assert(is_declaration(entry));
7036 type_t *decl_type = entry->declaration.type;
7037 error = semantic_assign(decl_type, arg_expr);
7038 if (error == ASSIGN_ERROR_INCOMPATIBLE
7039 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7042 if (error == ASSIGN_SUCCESS) {
7043 best_type = decl_type;
7044 } else if (best_type == NULL) {
7045 best_type = decl_type;
7049 if (best_type != NULL) {
7050 expected_type = best_type;
7054 error = semantic_assign(expected_type, arg_expr);
7055 argument->expression = create_implicit_cast(arg_expr, expected_type);
7057 if (error != ASSIGN_SUCCESS) {
7058 /* report exact scope in error messages (like "in argument 3") */
7060 snprintf(buf, sizeof(buf), "call argument %u", pos);
7061 report_assign_error(error, expected_type, arg_expr, buf,
7062 &arg_expr->base.pos);
7064 type_t *const promoted_type = get_default_promoted_type(arg_type);
7065 if (!types_compatible(expected_type_skip, promoted_type) &&
7066 !types_compatible(expected_type_skip, type_void_ptr) &&
7067 !types_compatible(type_void_ptr, promoted_type)) {
7068 /* Deliberately show the skipped types in this warning */
7069 position_t const *const apos = &arg_expr->base.pos;
7070 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7076 * Handle the semantic restrictions of builtin calls
7078 static void handle_builtin_argument_restrictions(call_expression_t *call)
7080 entity_t *entity = call->function->reference.entity;
7081 switch (entity->function.btk) {
7083 switch (entity->function.b.firm_builtin_kind) {
7084 case ir_bk_return_address:
7085 case ir_bk_frame_address: {
7086 /* argument must be constant */
7087 call_argument_t *argument = call->arguments;
7089 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7090 errorf(&call->base.pos,
7091 "argument of '%Y' must be a constant expression",
7092 call->function->reference.entity->base.symbol);
7096 case ir_bk_prefetch:
7097 /* second and third argument must be constant if existent */
7098 if (call->arguments == NULL)
7100 call_argument_t *rw = call->arguments->next;
7101 call_argument_t *locality = NULL;
7104 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7105 errorf(&call->base.pos,
7106 "second argument of '%Y' must be a constant expression",
7107 call->function->reference.entity->base.symbol);
7109 locality = rw->next;
7111 if (locality != NULL) {
7112 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7113 errorf(&call->base.pos,
7114 "third argument of '%Y' must be a constant expression",
7115 call->function->reference.entity->base.symbol);
7123 case BUILTIN_OBJECT_SIZE:
7124 if (call->arguments == NULL)
7127 call_argument_t *arg = call->arguments->next;
7128 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7129 errorf(&call->base.pos,
7130 "second argument of '%Y' must be a constant expression",
7131 call->function->reference.entity->base.symbol);
7140 * Parse a call expression, i.e. expression '( ... )'.
7142 * @param expression the function address
7144 static expression_t *parse_call_expression(expression_t *expression)
7146 expression_t *result = allocate_expression_zero(EXPR_CALL);
7147 call_expression_t *call = &result->call;
7148 call->function = expression;
7150 type_t *const orig_type = expression->base.type;
7151 type_t *const type = skip_typeref(orig_type);
7153 function_type_t *function_type = NULL;
7154 if (is_type_pointer(type)) {
7155 type_t *const to_type = skip_typeref(type->pointer.points_to);
7157 if (is_type_function(to_type)) {
7158 function_type = &to_type->function;
7159 call->base.type = function_type->return_type;
7163 if (function_type == NULL && is_type_valid(type)) {
7165 "called object '%E' (type '%T') is not a pointer to a function",
7166 expression, orig_type);
7169 /* parse arguments */
7171 add_anchor_token(')');
7172 add_anchor_token(',');
7174 if (token.kind != ')') {
7175 call_argument_t **anchor = &call->arguments;
7177 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7178 argument->expression = parse_assignment_expression();
7181 anchor = &argument->next;
7182 } while (accept(','));
7184 rem_anchor_token(',');
7185 rem_anchor_token(')');
7188 if (function_type == NULL)
7191 /* check type and count of call arguments */
7192 function_parameter_t *parameter = function_type->parameters;
7193 call_argument_t *argument = call->arguments;
7194 if (!function_type->unspecified_parameters) {
7195 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7196 parameter = parameter->next, argument = argument->next) {
7197 check_call_argument(parameter->type, argument, ++pos);
7200 if (parameter != NULL) {
7201 errorf(&expression->base.pos, "too few arguments to function '%E'",
7203 } else if (argument != NULL && !function_type->variadic) {
7204 errorf(&argument->expression->base.pos,
7205 "too many arguments to function '%E'", expression);
7209 /* do default promotion for other arguments */
7210 for (; argument != NULL; argument = argument->next) {
7211 type_t *argument_type = argument->expression->base.type;
7212 if (!is_type_object(skip_typeref(argument_type))) {
7213 errorf(&argument->expression->base.pos,
7214 "call argument '%E' must not be void", argument->expression);
7217 argument_type = get_default_promoted_type(argument_type);
7219 argument->expression
7220 = create_implicit_cast(argument->expression, argument_type);
7225 if (is_type_compound(skip_typeref(function_type->return_type))) {
7226 position_t const *const pos = &expression->base.pos;
7227 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7230 if (expression->kind == EXPR_REFERENCE) {
7231 reference_expression_t *reference = &expression->reference;
7232 if (reference->entity->kind == ENTITY_FUNCTION &&
7233 reference->entity->function.btk != BUILTIN_NONE)
7234 handle_builtin_argument_restrictions(call);
7240 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7242 static bool same_compound_type(const type_t *type1, const type_t *type2)
7245 is_type_compound(type1) &&
7246 type1->kind == type2->kind &&
7247 type1->compound.compound == type2->compound.compound;
7250 static expression_t const *get_reference_address(expression_t const *expr)
7252 bool regular_take_address = true;
7254 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7255 expr = expr->unary.value;
7257 regular_take_address = false;
7260 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7263 expr = expr->unary.value;
7266 if (expr->kind != EXPR_REFERENCE)
7269 /* special case for functions which are automatically converted to a
7270 * pointer to function without an extra TAKE_ADDRESS operation */
7271 if (!regular_take_address &&
7272 expr->reference.entity->kind != ENTITY_FUNCTION) {
7279 static void warn_reference_address_as_bool(expression_t const* expr)
7281 expr = get_reference_address(expr);
7283 position_t const *const pos = &expr->base.pos;
7284 entity_t const *const ent = expr->reference.entity;
7285 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7289 static void warn_assignment_in_condition(const expression_t *const expr)
7291 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7293 if (expr->base.parenthesized)
7295 position_t const *const pos = &expr->base.pos;
7296 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7299 static void semantic_condition(expression_t const *const expr,
7300 char const *const context)
7302 type_t *const type = skip_typeref(expr->base.type);
7303 if (is_type_scalar(type)) {
7304 warn_reference_address_as_bool(expr);
7305 warn_assignment_in_condition(expr);
7306 } else if (is_type_valid(type)) {
7307 errorf(&expr->base.pos, "%s must have scalar type", context);
7312 * Parse a conditional expression, i.e. 'expression ? ... : ...'.
7314 * @param expression the conditional expression
7316 static expression_t *parse_conditional_expression(expression_t *expression)
7318 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7320 conditional_expression_t *conditional = &result->conditional;
7321 conditional->condition = expression;
7324 add_anchor_token(':');
7326 /* §6.5.15:2 The first operand shall have scalar type. */
7327 semantic_condition(expression, "condition of conditional operator");
7329 expression_t *true_expression = expression;
7330 bool gnu_cond = false;
7331 if (GNU_MODE && token.kind == ':') {
7334 true_expression = parse_expression();
7336 rem_anchor_token(':');
7338 expression_t *false_expression =
7339 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7341 type_t *const orig_true_type = true_expression->base.type;
7342 type_t *const orig_false_type = false_expression->base.type;
7343 type_t *const true_type = skip_typeref(orig_true_type);
7344 type_t *const false_type = skip_typeref(orig_false_type);
7347 position_t const *const pos = &conditional->base.pos;
7348 type_t *result_type;
7349 if (is_type_void(true_type) || is_type_void(false_type)) {
7350 /* ISO/IEC 14882:1998(E) §5.16:2 */
7351 if (true_expression->kind == EXPR_UNARY_THROW) {
7352 result_type = false_type;
7353 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7354 result_type = true_type;
7356 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7357 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7359 result_type = type_void;
7361 } else if (is_type_arithmetic(true_type)
7362 && is_type_arithmetic(false_type)) {
7363 result_type = semantic_arithmetic(true_type, false_type);
7364 } else if (same_compound_type(true_type, false_type)) {
7365 /* just take 1 of the 2 types */
7366 result_type = true_type;
7367 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7368 type_t *pointer_type;
7370 expression_t *other_expression;
7371 if (is_type_pointer(true_type) &&
7372 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7373 pointer_type = true_type;
7374 other_type = false_type;
7375 other_expression = false_expression;
7377 pointer_type = false_type;
7378 other_type = true_type;
7379 other_expression = true_expression;
7382 if (is_null_pointer_constant(other_expression)) {
7383 result_type = pointer_type;
7384 } else if (is_type_pointer(other_type)) {
7385 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7386 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7389 if (is_type_void(to1) || is_type_void(to2)) {
7391 } else if (types_compatible(get_unqualified_type(to1),
7392 get_unqualified_type(to2))) {
7395 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7399 type_t *const type =
7400 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7401 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7402 } else if (is_type_integer(other_type)) {
7403 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7404 result_type = pointer_type;
7406 goto types_incompatible;
7410 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7411 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7413 result_type = type_error_type;
7416 conditional->true_expression
7417 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7418 conditional->false_expression
7419 = create_implicit_cast(false_expression, result_type);
7420 conditional->base.type = result_type;
7425 * Parse an extension expression.
7427 static expression_t *parse_extension(void)
7430 expression_t *expression = parse_subexpression(PREC_UNARY);
7436 * Parse a __builtin_classify_type() expression.
7438 static expression_t *parse_builtin_classify_type(void)
7440 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7441 result->base.type = type_int;
7443 eat(T___builtin_classify_type);
7445 add_anchor_token(')');
7447 expression_t *expression = parse_expression();
7448 rem_anchor_token(')');
7450 result->classify_type.type_expression = expression;
7456 * Parse a delete expression
7457 * ISO/IEC 14882:1998(E) §5.3.5
7459 static expression_t *parse_delete(void)
7461 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7462 result->base.type = type_void;
7467 result->kind = EXPR_UNARY_DELETE_ARRAY;
7471 expression_t *const value = parse_subexpression(PREC_CAST);
7472 result->unary.value = value;
7474 type_t *const type = skip_typeref(value->base.type);
7475 if (!is_type_pointer(type)) {
7476 if (is_type_valid(type)) {
7477 errorf(&value->base.pos,
7478 "operand of delete must have pointer type");
7480 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7481 position_t const *const pos = &value->base.pos;
7482 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7489 * Parse a throw expression
7490 * ISO/IEC 14882:1998(E) §15:1
7492 static expression_t *parse_throw(void)
7494 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7495 result->base.type = type_void;
7499 expression_t *value = NULL;
7500 switch (token.kind) {
7502 value = parse_assignment_expression();
7503 /* ISO/IEC 14882:1998(E) §15.1:3 */
7504 type_t *const orig_type = value->base.type;
7505 type_t *const type = skip_typeref(orig_type);
7506 if (is_type_incomplete(type)) {
7507 errorf(&value->base.pos,
7508 "cannot throw object of incomplete type '%T'", orig_type);
7509 } else if (is_type_pointer(type)) {
7510 type_t *const points_to = skip_typeref(type->pointer.points_to);
7511 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7512 errorf(&value->base.pos,
7513 "cannot throw pointer to incomplete type '%T'", orig_type);
7521 result->unary.value = value;
7526 static bool check_pointer_arithmetic(const position_t *pos,
7527 type_t *pointer_type,
7528 type_t *orig_pointer_type)
7530 type_t *points_to = pointer_type->pointer.points_to;
7531 points_to = skip_typeref(points_to);
7533 if (is_type_incomplete(points_to)) {
7534 if (!GNU_MODE || !is_type_void(points_to)) {
7536 "arithmetic with pointer to incomplete type '%T' not allowed",
7540 warningf(WARN_POINTER_ARITH, pos, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7542 } else if (is_type_function(points_to)) {
7545 "arithmetic with pointer to function type '%T' not allowed",
7549 warningf(WARN_POINTER_ARITH, pos,
7550 "pointer to a function '%T' used in arithmetic",
7557 static bool is_lvalue(const expression_t *expression)
7559 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7560 switch (expression->kind) {
7561 case EXPR_ARRAY_ACCESS:
7562 case EXPR_COMPOUND_LITERAL:
7563 case EXPR_REFERENCE:
7565 case EXPR_UNARY_DEREFERENCE:
7569 type_t *type = skip_typeref(expression->base.type);
7571 /* ISO/IEC 14882:1998(E) §3.10:3 */
7572 is_type_reference(type) ||
7573 /* Claim it is an lvalue, if the type is invalid. There was a parse
7574 * error before, which maybe prevented properly recognizing it as
7576 !is_type_valid(type);
7581 static void semantic_incdec(unary_expression_t *expression)
7583 type_t *orig_type = expression->value->base.type;
7584 type_t *type = skip_typeref(orig_type);
7585 if (is_type_pointer(type)) {
7586 if (!check_pointer_arithmetic(&expression->base.pos, type, orig_type)) {
7589 } else if (!is_type_real(type) &&
7590 (!GNU_MODE || !is_type_complex(type)) && is_type_valid(type)) {
7591 /* TODO: improve error message */
7592 errorf(&expression->base.pos,
7593 "operation needs an arithmetic or pointer type");
7594 orig_type = type = type_error_type;
7596 if (!is_lvalue(expression->value)) {
7597 /* TODO: improve error message */
7598 errorf(&expression->base.pos, "lvalue required as operand");
7600 expression->base.type = orig_type;
7603 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7605 atomic_type_kind_t akind = get_arithmetic_akind(type);
7607 if (get_akind_rank(akind) < get_akind_rank(ATOMIC_TYPE_INT)) {
7608 if (type->kind == TYPE_COMPLEX)
7609 res_type = make_complex_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
7611 res_type = type_int;
7615 expr->base.type = res_type;
7616 expr->value = create_implicit_cast(expr->value, res_type);
7619 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7621 type_t *const orig_type = expression->value->base.type;
7622 type_t *const type = skip_typeref(orig_type);
7623 if (!is_type_arithmetic(type)) {
7624 if (is_type_valid(type)) {
7625 position_t const *const pos = &expression->base.pos;
7626 errorf(pos, "operand of unary expression must have arithmetic type, but is '%T'", orig_type);
7629 } else if (is_type_integer(type)) {
7630 promote_unary_int_expr(expression, type);
7632 expression->base.type = orig_type;
7636 static void semantic_unexpr_plus(unary_expression_t *expression)
7638 semantic_unexpr_arithmetic(expression);
7639 position_t const *const pos = &expression->base.pos;
7640 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7643 static void semantic_not(unary_expression_t *expression)
7645 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7646 semantic_condition(expression->value, "operand of !");
7647 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7650 static void semantic_complement(unary_expression_t *expression)
7652 type_t *const orig_type = expression->value->base.type;
7653 type_t *const type = skip_typeref(orig_type);
7654 if (!is_type_integer(type) && (!GNU_MODE || !is_type_complex(type))) {
7655 if (is_type_valid(type)) {
7656 errorf(&expression->base.pos, "operand of ~ must be of integer type");
7661 if (is_type_integer(type)) {
7662 promote_unary_int_expr(expression, type);
7664 expression->base.type = orig_type;
7668 static void semantic_dereference(unary_expression_t *expression)
7670 type_t *const orig_type = expression->value->base.type;
7671 type_t *const type = skip_typeref(orig_type);
7672 if (!is_type_pointer(type)) {
7673 if (is_type_valid(type)) {
7674 errorf(&expression->base.pos,
7675 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7680 type_t *result_type = type->pointer.points_to;
7681 result_type = automatic_type_conversion(result_type);
7682 expression->base.type = result_type;
7686 * Record that an address is taken (expression represents an lvalue).
7688 * @param expression the expression
7689 * @param may_be_register if true, the expression might be an register
7691 static void set_address_taken(expression_t *expression, bool may_be_register)
7693 if (expression->kind != EXPR_REFERENCE)
7696 entity_t *const entity = expression->reference.entity;
7698 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7701 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7702 && !may_be_register) {
7703 position_t const *const pos = &expression->base.pos;
7704 errorf(pos, "address of register '%N' requested", entity);
7707 entity->variable.address_taken = true;
7711 * Check the semantic of the address taken expression.
7713 static void semantic_take_addr(unary_expression_t *expression)
7715 expression_t *value = expression->value;
7716 value->base.type = revert_automatic_type_conversion(value);
7718 type_t *orig_type = value->base.type;
7719 type_t *type = skip_typeref(orig_type);
7720 if (!is_type_valid(type))
7724 if (!is_lvalue(value)) {
7725 errorf(&expression->base.pos, "'&' requires an lvalue");
7727 if (is_bitfield(value)) {
7728 errorf(&expression->base.pos, "'&' not allowed on bitfield");
7731 set_address_taken(value, false);
7733 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7736 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7737 static expression_t *parse_##unexpression_type(void) \
7739 expression_t *unary_expression \
7740 = allocate_expression_zero(unexpression_type); \
7742 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7744 sfunc(&unary_expression->unary); \
7746 return unary_expression; \
7749 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7750 semantic_unexpr_arithmetic)
7751 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7752 semantic_unexpr_plus)
7753 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7755 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7756 semantic_dereference)
7757 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7759 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_COMPLEMENT,
7760 semantic_complement)
7761 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7763 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7766 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7768 static expression_t *parse_##unexpression_type(expression_t *left) \
7770 expression_t *unary_expression \
7771 = allocate_expression_zero(unexpression_type); \
7773 unary_expression->unary.value = left; \
7775 sfunc(&unary_expression->unary); \
7777 return unary_expression; \
7780 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7781 EXPR_UNARY_POSTFIX_INCREMENT,
7783 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7784 EXPR_UNARY_POSTFIX_DECREMENT,
7787 static atomic_type_kind_t semantic_arithmetic_(atomic_type_kind_t kind_left,
7788 atomic_type_kind_t kind_right)
7790 /* §6.3.1.8 Usual arithmetic conversions */
7791 if (kind_left == ATOMIC_TYPE_LONG_DOUBLE
7792 || kind_right == ATOMIC_TYPE_LONG_DOUBLE) {
7793 return ATOMIC_TYPE_LONG_DOUBLE;
7794 } else if (kind_left == ATOMIC_TYPE_DOUBLE
7795 || kind_right == ATOMIC_TYPE_DOUBLE) {
7796 return ATOMIC_TYPE_DOUBLE;
7797 } else if (kind_left == ATOMIC_TYPE_FLOAT
7798 || kind_right == ATOMIC_TYPE_FLOAT) {
7799 return ATOMIC_TYPE_FLOAT;
7802 unsigned rank_left = get_akind_rank(kind_left);
7803 unsigned rank_right = get_akind_rank(kind_right);
7804 unsigned const rank_int = get_akind_rank(ATOMIC_TYPE_INT);
7805 if (rank_left < rank_int) {
7806 kind_left = ATOMIC_TYPE_INT;
7807 rank_left = rank_int;
7809 if (rank_right < rank_int) {
7810 kind_right = ATOMIC_TYPE_INT;
7811 rank_right = rank_int;
7813 if (kind_left == kind_right)
7816 bool const signed_left = is_akind_signed(kind_left);
7817 bool const signed_right = is_akind_signed(kind_right);
7818 if (signed_left == signed_right)
7819 return rank_left >= rank_right ? kind_left : kind_right;
7823 atomic_type_kind_t s_kind;
7824 atomic_type_kind_t u_kind;
7828 u_kind = kind_right;
7829 u_rank = rank_right;
7831 s_kind = kind_right;
7832 s_rank = rank_right;
7836 if (u_rank >= s_rank)
7838 if (get_atomic_type_size(s_kind) > get_atomic_type_size(u_kind))
7842 case ATOMIC_TYPE_INT: return ATOMIC_TYPE_UINT;
7843 case ATOMIC_TYPE_LONG: return ATOMIC_TYPE_ULONG;
7844 case ATOMIC_TYPE_LONGLONG: return ATOMIC_TYPE_ULONGLONG;
7845 default: panic("invalid atomic type");
7849 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7851 atomic_type_kind_t kind_left = get_arithmetic_akind(type_left);
7852 atomic_type_kind_t kind_right = get_arithmetic_akind(type_right);
7853 atomic_type_kind_t kind_res = semantic_arithmetic_(kind_left, kind_right);
7855 if (type_left->kind == TYPE_COMPLEX || type_right->kind == TYPE_COMPLEX) {
7856 return make_complex_type(kind_res, TYPE_QUALIFIER_NONE);
7858 return make_atomic_type(kind_res, TYPE_QUALIFIER_NONE);
7862 * Check the semantic restrictions for a binary expression.
7864 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7866 expression_t *const left = expression->left;
7867 expression_t *const right = expression->right;
7868 type_t *const orig_type_left = left->base.type;
7869 type_t *const orig_type_right = right->base.type;
7870 type_t *const type_left = skip_typeref(orig_type_left);
7871 type_t *const type_right = skip_typeref(orig_type_right);
7873 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7874 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7875 position_t const *const pos = &expression->base.pos;
7876 errorf(pos, "operands of binary expression must have arithmetic types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7881 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7882 expression->left = create_implicit_cast(left, arithmetic_type);
7883 expression->right = create_implicit_cast(right, arithmetic_type);
7884 expression->base.type = arithmetic_type;
7887 static void semantic_binexpr_integer(binary_expression_t *const expression)
7889 expression_t *const left = expression->left;
7890 expression_t *const right = expression->right;
7891 type_t *const orig_type_left = left->base.type;
7892 type_t *const orig_type_right = right->base.type;
7893 type_t *const type_left = skip_typeref(orig_type_left);
7894 type_t *const type_right = skip_typeref(orig_type_right);
7896 if (!is_type_integer(type_left) || !is_type_integer(type_right)
7897 || is_type_complex(type_left) || is_type_complex(type_right)) {
7898 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7899 position_t const *const pos = &expression->base.pos;
7900 errorf(pos, "operands of binary expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7905 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7906 expression->left = create_implicit_cast(left, result_type);
7907 expression->right = create_implicit_cast(right, result_type);
7908 expression->base.type = result_type;
7911 static void warn_div_by_zero(binary_expression_t const *const expression)
7913 if (!is_type_integer(expression->base.type))
7916 expression_t const *const right = expression->right;
7917 /* The type of the right operand can be different for /= */
7918 if (is_type_integer(skip_typeref(right->base.type)) &&
7919 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7920 !fold_constant_to_bool(right)) {
7921 position_t const *const pos = &expression->base.pos;
7922 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7927 * Check the semantic restrictions for a div expression.
7929 static void semantic_div(binary_expression_t *expression)
7931 semantic_binexpr_arithmetic(expression);
7932 warn_div_by_zero(expression);
7936 * Check the semantic restrictions for a mod expression.
7938 static void semantic_mod(binary_expression_t *expression)
7940 semantic_binexpr_integer(expression);
7941 warn_div_by_zero(expression);
7944 static void warn_addsub_in_shift(const expression_t *const expr)
7946 if (expr->base.parenthesized)
7950 switch (expr->kind) {
7951 case EXPR_BINARY_ADD: op = '+'; break;
7952 case EXPR_BINARY_SUB: op = '-'; break;
7956 position_t const *const pos = &expr->base.pos;
7957 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7960 static bool semantic_shift(binary_expression_t *expression)
7962 expression_t *const left = expression->left;
7963 expression_t *const right = expression->right;
7964 type_t *const orig_type_left = left->base.type;
7965 type_t *const orig_type_right = right->base.type;
7966 type_t * type_left = skip_typeref(orig_type_left);
7967 type_t * type_right = skip_typeref(orig_type_right);
7969 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7970 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7971 position_t const *const pos = &expression->base.pos;
7972 errorf(pos, "operands of shift expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7977 type_left = promote_integer(type_left);
7979 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7980 position_t const *const pos = &right->base.pos;
7981 long const count = fold_constant_to_int(right);
7983 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7984 } else if ((unsigned long)count >=
7985 get_atomic_type_size(type_left->atomic.akind) * 8) {
7986 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7990 type_right = promote_integer(type_right);
7991 expression->right = create_implicit_cast(right, type_right);
7996 static void semantic_shift_op(binary_expression_t *expression)
7998 expression_t *const left = expression->left;
7999 expression_t *const right = expression->right;
8001 if (!semantic_shift(expression))
8004 warn_addsub_in_shift(left);
8005 warn_addsub_in_shift(right);
8007 type_t *const orig_type_left = left->base.type;
8008 type_t * type_left = skip_typeref(orig_type_left);
8010 type_left = promote_integer(type_left);
8011 expression->left = create_implicit_cast(left, type_left);
8012 expression->base.type = type_left;
8015 static void semantic_add(binary_expression_t *expression)
8017 expression_t *const left = expression->left;
8018 expression_t *const right = expression->right;
8019 type_t *const orig_type_left = left->base.type;
8020 type_t *const orig_type_right = right->base.type;
8021 type_t *const type_left = skip_typeref(orig_type_left);
8022 type_t *const type_right = skip_typeref(orig_type_right);
8025 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8026 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8027 expression->left = create_implicit_cast(left, arithmetic_type);
8028 expression->right = create_implicit_cast(right, arithmetic_type);
8029 expression->base.type = arithmetic_type;
8030 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8031 check_pointer_arithmetic(&expression->base.pos, type_left,
8033 expression->base.type = type_left;
8034 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8035 check_pointer_arithmetic(&expression->base.pos, type_right,
8037 expression->base.type = type_right;
8038 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8039 errorf(&expression->base.pos,
8040 "invalid operands to binary + ('%T', '%T')",
8041 orig_type_left, orig_type_right);
8045 static void semantic_sub(binary_expression_t *expression)
8047 expression_t *const left = expression->left;
8048 expression_t *const right = expression->right;
8049 type_t *const orig_type_left = left->base.type;
8050 type_t *const orig_type_right = right->base.type;
8051 type_t *const type_left = skip_typeref(orig_type_left);
8052 type_t *const type_right = skip_typeref(orig_type_right);
8053 position_t const *const pos = &expression->base.pos;
8056 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8057 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8058 expression->left = create_implicit_cast(left, arithmetic_type);
8059 expression->right = create_implicit_cast(right, arithmetic_type);
8060 expression->base.type = arithmetic_type;
8061 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8062 check_pointer_arithmetic(&expression->base.pos, type_left,
8064 expression->base.type = type_left;
8065 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8066 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8067 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8068 if (!types_compatible(unqual_left, unqual_right)) {
8070 "subtracting pointers to incompatible types '%T' and '%T'",
8071 orig_type_left, orig_type_right);
8072 } else if (!is_type_object(unqual_left)) {
8073 if (!is_type_void(unqual_left)) {
8074 errorf(pos, "subtracting pointers to non-object types '%T'",
8077 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8080 expression->base.type = type_ptrdiff_t;
8081 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8082 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8083 orig_type_left, orig_type_right);
8087 static void warn_string_literal_address(expression_t const* expr)
8089 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8090 expr = expr->unary.value;
8091 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8093 expr = expr->unary.value;
8096 if (expr->kind == EXPR_STRING_LITERAL) {
8097 position_t const *const pos = &expr->base.pos;
8098 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8102 static bool maybe_negative(expression_t const *const expr)
8104 switch (is_constant_expression(expr)) {
8105 case EXPR_CLASS_ERROR: return false;
8106 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8107 default: return true;
8111 static void warn_comparison(position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8113 warn_string_literal_address(expr);
8115 expression_t const* const ref = get_reference_address(expr);
8116 if (ref != NULL && is_null_pointer_constant(other)) {
8117 entity_t const *const ent = ref->reference.entity;
8118 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8121 if (!expr->base.parenthesized) {
8122 switch (expr->base.kind) {
8123 case EXPR_BINARY_LESS:
8124 case EXPR_BINARY_GREATER:
8125 case EXPR_BINARY_LESSEQUAL:
8126 case EXPR_BINARY_GREATEREQUAL:
8127 case EXPR_BINARY_NOTEQUAL:
8128 case EXPR_BINARY_EQUAL:
8129 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8138 * Check the semantics of comparison expressions.
8140 static void semantic_comparison(binary_expression_t *expression,
8143 position_t const *const pos = &expression->base.pos;
8144 expression_t *const left = expression->left;
8145 expression_t *const right = expression->right;
8147 warn_comparison(pos, left, right);
8148 warn_comparison(pos, right, left);
8150 type_t *orig_type_left = left->base.type;
8151 type_t *orig_type_right = right->base.type;
8152 type_t *type_left = skip_typeref(orig_type_left);
8153 type_t *type_right = skip_typeref(orig_type_right);
8155 /* TODO non-arithmetic types */
8156 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8157 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8159 /* test for signed vs unsigned compares */
8160 if (is_type_integer(arithmetic_type)) {
8161 bool const signed_left = is_type_signed(type_left);
8162 bool const signed_right = is_type_signed(type_right);
8163 if (signed_left != signed_right) {
8164 /* FIXME long long needs better const folding magic */
8165 /* TODO check whether constant value can be represented by other type */
8166 if ((signed_left && maybe_negative(left)) ||
8167 (signed_right && maybe_negative(right))) {
8168 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8173 expression->left = create_implicit_cast(left, arithmetic_type);
8174 expression->right = create_implicit_cast(right, arithmetic_type);
8175 expression->base.type = arithmetic_type;
8176 if (!is_relational && is_type_float(arithmetic_type)) {
8177 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8179 /* for relational ops we need real types, not just arithmetic */
8181 && (!is_type_real(type_left) || !is_type_real(type_right))) {
8182 type_error_incompatible("invalid operands for relational operator", pos, type_left, type_right);
8184 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8185 /* TODO check compatibility */
8186 } else if (is_type_pointer(type_left)) {
8187 expression->right = create_implicit_cast(right, type_left);
8188 } else if (is_type_pointer(type_right)) {
8189 expression->left = create_implicit_cast(left, type_right);
8190 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8191 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8193 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8196 static void semantic_relational(binary_expression_t *expression)
8198 semantic_comparison(expression, true);
8201 static void semantic_equality(binary_expression_t *expression)
8203 semantic_comparison(expression, false);
8207 * Checks if a compound type has constant fields.
8209 static bool has_const_fields(const compound_type_t *type)
8211 compound_t *compound = type->compound;
8212 entity_t *entry = compound->members.entities;
8214 for (; entry != NULL; entry = entry->base.next) {
8215 if (!is_declaration(entry))
8218 const type_t *decl_type = skip_typeref(entry->declaration.type);
8219 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8226 static bool is_valid_assignment_lhs(expression_t const* const left)
8228 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8229 type_t *const type_left = skip_typeref(orig_type_left);
8231 if (!is_lvalue(left)) {
8232 errorf(&left->base.pos,
8233 "left hand side '%E' of assignment is not an lvalue", left);
8237 if (left->kind == EXPR_REFERENCE
8238 && left->reference.entity->kind == ENTITY_FUNCTION) {
8239 errorf(&left->base.pos, "cannot assign to function '%E'", left);
8243 if (is_type_array(type_left)) {
8244 errorf(&left->base.pos, "cannot assign to array '%E'", left);
8247 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8248 errorf(&left->base.pos,
8249 "assignment to read-only location '%E' (type '%T')", left,
8253 if (is_type_incomplete(type_left)) {
8254 errorf(&left->base.pos, "left-hand side '%E' of assignment has incomplete type '%T'",
8255 left, orig_type_left);
8258 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8259 errorf(&left->base.pos, "cannot assign to '%E' because compound type '%T' has read-only fields",
8260 left, orig_type_left);
8267 static void semantic_arithmetic_assign(binary_expression_t *expression)
8269 expression_t *left = expression->left;
8270 expression_t *right = expression->right;
8271 type_t *orig_type_left = left->base.type;
8272 type_t *orig_type_right = right->base.type;
8274 if (!is_valid_assignment_lhs(left))
8277 type_t *type_left = skip_typeref(orig_type_left);
8278 type_t *type_right = skip_typeref(orig_type_right);
8280 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8281 /* TODO: improve error message */
8282 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8283 errorf(&expression->base.pos, "operation needs arithmetic types");
8288 /* combined instructions are tricky. We can't create an implicit cast on
8289 * the left side, because we need the uncasted form for the store.
8290 * The ast2firm pass has to know that left_type must be right_type
8291 * for the arithmetic operation and create a cast by itself */
8292 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8293 expression->right = create_implicit_cast(right, arithmetic_type);
8294 expression->base.type = type_left;
8297 static void semantic_divmod_assign(binary_expression_t *expression)
8299 semantic_arithmetic_assign(expression);
8300 warn_div_by_zero(expression);
8303 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8305 expression_t *const left = expression->left;
8306 expression_t *const right = expression->right;
8307 type_t *const orig_type_left = left->base.type;
8308 type_t *const orig_type_right = right->base.type;
8309 type_t *const type_left = skip_typeref(orig_type_left);
8310 type_t *const type_right = skip_typeref(orig_type_right);
8312 if (!is_valid_assignment_lhs(left))
8315 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8316 /* combined instructions are tricky. We can't create an implicit cast on
8317 * the left side, because we need the uncasted form for the store.
8318 * The ast2firm pass has to know that left_type must be right_type
8319 * for the arithmetic operation and create a cast by itself */
8320 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8321 expression->right = create_implicit_cast(right, arithmetic_type);
8322 expression->base.type = type_left;
8323 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8324 check_pointer_arithmetic(&expression->base.pos, type_left,
8326 expression->base.type = type_left;
8327 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8328 errorf(&expression->base.pos,
8329 "incompatible types '%T' and '%T' in assignment",
8330 orig_type_left, orig_type_right);
8334 static void semantic_integer_assign(binary_expression_t *expression)
8336 expression_t *left = expression->left;
8337 expression_t *right = expression->right;
8338 type_t *orig_type_left = left->base.type;
8339 type_t *orig_type_right = right->base.type;
8341 if (!is_valid_assignment_lhs(left))
8344 type_t *type_left = skip_typeref(orig_type_left);
8345 type_t *type_right = skip_typeref(orig_type_right);
8347 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8348 /* TODO: improve error message */
8349 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8350 errorf(&expression->base.pos, "operation needs integer types");
8355 /* combined instructions are tricky. We can't create an implicit cast on
8356 * the left side, because we need the uncasted form for the store.
8357 * The ast2firm pass has to know that left_type must be right_type
8358 * for the arithmetic operation and create a cast by itself */
8359 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8360 expression->right = create_implicit_cast(right, arithmetic_type);
8361 expression->base.type = type_left;
8364 static void semantic_shift_assign(binary_expression_t *expression)
8366 expression_t *left = expression->left;
8368 if (!is_valid_assignment_lhs(left))
8371 if (!semantic_shift(expression))
8374 expression->base.type = skip_typeref(left->base.type);
8377 static void warn_logical_and_within_or(const expression_t *const expr)
8379 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8381 if (expr->base.parenthesized)
8383 position_t const *const pos = &expr->base.pos;
8384 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8388 * Check the semantic restrictions of a logical expression.
8390 static void semantic_logical_op(binary_expression_t *expression)
8392 /* §6.5.13:2 Each of the operands shall have scalar type.
8393 * §6.5.14:2 Each of the operands shall have scalar type. */
8394 semantic_condition(expression->left, "left operand of logical operator");
8395 semantic_condition(expression->right, "right operand of logical operator");
8396 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8397 warn_logical_and_within_or(expression->left);
8398 warn_logical_and_within_or(expression->right);
8400 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8404 * Check the semantic restrictions of a binary assign expression.
8406 static void semantic_binexpr_assign(binary_expression_t *expression)
8408 expression_t *left = expression->left;
8409 type_t *orig_type_left = left->base.type;
8411 if (!is_valid_assignment_lhs(left))
8414 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8415 report_assign_error(error, orig_type_left, expression->right,
8416 "assignment", &left->base.pos);
8417 expression->right = create_implicit_cast(expression->right, orig_type_left);
8418 expression->base.type = orig_type_left;
8422 * Determine if the outermost operation (or parts thereof) of the given
8423 * expression has no effect in order to generate a warning about this fact.
8424 * Therefore in some cases this only examines some of the operands of the
8425 * expression (see comments in the function and examples below).
8427 * f() + 23; // warning, because + has no effect
8428 * x || f(); // no warning, because x controls execution of f()
8429 * x ? y : f(); // warning, because y has no effect
8430 * (void)x; // no warning to be able to suppress the warning
8431 * This function can NOT be used for an "expression has definitely no effect"-
8433 static bool expression_has_effect(const expression_t *const expr)
8435 switch (expr->kind) {
8436 case EXPR_ERROR: return true; /* do NOT warn */
8437 case EXPR_REFERENCE: return false;
8438 case EXPR_ENUM_CONSTANT: return false;
8439 case EXPR_LABEL_ADDRESS: return false;
8441 /* suppress the warning for microsoft __noop operations */
8442 case EXPR_LITERAL_MS_NOOP: return true;
8443 case EXPR_LITERAL_BOOLEAN:
8444 case EXPR_LITERAL_CHARACTER:
8445 case EXPR_LITERAL_INTEGER:
8446 case EXPR_LITERAL_FLOATINGPOINT:
8447 case EXPR_STRING_LITERAL: return false;
8450 const call_expression_t *const call = &expr->call;
8451 if (call->function->kind != EXPR_REFERENCE)
8454 switch (call->function->reference.entity->function.btk) {
8455 /* FIXME: which builtins have no effect? */
8456 default: return true;
8460 /* Generate the warning if either the left or right hand side of a
8461 * conditional expression has no effect */
8462 case EXPR_CONDITIONAL: {
8463 conditional_expression_t const *const cond = &expr->conditional;
8464 expression_t const *const t = cond->true_expression;
8466 (t == NULL || expression_has_effect(t)) &&
8467 expression_has_effect(cond->false_expression);
8470 case EXPR_SELECT: return false;
8471 case EXPR_ARRAY_ACCESS: return false;
8472 case EXPR_SIZEOF: return false;
8473 case EXPR_CLASSIFY_TYPE: return false;
8474 case EXPR_ALIGNOF: return false;
8476 case EXPR_FUNCNAME: return false;
8477 case EXPR_BUILTIN_CONSTANT_P: return false;
8478 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8479 case EXPR_OFFSETOF: return false;
8480 case EXPR_VA_START: return true;
8481 case EXPR_VA_ARG: return true;
8482 case EXPR_VA_COPY: return true;
8483 case EXPR_STATEMENT: return true; // TODO
8484 case EXPR_COMPOUND_LITERAL: return false;
8486 case EXPR_UNARY_NEGATE: return false;
8487 case EXPR_UNARY_PLUS: return false;
8488 case EXPR_UNARY_COMPLEMENT: return false;
8489 case EXPR_UNARY_NOT: return false;
8490 case EXPR_UNARY_DEREFERENCE: return false;
8491 case EXPR_UNARY_TAKE_ADDRESS: return false;
8492 case EXPR_UNARY_REAL: return false;
8493 case EXPR_UNARY_IMAG: return false;
8494 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8495 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8496 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8497 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8499 /* Treat void casts as if they have an effect in order to being able to
8500 * suppress the warning */
8501 case EXPR_UNARY_CAST: {
8502 type_t *const type = skip_typeref(expr->base.type);
8503 return is_type_void(type);
8506 case EXPR_UNARY_ASSUME: return true;
8507 case EXPR_UNARY_DELETE: return true;
8508 case EXPR_UNARY_DELETE_ARRAY: return true;
8509 case EXPR_UNARY_THROW: return true;
8511 case EXPR_BINARY_ADD: return false;
8512 case EXPR_BINARY_SUB: return false;
8513 case EXPR_BINARY_MUL: return false;
8514 case EXPR_BINARY_DIV: return false;
8515 case EXPR_BINARY_MOD: return false;
8516 case EXPR_BINARY_EQUAL: return false;
8517 case EXPR_BINARY_NOTEQUAL: return false;
8518 case EXPR_BINARY_LESS: return false;
8519 case EXPR_BINARY_LESSEQUAL: return false;
8520 case EXPR_BINARY_GREATER: return false;
8521 case EXPR_BINARY_GREATEREQUAL: return false;
8522 case EXPR_BINARY_BITWISE_AND: return false;
8523 case EXPR_BINARY_BITWISE_OR: return false;
8524 case EXPR_BINARY_BITWISE_XOR: return false;
8525 case EXPR_BINARY_SHIFTLEFT: return false;
8526 case EXPR_BINARY_SHIFTRIGHT: return false;
8527 case EXPR_BINARY_ASSIGN: return true;
8528 case EXPR_BINARY_MUL_ASSIGN: return true;
8529 case EXPR_BINARY_DIV_ASSIGN: return true;
8530 case EXPR_BINARY_MOD_ASSIGN: return true;
8531 case EXPR_BINARY_ADD_ASSIGN: return true;
8532 case EXPR_BINARY_SUB_ASSIGN: return true;
8533 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8534 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8535 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8536 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8537 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8539 /* Only examine the right hand side of && and ||, because the left hand
8540 * side already has the effect of controlling the execution of the right
8542 case EXPR_BINARY_LOGICAL_AND:
8543 case EXPR_BINARY_LOGICAL_OR:
8544 /* Only examine the right hand side of a comma expression, because the left
8545 * hand side has a separate warning */
8546 case EXPR_BINARY_COMMA:
8547 return expression_has_effect(expr->binary.right);
8549 case EXPR_BINARY_ISGREATER: return false;
8550 case EXPR_BINARY_ISGREATEREQUAL: return false;
8551 case EXPR_BINARY_ISLESS: return false;
8552 case EXPR_BINARY_ISLESSEQUAL: return false;
8553 case EXPR_BINARY_ISLESSGREATER: return false;
8554 case EXPR_BINARY_ISUNORDERED: return false;
8557 internal_errorf(HERE, "unexpected expression");
8560 static void semantic_comma(binary_expression_t *expression)
8562 const expression_t *const left = expression->left;
8563 if (!expression_has_effect(left)) {
8564 position_t const *const pos = &left->base.pos;
8565 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8567 expression->base.type = expression->right->base.type;
8571 * @param prec_r precedence of the right operand
8573 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8574 static expression_t *parse_##binexpression_type(expression_t *left) \
8576 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8577 binexpr->binary.left = left; \
8580 expression_t *right = parse_subexpression(prec_r); \
8582 binexpr->binary.right = right; \
8583 sfunc(&binexpr->binary); \
8588 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8589 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_div)
8590 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_mod)
8591 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8592 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8593 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8594 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8595 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_relational)
8596 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_relational)
8597 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_relational)
8598 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_relational)
8599 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_equality)
8600 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_equality)
8601 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8602 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8603 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8604 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8605 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8606 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8607 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8608 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8609 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8610 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8611 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8612 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8613 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8614 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8615 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8616 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8617 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8620 static expression_t *parse_subexpression(precedence_t precedence)
8622 expression_parser_function_t *parser
8623 = &expression_parsers[token.kind];
8626 if (parser->parser != NULL) {
8627 left = parser->parser();
8629 left = parse_primary_expression();
8631 assert(left != NULL);
8634 parser = &expression_parsers[token.kind];
8635 if (parser->infix_parser == NULL)
8637 if (parser->infix_precedence < precedence)
8640 left = parser->infix_parser(left);
8642 assert(left != NULL);
8649 * Parse an expression.
8651 static expression_t *parse_expression(void)
8653 return parse_subexpression(PREC_EXPRESSION);
8657 * Register a parser for a prefix-like operator.
8659 * @param parser the parser function
8660 * @param token_kind the token type of the prefix token
8662 static void register_expression_parser(parse_expression_function parser,
8665 expression_parser_function_t *entry = &expression_parsers[token_kind];
8667 assert(!entry->parser);
8668 entry->parser = parser;
8672 * Register a parser for an infix operator with given precedence.
8674 * @param parser the parser function
8675 * @param token_kind the token type of the infix operator
8676 * @param precedence the precedence of the operator
8678 static void register_infix_parser(parse_expression_infix_function parser,
8679 int token_kind, precedence_t precedence)
8681 expression_parser_function_t *entry = &expression_parsers[token_kind];
8683 assert(!entry->infix_parser);
8684 entry->infix_parser = parser;
8685 entry->infix_precedence = precedence;
8689 * Initialize the expression parsers.
8691 static void init_expression_parsers(void)
8693 memset(&expression_parsers, 0, sizeof(expression_parsers));
8695 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8696 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8697 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8698 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8699 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8700 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8701 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8702 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8703 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8704 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8705 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8706 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8707 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8708 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8709 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8710 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8711 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8712 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8713 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8714 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8715 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8716 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8717 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8718 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8719 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8720 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8721 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8722 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8723 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8724 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8725 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8726 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8727 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8728 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8729 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8730 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8731 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8733 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8734 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8735 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8736 register_expression_parser(parse_EXPR_UNARY_COMPLEMENT, '~');
8737 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8738 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8739 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8740 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8741 register_expression_parser(parse_sizeof, T_sizeof);
8742 register_expression_parser(parse_alignof, T__Alignof);
8743 register_expression_parser(parse_extension, T___extension__);
8744 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8745 register_expression_parser(parse_delete, T_delete);
8746 register_expression_parser(parse_throw, T_throw);
8750 * Parse a asm statement arguments specification.
8752 static void parse_asm_arguments(asm_argument_t **anchor, bool const is_out)
8754 if (token.kind == T_STRING_LITERAL || token.kind == '[') {
8755 add_anchor_token(',');
8757 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8759 add_anchor_token(')');
8760 add_anchor_token('(');
8761 add_anchor_token(T_STRING_LITERAL);
8764 add_anchor_token(']');
8765 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8766 rem_anchor_token(']');
8770 rem_anchor_token(T_STRING_LITERAL);
8771 argument->constraints = parse_string_literals("asm argument");
8772 rem_anchor_token('(');
8774 expression_t *expression = parse_expression();
8776 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8777 * change size or type representation (e.g. int -> long is ok, but
8778 * int -> float is not) */
8779 if (expression->kind == EXPR_UNARY_CAST) {
8780 type_t *const type = expression->base.type;
8781 type_kind_t const kind = type->kind;
8782 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8785 if (kind == TYPE_ATOMIC) {
8786 atomic_type_kind_t const akind = type->atomic.akind;
8787 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8788 size = get_atomic_type_size(akind);
8790 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8791 size = get_type_size(type_void_ptr);
8795 expression_t *const value = expression->unary.value;
8796 type_t *const value_type = value->base.type;
8797 type_kind_t const value_kind = value_type->kind;
8799 unsigned value_flags;
8800 unsigned value_size;
8801 if (value_kind == TYPE_ATOMIC) {
8802 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8803 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8804 value_size = get_atomic_type_size(value_akind);
8805 } else if (value_kind == TYPE_POINTER) {
8806 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8807 value_size = get_type_size(type_void_ptr);
8812 if (value_flags != flags || value_size != size)
8816 } while (expression->kind == EXPR_UNARY_CAST);
8820 if (!is_lvalue(expression))
8821 errorf(&expression->base.pos,
8822 "asm output argument is not an lvalue");
8824 if (argument->constraints.begin[0] == '=')
8825 determine_lhs_ent(expression, NULL);
8827 mark_vars_read(expression, NULL);
8829 mark_vars_read(expression, NULL);
8831 argument->expression = expression;
8832 rem_anchor_token(')');
8835 set_address_taken(expression, true);
8838 anchor = &argument->next;
8839 } while (accept(','));
8840 rem_anchor_token(',');
8845 * Parse a asm statement clobber specification.
8847 static void parse_asm_clobbers(asm_clobber_t **anchor)
8849 if (token.kind == T_STRING_LITERAL) {
8850 add_anchor_token(',');
8852 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8853 clobber->clobber = parse_string_literals(NULL);
8856 anchor = &clobber->next;
8857 } while (accept(','));
8858 rem_anchor_token(',');
8862 static void parse_asm_labels(asm_label_t **anchor)
8864 if (token.kind == T_IDENTIFIER) {
8865 add_anchor_token(',');
8867 label_t *const label = get_label("while parsing 'asm goto' labels");
8869 asm_label_t *const asm_label = allocate_ast_zero(sizeof(*asm_label));
8870 asm_label->label = label;
8872 *anchor = asm_label;
8873 anchor = &asm_label->next;
8875 } while (accept(','));
8876 rem_anchor_token(',');
8881 * Parse an asm statement.
8883 static statement_t *parse_asm_statement(void)
8885 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8886 asm_statement_t *asm_statement = &statement->asms;
8889 add_anchor_token(')');
8890 add_anchor_token(':');
8891 add_anchor_token(T_STRING_LITERAL);
8893 if (accept(T_volatile))
8894 asm_statement->is_volatile = true;
8896 bool const asm_goto = accept(T_goto);
8899 rem_anchor_token(T_STRING_LITERAL);
8900 asm_statement->asm_text = parse_string_literals("asm statement");
8902 if (accept(':')) parse_asm_arguments(&asm_statement->outputs, true);
8903 if (accept(':')) parse_asm_arguments(&asm_statement->inputs, false);
8904 if (accept(':')) parse_asm_clobbers( &asm_statement->clobbers);
8906 rem_anchor_token(':');
8909 warningf(WARN_OTHER, &statement->base.pos, "assembler statement with labels should be 'asm goto'");
8910 parse_asm_labels(&asm_statement->labels);
8911 if (asm_statement->labels)
8912 errorf(&statement->base.pos, "'asm goto' not supported");
8915 warningf(WARN_OTHER, &statement->base.pos, "'asm goto' without labels");
8918 rem_anchor_token(')');
8922 if (asm_statement->outputs == NULL) {
8923 /* GCC: An 'asm' instruction without any output operands will be treated
8924 * identically to a volatile 'asm' instruction. */
8925 asm_statement->is_volatile = true;
8931 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8933 statement_t *inner_stmt;
8934 switch (token.kind) {
8936 errorf(&label->base.pos, "%s at end of compound statement", label_kind);
8937 inner_stmt = create_error_statement();
8941 if (label->kind == STATEMENT_LABEL) {
8942 /* Eat an empty statement here, to avoid the warning about an empty
8943 * statement after a label. label:; is commonly used to have a label
8944 * before a closing brace. */
8945 inner_stmt = create_empty_statement();
8952 inner_stmt = parse_statement();
8953 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8954 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8955 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8956 errorf(&inner_stmt->base.pos, "declaration after %s", label_kind);
8964 * Parse a case statement.
8966 static statement_t *parse_case_statement(void)
8968 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8969 position_t *const pos = &statement->base.pos;
8972 add_anchor_token(':');
8974 expression_t *expression = parse_expression();
8975 type_t *expression_type = expression->base.type;
8976 type_t *skipped = skip_typeref(expression_type);
8977 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8978 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8979 expression, expression_type);
8982 type_t *type = expression_type;
8983 if (current_switch != NULL) {
8984 type_t *switch_type = current_switch->expression->base.type;
8985 if (is_type_valid(skip_typeref(switch_type))) {
8986 expression = create_implicit_cast(expression, switch_type);
8990 statement->case_label.expression = expression;
8991 expression_classification_t const expr_class = is_constant_expression(expression);
8992 if (expr_class != EXPR_CLASS_CONSTANT) {
8993 if (expr_class != EXPR_CLASS_ERROR) {
8994 errorf(pos, "case label does not reduce to an integer constant");
8996 statement->case_label.is_bad = true;
8998 ir_tarval *val = fold_constant_to_tarval(expression);
8999 statement->case_label.first_case = val;
9000 statement->case_label.last_case = val;
9004 if (accept(T_DOTDOTDOT)) {
9005 expression_t *end_range = parse_expression();
9006 expression_type = expression->base.type;
9007 skipped = skip_typeref(expression_type);
9008 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9009 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9010 expression, expression_type);
9013 end_range = create_implicit_cast(end_range, type);
9014 statement->case_label.end_range = end_range;
9015 expression_classification_t const end_class = is_constant_expression(end_range);
9016 if (end_class != EXPR_CLASS_CONSTANT) {
9017 if (end_class != EXPR_CLASS_ERROR) {
9018 errorf(pos, "case range does not reduce to an integer constant");
9020 statement->case_label.is_bad = true;
9022 ir_tarval *val = fold_constant_to_tarval(end_range);
9023 statement->case_label.last_case = val;
9025 if (tarval_cmp(val, statement->case_label.first_case)
9026 == ir_relation_less) {
9027 statement->case_label.is_empty_range = true;
9028 warningf(WARN_OTHER, pos, "empty range specified");
9034 PUSH_PARENT(statement);
9036 rem_anchor_token(':');
9039 if (current_switch != NULL) {
9040 if (! statement->case_label.is_bad) {
9041 /* Check for duplicate case values */
9042 case_label_statement_t *c = &statement->case_label;
9043 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9044 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9047 if (c->last_case < l->first_case || c->first_case > l->last_case)
9050 errorf(pos, "duplicate case value (previously used %P)",
9055 /* link all cases into the switch statement */
9056 if (current_switch->last_case == NULL) {
9057 current_switch->first_case = &statement->case_label;
9059 current_switch->last_case->next = &statement->case_label;
9061 current_switch->last_case = &statement->case_label;
9063 errorf(pos, "case label not within a switch statement");
9066 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9073 * Parse a default statement.
9075 static statement_t *parse_default_statement(void)
9077 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9081 PUSH_PARENT(statement);
9085 if (current_switch != NULL) {
9086 const case_label_statement_t *def_label = current_switch->default_label;
9087 if (def_label != NULL) {
9088 errorf(&statement->base.pos, "multiple default labels in one switch (previous declared %P)", &def_label->base.pos);
9090 current_switch->default_label = &statement->case_label;
9092 /* link all cases into the switch statement */
9093 if (current_switch->last_case == NULL) {
9094 current_switch->first_case = &statement->case_label;
9096 current_switch->last_case->next = &statement->case_label;
9098 current_switch->last_case = &statement->case_label;
9101 errorf(&statement->base.pos,
9102 "'default' label not within a switch statement");
9105 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9112 * Parse a label statement.
9114 static statement_t *parse_label_statement(void)
9116 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9117 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9118 statement->label.label = label;
9120 PUSH_PARENT(statement);
9122 /* if statement is already set then the label is defined twice,
9123 * otherwise it was just mentioned in a goto/local label declaration so far
9125 position_t const* const pos = &statement->base.pos;
9126 if (label->statement != NULL) {
9127 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.pos);
9129 label->base.pos = *pos;
9130 label->statement = statement;
9131 label->n_users += 1;
9136 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9137 parse_attributes(NULL); // TODO process attributes
9140 statement->label.statement = parse_label_inner_statement(statement, "label");
9142 /* remember the labels in a list for later checking */
9143 *label_anchor = &statement->label;
9144 label_anchor = &statement->label.next;
9150 static statement_t *parse_inner_statement(void)
9152 statement_t *const stmt = parse_statement();
9153 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9154 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9155 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9156 errorf(&stmt->base.pos, "declaration as inner statement, use {}");
9162 * Parse an expression in parentheses and mark its variables as read.
9164 static expression_t *parse_condition(void)
9166 add_anchor_token(')');
9168 expression_t *const expr = parse_expression();
9169 mark_vars_read(expr, NULL);
9170 rem_anchor_token(')');
9176 * Parse an if statement.
9178 static statement_t *parse_if(void)
9180 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9184 PUSH_PARENT(statement);
9185 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9187 add_anchor_token(T_else);
9189 expression_t *const expr = parse_condition();
9190 statement->ifs.condition = expr;
9191 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9193 semantic_condition(expr, "condition of 'if'-statment");
9195 statement_t *const true_stmt = parse_inner_statement();
9196 statement->ifs.true_statement = true_stmt;
9197 rem_anchor_token(T_else);
9199 if (true_stmt->kind == STATEMENT_EMPTY) {
9200 warningf(WARN_EMPTY_BODY, HERE,
9201 "suggest braces around empty body in an ‘if’ statement");
9204 if (accept(T_else)) {
9205 statement->ifs.false_statement = parse_inner_statement();
9207 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9208 warningf(WARN_EMPTY_BODY, HERE,
9209 "suggest braces around empty body in an ‘if’ statement");
9211 } else if (true_stmt->kind == STATEMENT_IF &&
9212 true_stmt->ifs.false_statement != NULL) {
9213 position_t const *const pos = &true_stmt->base.pos;
9214 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9223 * Check that all enums are handled in a switch.
9225 * @param statement the switch statement to check
9227 static void check_enum_cases(const switch_statement_t *statement)
9229 if (!is_warn_on(WARN_SWITCH_ENUM))
9231 type_t *type = skip_typeref(statement->expression->base.type);
9232 if (! is_type_enum(type))
9234 enum_type_t *enumt = &type->enumt;
9236 /* if we have a default, no warnings */
9237 if (statement->default_label != NULL)
9240 determine_enum_values(enumt);
9242 /* FIXME: calculation of value should be done while parsing */
9243 /* TODO: quadratic algorithm here. Change to an n log n one */
9244 const entity_t *entry = enumt->enume->base.next;
9245 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9246 entry = entry->base.next) {
9247 ir_tarval *value = entry->enum_value.tv;
9249 for (const case_label_statement_t *l = statement->first_case; l != NULL;
9251 if (l->expression == NULL)
9253 if (l->first_case == l->last_case && l->first_case != value)
9255 if ((tarval_cmp(l->first_case, value) & ir_relation_less_equal)
9256 && (tarval_cmp(value, l->last_case) & ir_relation_less_equal)) {
9262 position_t const *const pos = &statement->base.pos;
9263 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9269 * Parse a switch statement.
9271 static statement_t *parse_switch(void)
9273 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9277 PUSH_PARENT(statement);
9278 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9280 expression_t *const expr = parse_condition();
9281 type_t * type = skip_typeref(expr->base.type);
9282 if (is_type_integer(type)) {
9283 type = promote_integer(type);
9284 if (get_akind_rank(get_arithmetic_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9285 warningf(WARN_TRADITIONAL, &expr->base.pos,
9286 "'%T' switch expression not converted to '%T' in ISO C",
9289 } else if (is_type_valid(type)) {
9290 errorf(&expr->base.pos, "switch quantity is not an integer, but '%T'",
9292 type = type_error_type;
9294 statement->switchs.expression = create_implicit_cast(expr, type);
9296 switch_statement_t *rem = current_switch;
9297 current_switch = &statement->switchs;
9298 statement->switchs.body = parse_inner_statement();
9299 current_switch = rem;
9301 if (statement->switchs.default_label == NULL) {
9302 warningf(WARN_SWITCH_DEFAULT, &statement->base.pos, "switch has no default case");
9304 check_enum_cases(&statement->switchs);
9311 static statement_t *parse_loop_body(statement_t *const loop)
9313 statement_t *const rem = current_loop;
9314 current_loop = loop;
9316 statement_t *const body = parse_inner_statement();
9323 * Parse a while statement.
9325 static statement_t *parse_while(void)
9327 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9331 PUSH_PARENT(statement);
9332 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9334 expression_t *const cond = parse_condition();
9335 statement->fors.condition = cond;
9336 /* §6.8.5:2 The controlling expression of an iteration statement shall
9337 * have scalar type. */
9338 semantic_condition(cond, "condition of 'while'-statement");
9340 statement->fors.body = parse_loop_body(statement);
9348 * Parse a do statement.
9350 static statement_t *parse_do(void)
9352 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9356 PUSH_PARENT(statement);
9357 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9359 add_anchor_token(T_while);
9360 statement->do_while.body = parse_loop_body(statement);
9361 rem_anchor_token(T_while);
9364 expression_t *const cond = parse_condition();
9365 statement->do_while.condition = cond;
9366 /* §6.8.5:2 The controlling expression of an iteration statement shall
9367 * have scalar type. */
9368 semantic_condition(cond, "condition of 'do-while'-statement");
9377 * Parse a for statement.
9379 static statement_t *parse_for(void)
9381 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9385 PUSH_PARENT(statement);
9386 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9388 add_anchor_token(')');
9394 } else if (is_declaration_specifier(&token)) {
9395 parse_declaration(record_entity, DECL_FLAGS_NONE);
9397 add_anchor_token(';');
9398 expression_t *const init = parse_expression();
9399 statement->fors.initialisation = init;
9400 mark_vars_read(init, ENT_ANY);
9401 if (!expression_has_effect(init)) {
9402 warningf(WARN_UNUSED_VALUE, &init->base.pos, "initialisation of 'for'-statement has no effect");
9404 rem_anchor_token(';');
9410 if (token.kind != ';') {
9411 add_anchor_token(';');
9412 expression_t *const cond = parse_expression();
9413 statement->fors.condition = cond;
9414 /* §6.8.5:2 The controlling expression of an iteration statement
9415 * shall have scalar type. */
9416 semantic_condition(cond, "condition of 'for'-statement");
9417 mark_vars_read(cond, NULL);
9418 rem_anchor_token(';');
9421 if (token.kind != ')') {
9422 expression_t *const step = parse_expression();
9423 statement->fors.step = step;
9424 mark_vars_read(step, ENT_ANY);
9425 if (!expression_has_effect(step)) {
9426 warningf(WARN_UNUSED_VALUE, &step->base.pos, "step of 'for'-statement has no effect");
9429 rem_anchor_token(')');
9431 statement->fors.body = parse_loop_body(statement);
9439 * Parse a goto statement.
9441 static statement_t *parse_goto(void)
9443 statement_t *statement;
9444 if (GNU_MODE && look_ahead(1)->kind == '*') {
9445 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9449 expression_t *expression = parse_expression();
9450 mark_vars_read(expression, NULL);
9452 /* Argh: although documentation says the expression must be of type void*,
9453 * gcc accepts anything that can be casted into void* without error */
9454 type_t *type = expression->base.type;
9456 if (type != type_error_type) {
9457 if (!is_type_pointer(type) && !is_type_integer(type)) {
9458 errorf(&expression->base.pos, "cannot convert to a pointer type");
9459 } else if (type != type_void_ptr) {
9460 warningf(WARN_OTHER, &expression->base.pos, "type of computed goto expression should be 'void*' not '%T'", type);
9462 expression = create_implicit_cast(expression, type_void_ptr);
9465 statement->computed_goto.expression = expression;
9467 statement = allocate_statement_zero(STATEMENT_GOTO);
9470 label_t *const label = get_label("while parsing goto");
9472 label->n_users += 1;
9474 statement->gotos.label = label;
9476 /* remember the goto's in a list for later checking */
9477 *goto_anchor = &statement->gotos;
9478 goto_anchor = &statement->gotos.next;
9480 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_position)->label;
9489 * Parse a continue statement.
9491 static statement_t *parse_continue(void)
9493 if (current_loop == NULL) {
9494 errorf(HERE, "continue statement not within loop");
9497 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9505 * Parse a break statement.
9507 static statement_t *parse_break(void)
9509 if (current_switch == NULL && current_loop == NULL) {
9510 errorf(HERE, "break statement not within loop or switch");
9513 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9521 * Parse a __leave statement.
9523 static statement_t *parse_leave_statement(void)
9525 if (current_try == NULL) {
9526 errorf(HERE, "__leave statement not within __try");
9529 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9537 * Check if a given entity represents a local variable.
9539 static bool is_local_variable(const entity_t *entity)
9541 if (entity->kind != ENTITY_VARIABLE)
9544 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9545 case STORAGE_CLASS_AUTO:
9546 case STORAGE_CLASS_REGISTER: {
9547 const type_t *type = skip_typeref(entity->declaration.type);
9548 if (is_type_function(type)) {
9560 * Check if a given expression represents a local variable.
9562 static bool expression_is_local_variable(const expression_t *expression)
9564 if (expression->base.kind != EXPR_REFERENCE) {
9567 const entity_t *entity = expression->reference.entity;
9568 return is_local_variable(entity);
9571 static void err_or_warn(position_t const *const pos, char const *const msg)
9573 if (c_mode & _CXX || strict_mode) {
9576 warningf(WARN_OTHER, pos, msg);
9581 * Parse a return statement.
9583 static statement_t *parse_return(void)
9585 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9588 expression_t *return_value = NULL;
9589 if (token.kind != ';') {
9590 return_value = parse_expression();
9591 mark_vars_read(return_value, NULL);
9594 const type_t *const func_type = skip_typeref(current_function->base.type);
9595 assert(is_type_function(func_type));
9596 type_t *const return_type = skip_typeref(func_type->function.return_type);
9598 position_t const *const pos = &statement->base.pos;
9599 if (return_value != NULL) {
9600 type_t *return_value_type = skip_typeref(return_value->base.type);
9602 if (is_type_void(return_type)) {
9603 if (!is_type_void(return_value_type)) {
9604 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9605 /* Only warn in C mode, because GCC does the same */
9606 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9607 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9608 /* Only warn in C mode, because GCC does the same */
9609 err_or_warn(pos, "'return' with expression in function returning 'void'");
9612 assign_error_t error = semantic_assign(return_type, return_value);
9613 report_assign_error(error, return_type, return_value, "'return'",
9616 return_value = create_implicit_cast(return_value, return_type);
9617 /* check for returning address of a local var */
9618 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9619 const expression_t *expression = return_value->unary.value;
9620 if (expression_is_local_variable(expression)) {
9621 warningf(WARN_OTHER, pos, "function returns address of local variable");
9624 } else if (!is_type_void(return_type)) {
9625 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9626 err_or_warn(pos, "'return' without value, in function returning non-void");
9628 statement->returns.value = return_value;
9635 * Parse a declaration statement.
9637 static statement_t *parse_declaration_statement(void)
9639 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9641 entity_t *before = current_scope->last_entity;
9643 parse_external_declaration();
9645 parse_declaration(record_entity, DECL_FLAGS_NONE);
9648 declaration_statement_t *const decl = &statement->declaration;
9649 entity_t *const begin =
9650 before != NULL ? before->base.next : current_scope->entities;
9651 decl->declarations_begin = begin;
9652 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9658 * Parse an expression statement, i.e. expr ';'.
9660 static statement_t *parse_expression_statement(void)
9662 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9664 expression_t *const expr = parse_expression();
9665 statement->expression.expression = expr;
9666 mark_vars_read(expr, ENT_ANY);
9673 * Parse a microsoft __try { } __finally { } or
9674 * __try{ } __except() { }
9676 static statement_t *parse_ms_try_statment(void)
9678 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9681 PUSH_PARENT(statement);
9683 ms_try_statement_t *rem = current_try;
9684 current_try = &statement->ms_try;
9685 statement->ms_try.try_statement = parse_compound_statement(false);
9690 if (accept(T___except)) {
9691 expression_t *const expr = parse_condition();
9692 type_t * type = skip_typeref(expr->base.type);
9693 if (is_type_integer(type)) {
9694 type = promote_integer(type);
9695 } else if (is_type_valid(type)) {
9696 errorf(&expr->base.pos,
9697 "__expect expression is not an integer, but '%T'", type);
9698 type = type_error_type;
9700 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9701 } else if (!accept(T__finally)) {
9702 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9704 statement->ms_try.final_statement = parse_compound_statement(false);
9708 static statement_t *parse_empty_statement(void)
9710 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9711 statement_t *const statement = create_empty_statement();
9716 static statement_t *parse_local_label_declaration(void)
9718 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9722 entity_t *begin = NULL;
9723 entity_t *end = NULL;
9724 entity_t **anchor = &begin;
9725 add_anchor_token(';');
9726 add_anchor_token(',');
9729 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9731 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9732 if (entity != NULL && entity->base.parent_scope == current_scope) {
9733 position_t const *const ppos = &entity->base.pos;
9734 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9736 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9737 entity->base.parent_scope = current_scope;
9740 anchor = &entity->base.next;
9743 environment_push(entity);
9746 } while (accept(','));
9747 rem_anchor_token(',');
9748 rem_anchor_token(';');
9750 statement->declaration.declarations_begin = begin;
9751 statement->declaration.declarations_end = end;
9755 static void parse_namespace_definition(void)
9759 entity_t *entity = NULL;
9760 symbol_t *symbol = NULL;
9762 if (token.kind == T_IDENTIFIER) {
9763 symbol = token.base.symbol;
9764 entity = get_entity(symbol, NAMESPACE_NORMAL);
9765 if (entity && entity->kind != ENTITY_NAMESPACE) {
9767 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9768 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9774 if (entity == NULL) {
9775 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9776 entity->base.parent_scope = current_scope;
9779 if (token.kind == '=') {
9780 /* TODO: parse namespace alias */
9781 panic("namespace alias definition not supported yet");
9784 environment_push(entity);
9785 append_entity(current_scope, entity);
9787 PUSH_SCOPE(&entity->namespacee.members);
9788 PUSH_CURRENT_ENTITY(entity);
9790 add_anchor_token('}');
9793 rem_anchor_token('}');
9796 POP_CURRENT_ENTITY();
9801 * Parse a statement.
9802 * There's also parse_statement() which additionally checks for
9803 * "statement has no effect" warnings
9805 static statement_t *intern_parse_statement(void)
9807 /* declaration or statement */
9808 statement_t *statement;
9809 switch (token.kind) {
9810 case T_IDENTIFIER: {
9811 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9812 if (la1_type == ':') {
9813 statement = parse_label_statement();
9814 } else if (is_typedef_symbol(token.base.symbol)) {
9815 statement = parse_declaration_statement();
9817 /* it's an identifier, the grammar says this must be an
9818 * expression statement. However it is common that users mistype
9819 * declaration types, so we guess a bit here to improve robustness
9820 * for incorrect programs */
9824 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9826 statement = parse_expression_statement();
9830 statement = parse_declaration_statement();
9838 case T___extension__: {
9839 /* This can be a prefix to a declaration or an expression statement.
9840 * We simply eat it now and parse the rest with tail recursion. */
9842 statement = intern_parse_statement();
9848 statement = parse_declaration_statement();
9852 statement = parse_local_label_declaration();
9855 case ';': statement = parse_empty_statement(); break;
9856 case '{': statement = parse_compound_statement(false); break;
9857 case T___leave: statement = parse_leave_statement(); break;
9858 case T___try: statement = parse_ms_try_statment(); break;
9859 case T_asm: statement = parse_asm_statement(); break;
9860 case T_break: statement = parse_break(); break;
9861 case T_case: statement = parse_case_statement(); break;
9862 case T_continue: statement = parse_continue(); break;
9863 case T_default: statement = parse_default_statement(); break;
9864 case T_do: statement = parse_do(); break;
9865 case T_for: statement = parse_for(); break;
9866 case T_goto: statement = parse_goto(); break;
9867 case T_if: statement = parse_if(); break;
9868 case T_return: statement = parse_return(); break;
9869 case T_switch: statement = parse_switch(); break;
9870 case T_while: statement = parse_while(); break;
9873 statement = parse_expression_statement();
9877 errorf(HERE, "unexpected token %K while parsing statement", &token);
9878 statement = create_error_statement();
9887 * parse a statement and emits "statement has no effect" warning if needed
9888 * (This is really a wrapper around intern_parse_statement with check for 1
9889 * single warning. It is needed, because for statement expressions we have
9890 * to avoid the warning on the last statement)
9892 static statement_t *parse_statement(void)
9894 statement_t *statement = intern_parse_statement();
9896 if (statement->kind == STATEMENT_EXPRESSION) {
9897 expression_t *expression = statement->expression.expression;
9898 if (!expression_has_effect(expression)) {
9899 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
9900 "statement has no effect");
9908 * Parse a compound statement.
9910 static statement_t *parse_compound_statement(bool inside_expression_statement)
9912 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9914 PUSH_PARENT(statement);
9915 PUSH_SCOPE(&statement->compound.scope);
9918 add_anchor_token('}');
9919 /* tokens, which can start a statement */
9920 /* TODO MS, __builtin_FOO */
9921 add_anchor_token('!');
9922 add_anchor_token('&');
9923 add_anchor_token('(');
9924 add_anchor_token('*');
9925 add_anchor_token('+');
9926 add_anchor_token('-');
9927 add_anchor_token(';');
9928 add_anchor_token('{');
9929 add_anchor_token('~');
9930 add_anchor_token(T_CHARACTER_CONSTANT);
9931 add_anchor_token(T_COLONCOLON);
9932 add_anchor_token(T_IDENTIFIER);
9933 add_anchor_token(T_MINUSMINUS);
9934 add_anchor_token(T_NUMBER);
9935 add_anchor_token(T_PLUSPLUS);
9936 add_anchor_token(T_STRING_LITERAL);
9937 add_anchor_token(T__Alignof);
9938 add_anchor_token(T__Bool);
9939 add_anchor_token(T__Complex);
9940 add_anchor_token(T__Imaginary);
9941 add_anchor_token(T__Thread_local);
9942 add_anchor_token(T___PRETTY_FUNCTION__);
9943 add_anchor_token(T___attribute__);
9944 add_anchor_token(T___builtin_va_start);
9945 add_anchor_token(T___extension__);
9946 add_anchor_token(T___func__);
9947 add_anchor_token(T___imag__);
9948 add_anchor_token(T___label__);
9949 add_anchor_token(T___real__);
9950 add_anchor_token(T_asm);
9951 add_anchor_token(T_auto);
9952 add_anchor_token(T_bool);
9953 add_anchor_token(T_break);
9954 add_anchor_token(T_case);
9955 add_anchor_token(T_char);
9956 add_anchor_token(T_class);
9957 add_anchor_token(T_const);
9958 add_anchor_token(T_const_cast);
9959 add_anchor_token(T_continue);
9960 add_anchor_token(T_default);
9961 add_anchor_token(T_delete);
9962 add_anchor_token(T_double);
9963 add_anchor_token(T_do);
9964 add_anchor_token(T_dynamic_cast);
9965 add_anchor_token(T_enum);
9966 add_anchor_token(T_extern);
9967 add_anchor_token(T_false);
9968 add_anchor_token(T_float);
9969 add_anchor_token(T_for);
9970 add_anchor_token(T_goto);
9971 add_anchor_token(T_if);
9972 add_anchor_token(T_inline);
9973 add_anchor_token(T_int);
9974 add_anchor_token(T_long);
9975 add_anchor_token(T_new);
9976 add_anchor_token(T_operator);
9977 add_anchor_token(T_register);
9978 add_anchor_token(T_reinterpret_cast);
9979 add_anchor_token(T_restrict);
9980 add_anchor_token(T_return);
9981 add_anchor_token(T_short);
9982 add_anchor_token(T_signed);
9983 add_anchor_token(T_sizeof);
9984 add_anchor_token(T_static);
9985 add_anchor_token(T_static_cast);
9986 add_anchor_token(T_struct);
9987 add_anchor_token(T_switch);
9988 add_anchor_token(T_template);
9989 add_anchor_token(T_this);
9990 add_anchor_token(T_throw);
9991 add_anchor_token(T_true);
9992 add_anchor_token(T_try);
9993 add_anchor_token(T_typedef);
9994 add_anchor_token(T_typeid);
9995 add_anchor_token(T_typename);
9996 add_anchor_token(T_typeof);
9997 add_anchor_token(T_union);
9998 add_anchor_token(T_unsigned);
9999 add_anchor_token(T_using);
10000 add_anchor_token(T_void);
10001 add_anchor_token(T_volatile);
10002 add_anchor_token(T_wchar_t);
10003 add_anchor_token(T_while);
10005 statement_t **anchor = &statement->compound.statements;
10006 bool only_decls_so_far = true;
10007 while (token.kind != '}' && token.kind != T_EOF) {
10008 statement_t *sub_statement = intern_parse_statement();
10009 if (sub_statement->kind == STATEMENT_ERROR) {
10013 if (sub_statement->kind != STATEMENT_DECLARATION) {
10014 only_decls_so_far = false;
10015 } else if (!only_decls_so_far) {
10016 position_t const *const pos = &sub_statement->base.pos;
10017 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10020 *anchor = sub_statement;
10021 anchor = &sub_statement->base.next;
10025 /* look over all statements again to produce no effect warnings */
10026 if (is_warn_on(WARN_UNUSED_VALUE)) {
10027 statement_t *sub_statement = statement->compound.statements;
10028 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10029 if (sub_statement->kind != STATEMENT_EXPRESSION)
10031 /* don't emit a warning for the last expression in an expression
10032 * statement as it has always an effect */
10033 if (inside_expression_statement && sub_statement->base.next == NULL)
10036 expression_t *expression = sub_statement->expression.expression;
10037 if (!expression_has_effect(expression)) {
10038 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
10039 "statement has no effect");
10044 rem_anchor_token(T_while);
10045 rem_anchor_token(T_wchar_t);
10046 rem_anchor_token(T_volatile);
10047 rem_anchor_token(T_void);
10048 rem_anchor_token(T_using);
10049 rem_anchor_token(T_unsigned);
10050 rem_anchor_token(T_union);
10051 rem_anchor_token(T_typeof);
10052 rem_anchor_token(T_typename);
10053 rem_anchor_token(T_typeid);
10054 rem_anchor_token(T_typedef);
10055 rem_anchor_token(T_try);
10056 rem_anchor_token(T_true);
10057 rem_anchor_token(T_throw);
10058 rem_anchor_token(T_this);
10059 rem_anchor_token(T_template);
10060 rem_anchor_token(T_switch);
10061 rem_anchor_token(T_struct);
10062 rem_anchor_token(T_static_cast);
10063 rem_anchor_token(T_static);
10064 rem_anchor_token(T_sizeof);
10065 rem_anchor_token(T_signed);
10066 rem_anchor_token(T_short);
10067 rem_anchor_token(T_return);
10068 rem_anchor_token(T_restrict);
10069 rem_anchor_token(T_reinterpret_cast);
10070 rem_anchor_token(T_register);
10071 rem_anchor_token(T_operator);
10072 rem_anchor_token(T_new);
10073 rem_anchor_token(T_long);
10074 rem_anchor_token(T_int);
10075 rem_anchor_token(T_inline);
10076 rem_anchor_token(T_if);
10077 rem_anchor_token(T_goto);
10078 rem_anchor_token(T_for);
10079 rem_anchor_token(T_float);
10080 rem_anchor_token(T_false);
10081 rem_anchor_token(T_extern);
10082 rem_anchor_token(T_enum);
10083 rem_anchor_token(T_dynamic_cast);
10084 rem_anchor_token(T_do);
10085 rem_anchor_token(T_double);
10086 rem_anchor_token(T_delete);
10087 rem_anchor_token(T_default);
10088 rem_anchor_token(T_continue);
10089 rem_anchor_token(T_const_cast);
10090 rem_anchor_token(T_const);
10091 rem_anchor_token(T_class);
10092 rem_anchor_token(T_char);
10093 rem_anchor_token(T_case);
10094 rem_anchor_token(T_break);
10095 rem_anchor_token(T_bool);
10096 rem_anchor_token(T_auto);
10097 rem_anchor_token(T_asm);
10098 rem_anchor_token(T___real__);
10099 rem_anchor_token(T___label__);
10100 rem_anchor_token(T___imag__);
10101 rem_anchor_token(T___func__);
10102 rem_anchor_token(T___extension__);
10103 rem_anchor_token(T___builtin_va_start);
10104 rem_anchor_token(T___attribute__);
10105 rem_anchor_token(T___PRETTY_FUNCTION__);
10106 rem_anchor_token(T__Thread_local);
10107 rem_anchor_token(T__Imaginary);
10108 rem_anchor_token(T__Complex);
10109 rem_anchor_token(T__Bool);
10110 rem_anchor_token(T__Alignof);
10111 rem_anchor_token(T_STRING_LITERAL);
10112 rem_anchor_token(T_PLUSPLUS);
10113 rem_anchor_token(T_NUMBER);
10114 rem_anchor_token(T_MINUSMINUS);
10115 rem_anchor_token(T_IDENTIFIER);
10116 rem_anchor_token(T_COLONCOLON);
10117 rem_anchor_token(T_CHARACTER_CONSTANT);
10118 rem_anchor_token('~');
10119 rem_anchor_token('{');
10120 rem_anchor_token(';');
10121 rem_anchor_token('-');
10122 rem_anchor_token('+');
10123 rem_anchor_token('*');
10124 rem_anchor_token('(');
10125 rem_anchor_token('&');
10126 rem_anchor_token('!');
10127 rem_anchor_token('}');
10135 * Check for unused global static functions and variables
10137 static void check_unused_globals(void)
10139 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10142 for (const entity_t *entity = file_scope->entities; entity != NULL;
10143 entity = entity->base.next) {
10144 if (!is_declaration(entity))
10147 const declaration_t *declaration = &entity->declaration;
10148 if (declaration->used ||
10149 declaration->modifiers & DM_UNUSED ||
10150 declaration->modifiers & DM_USED ||
10151 declaration->storage_class != STORAGE_CLASS_STATIC)
10156 if (entity->kind == ENTITY_FUNCTION) {
10157 /* inhibit warning for static inline functions */
10158 if (entity->function.is_inline)
10161 why = WARN_UNUSED_FUNCTION;
10162 s = entity->function.body != NULL ? "defined" : "declared";
10164 why = WARN_UNUSED_VARIABLE;
10168 warningf(why, &declaration->base.pos, "'%#N' %s but not used", entity, s);
10172 static void parse_global_asm(void)
10174 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10177 add_anchor_token(';');
10178 add_anchor_token(')');
10179 add_anchor_token(T_STRING_LITERAL);
10182 rem_anchor_token(T_STRING_LITERAL);
10183 statement->asms.asm_text = parse_string_literals("global asm");
10184 statement->base.next = unit->global_asm;
10185 unit->global_asm = statement;
10187 rem_anchor_token(')');
10189 rem_anchor_token(';');
10193 static void parse_linkage_specification(void)
10197 position_t const pos = *HERE;
10198 char const *const linkage = parse_string_literals(NULL).begin;
10200 linkage_kind_t old_linkage = current_linkage;
10201 linkage_kind_t new_linkage;
10202 if (streq(linkage, "C")) {
10203 new_linkage = LINKAGE_C;
10204 } else if (streq(linkage, "C++")) {
10205 new_linkage = LINKAGE_CXX;
10207 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10208 new_linkage = LINKAGE_C;
10210 current_linkage = new_linkage;
10219 assert(current_linkage == new_linkage);
10220 current_linkage = old_linkage;
10223 static void parse_external(void)
10225 switch (token.kind) {
10227 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10228 parse_linkage_specification();
10230 DECLARATION_START_NO_EXTERN
10232 case T___extension__:
10233 /* tokens below are for implicit int */
10234 case '&': /* & x; -> int& x; (and error later, because C++ has no
10236 case '*': /* * x; -> int* x; */
10237 case '(': /* (x); -> int (x); */
10239 parse_external_declaration();
10245 parse_global_asm();
10249 parse_namespace_definition();
10253 if (!strict_mode) {
10254 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10261 errorf(HERE, "stray %K outside of function", &token);
10262 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10263 eat_until_matching_token(token.kind);
10269 static void parse_externals(void)
10271 add_anchor_token('}');
10272 add_anchor_token(T_EOF);
10275 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10276 unsigned short token_anchor_copy[T_LAST_TOKEN];
10277 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10280 while (token.kind != T_EOF && token.kind != '}') {
10282 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10283 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10285 /* the anchor set and its copy differs */
10286 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10289 if (in_gcc_extension) {
10290 /* an gcc extension scope was not closed */
10291 internal_errorf(HERE, "Leaked __extension__");
10298 rem_anchor_token(T_EOF);
10299 rem_anchor_token('}');
10303 * Parse a translation unit.
10305 static void parse_translation_unit(void)
10307 add_anchor_token(T_EOF);
10312 if (token.kind == T_EOF)
10315 errorf(HERE, "stray %K outside of function", &token);
10316 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10317 eat_until_matching_token(token.kind);
10322 void set_default_visibility(elf_visibility_tag_t visibility)
10324 default_visibility = visibility;
10330 * @return the translation unit or NULL if errors occurred.
10332 void start_parsing(void)
10334 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10335 label_stack = NEW_ARR_F(stack_entry_t, 0);
10337 print_to_file(stderr);
10339 assert(unit == NULL);
10340 unit = allocate_ast_zero(sizeof(unit[0]));
10342 assert(file_scope == NULL);
10343 file_scope = &unit->scope;
10345 assert(current_scope == NULL);
10346 scope_push(&unit->scope);
10348 create_gnu_builtins();
10350 create_microsoft_intrinsics();
10353 translation_unit_t *finish_parsing(void)
10355 assert(current_scope == &unit->scope);
10358 assert(file_scope == &unit->scope);
10359 check_unused_globals();
10362 DEL_ARR_F(environment_stack);
10363 DEL_ARR_F(label_stack);
10365 translation_unit_t *result = unit;
10370 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10371 * are given length one. */
10372 static void complete_incomplete_arrays(void)
10374 size_t n = ARR_LEN(incomplete_arrays);
10375 for (size_t i = 0; i != n; ++i) {
10376 declaration_t *const decl = incomplete_arrays[i];
10377 type_t *const type = skip_typeref(decl->type);
10379 if (!is_type_incomplete(type))
10382 position_t const *const pos = &decl->base.pos;
10383 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10385 type_t *const new_type = duplicate_type(type);
10386 new_type->array.size_constant = true;
10387 new_type->array.has_implicit_size = true;
10388 new_type->array.size = 1;
10390 type_t *const result = identify_new_type(new_type);
10392 decl->type = result;
10396 static void prepare_main_collect2(entity_t *const entity)
10398 PUSH_SCOPE(&entity->function.body->compound.scope);
10400 // create call to __main
10401 symbol_t *symbol = symbol_table_insert("__main");
10402 entity_t *subsubmain_ent
10403 = create_implicit_function(symbol, &builtin_position);
10405 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10406 type_t *ftype = subsubmain_ent->declaration.type;
10407 ref->base.pos = builtin_position;
10408 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10409 ref->reference.entity = subsubmain_ent;
10411 expression_t *call = allocate_expression_zero(EXPR_CALL);
10412 call->base.pos = builtin_position;
10413 call->base.type = type_void;
10414 call->call.function = ref;
10416 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10417 expr_statement->base.pos = builtin_position;
10418 expr_statement->expression.expression = call;
10420 statement_t *const body = entity->function.body;
10421 assert(body->kind == STATEMENT_COMPOUND);
10422 compound_statement_t *compounds = &body->compound;
10424 expr_statement->base.next = compounds->statements;
10425 compounds->statements = expr_statement;
10432 lookahead_bufpos = 0;
10433 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10436 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10437 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10438 parse_translation_unit();
10439 complete_incomplete_arrays();
10440 DEL_ARR_F(incomplete_arrays);
10441 incomplete_arrays = NULL;
10445 * Initialize the parser.
10447 void init_parser(void)
10449 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10451 init_expression_parsers();
10452 obstack_init(&temp_obst);
10456 * Terminate the parser.
10458 void exit_parser(void)
10460 obstack_free(&temp_obst, NULL);