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 (type == type_void_ptr)
860 expression = expression->unary.value;
863 switch (is_constant_expression(expression)) {
864 case EXPR_CLASS_VARIABLE: return false;
865 case EXPR_CLASS_ERROR: return true;
866 case EXPR_CLASS_CONSTANT: return false;
867 case EXPR_CLASS_INTEGER_CONSTANT: return !fold_constant_to_bool(expression);
869 panic("invalid expression classification");
873 * Create an implicit cast expression.
875 * @param expression the expression to cast
876 * @param dest_type the destination type
878 static expression_t *create_implicit_cast(expression_t *expression,
881 type_t *const source_type = skip_typeref(expression->base.type);
882 if (source_type == skip_typeref(dest_type))
885 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
886 cast->unary.value = expression;
887 cast->base.type = dest_type;
888 cast->base.implicit = true;
893 typedef enum assign_error_t {
895 ASSIGN_ERROR_INCOMPATIBLE,
896 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
897 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
898 ASSIGN_WARNING_POINTER_FROM_INT,
899 ASSIGN_WARNING_INT_FROM_POINTER
902 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)
904 type_t *const orig_type_right = right->base.type;
905 type_t *const type_left = skip_typeref(orig_type_left);
906 type_t *const type_right = skip_typeref(orig_type_right);
911 case ASSIGN_ERROR_INCOMPATIBLE:
912 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
915 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
916 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
917 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
919 /* the left type has all qualifiers from the right type */
920 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
921 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);
925 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
926 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
929 case ASSIGN_WARNING_POINTER_FROM_INT:
930 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
933 case ASSIGN_WARNING_INT_FROM_POINTER:
934 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
938 panic("invalid error value");
942 /** Implements the rules from §6.5.16.1 */
943 static assign_error_t semantic_assign(type_t *orig_type_left,
944 const expression_t *const right)
946 type_t *const orig_type_right = right->base.type;
947 type_t *const type_left = skip_typeref(orig_type_left);
948 type_t *const type_right = skip_typeref(orig_type_right);
950 if (is_type_pointer(type_left)) {
951 if (is_null_pointer_constant(right)) {
952 return ASSIGN_SUCCESS;
953 } else if (is_type_pointer(type_right)) {
954 type_t *points_to_left
955 = skip_typeref(type_left->pointer.points_to);
956 type_t *points_to_right
957 = skip_typeref(type_right->pointer.points_to);
958 assign_error_t res = ASSIGN_SUCCESS;
960 /* the left type has all qualifiers from the right type */
961 unsigned missing_qualifiers
962 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
963 if (missing_qualifiers != 0) {
964 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
967 points_to_left = get_unqualified_type(points_to_left);
968 points_to_right = get_unqualified_type(points_to_right);
970 if (is_type_void(points_to_left))
973 if (is_type_void(points_to_right)) {
974 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
975 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
978 if (!types_compatible(points_to_left, points_to_right)) {
979 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
983 } else if (is_type_integer(type_right)) {
984 return ASSIGN_WARNING_POINTER_FROM_INT;
986 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
987 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
988 && is_type_pointer(type_right))) {
989 return ASSIGN_SUCCESS;
990 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
991 type_t *const unqual_type_left = get_unqualified_type(type_left);
992 type_t *const unqual_type_right = get_unqualified_type(type_right);
993 if (types_compatible(unqual_type_left, unqual_type_right)) {
994 return ASSIGN_SUCCESS;
996 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
997 return ASSIGN_WARNING_INT_FROM_POINTER;
1000 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1001 return ASSIGN_SUCCESS;
1003 return ASSIGN_ERROR_INCOMPATIBLE;
1006 static expression_t *parse_constant_expression(void)
1008 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1010 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1011 errorf(&result->base.pos, "expression '%E' is not constant", result);
1017 static expression_t *parse_assignment_expression(void)
1019 return parse_subexpression(PREC_ASSIGNMENT);
1022 static void append_string(string_t const *const s)
1024 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1025 * possible, because other tokens are grown there alongside. */
1026 obstack_grow(&ast_obstack, s->begin, s->size);
1029 static string_t finish_string(string_encoding_t const enc)
1031 obstack_1grow(&ast_obstack, '\0');
1032 size_t const size = obstack_object_size(&ast_obstack) - 1;
1033 char const *const string = obstack_finish(&ast_obstack);
1034 return (string_t){ string, size, enc };
1037 static string_t concat_string_literals(void)
1039 assert(token.kind == T_STRING_LITERAL);
1042 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1043 append_string(&token.literal.string);
1044 eat(T_STRING_LITERAL);
1045 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1046 string_encoding_t enc = token.literal.string.encoding;
1048 string_encoding_t const new_enc = token.literal.string.encoding;
1049 if (new_enc != enc && new_enc != STRING_ENCODING_CHAR) {
1050 if (enc == STRING_ENCODING_CHAR) {
1053 errorf(HERE, "concatenating string literals with encodings %s and %s", get_string_encoding_prefix(enc), get_string_encoding_prefix(new_enc));
1056 append_string(&token.literal.string);
1057 eat(T_STRING_LITERAL);
1058 } while (token.kind == T_STRING_LITERAL);
1059 result = finish_string(enc);
1061 result = token.literal.string;
1062 eat(T_STRING_LITERAL);
1068 static string_t parse_string_literals(char const *const context)
1070 if (!skip_till(T_STRING_LITERAL, context))
1071 return (string_t){ "", 0, STRING_ENCODING_CHAR };
1073 position_t const pos = *HERE;
1074 string_t const res = concat_string_literals();
1076 if (res.encoding != STRING_ENCODING_CHAR) {
1077 errorf(&pos, "expected plain string literal, got %s string literal", get_string_encoding_prefix(res.encoding));
1083 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1085 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1086 attribute->kind = kind;
1087 attribute->pos = *HERE;
1092 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1095 * __attribute__ ( ( attribute-list ) )
1099 * attribute_list , attrib
1104 * any-word ( identifier )
1105 * any-word ( identifier , nonempty-expr-list )
1106 * any-word ( expr-list )
1108 * where the "identifier" must not be declared as a type, and
1109 * "any-word" may be any identifier (including one declared as a
1110 * type), a reserved word storage class specifier, type specifier or
1111 * type qualifier. ??? This still leaves out most reserved keywords
1112 * (following the old parser), shouldn't we include them, and why not
1113 * allow identifiers declared as types to start the arguments?
1115 * Matze: this all looks confusing and little systematic, so we're even less
1116 * strict and parse any list of things which are identifiers or
1117 * (assignment-)expressions.
1119 static attribute_argument_t *parse_attribute_arguments(void)
1121 attribute_argument_t *first = NULL;
1122 attribute_argument_t **anchor = &first;
1123 if (token.kind != ')') do {
1124 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1126 /* is it an identifier */
1127 if (token.kind == T_IDENTIFIER
1128 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1129 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1130 argument->v.symbol = token.base.symbol;
1133 /* must be an expression */
1134 expression_t *expression = parse_assignment_expression();
1136 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1137 argument->v.expression = expression;
1140 /* append argument */
1142 anchor = &argument->next;
1143 } while (accept(','));
1148 static attribute_t *parse_attribute_asm(void)
1150 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1153 attribute->a.arguments = parse_attribute_arguments();
1157 static attribute_t *parse_attribute_gnu_single(void)
1159 /* parse "any-word" */
1160 symbol_t *const symbol = token.base.symbol;
1161 if (symbol == NULL) {
1162 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1166 attribute_kind_t kind;
1167 char const *const name = symbol->string;
1168 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1169 if (kind > ATTRIBUTE_GNU_LAST) {
1170 /* special case for "__const" */
1171 if (token.kind == T_const) {
1172 kind = ATTRIBUTE_GNU_CONST;
1176 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1177 /* TODO: we should still save the attribute in the list... */
1178 kind = ATTRIBUTE_UNKNOWN;
1182 const char *attribute_name = get_attribute_name(kind);
1183 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1187 attribute_t *attribute = allocate_attribute_zero(kind);
1190 /* parse arguments */
1192 attribute->a.arguments = parse_attribute_arguments();
1197 static attribute_t *parse_attribute_gnu(void)
1199 attribute_t *first = NULL;
1200 attribute_t **anchor = &first;
1202 eat(T___attribute__);
1203 add_anchor_token(')');
1204 add_anchor_token(',');
1208 if (token.kind != ')') do {
1209 attribute_t *attribute = parse_attribute_gnu_single();
1211 *anchor = attribute;
1212 anchor = &attribute->next;
1214 } while (accept(','));
1215 rem_anchor_token(',');
1216 rem_anchor_token(')');
1223 /** Parse attributes. */
1224 static attribute_t *parse_attributes(attribute_t *first)
1226 attribute_t **anchor = &first;
1228 while (*anchor != NULL)
1229 anchor = &(*anchor)->next;
1231 attribute_t *attribute;
1232 switch (token.kind) {
1233 case T___attribute__:
1234 attribute = parse_attribute_gnu();
1235 if (attribute == NULL)
1240 attribute = parse_attribute_asm();
1244 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1249 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1253 case T__forceinline:
1254 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1255 eat(T__forceinline);
1259 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1264 /* TODO record modifier */
1265 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1266 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1274 *anchor = attribute;
1275 anchor = &attribute->next;
1279 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1281 static entity_t *determine_lhs_ent(expression_t *const expr,
1284 switch (expr->kind) {
1285 case EXPR_REFERENCE: {
1286 entity_t *const entity = expr->reference.entity;
1287 /* we should only find variables as lvalues... */
1288 if (entity->base.kind != ENTITY_VARIABLE
1289 && entity->base.kind != ENTITY_PARAMETER)
1295 case EXPR_ARRAY_ACCESS: {
1296 expression_t *const ref = expr->array_access.array_ref;
1297 entity_t * ent = NULL;
1298 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1299 ent = determine_lhs_ent(ref, lhs_ent);
1302 mark_vars_read(ref, lhs_ent);
1304 mark_vars_read(expr->array_access.index, lhs_ent);
1309 mark_vars_read(expr->select.compound, lhs_ent);
1310 if (is_type_compound(skip_typeref(expr->base.type)))
1311 return determine_lhs_ent(expr->select.compound, lhs_ent);
1315 case EXPR_UNARY_DEREFERENCE: {
1316 expression_t *const val = expr->unary.value;
1317 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1319 return determine_lhs_ent(val->unary.value, lhs_ent);
1321 mark_vars_read(val, NULL);
1327 mark_vars_read(expr, NULL);
1332 #define ENT_ANY ((entity_t*)-1)
1335 * Mark declarations, which are read. This is used to detect variables, which
1339 * x is not marked as "read", because it is only read to calculate its own new
1343 * x and y are not detected as "not read", because multiple variables are
1346 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1348 switch (expr->kind) {
1349 case EXPR_REFERENCE: {
1350 entity_t *const entity = expr->reference.entity;
1351 if (entity->kind != ENTITY_VARIABLE
1352 && entity->kind != ENTITY_PARAMETER)
1355 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1356 entity->variable.read = true;
1362 // TODO respect pure/const
1363 mark_vars_read(expr->call.function, NULL);
1364 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1365 mark_vars_read(arg->expression, NULL);
1369 case EXPR_CONDITIONAL:
1370 // TODO lhs_decl should depend on whether true/false have an effect
1371 mark_vars_read(expr->conditional.condition, NULL);
1372 if (expr->conditional.true_expression != NULL)
1373 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1374 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1378 if (lhs_ent == ENT_ANY
1379 && !is_type_compound(skip_typeref(expr->base.type)))
1381 mark_vars_read(expr->select.compound, lhs_ent);
1384 case EXPR_ARRAY_ACCESS: {
1385 mark_vars_read(expr->array_access.index, lhs_ent);
1386 expression_t *const ref = expr->array_access.array_ref;
1387 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1388 if (lhs_ent == ENT_ANY)
1391 mark_vars_read(ref, lhs_ent);
1396 mark_vars_read(expr->va_arge.ap, lhs_ent);
1400 mark_vars_read(expr->va_copye.src, lhs_ent);
1403 case EXPR_UNARY_CAST:
1404 /* Special case: Use void cast to mark a variable as "read" */
1405 if (is_type_void(skip_typeref(expr->base.type)))
1410 case EXPR_UNARY_THROW:
1411 if (expr->unary.value == NULL)
1414 case EXPR_UNARY_DEREFERENCE:
1415 case EXPR_UNARY_DELETE:
1416 case EXPR_UNARY_DELETE_ARRAY:
1417 if (lhs_ent == ENT_ANY)
1421 case EXPR_UNARY_NEGATE:
1422 case EXPR_UNARY_PLUS:
1423 case EXPR_UNARY_COMPLEMENT:
1424 case EXPR_UNARY_NOT:
1425 case EXPR_UNARY_TAKE_ADDRESS:
1426 case EXPR_UNARY_POSTFIX_INCREMENT:
1427 case EXPR_UNARY_POSTFIX_DECREMENT:
1428 case EXPR_UNARY_PREFIX_INCREMENT:
1429 case EXPR_UNARY_PREFIX_DECREMENT:
1430 case EXPR_UNARY_ASSUME:
1431 case EXPR_UNARY_IMAG:
1432 case EXPR_UNARY_REAL:
1434 mark_vars_read(expr->unary.value, lhs_ent);
1437 case EXPR_BINARY_ADD:
1438 case EXPR_BINARY_SUB:
1439 case EXPR_BINARY_MUL:
1440 case EXPR_BINARY_DIV:
1441 case EXPR_BINARY_MOD:
1442 case EXPR_BINARY_EQUAL:
1443 case EXPR_BINARY_NOTEQUAL:
1444 case EXPR_BINARY_LESS:
1445 case EXPR_BINARY_LESSEQUAL:
1446 case EXPR_BINARY_GREATER:
1447 case EXPR_BINARY_GREATEREQUAL:
1448 case EXPR_BINARY_BITWISE_AND:
1449 case EXPR_BINARY_BITWISE_OR:
1450 case EXPR_BINARY_BITWISE_XOR:
1451 case EXPR_BINARY_LOGICAL_AND:
1452 case EXPR_BINARY_LOGICAL_OR:
1453 case EXPR_BINARY_SHIFTLEFT:
1454 case EXPR_BINARY_SHIFTRIGHT:
1455 case EXPR_BINARY_COMMA:
1456 case EXPR_BINARY_ISGREATER:
1457 case EXPR_BINARY_ISGREATEREQUAL:
1458 case EXPR_BINARY_ISLESS:
1459 case EXPR_BINARY_ISLESSEQUAL:
1460 case EXPR_BINARY_ISLESSGREATER:
1461 case EXPR_BINARY_ISUNORDERED:
1462 mark_vars_read(expr->binary.left, lhs_ent);
1463 mark_vars_read(expr->binary.right, lhs_ent);
1466 case EXPR_BINARY_ASSIGN:
1467 case EXPR_BINARY_MUL_ASSIGN:
1468 case EXPR_BINARY_DIV_ASSIGN:
1469 case EXPR_BINARY_MOD_ASSIGN:
1470 case EXPR_BINARY_ADD_ASSIGN:
1471 case EXPR_BINARY_SUB_ASSIGN:
1472 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1473 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1474 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1475 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1476 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1477 if (lhs_ent == ENT_ANY)
1479 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1480 mark_vars_read(expr->binary.right, lhs_ent);
1485 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1488 case EXPR_LITERAL_CASES:
1489 case EXPR_LITERAL_CHARACTER:
1491 case EXPR_STRING_LITERAL:
1492 case EXPR_COMPOUND_LITERAL: // TODO init?
1494 case EXPR_CLASSIFY_TYPE:
1497 case EXPR_BUILTIN_CONSTANT_P:
1498 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1500 case EXPR_STATEMENT: // TODO
1501 case EXPR_LABEL_ADDRESS:
1502 case EXPR_ENUM_CONSTANT:
1506 panic("unhandled expression");
1509 static designator_t *parse_designation(void)
1511 designator_t *result = NULL;
1512 designator_t **anchor = &result;
1515 designator_t *designator;
1516 switch (token.kind) {
1518 designator = allocate_ast_zero(sizeof(designator[0]));
1519 designator->pos = *HERE;
1521 add_anchor_token(']');
1522 add_anchor_token(T_DOTDOTDOT);
1523 designator->array_index = parse_constant_expression();
1524 if (accept(T_DOTDOTDOT)) {
1525 designator->range_last = parse_constant_expression();
1526 errorf(&designator->pos, "range initializer not supported");
1528 rem_anchor_token(T_DOTDOTDOT);
1529 rem_anchor_token(']');
1533 designator = allocate_ast_zero(sizeof(designator[0]));
1534 designator->pos = *HERE;
1536 designator->symbol = expect_identifier("while parsing designator", NULL);
1537 if (!designator->symbol)
1545 assert(designator != NULL);
1546 *anchor = designator;
1547 anchor = &designator->next;
1552 * Build an initializer from a given expression.
1554 static initializer_t *initializer_from_expression(type_t *orig_type,
1555 expression_t *expression)
1557 /* TODO check that expression is a constant expression */
1559 type_t *const type = skip_typeref(orig_type);
1561 /* §6.7.8.14/15 char array may be initialized by string literals */
1562 if (expression->kind == EXPR_STRING_LITERAL && is_type_array(type)) {
1563 array_type_t *const array_type = &type->array;
1564 type_t *const element_type = skip_typeref(array_type->element_type);
1565 switch (expression->string_literal.value.encoding) {
1566 case STRING_ENCODING_CHAR:
1567 case STRING_ENCODING_UTF8: {
1568 if (is_type_atomic(element_type, ATOMIC_TYPE_CHAR) ||
1569 is_type_atomic(element_type, ATOMIC_TYPE_SCHAR) ||
1570 is_type_atomic(element_type, ATOMIC_TYPE_UCHAR)) {
1571 goto make_string_init;
1576 case STRING_ENCODING_CHAR16:
1577 case STRING_ENCODING_CHAR32:
1578 case STRING_ENCODING_WIDE: {
1579 assert(is_type_pointer(expression->base.type));
1580 type_t *const init_type = get_unqualified_type(expression->base.type->pointer.points_to);
1581 if (types_compatible(get_unqualified_type(element_type), init_type)) {
1583 initializer_t *const init = allocate_initializer_zero(INITIALIZER_STRING);
1584 init->value.value = expression;
1592 assign_error_t error = semantic_assign(type, expression);
1593 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1595 report_assign_error(error, type, expression, "initializer",
1596 &expression->base.pos);
1598 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1599 result->value.value = create_implicit_cast(expression, type);
1605 * Parses an scalar initializer.
1607 * §6.7.8.11; eat {} without warning
1609 static initializer_t *parse_scalar_initializer(type_t *type,
1610 bool must_be_constant)
1612 /* there might be extra {} hierarchies */
1614 if (token.kind == '{') {
1615 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1619 } while (token.kind == '{');
1622 expression_t *expression = parse_assignment_expression();
1623 mark_vars_read(expression, NULL);
1624 if (must_be_constant && !is_linker_constant(expression)) {
1625 errorf(&expression->base.pos,
1626 "initialisation expression '%E' is not constant",
1630 initializer_t *initializer = initializer_from_expression(type, expression);
1632 if (initializer == NULL) {
1633 errorf(&expression->base.pos,
1634 "expression '%E' (type '%T') doesn't match expected type '%T'",
1635 expression, expression->base.type, type);
1640 bool additional_warning_displayed = false;
1641 while (braces > 0) {
1643 if (token.kind != '}') {
1644 if (!additional_warning_displayed) {
1645 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1646 additional_warning_displayed = true;
1657 * An entry in the type path.
1659 typedef struct type_path_entry_t type_path_entry_t;
1660 struct type_path_entry_t {
1661 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1663 size_t index; /**< For array types: the current index. */
1664 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1669 * A type path expression a position inside compound or array types.
1671 typedef struct type_path_t type_path_t;
1672 struct type_path_t {
1673 type_path_entry_t *path; /**< An flexible array containing the current path. */
1674 type_t *top_type; /**< type of the element the path points */
1675 size_t max_index; /**< largest index in outermost array */
1679 * Prints a type path for debugging.
1681 static __attribute__((unused)) void debug_print_type_path(
1682 const type_path_t *path)
1684 size_t len = ARR_LEN(path->path);
1686 for (size_t i = 0; i < len; ++i) {
1687 const type_path_entry_t *entry = & path->path[i];
1689 type_t *type = skip_typeref(entry->type);
1690 if (is_type_compound(type)) {
1691 /* in gcc mode structs can have no members */
1692 if (entry->v.compound_entry == NULL) {
1696 fprintf(stderr, ".%s",
1697 entry->v.compound_entry->base.symbol->string);
1698 } else if (is_type_array(type)) {
1699 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1701 fprintf(stderr, "-INVALID-");
1704 if (path->top_type != NULL) {
1705 fprintf(stderr, " (");
1706 print_type(path->top_type);
1707 fprintf(stderr, ")");
1712 * Return the top type path entry, i.e. in a path
1713 * (type).a.b returns the b.
1715 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1717 size_t len = ARR_LEN(path->path);
1719 return &path->path[len-1];
1723 * Enlarge the type path by an (empty) element.
1725 static type_path_entry_t *append_to_type_path(type_path_t *path)
1727 size_t len = ARR_LEN(path->path);
1728 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1730 type_path_entry_t *result = & path->path[len];
1731 memset(result, 0, sizeof(result[0]));
1736 * Descending into a sub-type. Enter the scope of the current top_type.
1738 static void descend_into_subtype(type_path_t *path)
1740 type_t *orig_top_type = path->top_type;
1741 type_t *top_type = skip_typeref(orig_top_type);
1743 type_path_entry_t *top = append_to_type_path(path);
1744 top->type = top_type;
1746 if (is_type_compound(top_type)) {
1747 compound_t *const compound = top_type->compound.compound;
1748 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1750 if (entry != NULL) {
1751 top->v.compound_entry = &entry->declaration;
1752 path->top_type = entry->declaration.type;
1754 path->top_type = NULL;
1756 } else if (is_type_array(top_type)) {
1758 path->top_type = top_type->array.element_type;
1760 assert(!is_type_valid(top_type));
1765 * Pop an entry from the given type path, i.e. returning from
1766 * (type).a.b to (type).a
1768 static void ascend_from_subtype(type_path_t *path)
1770 type_path_entry_t *top = get_type_path_top(path);
1772 path->top_type = top->type;
1774 size_t len = ARR_LEN(path->path);
1775 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1779 * Pop entries from the given type path until the given
1780 * path level is reached.
1782 static void ascend_to(type_path_t *path, size_t top_path_level)
1784 size_t len = ARR_LEN(path->path);
1786 while (len > top_path_level) {
1787 ascend_from_subtype(path);
1788 len = ARR_LEN(path->path);
1792 static bool walk_designator(type_path_t *path, const designator_t *designator,
1793 bool used_in_offsetof)
1795 for (; designator != NULL; designator = designator->next) {
1796 type_path_entry_t *top = get_type_path_top(path);
1797 type_t *orig_type = top->type;
1799 type_t *type = skip_typeref(orig_type);
1801 if (designator->symbol != NULL) {
1802 symbol_t *symbol = designator->symbol;
1803 if (!is_type_compound(type)) {
1804 if (is_type_valid(type)) {
1805 errorf(&designator->pos,
1806 "'.%Y' designator used for non-compound type '%T'",
1810 top->type = type_error_type;
1811 top->v.compound_entry = NULL;
1812 orig_type = type_error_type;
1814 compound_t *compound = type->compound.compound;
1815 entity_t *iter = compound->members.entities;
1816 for (; iter != NULL; iter = iter->base.next) {
1817 if (iter->base.symbol == symbol) {
1822 errorf(&designator->pos,
1823 "'%T' has no member named '%Y'", orig_type, symbol);
1826 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1827 if (used_in_offsetof && iter->compound_member.bitfield) {
1828 errorf(&designator->pos,
1829 "offsetof designator '%Y' must not specify bitfield",
1834 top->type = orig_type;
1835 top->v.compound_entry = &iter->declaration;
1836 orig_type = iter->declaration.type;
1839 expression_t *array_index = designator->array_index;
1840 if (is_constant_expression(array_index) < EXPR_CLASS_CONSTANT)
1843 if (!is_type_array(type)) {
1844 if (is_type_valid(type)) {
1845 errorf(&designator->pos,
1846 "[%E] designator used for non-array type '%T'",
1847 array_index, orig_type);
1852 long index = fold_constant_to_int(array_index);
1853 if (!used_in_offsetof) {
1855 errorf(&designator->pos,
1856 "array index [%E] must be positive", array_index);
1857 } else if (type->array.size_constant) {
1858 long array_size = type->array.size;
1859 if (index >= array_size) {
1860 errorf(&designator->pos,
1861 "designator [%E] (%d) exceeds array size %d",
1862 array_index, index, array_size);
1867 top->type = orig_type;
1868 top->v.index = (size_t) index;
1869 orig_type = type->array.element_type;
1871 path->top_type = orig_type;
1873 if (designator->next != NULL) {
1874 descend_into_subtype(path);
1880 static void advance_current_object(type_path_t *path, size_t top_path_level)
1882 type_path_entry_t *top = get_type_path_top(path);
1884 type_t *type = skip_typeref(top->type);
1885 if (is_type_union(type)) {
1886 /* in unions only the first element is initialized */
1887 top->v.compound_entry = NULL;
1888 } else if (is_type_struct(type)) {
1889 declaration_t *entry = top->v.compound_entry;
1891 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1892 if (next_entity != NULL) {
1893 assert(is_declaration(next_entity));
1894 entry = &next_entity->declaration;
1899 top->v.compound_entry = entry;
1900 if (entry != NULL) {
1901 path->top_type = entry->type;
1904 } else if (is_type_array(type)) {
1905 assert(is_type_array(type));
1909 if (!type->array.size_constant || top->v.index < type->array.size) {
1913 assert(!is_type_valid(type));
1917 /* we're past the last member of the current sub-aggregate, try if we
1918 * can ascend in the type hierarchy and continue with another subobject */
1919 size_t len = ARR_LEN(path->path);
1921 if (len > top_path_level) {
1922 ascend_from_subtype(path);
1923 advance_current_object(path, top_path_level);
1925 path->top_type = NULL;
1930 * skip any {...} blocks until a closing bracket is reached.
1932 static void skip_initializers(void)
1936 while (token.kind != '}') {
1937 if (token.kind == T_EOF)
1939 if (token.kind == '{') {
1947 static initializer_t *create_empty_initializer(void)
1949 static initializer_t empty_initializer
1950 = { .list = { { INITIALIZER_LIST }, 0 } };
1951 return &empty_initializer;
1955 * Parse a part of an initialiser for a struct or union,
1957 static initializer_t *parse_sub_initializer(type_path_t *path,
1958 type_t *outer_type, size_t top_path_level,
1959 parse_initializer_env_t *env)
1961 if (token.kind == '}') {
1962 /* empty initializer */
1963 return create_empty_initializer();
1966 initializer_t *result = NULL;
1968 type_t *orig_type = path->top_type;
1969 type_t *type = NULL;
1971 if (orig_type == NULL) {
1972 /* We are initializing an empty compound. */
1974 type = skip_typeref(orig_type);
1977 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1980 designator_t *designator = NULL;
1981 if (token.kind == '.' || token.kind == '[') {
1982 designator = parse_designation();
1983 goto finish_designator;
1984 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1985 /* GNU-style designator ("identifier: value") */
1986 designator = allocate_ast_zero(sizeof(designator[0]));
1987 designator->pos = *HERE;
1988 designator->symbol = token.base.symbol;
1993 /* reset path to toplevel, evaluate designator from there */
1994 ascend_to(path, top_path_level);
1995 if (!walk_designator(path, designator, false)) {
1996 /* can't continue after designation error */
2000 initializer_t *designator_initializer
2001 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2002 designator_initializer->designator.designator = designator;
2003 ARR_APP1(initializer_t*, initializers, designator_initializer);
2005 orig_type = path->top_type;
2006 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2011 if (token.kind == '{') {
2012 if (type != NULL && is_type_scalar(type)) {
2013 sub = parse_scalar_initializer(type, env->must_be_constant);
2016 if (env->entity != NULL) {
2017 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2019 errorf(HERE, "extra brace group at end of initializer");
2024 descend_into_subtype(path);
2027 add_anchor_token('}');
2028 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2030 rem_anchor_token('}');
2035 goto error_parse_next;
2037 ascend_from_subtype(path);
2040 /* must be an expression */
2041 expression_t *expression = parse_assignment_expression();
2042 mark_vars_read(expression, NULL);
2044 if (env->must_be_constant && !is_linker_constant(expression)) {
2045 errorf(&expression->base.pos,
2046 "Initialisation expression '%E' is not constant",
2051 /* we are already outside, ... */
2052 if (outer_type == NULL)
2053 goto error_parse_next;
2054 type_t *const outer_type_skip = skip_typeref(outer_type);
2055 if (is_type_compound(outer_type_skip) &&
2056 !outer_type_skip->compound.compound->complete) {
2057 goto error_parse_next;
2060 position_t const* const pos = &expression->base.pos;
2061 if (env->entity != NULL) {
2062 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2064 warningf(WARN_OTHER, pos, "excess elements in initializer");
2066 goto error_parse_next;
2069 /* handle { "string" } special case */
2070 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2071 result = initializer_from_expression(outer_type, expression);
2072 if (result != NULL) {
2074 if (token.kind != '}') {
2075 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", outer_type);
2077 /* TODO: eat , ... */
2082 /* descend into subtypes until expression matches type */
2084 orig_type = path->top_type;
2085 type = skip_typeref(orig_type);
2087 sub = initializer_from_expression(orig_type, expression);
2091 if (!is_type_valid(type)) {
2094 if (is_type_scalar(type)) {
2095 errorf(&expression->base.pos,
2096 "expression '%E' doesn't match expected type '%T'",
2097 expression, orig_type);
2101 descend_into_subtype(path);
2105 /* update largest index of top array */
2106 const type_path_entry_t *first = &path->path[0];
2107 type_t *first_type = first->type;
2108 first_type = skip_typeref(first_type);
2109 if (is_type_array(first_type)) {
2110 size_t index = first->v.index;
2111 if (index > path->max_index)
2112 path->max_index = index;
2115 /* append to initializers list */
2116 ARR_APP1(initializer_t*, initializers, sub);
2121 if (token.kind == '}') {
2126 /* advance to the next declaration if we are not at the end */
2127 advance_current_object(path, top_path_level);
2128 orig_type = path->top_type;
2129 if (orig_type != NULL)
2130 type = skip_typeref(orig_type);
2136 size_t len = ARR_LEN(initializers);
2137 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2138 result = allocate_ast_zero(size);
2139 result->kind = INITIALIZER_LIST;
2140 result->list.len = len;
2141 memcpy(&result->list.initializers, initializers,
2142 len * sizeof(initializers[0]));
2146 skip_initializers();
2148 DEL_ARR_F(initializers);
2149 ascend_to(path, top_path_level+1);
2153 static expression_t *make_size_literal(size_t value)
2155 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2156 literal->base.type = type_size_t;
2159 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2160 literal->literal.value = make_string(buf);
2166 * Parses an initializer. Parsers either a compound literal
2167 * (env->declaration == NULL) or an initializer of a declaration.
2169 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2171 type_t *type = skip_typeref(env->type);
2172 size_t max_index = 0;
2173 initializer_t *result;
2175 if (is_type_scalar(type)) {
2176 result = parse_scalar_initializer(type, env->must_be_constant);
2177 } else if (token.kind == '{') {
2181 memset(&path, 0, sizeof(path));
2182 path.top_type = env->type;
2183 path.path = NEW_ARR_F(type_path_entry_t, 0);
2185 descend_into_subtype(&path);
2187 add_anchor_token('}');
2188 result = parse_sub_initializer(&path, env->type, 1, env);
2189 rem_anchor_token('}');
2191 max_index = path.max_index;
2192 DEL_ARR_F(path.path);
2196 /* parse_scalar_initializer() also works in this case: we simply
2197 * have an expression without {} around it */
2198 result = parse_scalar_initializer(type, env->must_be_constant);
2201 /* §6.7.8:22 array initializers for arrays with unknown size determine
2202 * the array type size */
2203 if (is_type_array(type) && type->array.size_expression == NULL
2204 && result != NULL) {
2206 switch (result->kind) {
2207 case INITIALIZER_LIST:
2208 assert(max_index != 0xdeadbeaf);
2209 size = max_index + 1;
2212 case INITIALIZER_STRING: {
2213 size = get_string_len(&get_init_string(result)->value) + 1;
2217 case INITIALIZER_DESIGNATOR:
2218 case INITIALIZER_VALUE:
2219 /* can happen for parse errors */
2224 internal_errorf(HERE, "invalid initializer type");
2227 type_t *new_type = duplicate_type(type);
2229 new_type->array.size_expression = make_size_literal(size);
2230 new_type->array.size_constant = true;
2231 new_type->array.has_implicit_size = true;
2232 new_type->array.size = size;
2233 env->type = new_type;
2239 static void append_entity(scope_t *scope, entity_t *entity)
2241 if (scope->last_entity != NULL) {
2242 scope->last_entity->base.next = entity;
2244 scope->entities = entity;
2246 entity->base.parent_entity = current_entity;
2247 scope->last_entity = entity;
2251 static compound_t *parse_compound_type_specifier(bool is_struct)
2253 position_t const pos = *HERE;
2254 eat(is_struct ? T_struct : T_union);
2256 symbol_t *symbol = NULL;
2257 entity_t *entity = NULL;
2258 attribute_t *attributes = NULL;
2260 if (token.kind == T___attribute__) {
2261 attributes = parse_attributes(NULL);
2264 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2265 if (token.kind == T_IDENTIFIER) {
2266 /* the compound has a name, check if we have seen it already */
2267 symbol = token.base.symbol;
2268 entity = get_tag(symbol, kind);
2271 if (entity != NULL) {
2272 if (entity->base.parent_scope != current_scope &&
2273 (token.kind == '{' || token.kind == ';')) {
2274 /* we're in an inner scope and have a definition. Shadow
2275 * existing definition in outer scope */
2277 } else if (entity->compound.complete && token.kind == '{') {
2278 position_t const *const ppos = &entity->base.pos;
2279 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2280 /* clear members in the hope to avoid further errors */
2281 entity->compound.members.entities = NULL;
2284 } else if (token.kind != '{') {
2285 char const *const msg =
2286 is_struct ? "while parsing struct type specifier" :
2287 "while parsing union type specifier";
2288 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2293 if (entity == NULL) {
2294 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2295 entity->compound.alignment = 1;
2296 entity->base.parent_scope = current_scope;
2297 if (symbol != NULL) {
2298 environment_push(entity);
2300 append_entity(current_scope, entity);
2303 if (token.kind == '{') {
2304 parse_compound_type_entries(&entity->compound);
2306 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2307 if (symbol == NULL) {
2308 assert(anonymous_entity == NULL);
2309 anonymous_entity = entity;
2313 if (attributes != NULL) {
2314 entity->compound.attributes = attributes;
2315 handle_entity_attributes(attributes, entity);
2318 return &entity->compound;
2321 static void parse_enum_entries(type_t *const enum_type)
2325 if (token.kind == '}') {
2326 errorf(HERE, "empty enum not allowed");
2331 add_anchor_token('}');
2332 add_anchor_token(',');
2334 add_anchor_token('=');
2336 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2337 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2338 entity->enum_value.enum_type = enum_type;
2339 rem_anchor_token('=');
2342 expression_t *value = parse_constant_expression();
2344 value = create_implicit_cast(value, enum_type);
2345 entity->enum_value.value = value;
2350 record_entity(entity, false);
2351 } while (accept(',') && token.kind != '}');
2352 rem_anchor_token(',');
2353 rem_anchor_token('}');
2358 static type_t *parse_enum_specifier(void)
2360 position_t const pos = *HERE;
2365 switch (token.kind) {
2367 symbol = token.base.symbol;
2368 entity = get_tag(symbol, ENTITY_ENUM);
2371 if (entity != NULL) {
2372 if (entity->base.parent_scope != current_scope &&
2373 (token.kind == '{' || token.kind == ';')) {
2374 /* we're in an inner scope and have a definition. Shadow
2375 * existing definition in outer scope */
2377 } else if (entity->enume.complete && token.kind == '{') {
2378 position_t const *const ppos = &entity->base.pos;
2379 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2390 parse_error_expected("while parsing enum type specifier",
2391 T_IDENTIFIER, '{', NULL);
2395 if (entity == NULL) {
2396 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2397 entity->base.parent_scope = current_scope;
2400 type_t *const type = allocate_type_zero(TYPE_ENUM);
2401 type->enumt.enume = &entity->enume;
2402 type->enumt.base.akind = ATOMIC_TYPE_INT;
2404 if (token.kind == '{') {
2405 if (symbol != NULL) {
2406 environment_push(entity);
2408 append_entity(current_scope, entity);
2409 entity->enume.complete = true;
2411 parse_enum_entries(type);
2412 parse_attributes(NULL);
2414 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2415 if (symbol == NULL) {
2416 assert(anonymous_entity == NULL);
2417 anonymous_entity = entity;
2419 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2420 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2427 * if a symbol is a typedef to another type, return true
2429 static bool is_typedef_symbol(symbol_t *symbol)
2431 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2432 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2435 static type_t *parse_typeof(void)
2441 add_anchor_token(')');
2444 expression_t *expression = NULL;
2446 switch (token.kind) {
2448 if (is_typedef_symbol(token.base.symbol)) {
2450 type = parse_typename();
2453 expression = parse_expression();
2454 type = revert_automatic_type_conversion(expression);
2459 rem_anchor_token(')');
2462 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2463 typeof_type->typeoft.expression = expression;
2464 typeof_type->typeoft.typeof_type = type;
2469 typedef enum specifiers_t {
2471 SPECIFIER_SIGNED = 1 << 0,
2472 SPECIFIER_UNSIGNED = 1 << 1,
2473 SPECIFIER_LONG = 1 << 2,
2474 SPECIFIER_INT = 1 << 3,
2475 SPECIFIER_DOUBLE = 1 << 4,
2476 SPECIFIER_CHAR = 1 << 5,
2477 SPECIFIER_WCHAR_T = 1 << 6,
2478 SPECIFIER_SHORT = 1 << 7,
2479 SPECIFIER_LONG_LONG = 1 << 8,
2480 SPECIFIER_FLOAT = 1 << 9,
2481 SPECIFIER_BOOL = 1 << 10,
2482 SPECIFIER_VOID = 1 << 11,
2483 SPECIFIER_INT8 = 1 << 12,
2484 SPECIFIER_INT16 = 1 << 13,
2485 SPECIFIER_INT32 = 1 << 14,
2486 SPECIFIER_INT64 = 1 << 15,
2487 SPECIFIER_INT128 = 1 << 16,
2488 SPECIFIER_COMPLEX = 1 << 17,
2489 SPECIFIER_IMAGINARY = 1 << 18,
2492 static type_t *get_typedef_type(symbol_t *symbol)
2494 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2495 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2498 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2499 type->typedeft.typedefe = &entity->typedefe;
2504 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2506 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2508 add_anchor_token(')');
2509 add_anchor_token(',');
2513 add_anchor_token('=');
2515 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2516 rem_anchor_token('=');
2518 symbol_t **prop = NULL;
2520 if (streq(prop_sym->string, "put")) {
2521 prop = &property->put_symbol;
2522 } else if (streq(prop_sym->string, "get")) {
2523 prop = &property->get_symbol;
2525 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2529 add_anchor_token(T_IDENTIFIER);
2531 rem_anchor_token(T_IDENTIFIER);
2533 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2535 *prop = sym ? sym : sym_anonymous;
2536 } while (accept(','));
2537 rem_anchor_token(',');
2538 rem_anchor_token(')');
2540 attribute->a.property = property;
2546 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2548 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2549 if (accept(T_restrict)) {
2550 kind = ATTRIBUTE_MS_RESTRICT;
2551 } else if (token.kind == T_IDENTIFIER) {
2552 char const *const name = token.base.symbol->string;
2553 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2555 const char *attribute_name = get_attribute_name(k);
2556 if (attribute_name != NULL && streq(attribute_name, name)) {
2562 if (kind == ATTRIBUTE_UNKNOWN) {
2563 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2566 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2570 attribute_t *attribute = allocate_attribute_zero(kind);
2573 if (kind == ATTRIBUTE_MS_PROPERTY) {
2574 return parse_attribute_ms_property(attribute);
2577 /* parse arguments */
2579 attribute->a.arguments = parse_attribute_arguments();
2584 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2588 add_anchor_token(')');
2590 if (token.kind != ')') {
2591 attribute_t **anchor = &first;
2593 while (*anchor != NULL)
2594 anchor = &(*anchor)->next;
2596 attribute_t *attribute
2597 = parse_microsoft_extended_decl_modifier_single();
2598 if (attribute == NULL)
2601 *anchor = attribute;
2602 anchor = &attribute->next;
2603 } while (accept(','));
2605 rem_anchor_token(')');
2610 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2612 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2613 if (is_declaration(entity)) {
2614 entity->declaration.type = type_error_type;
2615 entity->declaration.implicit = true;
2616 } else if (kind == ENTITY_TYPEDEF) {
2617 entity->typedefe.type = type_error_type;
2618 entity->typedefe.builtin = true;
2620 if (kind != ENTITY_COMPOUND_MEMBER)
2621 record_entity(entity, false);
2625 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2627 type_t *type = NULL;
2628 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2629 unsigned type_specifiers = 0;
2630 bool newtype = false;
2631 bool saw_error = false;
2633 memset(specifiers, 0, sizeof(*specifiers));
2634 specifiers->pos = *HERE;
2637 specifiers->attributes = parse_attributes(specifiers->attributes);
2639 switch (token.kind) {
2641 #define MATCH_STORAGE_CLASS(token, class) \
2643 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2644 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2646 specifiers->storage_class = class; \
2647 if (specifiers->thread_local) \
2648 goto check_thread_storage_class; \
2652 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2653 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2654 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2655 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2656 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2659 specifiers->attributes
2660 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2663 case T__Thread_local:
2664 if (specifiers->thread_local) {
2665 errorf(HERE, "duplicate %K", &token);
2667 specifiers->thread_local = true;
2668 check_thread_storage_class:
2669 switch (specifiers->storage_class) {
2670 case STORAGE_CLASS_EXTERN:
2671 case STORAGE_CLASS_NONE:
2672 case STORAGE_CLASS_STATIC:
2676 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2677 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2678 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2679 wrong_thread_storage_class:
2680 errorf(HERE, "%K used with '%s'", &token, wrong);
2687 /* type qualifiers */
2688 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2690 qualifiers |= qualifier; \
2694 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2695 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2696 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2697 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2698 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2699 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2700 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2701 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2703 /* type specifiers */
2704 #define MATCH_SPECIFIER(token, specifier, name) \
2706 if (type_specifiers & specifier) { \
2707 errorf(HERE, "multiple " name " type specifiers given"); \
2709 type_specifiers |= specifier; \
2714 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2715 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2716 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2717 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2718 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2719 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2720 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2721 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2722 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2723 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2724 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2725 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2726 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2727 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2728 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2729 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2730 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2731 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2735 specifiers->is_inline = true;
2739 case T__forceinline:
2740 eat(T__forceinline);
2741 specifiers->modifiers |= DM_FORCEINLINE;
2746 if (type_specifiers & SPECIFIER_LONG_LONG) {
2747 errorf(HERE, "too many long type specifiers given");
2748 } else if (type_specifiers & SPECIFIER_LONG) {
2749 type_specifiers |= SPECIFIER_LONG_LONG;
2751 type_specifiers |= SPECIFIER_LONG;
2756 #define CHECK_DOUBLE_TYPE() \
2757 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2760 CHECK_DOUBLE_TYPE();
2761 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2763 type->compound.compound = parse_compound_type_specifier(true);
2766 CHECK_DOUBLE_TYPE();
2767 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2768 type->compound.compound = parse_compound_type_specifier(false);
2771 CHECK_DOUBLE_TYPE();
2772 type = parse_enum_specifier();
2775 CHECK_DOUBLE_TYPE();
2776 type = parse_typeof();
2778 case T___builtin_va_list:
2779 CHECK_DOUBLE_TYPE();
2780 type = duplicate_type(type_valist);
2781 eat(T___builtin_va_list);
2784 case T_IDENTIFIER: {
2785 /* only parse identifier if we haven't found a type yet */
2786 if (type != NULL || type_specifiers != 0) {
2787 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2788 * declaration, so it doesn't generate errors about expecting '(' or
2790 switch (look_ahead(1)->kind) {
2797 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2801 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2806 goto finish_specifiers;
2810 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2811 if (typedef_type == NULL) {
2812 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2813 * declaration, so it doesn't generate 'implicit int' followed by more
2814 * errors later on. */
2815 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2821 errorf(HERE, "%K does not name a type", &token);
2823 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2825 type = allocate_type_zero(TYPE_TYPEDEF);
2826 type->typedeft.typedefe = &entity->typedefe;
2834 goto finish_specifiers;
2839 type = typedef_type;
2843 /* function specifier */
2845 goto finish_specifiers;
2850 specifiers->attributes = parse_attributes(specifiers->attributes);
2852 if (type == NULL || (saw_error && type_specifiers != 0)) {
2853 position_t const* const pos = &specifiers->pos;
2854 atomic_type_kind_t atomic_type;
2856 /* match valid basic types */
2857 switch (type_specifiers & ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2858 case SPECIFIER_VOID:
2859 if (type_specifiers & (SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2860 if (type_specifiers & SPECIFIER_COMPLEX)
2861 errorf(pos, "_Complex specifier is invalid for void");
2862 if (type_specifiers & SPECIFIER_IMAGINARY)
2863 errorf(pos, "_Imaginary specifier is invalid for void");
2864 type_specifiers &= ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY);
2866 atomic_type = ATOMIC_TYPE_VOID;
2868 case SPECIFIER_WCHAR_T:
2869 atomic_type = ATOMIC_TYPE_WCHAR_T;
2871 case SPECIFIER_CHAR:
2872 atomic_type = ATOMIC_TYPE_CHAR;
2874 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2875 atomic_type = ATOMIC_TYPE_SCHAR;
2877 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2878 atomic_type = ATOMIC_TYPE_UCHAR;
2880 case SPECIFIER_SHORT:
2881 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2882 case SPECIFIER_SHORT | SPECIFIER_INT:
2883 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2884 atomic_type = ATOMIC_TYPE_SHORT;
2886 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2887 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2888 atomic_type = ATOMIC_TYPE_USHORT;
2891 case SPECIFIER_SIGNED:
2892 case SPECIFIER_SIGNED | SPECIFIER_INT:
2893 atomic_type = ATOMIC_TYPE_INT;
2895 case SPECIFIER_UNSIGNED:
2896 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2897 atomic_type = ATOMIC_TYPE_UINT;
2899 case SPECIFIER_LONG:
2900 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2901 case SPECIFIER_LONG | SPECIFIER_INT:
2902 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2903 atomic_type = ATOMIC_TYPE_LONG;
2905 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2906 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2907 atomic_type = ATOMIC_TYPE_ULONG;
2910 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2911 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2912 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2913 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2915 atomic_type = ATOMIC_TYPE_LONGLONG;
2916 goto warn_about_long_long;
2918 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2919 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2921 atomic_type = ATOMIC_TYPE_ULONGLONG;
2922 warn_about_long_long:
2923 warningf(WARN_LONG_LONG, &specifiers->pos, "ISO C90 does not support 'long long'");
2926 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2927 atomic_type = unsigned_int8_type_kind;
2930 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2931 atomic_type = unsigned_int16_type_kind;
2934 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2935 atomic_type = unsigned_int32_type_kind;
2938 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2939 atomic_type = unsigned_int64_type_kind;
2942 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2943 atomic_type = unsigned_int128_type_kind;
2946 case SPECIFIER_INT8:
2947 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2948 atomic_type = int8_type_kind;
2951 case SPECIFIER_INT16:
2952 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2953 atomic_type = int16_type_kind;
2956 case SPECIFIER_INT32:
2957 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2958 atomic_type = int32_type_kind;
2961 case SPECIFIER_INT64:
2962 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2963 atomic_type = int64_type_kind;
2966 case SPECIFIER_INT128:
2967 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2968 atomic_type = int128_type_kind;
2971 case SPECIFIER_FLOAT:
2972 atomic_type = ATOMIC_TYPE_FLOAT;
2974 case SPECIFIER_DOUBLE:
2975 atomic_type = ATOMIC_TYPE_DOUBLE;
2977 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2978 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2980 case SPECIFIER_BOOL:
2981 if (type_specifiers & (SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2982 if (type_specifiers & SPECIFIER_COMPLEX)
2983 errorf(pos, "_Complex specifier is invalid for _Bool");
2984 if (type_specifiers & SPECIFIER_IMAGINARY)
2985 errorf(pos, "_Imaginary specifier is invalid for _Bool");
2986 type_specifiers &= ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY);
2988 atomic_type = ATOMIC_TYPE_BOOL;
2991 /* invalid specifier combination, give an error message */
2992 if (type_specifiers == 0) {
2994 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
2995 if (!(c_mode & _CXX) && !strict_mode) {
2996 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
2997 atomic_type = ATOMIC_TYPE_INT;
3000 errorf(pos, "no type specifiers given in declaration");
3003 } else if (type_specifiers == SPECIFIER_COMPLEX) {
3004 warningf(WARN_OTHER, pos, "_Complex requires a type specifier; assuming '_Complex double'");
3005 atomic_type = ATOMIC_TYPE_DOUBLE;
3007 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3008 (type_specifiers & SPECIFIER_UNSIGNED)) {
3009 errorf(pos, "signed and unsigned specifiers given");
3010 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3011 errorf(pos, "only integer types can be signed or unsigned");
3013 errorf(pos, "multiple datatypes in declaration");
3015 specifiers->type = type_error_type;
3020 if (type_specifiers & SPECIFIER_COMPLEX) {
3021 type = allocate_type_zero(TYPE_COMPLEX);
3022 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3023 type = allocate_type_zero(TYPE_IMAGINARY);
3025 type = allocate_type_zero(TYPE_ATOMIC);
3027 type->atomic.akind = atomic_type;
3029 } else if (type_specifiers != 0) {
3030 errorf(&specifiers->pos, "multiple datatypes in declaration");
3033 /* FIXME: check type qualifiers here */
3034 type->base.qualifiers = qualifiers;
3037 type = identify_new_type(type);
3039 type = typehash_insert(type);
3042 if (specifiers->attributes != NULL)
3043 type = handle_type_attributes(specifiers->attributes, type);
3044 specifiers->type = type;
3047 static type_qualifiers_t parse_type_qualifiers(void)
3049 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3052 switch (token.kind) {
3053 /* type qualifiers */
3054 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3055 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3056 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3057 /* microsoft extended type modifiers */
3058 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3059 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3060 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3061 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3062 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3071 * Parses an K&R identifier list
3073 static void parse_identifier_list(scope_t *scope)
3075 assert(token.kind == T_IDENTIFIER);
3077 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3078 /* a K&R parameter has no type, yet */
3082 append_entity(scope, entity);
3083 } while (accept(',') && token.kind == T_IDENTIFIER);
3086 static entity_t *parse_parameter(void)
3088 declaration_specifiers_t specifiers;
3089 parse_declaration_specifiers(&specifiers);
3091 entity_t *entity = parse_declarator(&specifiers,
3092 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3093 anonymous_entity = NULL;
3097 static void semantic_parameter_incomplete(const entity_t *entity)
3099 assert(entity->kind == ENTITY_PARAMETER);
3101 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3102 * list in a function declarator that is part of a
3103 * definition of that function shall not have
3104 * incomplete type. */
3105 type_t *type = skip_typeref(entity->declaration.type);
3106 if (is_type_incomplete(type)) {
3107 errorf(&entity->base.pos, "'%N' has incomplete type", entity);
3111 static bool has_parameters(void)
3113 /* func(void) is not a parameter */
3114 if (look_ahead(1)->kind != ')')
3116 if (token.kind == T_IDENTIFIER) {
3117 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3120 if (entity->kind != ENTITY_TYPEDEF)
3122 type_t const *const type = skip_typeref(entity->typedefe.type);
3123 if (!is_type_void(type))
3125 if (c_mode & _CXX) {
3126 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3127 * is not allowed. */
3128 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3129 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3130 /* §6.7.5.3:10 Qualification is not allowed here. */
3131 errorf(HERE, "'void' as parameter must not have type qualifiers");
3133 } else if (token.kind != T_void) {
3141 * Parses function type parameters (and optionally creates variable_t entities
3142 * for them in a scope)
3144 static void parse_parameters(function_type_t *type, scope_t *scope)
3146 add_anchor_token(')');
3149 if (token.kind == T_IDENTIFIER &&
3150 !is_typedef_symbol(token.base.symbol) &&
3151 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3152 type->kr_style_parameters = true;
3153 parse_identifier_list(scope);
3154 } else if (token.kind == ')') {
3155 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3156 if (!(c_mode & _CXX))
3157 type->unspecified_parameters = true;
3158 } else if (has_parameters()) {
3159 function_parameter_t **anchor = &type->parameters;
3160 add_anchor_token(',');
3162 switch (token.kind) {
3165 type->variadic = true;
3166 goto parameters_finished;
3171 entity_t *entity = parse_parameter();
3172 if (entity->kind == ENTITY_TYPEDEF) {
3173 errorf(&entity->base.pos,
3174 "typedef not allowed as function parameter");
3177 assert(is_declaration(entity));
3179 semantic_parameter_incomplete(entity);
3181 function_parameter_t *const parameter =
3182 allocate_parameter(entity->declaration.type);
3184 if (scope != NULL) {
3185 append_entity(scope, entity);
3188 *anchor = parameter;
3189 anchor = ¶meter->next;
3194 goto parameters_finished;
3196 } while (accept(','));
3197 parameters_finished:
3198 rem_anchor_token(',');
3201 rem_anchor_token(')');
3205 typedef enum construct_type_kind_t {
3206 CONSTRUCT_POINTER = 1,
3207 CONSTRUCT_REFERENCE,
3210 } construct_type_kind_t;
3212 typedef union construct_type_t construct_type_t;
3214 typedef struct construct_type_base_t {
3215 construct_type_kind_t kind;
3217 construct_type_t *next;
3218 } construct_type_base_t;
3220 typedef struct parsed_pointer_t {
3221 construct_type_base_t base;
3222 type_qualifiers_t type_qualifiers;
3223 variable_t *base_variable; /**< MS __based extension. */
3226 typedef struct parsed_reference_t {
3227 construct_type_base_t base;
3228 } parsed_reference_t;
3230 typedef struct construct_function_type_t {
3231 construct_type_base_t base;
3232 type_t *function_type;
3233 } construct_function_type_t;
3235 typedef struct parsed_array_t {
3236 construct_type_base_t base;
3237 type_qualifiers_t type_qualifiers;
3243 union construct_type_t {
3244 construct_type_kind_t kind;
3245 construct_type_base_t base;
3246 parsed_pointer_t pointer;
3247 parsed_reference_t reference;
3248 construct_function_type_t function;
3249 parsed_array_t array;
3252 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3254 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3255 memset(cons, 0, size);
3257 cons->base.pos = *HERE;
3262 static construct_type_t *parse_pointer_declarator(void)
3264 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3266 cons->pointer.type_qualifiers = parse_type_qualifiers();
3267 //cons->pointer.base_variable = base_variable;
3272 /* ISO/IEC 14882:1998(E) §8.3.2 */
3273 static construct_type_t *parse_reference_declarator(void)
3275 if (!(c_mode & _CXX))
3276 errorf(HERE, "references are only available for C++");
3278 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3285 static construct_type_t *parse_array_declarator(void)
3287 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3288 parsed_array_t *const array = &cons->array;
3291 add_anchor_token(']');
3293 bool is_static = accept(T_static);
3295 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3298 is_static = accept(T_static);
3300 array->type_qualifiers = type_qualifiers;
3301 array->is_static = is_static;
3303 expression_t *size = NULL;
3304 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3305 array->is_variable = true;
3307 } else if (token.kind != ']') {
3308 size = parse_assignment_expression();
3310 /* §6.7.5.2:1 Array size must have integer type */
3311 type_t *const orig_type = size->base.type;
3312 type_t *const type = skip_typeref(orig_type);
3313 if (!is_type_integer(type) && is_type_valid(type)) {
3314 errorf(&size->base.pos,
3315 "array size '%E' must have integer type but has type '%T'",
3320 mark_vars_read(size, NULL);
3323 if (is_static && size == NULL)
3324 errorf(&array->base.pos, "static array parameters require a size");
3326 rem_anchor_token(']');
3332 static construct_type_t *parse_function_declarator(scope_t *scope)
3334 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3336 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3337 function_type_t *ftype = &type->function;
3339 ftype->linkage = current_linkage;
3340 ftype->calling_convention = CC_DEFAULT;
3342 parse_parameters(ftype, scope);
3344 cons->function.function_type = type;
3349 typedef struct parse_declarator_env_t {
3350 bool may_be_abstract : 1;
3351 bool must_be_abstract : 1;
3352 decl_modifiers_t modifiers;
3356 attribute_t *attributes;
3357 } parse_declarator_env_t;
3360 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3362 /* construct a single linked list of construct_type_t's which describe
3363 * how to construct the final declarator type */
3364 construct_type_t *first = NULL;
3365 construct_type_t **anchor = &first;
3367 env->attributes = parse_attributes(env->attributes);
3370 construct_type_t *type;
3371 //variable_t *based = NULL; /* MS __based extension */
3372 switch (token.kind) {
3374 type = parse_reference_declarator();
3378 panic("based not supported anymore");
3383 type = parse_pointer_declarator();
3387 goto ptr_operator_end;
3391 anchor = &type->base.next;
3393 /* TODO: find out if this is correct */
3394 env->attributes = parse_attributes(env->attributes);
3398 construct_type_t *inner_types = NULL;
3400 switch (token.kind) {
3402 if (env->must_be_abstract) {
3403 errorf(HERE, "no identifier expected in typename");
3405 env->symbol = token.base.symbol;
3412 /* Parenthesized declarator or function declarator? */
3413 token_t const *const la1 = look_ahead(1);
3414 switch (la1->kind) {
3416 if (is_typedef_symbol(la1->base.symbol)) {
3418 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3419 * interpreted as ``function with no parameter specification'', rather
3420 * than redundant parentheses around the omitted identifier. */
3422 /* Function declarator. */
3423 if (!env->may_be_abstract) {
3424 errorf(HERE, "function declarator must have a name");
3431 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3432 /* Paranthesized declarator. */
3434 add_anchor_token(')');
3435 inner_types = parse_inner_declarator(env);
3436 if (inner_types != NULL) {
3437 /* All later declarators only modify the return type */
3438 env->must_be_abstract = true;
3440 rem_anchor_token(')');
3449 if (env->may_be_abstract)
3451 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3456 construct_type_t **const p = anchor;
3459 construct_type_t *type;
3460 switch (token.kind) {
3462 scope_t *scope = NULL;
3463 if (!env->must_be_abstract) {
3464 scope = &env->parameters;
3467 type = parse_function_declarator(scope);
3471 type = parse_array_declarator();
3474 goto declarator_finished;
3477 /* insert in the middle of the list (at p) */
3478 type->base.next = *p;
3481 anchor = &type->base.next;
3484 declarator_finished:
3485 /* append inner_types at the end of the list, we don't to set anchor anymore
3486 * as it's not needed anymore */
3487 *anchor = inner_types;
3492 static type_t *construct_declarator_type(construct_type_t *construct_list,
3495 construct_type_t *iter = construct_list;
3496 for (; iter != NULL; iter = iter->base.next) {
3497 position_t const* const pos = &iter->base.pos;
3498 switch (iter->kind) {
3499 case CONSTRUCT_FUNCTION: {
3500 construct_function_type_t *function = &iter->function;
3501 type_t *function_type = function->function_type;
3503 function_type->function.return_type = type;
3505 type_t *skipped_return_type = skip_typeref(type);
3507 if (is_type_function(skipped_return_type)) {
3508 errorf(pos, "function returning function is not allowed");
3509 } else if (is_type_array(skipped_return_type)) {
3510 errorf(pos, "function returning array is not allowed");
3512 if (skipped_return_type->base.qualifiers != 0) {
3513 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3517 /* The function type was constructed earlier. Freeing it here will
3518 * destroy other types. */
3519 type = typehash_insert(function_type);
3523 case CONSTRUCT_POINTER: {
3524 if (is_type_reference(skip_typeref(type)))
3525 errorf(pos, "cannot declare a pointer to reference");
3527 parsed_pointer_t *pointer = &iter->pointer;
3528 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3532 case CONSTRUCT_REFERENCE:
3533 if (is_type_reference(skip_typeref(type)))
3534 errorf(pos, "cannot declare a reference to reference");
3536 type = make_reference_type(type);
3539 case CONSTRUCT_ARRAY: {
3540 if (is_type_reference(skip_typeref(type)))
3541 errorf(pos, "cannot declare an array of references");
3543 parsed_array_t *array = &iter->array;
3544 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3546 expression_t *size_expression = array->size;
3547 if (size_expression != NULL) {
3549 = create_implicit_cast(size_expression, type_size_t);
3552 array_type->base.qualifiers = array->type_qualifiers;
3553 array_type->array.element_type = type;
3554 array_type->array.is_static = array->is_static;
3555 array_type->array.is_variable = array->is_variable;
3556 array_type->array.size_expression = size_expression;
3558 if (size_expression != NULL) {
3559 switch (is_constant_expression(size_expression)) {
3560 case EXPR_CLASS_INTEGER_CONSTANT: {
3561 long const size = fold_constant_to_int(size_expression);
3562 array_type->array.size = size;
3563 array_type->array.size_constant = true;
3564 /* §6.7.5.2:1 If the expression is a constant expression,
3565 * it shall have a value greater than zero. */
3567 errorf(&size_expression->base.pos,
3568 "size of array must be greater than zero");
3569 } else if (size == 0 && !GNU_MODE) {
3570 errorf(&size_expression->base.pos,
3571 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3576 case EXPR_CLASS_CONSTANT:
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 && is_type_valid(prev_type)) {
4075 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4077 } else if (current_function == NULL) {
4078 if (old_storage_class != STORAGE_CLASS_STATIC &&
4079 new_storage_class == STORAGE_CLASS_STATIC) {
4080 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4081 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4082 prev_decl->storage_class = STORAGE_CLASS_NONE;
4083 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4085 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4087 goto error_redeclaration;
4088 goto warn_redundant_declaration;
4090 } else if (is_type_valid(prev_type)) {
4091 if (old_storage_class == new_storage_class) {
4092 error_redeclaration:
4093 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4095 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4100 prev_decl->modifiers |= decl->modifiers;
4101 if (entity->kind == ENTITY_FUNCTION) {
4102 previous_entity->function.is_inline |= entity->function.is_inline;
4104 return previous_entity;
4108 if (is_warn_on(why = WARN_SHADOW) ||
4109 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4110 char const *const what = get_entity_kind_name(previous_entity->kind);
4111 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4115 if (entity->kind == ENTITY_FUNCTION) {
4116 if (is_definition &&
4117 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4119 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4120 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4122 goto warn_missing_declaration;
4125 } else if (entity->kind == ENTITY_VARIABLE) {
4126 if (current_scope == file_scope &&
4127 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4128 !entity->declaration.implicit) {
4129 warn_missing_declaration:
4130 if (is_type_valid(skip_typeref(entity->declaration.type)))
4131 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4136 environment_push(entity);
4137 append_entity(current_scope, entity);
4142 static void parser_error_multiple_definition(entity_t *entity,
4143 const position_t *pos)
4145 errorf(pos, "redefinition of '%N' (declared %P)", entity, &entity->base.pos);
4148 static bool is_declaration_specifier(token_t const *const tk)
4154 return is_typedef_symbol(tk->base.symbol);
4161 static void parse_init_declarator_rest(entity_t *entity)
4163 type_t *orig_type = type_error_type;
4165 if (entity->base.kind == ENTITY_TYPEDEF) {
4166 position_t const *const pos = &entity->base.pos;
4167 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4169 assert(is_declaration(entity));
4170 orig_type = entity->declaration.type;
4173 type_t *type = skip_typeref(orig_type);
4175 if (entity->kind == ENTITY_VARIABLE
4176 && entity->variable.initializer != NULL) {
4177 parser_error_multiple_definition(entity, HERE);
4181 declaration_t *const declaration = &entity->declaration;
4182 bool must_be_constant = false;
4183 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4184 entity->base.parent_scope == file_scope) {
4185 must_be_constant = true;
4188 if (is_type_function(type)) {
4189 position_t const *const pos = &entity->base.pos;
4190 errorf(pos, "'%N' is initialized like a variable", entity);
4191 orig_type = type_error_type;
4194 parse_initializer_env_t env;
4195 env.type = orig_type;
4196 env.must_be_constant = must_be_constant;
4197 env.entity = entity;
4199 initializer_t *initializer = parse_initializer(&env);
4201 if (entity->kind == ENTITY_VARIABLE) {
4202 /* §6.7.5:22 array initializers for arrays with unknown size
4203 * determine the array type size */
4204 declaration->type = env.type;
4205 entity->variable.initializer = initializer;
4209 /* parse rest of a declaration without any declarator */
4210 static void parse_anonymous_declaration_rest(
4211 const declaration_specifiers_t *specifiers)
4214 anonymous_entity = NULL;
4216 position_t const *const pos = &specifiers->pos;
4217 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4218 specifiers->thread_local) {
4219 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4222 type_t *type = specifiers->type;
4223 switch (type->kind) {
4224 case TYPE_COMPOUND_STRUCT:
4225 case TYPE_COMPOUND_UNION: {
4226 if (type->compound.compound->base.symbol == NULL) {
4227 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4236 warningf(WARN_OTHER, pos, "empty declaration");
4241 static void check_variable_type_complete(entity_t *ent)
4243 if (ent->kind != ENTITY_VARIABLE)
4246 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4247 * type for the object shall be complete [...] */
4248 declaration_t *decl = &ent->declaration;
4249 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4250 decl->storage_class == STORAGE_CLASS_STATIC)
4253 type_t *const type = skip_typeref(decl->type);
4254 if (!is_type_incomplete(type))
4257 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4258 * are given length one. */
4259 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4260 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4264 errorf(&ent->base.pos, "variable '%#N' has incomplete type", ent);
4268 static void parse_declaration_rest(entity_t *ndeclaration,
4269 const declaration_specifiers_t *specifiers,
4270 parsed_declaration_func finished_declaration,
4271 declarator_flags_t flags)
4273 add_anchor_token(';');
4274 add_anchor_token(',');
4276 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4278 if (token.kind == '=') {
4279 parse_init_declarator_rest(entity);
4280 } else if (entity->kind == ENTITY_VARIABLE) {
4281 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4282 * [...] where the extern specifier is explicitly used. */
4283 declaration_t *decl = &entity->declaration;
4284 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4285 is_type_reference(skip_typeref(decl->type))) {
4286 position_t const *const pos = &entity->base.pos;
4287 errorf(pos, "reference '%#N' must be initialized", entity);
4291 check_variable_type_complete(entity);
4296 add_anchor_token('=');
4297 ndeclaration = parse_declarator(specifiers, flags);
4298 rem_anchor_token('=');
4300 rem_anchor_token(',');
4301 rem_anchor_token(';');
4304 anonymous_entity = NULL;
4307 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4309 symbol_t *symbol = entity->base.symbol;
4313 assert(entity->base.namespc == NAMESPACE_NORMAL);
4314 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4315 if (previous_entity == NULL
4316 || previous_entity->base.parent_scope != current_scope) {
4317 errorf(&entity->base.pos, "expected declaration of a function parameter, found '%Y'",
4322 if (is_definition) {
4323 errorf(HERE, "'%N' is initialised", entity);
4326 return record_entity(entity, false);
4329 static void parse_declaration(parsed_declaration_func finished_declaration,
4330 declarator_flags_t flags)
4332 add_anchor_token(';');
4333 declaration_specifiers_t specifiers;
4334 parse_declaration_specifiers(&specifiers);
4335 rem_anchor_token(';');
4337 if (token.kind == ';') {
4338 parse_anonymous_declaration_rest(&specifiers);
4340 entity_t *entity = parse_declarator(&specifiers, flags);
4341 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4346 static type_t *get_default_promoted_type(type_t *orig_type)
4348 type_t *result = orig_type;
4350 type_t *type = skip_typeref(orig_type);
4351 if (is_type_integer(type)) {
4352 result = promote_integer(type);
4353 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4354 result = type_double;
4360 static void parse_kr_declaration_list(entity_t *entity)
4362 if (entity->kind != ENTITY_FUNCTION)
4365 type_t *type = skip_typeref(entity->declaration.type);
4366 assert(is_type_function(type));
4367 if (!type->function.kr_style_parameters)
4370 add_anchor_token('{');
4372 PUSH_SCOPE(&entity->function.parameters);
4374 entity_t *parameter = entity->function.parameters.entities;
4375 for ( ; parameter != NULL; parameter = parameter->base.next) {
4376 assert(parameter->base.parent_scope == NULL);
4377 parameter->base.parent_scope = current_scope;
4378 environment_push(parameter);
4381 /* parse declaration list */
4383 switch (token.kind) {
4385 /* This covers symbols, which are no type, too, and results in
4386 * better error messages. The typical cases are misspelled type
4387 * names and missing includes. */
4389 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4399 /* update function type */
4400 type_t *new_type = duplicate_type(type);
4402 function_parameter_t *parameters = NULL;
4403 function_parameter_t **anchor = ¶meters;
4405 /* did we have an earlier prototype? */
4406 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4407 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4410 function_parameter_t *proto_parameter = NULL;
4411 if (proto_type != NULL) {
4412 type_t *proto_type_type = proto_type->declaration.type;
4413 proto_parameter = proto_type_type->function.parameters;
4414 /* If a K&R function definition has a variadic prototype earlier, then
4415 * make the function definition variadic, too. This should conform to
4416 * §6.7.5.3:15 and §6.9.1:8. */
4417 new_type->function.variadic = proto_type_type->function.variadic;
4419 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4421 new_type->function.unspecified_parameters = true;
4424 bool need_incompatible_warning = false;
4425 parameter = entity->function.parameters.entities;
4426 for (; parameter != NULL; parameter = parameter->base.next,
4428 proto_parameter == NULL ? NULL : proto_parameter->next) {
4429 if (parameter->kind != ENTITY_PARAMETER)
4432 type_t *parameter_type = parameter->declaration.type;
4433 if (parameter_type == NULL) {
4434 position_t const* const pos = ¶meter->base.pos;
4436 errorf(pos, "no type specified for function '%N'", parameter);
4437 parameter_type = type_error_type;
4439 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4440 parameter_type = type_int;
4442 parameter->declaration.type = parameter_type;
4445 semantic_parameter_incomplete(parameter);
4447 /* we need the default promoted types for the function type */
4448 type_t *not_promoted = parameter_type;
4449 parameter_type = get_default_promoted_type(parameter_type);
4451 /* gcc special: if the type of the prototype matches the unpromoted
4452 * type don't promote */
4453 if (!strict_mode && proto_parameter != NULL) {
4454 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4455 type_t *promo_skip = skip_typeref(parameter_type);
4456 type_t *param_skip = skip_typeref(not_promoted);
4457 if (!types_compatible(proto_p_type, promo_skip)
4458 && types_compatible(proto_p_type, param_skip)) {
4460 need_incompatible_warning = true;
4461 parameter_type = not_promoted;
4464 function_parameter_t *const function_parameter
4465 = allocate_parameter(parameter_type);
4467 *anchor = function_parameter;
4468 anchor = &function_parameter->next;
4471 new_type->function.parameters = parameters;
4472 new_type = identify_new_type(new_type);
4474 if (need_incompatible_warning) {
4475 symbol_t const *const sym = entity->base.symbol;
4476 position_t const *const pos = &entity->base.pos;
4477 position_t const *const ppos = &proto_type->base.pos;
4478 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4480 entity->declaration.type = new_type;
4482 rem_anchor_token('{');
4485 static bool first_err = true;
4488 * When called with first_err set, prints the name of the current function,
4491 static void print_in_function(void)
4495 char const *const file = current_function->base.base.pos.input_name;
4496 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4501 * Check if all labels are defined in the current function.
4502 * Check if all labels are used in the current function.
4504 static void check_labels(void)
4506 for (const goto_statement_t *goto_statement = goto_first;
4507 goto_statement != NULL;
4508 goto_statement = goto_statement->next) {
4509 label_t *label = goto_statement->label;
4510 if (label->base.pos.input_name == NULL) {
4511 print_in_function();
4512 position_t const *const pos = &goto_statement->base.pos;
4513 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4517 if (is_warn_on(WARN_UNUSED_LABEL)) {
4518 for (const label_statement_t *label_statement = label_first;
4519 label_statement != NULL;
4520 label_statement = label_statement->next) {
4521 label_t *label = label_statement->label;
4523 if (! label->used) {
4524 print_in_function();
4525 position_t const *const pos = &label_statement->base.pos;
4526 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4532 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4534 entity_t const *const end = last != NULL ? last->base.next : NULL;
4535 for (; entity != end; entity = entity->base.next) {
4536 if (!is_declaration(entity))
4539 declaration_t *declaration = &entity->declaration;
4540 if (declaration->implicit)
4543 if (!declaration->used) {
4544 print_in_function();
4545 warningf(why, &entity->base.pos, "'%N' is unused", entity);
4546 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4547 print_in_function();
4548 warningf(why, &entity->base.pos, "'%N' is never read", entity);
4553 static void check_unused_variables(statement_t *const stmt, void *const env)
4557 switch (stmt->kind) {
4558 case STATEMENT_DECLARATION: {
4559 declaration_statement_t const *const decls = &stmt->declaration;
4560 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4565 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4574 * Check declarations of current_function for unused entities.
4576 static void check_declarations(void)
4578 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4579 const scope_t *scope = ¤t_function->parameters;
4580 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4582 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4583 walk_statements(current_function->body, check_unused_variables, NULL);
4587 static int determine_truth(expression_t const* const cond)
4590 is_constant_expression(cond) < EXPR_CLASS_CONSTANT ? 0 :
4591 fold_constant_to_bool(cond) ? 1 :
4595 static void check_reachable(statement_t *);
4596 static bool reaches_end;
4598 static bool expression_returns(expression_t const *const expr)
4600 switch (expr->kind) {
4602 expression_t const *const func = expr->call.function;
4603 type_t const *const type = skip_typeref(func->base.type);
4604 if (type->kind == TYPE_POINTER) {
4605 type_t const *const points_to
4606 = skip_typeref(type->pointer.points_to);
4607 if (points_to->kind == TYPE_FUNCTION
4608 && points_to->function.modifiers & DM_NORETURN)
4612 if (!expression_returns(func))
4615 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4616 if (!expression_returns(arg->expression))
4623 case EXPR_REFERENCE:
4624 case EXPR_ENUM_CONSTANT:
4625 case EXPR_LITERAL_CASES:
4626 case EXPR_LITERAL_CHARACTER:
4627 case EXPR_STRING_LITERAL:
4628 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4629 case EXPR_LABEL_ADDRESS:
4630 case EXPR_CLASSIFY_TYPE:
4631 case EXPR_SIZEOF: // TODO handle obscure VLA case
4634 case EXPR_BUILTIN_CONSTANT_P:
4635 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4640 case EXPR_STATEMENT: {
4641 bool old_reaches_end = reaches_end;
4642 reaches_end = false;
4643 check_reachable(expr->statement.statement);
4644 bool returns = reaches_end;
4645 reaches_end = old_reaches_end;
4649 case EXPR_CONDITIONAL:
4650 // TODO handle constant expression
4652 if (!expression_returns(expr->conditional.condition))
4655 if (expr->conditional.true_expression != NULL
4656 && expression_returns(expr->conditional.true_expression))
4659 return expression_returns(expr->conditional.false_expression);
4662 return expression_returns(expr->select.compound);
4664 case EXPR_ARRAY_ACCESS:
4666 expression_returns(expr->array_access.array_ref) &&
4667 expression_returns(expr->array_access.index);
4670 return expression_returns(expr->va_starte.ap);
4673 return expression_returns(expr->va_arge.ap);
4676 return expression_returns(expr->va_copye.src);
4678 case EXPR_UNARY_CASES_MANDATORY:
4679 return expression_returns(expr->unary.value);
4681 case EXPR_UNARY_THROW:
4684 case EXPR_BINARY_CASES:
4685 // TODO handle constant lhs of && and ||
4687 expression_returns(expr->binary.left) &&
4688 expression_returns(expr->binary.right);
4691 panic("unhandled expression");
4694 static bool initializer_returns(initializer_t const *const init)
4696 switch (init->kind) {
4697 case INITIALIZER_VALUE:
4698 return expression_returns(init->value.value);
4700 case INITIALIZER_LIST: {
4701 initializer_t * const* i = init->list.initializers;
4702 initializer_t * const* const end = i + init->list.len;
4703 bool returns = true;
4704 for (; i != end; ++i) {
4705 if (!initializer_returns(*i))
4711 case INITIALIZER_STRING:
4712 case INITIALIZER_DESIGNATOR: // designators have no payload
4715 panic("unhandled initializer");
4718 static bool noreturn_candidate;
4720 static void check_reachable(statement_t *const stmt)
4722 if (stmt->base.reachable)
4724 if (stmt->kind != STATEMENT_DO_WHILE)
4725 stmt->base.reachable = true;
4727 statement_t *last = stmt;
4729 switch (stmt->kind) {
4730 case STATEMENT_ERROR:
4731 case STATEMENT_EMPTY:
4733 next = stmt->base.next;
4736 case STATEMENT_DECLARATION: {
4737 declaration_statement_t const *const decl = &stmt->declaration;
4738 entity_t const * ent = decl->declarations_begin;
4739 entity_t const *const last_decl = decl->declarations_end;
4741 for (;; ent = ent->base.next) {
4742 if (ent->kind == ENTITY_VARIABLE &&
4743 ent->variable.initializer != NULL &&
4744 !initializer_returns(ent->variable.initializer)) {
4747 if (ent == last_decl)
4751 next = stmt->base.next;
4755 case STATEMENT_COMPOUND:
4756 next = stmt->compound.statements;
4758 next = stmt->base.next;
4761 case STATEMENT_RETURN: {
4762 expression_t const *const val = stmt->returns.value;
4763 if (val == NULL || expression_returns(val))
4764 noreturn_candidate = false;
4768 case STATEMENT_IF: {
4769 if_statement_t const *const ifs = &stmt->ifs;
4770 expression_t const *const cond = ifs->condition;
4772 if (!expression_returns(cond))
4775 int const val = determine_truth(cond);
4778 check_reachable(ifs->true_statement);
4783 if (ifs->false_statement != NULL) {
4784 check_reachable(ifs->false_statement);
4788 next = stmt->base.next;
4792 case STATEMENT_SWITCH: {
4793 switch_statement_t const *const switchs = &stmt->switchs;
4794 expression_t const *const expr = switchs->expression;
4796 if (!expression_returns(expr))
4799 if (is_constant_expression(expr) >= EXPR_CLASS_CONSTANT) {
4800 ir_tarval *const val = fold_constant_to_tarval(expr);
4801 case_label_statement_t * defaults = NULL;
4802 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4803 if (i->expression == NULL) {
4808 if (i->first_case == val || i->last_case == val ||
4809 ((tarval_cmp(i->first_case, val) & ir_relation_less_equal)
4810 && (tarval_cmp(val, i->last_case) & ir_relation_less_equal))) {
4811 check_reachable((statement_t*)i);
4816 if (defaults != NULL) {
4817 check_reachable((statement_t*)defaults);
4821 bool has_default = false;
4822 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4823 if (i->expression == NULL)
4826 check_reachable((statement_t*)i);
4833 next = stmt->base.next;
4837 case STATEMENT_EXPRESSION: {
4838 /* Check for noreturn function call */
4839 expression_t const *const expr = stmt->expression.expression;
4840 if (!expression_returns(expr))
4843 next = stmt->base.next;
4847 case STATEMENT_CONTINUE:
4848 for (statement_t *parent = stmt;;) {
4849 parent = parent->base.parent;
4850 if (parent == NULL) /* continue not within loop */
4854 switch (parent->kind) {
4855 case STATEMENT_DO_WHILE: goto continue_do_while;
4856 case STATEMENT_FOR: goto continue_for;
4862 case STATEMENT_BREAK:
4863 for (statement_t *parent = stmt;;) {
4864 parent = parent->base.parent;
4865 if (parent == NULL) /* break not within loop/switch */
4868 switch (parent->kind) {
4869 case STATEMENT_SWITCH:
4870 case STATEMENT_DO_WHILE:
4873 next = parent->base.next;
4874 goto found_break_parent;
4882 case STATEMENT_COMPUTED_GOTO: {
4883 if (!expression_returns(stmt->computed_goto.expression))
4886 statement_t *parent = stmt->base.parent;
4887 if (parent == NULL) /* top level goto */
4893 case STATEMENT_GOTO:
4894 next = stmt->gotos.label->statement;
4895 if (next == NULL) /* missing label */
4899 case STATEMENT_LABEL:
4900 next = stmt->label.statement;
4903 case STATEMENT_CASE_LABEL:
4904 next = stmt->case_label.statement;
4907 case STATEMENT_DO_WHILE:
4908 next = stmt->do_while.body;
4911 case STATEMENT_FOR: {
4912 for_statement_t *const fors = &stmt->fors;
4914 if (fors->condition_reachable)
4916 fors->condition_reachable = true;
4918 expression_t const *const cond = fors->condition;
4923 } else if (expression_returns(cond)) {
4924 val = determine_truth(cond);
4930 check_reachable(fors->body);
4935 next = stmt->base.next;
4939 case STATEMENT_MS_TRY: {
4940 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4941 check_reachable(ms_try->try_statement);
4942 next = ms_try->final_statement;
4946 case STATEMENT_LEAVE: {
4947 statement_t *parent = stmt;
4949 parent = parent->base.parent;
4950 if (parent == NULL) /* __leave not within __try */
4953 if (parent->kind == STATEMENT_MS_TRY) {
4955 next = parent->ms_try.final_statement;
4963 panic("invalid statement kind");
4966 while (next == NULL) {
4967 next = last->base.parent;
4969 noreturn_candidate = false;
4971 type_t *const type = skip_typeref(current_function->base.type);
4972 assert(is_type_function(type));
4973 type_t *const ret = skip_typeref(type->function.return_type);
4974 if (!is_type_void(ret) &&
4975 is_type_valid(ret) &&
4976 !is_main(current_entity)) {
4977 position_t const *const pos = &stmt->base.pos;
4978 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4983 switch (next->kind) {
4984 case STATEMENT_ERROR:
4985 case STATEMENT_EMPTY:
4986 case STATEMENT_DECLARATION:
4987 case STATEMENT_EXPRESSION:
4989 case STATEMENT_RETURN:
4990 case STATEMENT_CONTINUE:
4991 case STATEMENT_BREAK:
4992 case STATEMENT_COMPUTED_GOTO:
4993 case STATEMENT_GOTO:
4994 case STATEMENT_LEAVE:
4995 panic("invalid control flow in function");
4997 case STATEMENT_COMPOUND:
4998 if (next->compound.stmt_expr) {
5004 case STATEMENT_SWITCH:
5005 case STATEMENT_LABEL:
5006 case STATEMENT_CASE_LABEL:
5008 next = next->base.next;
5011 case STATEMENT_DO_WHILE: {
5013 if (next->base.reachable)
5015 next->base.reachable = true;
5017 do_while_statement_t const *const dw = &next->do_while;
5018 expression_t const *const cond = dw->condition;
5020 if (!expression_returns(cond))
5023 int const val = determine_truth(cond);
5026 check_reachable(dw->body);
5032 next = next->base.next;
5036 case STATEMENT_FOR: {
5038 for_statement_t *const fors = &next->fors;
5040 fors->step_reachable = true;
5042 if (fors->condition_reachable)
5044 fors->condition_reachable = true;
5046 expression_t const *const cond = fors->condition;
5051 } else if (expression_returns(cond)) {
5052 val = determine_truth(cond);
5058 check_reachable(fors->body);
5064 next = next->base.next;
5068 case STATEMENT_MS_TRY:
5070 next = next->ms_try.final_statement;
5075 check_reachable(next);
5078 static void check_unreachable(statement_t* const stmt, void *const env)
5082 switch (stmt->kind) {
5083 case STATEMENT_DO_WHILE:
5084 if (!stmt->base.reachable) {
5085 expression_t const *const cond = stmt->do_while.condition;
5086 if (determine_truth(cond) >= 0) {
5087 position_t const *const pos = &cond->base.pos;
5088 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5093 case STATEMENT_FOR: {
5094 for_statement_t const* const fors = &stmt->fors;
5096 // if init and step are unreachable, cond is unreachable, too
5097 if (!stmt->base.reachable && !fors->step_reachable) {
5098 goto warn_unreachable;
5100 if (!stmt->base.reachable && fors->initialisation != NULL) {
5101 position_t const *const pos = &fors->initialisation->base.pos;
5102 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5105 if (!fors->condition_reachable && fors->condition != NULL) {
5106 position_t const *const pos = &fors->condition->base.pos;
5107 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5110 if (!fors->step_reachable && fors->step != NULL) {
5111 position_t const *const pos = &fors->step->base.pos;
5112 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5118 case STATEMENT_COMPOUND:
5119 if (stmt->compound.statements != NULL)
5121 goto warn_unreachable;
5123 case STATEMENT_DECLARATION: {
5124 /* Only warn if there is at least one declarator with an initializer.
5125 * This typically occurs in switch statements. */
5126 declaration_statement_t const *const decl = &stmt->declaration;
5127 entity_t const * ent = decl->declarations_begin;
5128 entity_t const *const last = decl->declarations_end;
5130 for (;; ent = ent->base.next) {
5131 if (ent->kind == ENTITY_VARIABLE &&
5132 ent->variable.initializer != NULL) {
5133 goto warn_unreachable;
5143 if (!stmt->base.reachable) {
5144 position_t const *const pos = &stmt->base.pos;
5145 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5151 static bool is_main(entity_t *entity)
5153 static symbol_t *sym_main = NULL;
5154 if (sym_main == NULL) {
5155 sym_main = symbol_table_insert("main");
5158 if (entity->base.symbol != sym_main)
5160 /* must be in outermost scope */
5161 if (entity->base.parent_scope != file_scope)
5167 static void prepare_main_collect2(entity_t*);
5169 static void parse_external_declaration(void)
5171 /* function-definitions and declarations both start with declaration
5173 add_anchor_token(';');
5174 declaration_specifiers_t specifiers;
5175 parse_declaration_specifiers(&specifiers);
5176 rem_anchor_token(';');
5178 /* must be a declaration */
5179 if (token.kind == ';') {
5180 parse_anonymous_declaration_rest(&specifiers);
5184 add_anchor_token(',');
5185 add_anchor_token('=');
5186 add_anchor_token(';');
5187 add_anchor_token('{');
5189 /* declarator is common to both function-definitions and declarations */
5190 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5192 rem_anchor_token('{');
5193 rem_anchor_token(';');
5194 rem_anchor_token('=');
5195 rem_anchor_token(',');
5197 /* must be a declaration */
5198 switch (token.kind) {
5202 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5207 /* must be a function definition */
5208 parse_kr_declaration_list(ndeclaration);
5210 if (token.kind != '{') {
5211 parse_error_expected("while parsing function definition", '{', NULL);
5212 eat_until_matching_token(';');
5217 assert(is_declaration(ndeclaration));
5218 type_t *const orig_type = ndeclaration->declaration.type;
5219 type_t *const type = skip_typeref(orig_type);
5221 if (!is_type_function(type)) {
5222 if (is_type_valid(type)) {
5223 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5229 position_t const *const pos = &ndeclaration->base.pos;
5230 if (is_typeref(orig_type)) {
5232 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5235 if (is_type_compound(skip_typeref(type->function.return_type))) {
5236 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5238 if (type->function.unspecified_parameters) {
5239 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5241 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5244 /* §6.7.5.3:14 a function definition with () means no
5245 * parameters (and not unspecified parameters) */
5246 if (type->function.unspecified_parameters &&
5247 type->function.parameters == NULL) {
5248 type_t *copy = duplicate_type(type);
5249 copy->function.unspecified_parameters = false;
5250 ndeclaration->declaration.type = identify_new_type(copy);
5254 entity_t *const entity = record_entity(ndeclaration, true);
5255 assert(entity->kind == ENTITY_FUNCTION);
5256 assert(ndeclaration->kind == ENTITY_FUNCTION);
5258 function_t *const function = &entity->function;
5259 if (ndeclaration != entity) {
5260 function->parameters = ndeclaration->function.parameters;
5263 PUSH_SCOPE(&function->parameters);
5265 entity_t *parameter = function->parameters.entities;
5266 for (; parameter != NULL; parameter = parameter->base.next) {
5267 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5268 parameter->base.parent_scope = current_scope;
5270 assert(parameter->base.parent_scope == NULL
5271 || parameter->base.parent_scope == current_scope);
5272 parameter->base.parent_scope = current_scope;
5273 if (parameter->base.symbol == NULL) {
5274 errorf(¶meter->base.pos, "parameter name omitted");
5277 environment_push(parameter);
5280 if (function->body != NULL) {
5281 parser_error_multiple_definition(entity, HERE);
5284 /* parse function body */
5285 int label_stack_top = label_top();
5286 function_t *old_current_function = current_function;
5287 current_function = function;
5288 PUSH_CURRENT_ENTITY(entity);
5292 goto_anchor = &goto_first;
5294 label_anchor = &label_first;
5296 statement_t *const body = parse_compound_statement(false);
5297 function->body = body;
5300 check_declarations();
5301 if (is_warn_on(WARN_RETURN_TYPE) ||
5302 is_warn_on(WARN_UNREACHABLE_CODE) ||
5303 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5304 noreturn_candidate = true;
5305 check_reachable(body);
5306 if (is_warn_on(WARN_UNREACHABLE_CODE))
5307 walk_statements(body, check_unreachable, NULL);
5308 if (noreturn_candidate &&
5309 !(function->base.modifiers & DM_NORETURN)) {
5310 warningf(WARN_MISSING_NORETURN, &body->base.pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5314 if (is_main(entity)) {
5315 /* Force main to C linkage. */
5316 type_t *const type = entity->declaration.type;
5317 assert(is_type_function(type));
5318 if (type->function.linkage != LINKAGE_C) {
5319 type_t *new_type = duplicate_type(type);
5320 new_type->function.linkage = LINKAGE_C;
5321 entity->declaration.type = identify_new_type(new_type);
5324 if (enable_main_collect2_hack)
5325 prepare_main_collect2(entity);
5328 POP_CURRENT_ENTITY();
5330 assert(current_function == function);
5331 current_function = old_current_function;
5332 label_pop_to(label_stack_top);
5338 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5340 entity_t *iter = compound->members.entities;
5341 for (; iter != NULL; iter = iter->base.next) {
5342 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5345 if (iter->base.symbol == symbol) {
5347 } else if (iter->base.symbol == NULL) {
5348 /* search in anonymous structs and unions */
5349 type_t *type = skip_typeref(iter->declaration.type);
5350 if (is_type_compound(type)) {
5351 if (find_compound_entry(type->compound.compound, symbol)
5362 static void check_deprecated(const position_t *pos, const entity_t *entity)
5364 if (!is_declaration(entity))
5366 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5369 position_t const *const epos = &entity->base.pos;
5370 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5372 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5374 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P)", entity, epos);
5379 static expression_t *create_select(const position_t *pos, expression_t *addr,
5380 type_qualifiers_t qualifiers,
5383 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5385 check_deprecated(pos, entry);
5387 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5388 select->base.pos = *pos;
5389 select->select.compound = addr;
5390 select->select.compound_entry = entry;
5392 type_t *entry_type = entry->declaration.type;
5393 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5395 /* bitfields need special treatment */
5396 if (entry->compound_member.bitfield) {
5397 unsigned bit_size = entry->compound_member.bit_size;
5398 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5399 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5400 res_type = type_int;
5404 /* we always do the auto-type conversions; the & and sizeof parser contains
5405 * code to revert this! */
5406 select->base.type = automatic_type_conversion(res_type);
5413 * Find entry with symbol in compound. Search anonymous structs and unions and
5414 * creates implicit select expressions for them.
5415 * Returns the adress for the innermost compound.
5417 static expression_t *find_create_select(const position_t *pos,
5419 type_qualifiers_t qualifiers,
5420 compound_t *compound, symbol_t *symbol)
5422 entity_t *iter = compound->members.entities;
5423 for (; iter != NULL; iter = iter->base.next) {
5424 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5427 symbol_t *iter_symbol = iter->base.symbol;
5428 if (iter_symbol == NULL) {
5429 type_t *type = iter->declaration.type;
5430 if (!is_type_compound(type))
5433 compound_t *sub_compound = type->compound.compound;
5435 if (find_compound_entry(sub_compound, symbol) == NULL)
5438 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5439 sub_addr->base.implicit = true;
5440 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5444 if (iter_symbol == symbol) {
5445 return create_select(pos, addr, qualifiers, iter);
5452 static void parse_bitfield_member(entity_t *entity)
5456 expression_t *size = parse_constant_expression();
5459 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5460 type_t *type = entity->declaration.type;
5461 if (!is_type_integer(skip_typeref(type))) {
5462 errorf(HERE, "bitfield base type '%T' is not an integer type",
5466 if (is_constant_expression(size) < EXPR_CLASS_CONSTANT) {
5467 /* error already reported by parse_constant_expression */
5468 size_long = get_type_size(type) * 8;
5470 size_long = fold_constant_to_int(size);
5472 const symbol_t *symbol = entity->base.symbol;
5473 const symbol_t *user_symbol
5474 = symbol == NULL ? sym_anonymous : symbol;
5475 unsigned bit_size = get_type_size(type) * 8;
5476 if (size_long < 0) {
5477 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5478 } else if (size_long == 0 && symbol != NULL) {
5479 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5480 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5481 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5484 /* hope that people don't invent crazy types with more bits
5485 * than our struct can hold */
5487 (1 << sizeof(entity->compound_member.bit_size)*8));
5491 entity->compound_member.bitfield = true;
5492 entity->compound_member.bit_size = (unsigned char)size_long;
5495 static void parse_compound_declarators(compound_t *compound,
5496 const declaration_specifiers_t *specifiers)
5498 add_anchor_token(';');
5499 add_anchor_token(',');
5502 if (token.kind == ':') {
5503 /* anonymous bitfield */
5504 type_t *type = specifiers->type;
5505 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5506 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5507 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5508 entity->declaration.type = type;
5510 parse_bitfield_member(entity);
5512 attribute_t *attributes = parse_attributes(NULL);
5513 attribute_t **anchor = &attributes;
5514 while (*anchor != NULL)
5515 anchor = &(*anchor)->next;
5516 *anchor = specifiers->attributes;
5517 if (attributes != NULL) {
5518 handle_entity_attributes(attributes, entity);
5520 entity->declaration.attributes = attributes;
5522 entity = parse_declarator(specifiers, DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5523 position_t const *const pos = &entity->base.pos;
5524 if (entity->kind == ENTITY_TYPEDEF) {
5525 errorf(pos, "typedef not allowed as compound member");
5529 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5531 /* make sure we don't define a symbol multiple times */
5532 symbol_t *symbol = entity->base.symbol;
5533 if (symbol != NULL) {
5534 entity_t *prev = find_compound_entry(compound, symbol);
5536 position_t const *const ppos = &prev->base.pos;
5537 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5541 if (token.kind == ':') {
5542 parse_bitfield_member(entity);
5544 attribute_t *attributes = parse_attributes(NULL);
5545 handle_entity_attributes(attributes, entity);
5547 type_t *orig_type = entity->declaration.type;
5548 type_t *type = skip_typeref(orig_type);
5549 if (is_type_function(type)) {
5550 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5551 } else if (is_type_incomplete(type)) {
5552 /* §6.7.2.1:16 flexible array member */
5553 if (!is_type_array(type) ||
5554 token.kind != ';' ||
5555 look_ahead(1)->kind != '}') {
5556 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5557 } else if (compound->members.entities == NULL) {
5558 errorf(pos, "flexible array member in otherwise empty struct");
5564 append_entity(&compound->members, entity);
5565 } while (accept(','));
5566 rem_anchor_token(',');
5567 rem_anchor_token(';');
5570 anonymous_entity = NULL;
5573 static void parse_compound_type_entries(compound_t *compound)
5576 add_anchor_token('}');
5579 switch (token.kind) {
5581 case T___extension__:
5582 case T_IDENTIFIER: {
5584 declaration_specifiers_t specifiers;
5585 parse_declaration_specifiers(&specifiers);
5586 parse_compound_declarators(compound, &specifiers);
5592 rem_anchor_token('}');
5595 compound->complete = true;
5601 static type_t *parse_typename(void)
5603 declaration_specifiers_t specifiers;
5604 parse_declaration_specifiers(&specifiers);
5605 if (specifiers.storage_class != STORAGE_CLASS_NONE
5606 || specifiers.thread_local) {
5607 /* TODO: improve error message, user does probably not know what a
5608 * storage class is...
5610 errorf(&specifiers.pos, "typename must not have a storage class");
5613 type_t *result = parse_abstract_declarator(specifiers.type);
5621 typedef expression_t* (*parse_expression_function)(void);
5622 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5624 typedef struct expression_parser_function_t expression_parser_function_t;
5625 struct expression_parser_function_t {
5626 parse_expression_function parser;
5627 precedence_t infix_precedence;
5628 parse_expression_infix_function infix_parser;
5631 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5633 static type_t *get_string_type(string_encoding_t const enc)
5635 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5637 case STRING_ENCODING_CHAR:
5638 case STRING_ENCODING_UTF8: return warn ? type_const_char_ptr : type_char_ptr;
5639 case STRING_ENCODING_CHAR16: return warn ? type_char16_t_const_ptr : type_char16_t_ptr;
5640 case STRING_ENCODING_CHAR32: return warn ? type_char32_t_const_ptr : type_char32_t_ptr;
5641 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5643 panic("invalid string encoding");
5647 * Parse a string constant.
5649 static expression_t *parse_string_literal(void)
5651 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5652 expr->string_literal.value = concat_string_literals();
5653 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5658 * Parse a boolean constant.
5660 static expression_t *parse_boolean_literal(bool value)
5662 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5663 literal->base.type = type_bool;
5664 literal->literal.value.begin = value ? "true" : "false";
5665 literal->literal.value.size = value ? 4 : 5;
5667 eat(value ? T_true : T_false);
5671 static void check_number_suffix(expression_t *const expr, char const *const suffix, bool const is_float)
5673 unsigned spec = SPECIFIER_NONE;
5674 for (char const *c = suffix; *c != '\0'; ++c) {
5678 add = SPECIFIER_FLOAT;
5682 add = SPECIFIER_LONG;
5683 if (*c == c[1] && !is_float) {
5684 add |= SPECIFIER_LONG_LONG;
5690 add = SPECIFIER_UNSIGNED;
5695 add = SPECIFIER_COMPLEX;
5706 if (!(spec & SPECIFIER_FLOAT) && is_float)
5707 spec |= SPECIFIER_DOUBLE;
5709 if (!(spec & (SPECIFIER_FLOAT | SPECIFIER_DOUBLE)) == is_float)
5713 switch (spec & ~SPECIFIER_COMPLEX) {
5714 case SPECIFIER_NONE: type = type_int; break;
5715 case SPECIFIER_LONG: type = type_long; break;
5716 case SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long; break;
5717 case SPECIFIER_UNSIGNED: type = type_unsigned_int; break;
5718 case SPECIFIER_UNSIGNED | SPECIFIER_LONG: type = type_unsigned_long; break;
5719 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5720 case SPECIFIER_FLOAT: type = type_float; break;
5721 case SPECIFIER_DOUBLE: type = type_double; break;
5722 case SPECIFIER_DOUBLE | SPECIFIER_LONG: type = type_long_double; break;
5726 errorf(HERE, "invalid suffix '%s' on %s constant", suffix, is_float ? "floatingpoint" : "integer");
5730 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG && spec != SPECIFIER_DOUBLE)
5731 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5733 if (spec & SPECIFIER_COMPLEX)
5734 type = make_complex_type(get_arithmetic_akind(type), TYPE_QUALIFIER_NONE);
5736 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);
5745 static expression_t *parse_number_literal(void)
5747 string_t const *const str = &token.literal.string;
5748 char const * i = str->begin;
5749 unsigned digits = 0;
5750 bool is_float = false;
5752 /* Parse base prefix. */
5756 case 'B': case 'b': base = 2; ++i; break;
5757 case 'X': case 'x': base = 16; ++i; break;
5758 default: base = 8; digits |= 1U << 0; break;
5764 /* Parse mantissa. */
5770 errorf(HERE, "multiple decimal points in %K", &token);
5779 case '0': digit = 0; break;
5780 case '1': digit = 1; break;
5781 case '2': digit = 2; break;
5782 case '3': digit = 3; break;
5783 case '4': digit = 4; break;
5784 case '5': digit = 5; break;
5785 case '6': digit = 6; break;
5786 case '7': digit = 7; break;
5787 case '8': digit = 8; break;
5788 case '9': digit = 9; break;
5789 case 'A': case 'a': digit = 10; break;
5790 case 'B': case 'b': digit = 11; break;
5791 case 'C': case 'c': digit = 12; break;
5792 case 'D': case 'd': digit = 13; break;
5793 case 'E': case 'e': digit = 14; break;
5794 case 'F': case 'f': digit = 15; break;
5796 default: goto done_mantissa;
5799 if (digit >= 10 && base != 16)
5802 digits |= 1U << digit;
5806 /* Parse exponent. */
5810 errorf(HERE, "binary floating %K not allowed", &token);
5815 if (*i == 'E' || *i == 'e') {
5817 goto parse_exponent;
5822 if (*i == 'P' || *i == 'p') {
5827 if (*i == '-' || *i == '+')
5833 } while (isdigit(*i));
5835 errorf(HERE, "exponent of %K has no digits", &token);
5837 } else if (is_float) {
5838 errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5844 panic("invalid base");
5848 expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5849 expr->literal.value = *str;
5853 errorf(HERE, "%K has no digits", &token);
5854 } else if (digits & ~((1U << base) - 1)) {
5855 errorf(HERE, "invalid digit in %K", &token);
5857 expr->literal.suffix = i;
5858 check_number_suffix(expr, i, is_float);
5867 * Parse a character constant.
5869 static expression_t *parse_character_constant(void)
5871 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5872 literal->string_literal.value = token.literal.string;
5874 size_t const size = get_string_len(&token.literal.string);
5875 switch (token.literal.string.encoding) {
5876 case STRING_ENCODING_CHAR:
5877 case STRING_ENCODING_UTF8:
5878 literal->base.type = c_mode & _CXX ? type_char : type_int;
5880 if (!GNU_MODE && !(c_mode & _C99)) {
5881 errorf(HERE, "more than 1 character in character constant");
5883 literal->base.type = type_int;
5884 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5889 case STRING_ENCODING_CHAR16: literal->base.type = type_char16_t; goto warn_multi;
5890 case STRING_ENCODING_CHAR32: literal->base.type = type_char32_t; goto warn_multi;
5891 case STRING_ENCODING_WIDE: literal->base.type = type_wchar_t; goto warn_multi;
5894 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5899 eat(T_CHARACTER_CONSTANT);
5903 static entity_t *create_implicit_function(symbol_t *symbol, position_t const *const pos)
5905 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5906 ntype->function.return_type = type_int;
5907 ntype->function.unspecified_parameters = true;
5908 ntype->function.linkage = LINKAGE_C;
5909 type_t *type = identify_new_type(ntype);
5911 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5912 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5913 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5914 entity->declaration.type = type;
5915 entity->declaration.implicit = true;
5917 if (current_scope != NULL)
5918 record_entity(entity, false);
5924 * Performs automatic type cast as described in §6.3.2.1.
5926 * @param orig_type the original type
5928 static type_t *automatic_type_conversion(type_t *orig_type)
5930 type_t *type = skip_typeref(orig_type);
5931 if (is_type_array(type)) {
5932 array_type_t *array_type = &type->array;
5933 type_t *element_type = array_type->element_type;
5934 unsigned qualifiers = array_type->base.qualifiers;
5936 return make_pointer_type(element_type, qualifiers);
5939 if (is_type_function(type)) {
5940 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5947 * reverts the automatic casts of array to pointer types and function
5948 * to function-pointer types as defined §6.3.2.1
5950 type_t *revert_automatic_type_conversion(const expression_t *expression)
5952 switch (expression->kind) {
5953 case EXPR_REFERENCE: {
5954 entity_t *entity = expression->reference.entity;
5955 if (is_declaration(entity)) {
5956 return entity->declaration.type;
5957 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5958 return entity->enum_value.enum_type;
5960 panic("no declaration or enum in reference");
5965 entity_t *entity = expression->select.compound_entry;
5966 assert(is_declaration(entity));
5967 type_t *type = entity->declaration.type;
5968 return get_qualified_type(type, expression->base.type->base.qualifiers);
5971 case EXPR_UNARY_DEREFERENCE: {
5972 const expression_t *const value = expression->unary.value;
5973 type_t *const type = skip_typeref(value->base.type);
5974 if (!is_type_pointer(type))
5975 return type_error_type;
5976 return type->pointer.points_to;
5979 case EXPR_ARRAY_ACCESS: {
5980 const expression_t *array_ref = expression->array_access.array_ref;
5981 type_t *type_left = skip_typeref(array_ref->base.type);
5982 if (!is_type_pointer(type_left))
5983 return type_error_type;
5984 return type_left->pointer.points_to;
5987 case EXPR_STRING_LITERAL: {
5988 size_t const size = get_string_len(&expression->string_literal.value) + 1;
5989 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
5990 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
5993 case EXPR_COMPOUND_LITERAL:
5994 return expression->compound_literal.type;
5999 return expression->base.type;
6003 * Find an entity matching a symbol in a scope.
6004 * Uses current scope if scope is NULL
6006 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6007 namespace_tag_t namespc)
6009 if (scope == NULL) {
6010 return get_entity(symbol, namespc);
6013 /* we should optimize here, if scope grows above a certain size we should
6014 construct a hashmap here... */
6015 entity_t *entity = scope->entities;
6016 for ( ; entity != NULL; entity = entity->base.next) {
6017 if (entity->base.symbol == symbol
6018 && (namespace_tag_t)entity->base.namespc == namespc)
6025 static entity_t *parse_qualified_identifier(void)
6027 /* namespace containing the symbol */
6030 const scope_t *lookup_scope = NULL;
6032 if (accept(T_COLONCOLON))
6033 lookup_scope = &unit->scope;
6037 symbol = expect_identifier("while parsing identifier", &pos);
6039 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6042 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6044 if (!accept(T_COLONCOLON))
6047 switch (entity->kind) {
6048 case ENTITY_NAMESPACE:
6049 lookup_scope = &entity->namespacee.members;
6054 lookup_scope = &entity->compound.members;
6057 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6058 symbol, get_entity_kind_name(entity->kind));
6060 /* skip further qualifications */
6061 while (accept(T_IDENTIFIER) && accept(T_COLONCOLON)) {}
6063 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6067 if (entity == NULL) {
6068 if (!strict_mode && token.kind == '(') {
6069 /* an implicitly declared function */
6070 entity = create_implicit_function(symbol, &pos);
6071 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6073 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6074 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6081 static expression_t *parse_reference(void)
6083 position_t const pos = *HERE;
6084 entity_t *const entity = parse_qualified_identifier();
6087 if (is_declaration(entity)) {
6088 orig_type = entity->declaration.type;
6089 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6090 orig_type = entity->enum_value.enum_type;
6092 panic("expected declaration or enum value in reference");
6095 /* we always do the auto-type conversions; the & and sizeof parser contains
6096 * code to revert this! */
6097 type_t *type = automatic_type_conversion(orig_type);
6099 expression_kind_t kind = EXPR_REFERENCE;
6100 if (entity->kind == ENTITY_ENUM_VALUE)
6101 kind = EXPR_ENUM_CONSTANT;
6103 expression_t *expression = allocate_expression_zero(kind);
6104 expression->base.pos = pos;
6105 expression->base.type = type;
6106 expression->reference.entity = entity;
6108 /* this declaration is used */
6109 if (is_declaration(entity)) {
6110 entity->declaration.used = true;
6113 if (entity->base.parent_scope != file_scope
6114 && (current_function != NULL
6115 && entity->base.parent_scope->depth < current_function->parameters.depth)
6116 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6117 /* access of a variable from an outer function */
6118 entity->variable.address_taken = true;
6119 current_function->need_closure = true;
6122 check_deprecated(&pos, entity);
6127 static bool semantic_cast(expression_t *cast)
6129 expression_t *expression = cast->unary.value;
6130 type_t *orig_dest_type = cast->base.type;
6131 type_t *orig_type_right = expression->base.type;
6132 type_t const *dst_type = skip_typeref(orig_dest_type);
6133 type_t const *src_type = skip_typeref(orig_type_right);
6134 position_t const *pos = &cast->base.pos;
6136 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation
6137 * than for utility. */
6138 if (is_type_void(dst_type))
6141 /* only integer and pointer can be casted to pointer */
6142 if (is_type_pointer(dst_type) &&
6143 !is_type_pointer(src_type) &&
6144 !is_type_integer(src_type) &&
6145 is_type_valid(src_type)) {
6146 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6150 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6151 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6155 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6156 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6160 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6161 type_t *src = skip_typeref(src_type->pointer.points_to);
6162 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6163 unsigned missing_qualifiers =
6164 src->base.qualifiers & ~dst->base.qualifiers;
6165 if (missing_qualifiers != 0) {
6166 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6172 static void semantic_complex_extract(unary_expression_t *extract)
6174 type_t *orig_value_type = extract->value->base.type;
6175 type_t *value_type = skip_typeref(orig_value_type);
6176 if (!is_type_valid(value_type)) {
6177 extract->base.type = type_error_type;
6181 type_t *type = value_type;
6182 if (!is_type_complex(type)) {
6183 if (!is_type_arithmetic(type)) {
6184 errorf(&extract->base.pos,
6185 "%s requires an argument with complex or arithmetic type, got '%T'",
6186 extract->base.kind == EXPR_UNARY_IMAG ? "__imag__" : "__real__",
6188 extract->base.type = type_error_type;
6191 atomic_type_kind_t const akind = get_arithmetic_akind(type);
6192 type = make_complex_type(akind, TYPE_QUALIFIER_NONE);
6193 extract->value = create_implicit_cast(extract->value, type);
6195 assert(type->kind == TYPE_COMPLEX);
6196 type = make_atomic_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
6197 extract->base.type = type;
6200 static expression_t *parse_compound_literal(position_t const *const pos,
6203 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6204 expression->base.pos = *pos;
6205 bool global_scope = current_scope == file_scope;
6207 parse_initializer_env_t env;
6210 env.must_be_constant = global_scope;
6211 initializer_t *initializer = parse_initializer(&env);
6214 expression->base.type = automatic_type_conversion(type);
6215 expression->compound_literal.initializer = initializer;
6216 expression->compound_literal.type = type;
6217 expression->compound_literal.global_scope = global_scope;
6223 * Parse a cast expression.
6225 static expression_t *parse_cast(void)
6227 position_t const pos = *HERE;
6230 add_anchor_token(')');
6232 type_t *type = parse_typename();
6234 rem_anchor_token(')');
6237 if (token.kind == '{') {
6238 return parse_compound_literal(&pos, type);
6241 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6242 cast->base.pos = pos;
6244 expression_t *value = parse_subexpression(PREC_CAST);
6245 cast->base.type = type;
6246 cast->unary.value = value;
6248 if (!semantic_cast(cast)) {
6249 cast->base.type = type_error_type;
6255 static expression_t *parse_complex_extract_expression(expression_kind_t const kind)
6257 expression_t *extract = allocate_expression_zero(kind);
6260 extract->unary.value = parse_subexpression(PREC_CAST);
6261 semantic_complex_extract(&extract->unary);
6266 * Parse a statement expression.
6268 static expression_t *parse_statement_expression(void)
6270 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6273 add_anchor_token(')');
6275 statement_t *statement = parse_compound_statement(true);
6276 statement->compound.stmt_expr = true;
6277 expression->statement.statement = statement;
6279 /* find last statement and use its type */
6280 type_t *type = type_void;
6281 const statement_t *stmt = statement->compound.statements;
6283 while (stmt->base.next != NULL)
6284 stmt = stmt->base.next;
6286 if (stmt->kind == STATEMENT_EXPRESSION) {
6287 type = stmt->expression.expression->base.type;
6290 position_t const *const pos = &expression->base.pos;
6291 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6293 expression->base.type = type;
6295 rem_anchor_token(')');
6301 * Parse a parenthesized expression.
6303 static expression_t *parse_parenthesized_expression(void)
6305 token_t const* const la1 = look_ahead(1);
6306 switch (la1->kind) {
6308 /* gcc extension: a statement expression */
6309 return parse_statement_expression();
6312 if (is_typedef_symbol(la1->base.symbol)) {
6314 return parse_cast();
6319 add_anchor_token(')');
6320 expression_t *result = parse_expression();
6321 result->base.parenthesized = true;
6322 rem_anchor_token(')');
6328 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6330 if (current_function == NULL) {
6331 errorf(HERE, "%K used outside of a function", &token);
6334 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6335 expression->base.type = type_char_ptr;
6336 expression->funcname.kind = kind;
6343 static designator_t *parse_designator(void)
6345 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6346 result->symbol = expect_identifier("while parsing member designator", &result->pos);
6347 if (!result->symbol)
6350 designator_t *last_designator = result;
6353 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6354 designator->symbol = expect_identifier("while parsing member designator", &designator->pos);
6355 if (!designator->symbol)
6358 last_designator->next = designator;
6359 last_designator = designator;
6363 add_anchor_token(']');
6364 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6365 designator->pos = *HERE;
6366 designator->array_index = parse_expression();
6367 rem_anchor_token(']');
6370 last_designator->next = designator;
6371 last_designator = designator;
6381 * Parse the __builtin_offsetof() expression.
6383 static expression_t *parse_offsetof(void)
6385 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6386 expression->base.type = type_size_t;
6388 eat(T___builtin_offsetof);
6390 add_anchor_token(')');
6391 add_anchor_token(',');
6393 type_t *type = parse_typename();
6394 rem_anchor_token(',');
6396 designator_t *designator = parse_designator();
6397 rem_anchor_token(')');
6400 expression->offsetofe.type = type;
6401 expression->offsetofe.designator = designator;
6404 memset(&path, 0, sizeof(path));
6405 path.top_type = type;
6406 path.path = NEW_ARR_F(type_path_entry_t, 0);
6408 descend_into_subtype(&path);
6410 if (!walk_designator(&path, designator, true)) {
6411 return create_error_expression();
6414 DEL_ARR_F(path.path);
6419 static bool is_last_parameter(expression_t *const param)
6421 if (param->kind == EXPR_REFERENCE) {
6422 entity_t *const entity = param->reference.entity;
6423 if (entity->kind == ENTITY_PARAMETER &&
6424 !entity->base.next &&
6425 entity->base.parent_scope == ¤t_function->parameters) {
6430 if (!is_type_valid(skip_typeref(param->base.type)))
6437 * Parses a __builtin_va_start() expression.
6439 static expression_t *parse_va_start(void)
6441 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6443 eat(T___builtin_va_start);
6445 add_anchor_token(')');
6446 add_anchor_token(',');
6448 expression->va_starte.ap = parse_assignment_expression();
6449 rem_anchor_token(',');
6451 expression_t *const param = parse_assignment_expression();
6452 expression->va_starte.parameter = param;
6453 rem_anchor_token(')');
6456 if (!current_function) {
6457 errorf(&expression->base.pos, "'va_start' used outside of function");
6458 } else if (!current_function->base.type->function.variadic) {
6459 errorf(&expression->base.pos, "'va_start' used in non-variadic function");
6460 } else if (!is_last_parameter(param)) {
6461 errorf(¶m->base.pos, "second argument of 'va_start' must be last parameter of the current function");
6468 * Parses a __builtin_va_arg() expression.
6470 static expression_t *parse_va_arg(void)
6472 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6474 eat(T___builtin_va_arg);
6476 add_anchor_token(')');
6477 add_anchor_token(',');
6480 ap.expression = parse_assignment_expression();
6481 expression->va_arge.ap = ap.expression;
6482 check_call_argument(type_valist, &ap, 1);
6484 rem_anchor_token(',');
6486 expression->base.type = parse_typename();
6487 rem_anchor_token(')');
6494 * Parses a __builtin_va_copy() expression.
6496 static expression_t *parse_va_copy(void)
6498 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6500 eat(T___builtin_va_copy);
6502 add_anchor_token(')');
6503 add_anchor_token(',');
6505 expression_t *dst = parse_assignment_expression();
6506 assign_error_t error = semantic_assign(type_valist, dst);
6507 report_assign_error(error, type_valist, dst, "call argument 1",
6509 expression->va_copye.dst = dst;
6511 rem_anchor_token(',');
6514 call_argument_t src;
6515 src.expression = parse_assignment_expression();
6516 check_call_argument(type_valist, &src, 2);
6517 expression->va_copye.src = src.expression;
6518 rem_anchor_token(')');
6525 * Parses a __builtin_constant_p() expression.
6527 static expression_t *parse_builtin_constant(void)
6529 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6531 eat(T___builtin_constant_p);
6533 add_anchor_token(')');
6535 expression->builtin_constant.value = parse_expression();
6536 rem_anchor_token(')');
6538 expression->base.type = type_int;
6544 * Parses a __builtin_types_compatible_p() expression.
6546 static expression_t *parse_builtin_types_compatible(void)
6548 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6550 eat(T___builtin_types_compatible_p);
6552 add_anchor_token(')');
6553 add_anchor_token(',');
6555 expression->builtin_types_compatible.left = parse_typename();
6556 rem_anchor_token(',');
6558 expression->builtin_types_compatible.right = parse_typename();
6559 rem_anchor_token(')');
6561 expression->base.type = type_int;
6567 * Parses a __builtin_is_*() compare expression.
6569 static expression_t *parse_compare_builtin(void)
6571 expression_kind_t kind;
6572 switch (token.kind) {
6573 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6574 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6575 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6576 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6577 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6578 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6579 default: internal_errorf(HERE, "invalid compare builtin found");
6581 expression_t *const expression = allocate_expression_zero(kind);
6584 add_anchor_token(')');
6585 add_anchor_token(',');
6587 expression->binary.left = parse_assignment_expression();
6588 rem_anchor_token(',');
6590 expression->binary.right = parse_assignment_expression();
6591 rem_anchor_token(')');
6594 type_t *const orig_type_left = expression->binary.left->base.type;
6595 type_t *const orig_type_right = expression->binary.right->base.type;
6597 type_t *const type_left = skip_typeref(orig_type_left);
6598 type_t *const type_right = skip_typeref(orig_type_right);
6599 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6600 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6601 type_error_incompatible("invalid operands in comparison",
6602 &expression->base.pos, orig_type_left, orig_type_right);
6605 semantic_comparison(&expression->binary, true);
6612 * Parses a MS assume() expression.
6614 static expression_t *parse_assume(void)
6616 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6620 add_anchor_token(')');
6622 expression->unary.value = parse_expression();
6623 rem_anchor_token(')');
6626 expression->base.type = type_void;
6631 * Return the label for the current symbol or create a new one.
6633 static label_t *get_label(char const *const context)
6635 assert(current_function != NULL);
6637 symbol_t *const sym = expect_identifier(context, NULL);
6641 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6642 /* If we find a local label, we already created the declaration. */
6643 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6644 if (label->base.parent_scope != current_scope) {
6645 assert(label->base.parent_scope->depth < current_scope->depth);
6646 current_function->goto_to_outer = true;
6648 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6649 /* There is no matching label in the same function, so create a new one. */
6650 position_t const nowhere = { NULL, 0, 0, false };
6651 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6655 return &label->label;
6659 * Parses a GNU && label address expression.
6661 static expression_t *parse_label_address(void)
6663 position_t const pos = *HERE;
6666 label_t *const label = get_label("while parsing label address");
6668 return create_error_expression();
6671 label->address_taken = true;
6673 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6674 expression->base.pos = pos;
6676 /* label address is treated as a void pointer */
6677 expression->base.type = type_void_ptr;
6678 expression->label_address.label = label;
6683 * Parse a microsoft __noop expression.
6685 static expression_t *parse_noop_expression(void)
6687 /* the result is a (int)0 */
6688 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6689 literal->base.type = type_int;
6690 literal->literal.value.begin = "__noop";
6691 literal->literal.value.size = 6;
6695 if (token.kind == '(') {
6696 /* parse arguments */
6698 add_anchor_token(')');
6699 add_anchor_token(',');
6701 if (token.kind != ')') do {
6702 (void)parse_assignment_expression();
6703 } while (accept(','));
6705 rem_anchor_token(',');
6706 rem_anchor_token(')');
6714 * Parses a primary expression.
6716 static expression_t *parse_primary_expression(void)
6718 switch (token.kind) {
6719 case T_false: return parse_boolean_literal(false);
6720 case T_true: return parse_boolean_literal(true);
6721 case T_NUMBER: return parse_number_literal();
6722 case T_CHARACTER_CONSTANT: return parse_character_constant();
6723 case T_STRING_LITERAL: return parse_string_literal();
6724 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6725 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6726 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6727 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6728 case T___builtin_offsetof: return parse_offsetof();
6729 case T___builtin_va_start: return parse_va_start();
6730 case T___builtin_va_arg: return parse_va_arg();
6731 case T___builtin_va_copy: return parse_va_copy();
6732 case T___builtin_isgreater:
6733 case T___builtin_isgreaterequal:
6734 case T___builtin_isless:
6735 case T___builtin_islessequal:
6736 case T___builtin_islessgreater:
6737 case T___builtin_isunordered: return parse_compare_builtin();
6738 case T___builtin_constant_p: return parse_builtin_constant();
6739 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6740 case T__assume: return parse_assume();
6743 return parse_label_address();
6746 case '(': return parse_parenthesized_expression();
6747 case T___noop: return parse_noop_expression();
6748 case T___imag__: return parse_complex_extract_expression(EXPR_UNARY_IMAG);
6749 case T___real__: return parse_complex_extract_expression(EXPR_UNARY_REAL);
6751 /* Gracefully handle type names while parsing expressions. */
6753 return parse_reference();
6755 if (!is_typedef_symbol(token.base.symbol)) {
6756 return parse_reference();
6760 position_t const pos = *HERE;
6761 declaration_specifiers_t specifiers;
6762 parse_declaration_specifiers(&specifiers);
6763 type_t const *const type = parse_abstract_declarator(specifiers.type);
6764 errorf(&pos, "encountered type '%T' while parsing expression", type);
6765 return create_error_expression();
6769 errorf(HERE, "unexpected token %K, expected an expression", &token);
6771 return create_error_expression();
6774 static expression_t *parse_array_expression(expression_t *left)
6776 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6777 array_access_expression_t *const arr = &expr->array_access;
6780 add_anchor_token(']');
6782 expression_t *const inside = parse_expression();
6784 type_t *const orig_type_left = left->base.type;
6785 type_t *const orig_type_inside = inside->base.type;
6787 type_t *const type_left = skip_typeref(orig_type_left);
6788 type_t *const type_inside = skip_typeref(orig_type_inside);
6794 if (is_type_pointer(type_left)) {
6797 idx_type = type_inside;
6798 res_type = type_left->pointer.points_to;
6800 } else if (is_type_pointer(type_inside)) {
6801 arr->flipped = true;
6804 idx_type = type_left;
6805 res_type = type_inside->pointer.points_to;
6807 res_type = automatic_type_conversion(res_type);
6808 if (!is_type_integer(idx_type)) {
6809 if (is_type_valid(idx_type))
6810 errorf(&idx->base.pos, "array subscript must have integer type");
6811 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6812 position_t const *const pos = &idx->base.pos;
6813 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6816 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6817 errorf(&expr->base.pos, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6819 res_type = type_error_type;
6824 arr->array_ref = ref;
6826 arr->base.type = res_type;
6828 rem_anchor_token(']');
6833 static bool is_bitfield(const expression_t *expression)
6835 return expression->kind == EXPR_SELECT
6836 && expression->select.compound_entry->compound_member.bitfield;
6839 static expression_t *parse_typeprop(expression_kind_t const kind)
6841 expression_t *tp_expression = allocate_expression_zero(kind);
6842 tp_expression->base.type = type_size_t;
6844 eat(kind == EXPR_SIZEOF ? T_sizeof : T__Alignof);
6847 expression_t *expression;
6848 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6849 position_t const pos = *HERE;
6851 add_anchor_token(')');
6852 orig_type = parse_typename();
6853 rem_anchor_token(')');
6856 if (token.kind == '{') {
6857 /* It was not sizeof(type) after all. It is sizeof of an expression
6858 * starting with a compound literal */
6859 expression = parse_compound_literal(&pos, orig_type);
6860 goto typeprop_expression;
6863 expression = parse_subexpression(PREC_UNARY);
6865 typeprop_expression:
6866 if (is_bitfield(expression)) {
6867 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6868 errorf(&tp_expression->base.pos,
6869 "operand of %s expression must not be a bitfield", what);
6872 tp_expression->typeprop.tp_expression = expression;
6874 orig_type = revert_automatic_type_conversion(expression);
6875 expression->base.type = orig_type;
6878 tp_expression->typeprop.type = orig_type;
6879 type_t const* const type = skip_typeref(orig_type);
6880 char const* wrong_type = NULL;
6881 if (is_type_incomplete(type)) {
6882 if (!is_type_void(type) || !GNU_MODE)
6883 wrong_type = "incomplete";
6884 } else if (type->kind == TYPE_FUNCTION) {
6886 /* function types are allowed (and return 1) */
6887 position_t const *const pos = &tp_expression->base.pos;
6888 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6889 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6891 wrong_type = "function";
6895 if (wrong_type != NULL) {
6896 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6897 errorf(&tp_expression->base.pos,
6898 "operand of %s expression must not be of %s type '%T'",
6899 what, wrong_type, orig_type);
6902 return tp_expression;
6905 static expression_t *parse_sizeof(void)
6907 return parse_typeprop(EXPR_SIZEOF);
6910 static expression_t *parse_alignof(void)
6912 return parse_typeprop(EXPR_ALIGNOF);
6915 static expression_t *parse_select_expression(expression_t *addr)
6917 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6918 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6919 position_t const pos = *HERE;
6922 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6924 return create_error_expression();
6926 type_t *const orig_type = addr->base.type;
6927 type_t *const type = skip_typeref(orig_type);
6930 bool saw_error = false;
6931 if (is_type_pointer(type)) {
6932 if (!select_left_arrow) {
6934 "request for member '%Y' in something not a struct or union, but '%T'",
6938 type_left = skip_typeref(type->pointer.points_to);
6940 if (select_left_arrow && is_type_valid(type)) {
6941 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6947 if (!is_type_compound(type_left)) {
6948 if (is_type_valid(type_left) && !saw_error) {
6950 "request for member '%Y' in something not a struct or union, but '%T'",
6953 return create_error_expression();
6956 compound_t *compound = type_left->compound.compound;
6957 if (!compound->complete) {
6958 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6960 return create_error_expression();
6963 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6964 expression_t *result =
6965 find_create_select(&pos, addr, qualifiers, compound, symbol);
6967 if (result == NULL) {
6968 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6969 return create_error_expression();
6975 static void check_call_argument(type_t *expected_type,
6976 call_argument_t *argument, unsigned pos)
6978 type_t *expected_type_skip = skip_typeref(expected_type);
6979 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6980 expression_t *arg_expr = argument->expression;
6981 type_t *arg_type = skip_typeref(arg_expr->base.type);
6983 /* handle transparent union gnu extension */
6984 if (is_type_union(expected_type_skip)
6985 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6986 compound_t *union_decl = expected_type_skip->compound.compound;
6987 type_t *best_type = NULL;
6988 entity_t *entry = union_decl->members.entities;
6989 for ( ; entry != NULL; entry = entry->base.next) {
6990 assert(is_declaration(entry));
6991 type_t *decl_type = entry->declaration.type;
6992 error = semantic_assign(decl_type, arg_expr);
6993 if (error == ASSIGN_ERROR_INCOMPATIBLE
6994 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6997 if (error == ASSIGN_SUCCESS) {
6998 best_type = decl_type;
6999 } else if (best_type == NULL) {
7000 best_type = decl_type;
7004 if (best_type != NULL) {
7005 expected_type = best_type;
7009 error = semantic_assign(expected_type, arg_expr);
7010 argument->expression = create_implicit_cast(arg_expr, expected_type);
7012 if (error != ASSIGN_SUCCESS) {
7013 /* report exact scope in error messages (like "in argument 3") */
7015 snprintf(buf, sizeof(buf), "call argument %u", pos);
7016 report_assign_error(error, expected_type, arg_expr, buf,
7017 &arg_expr->base.pos);
7019 type_t *const promoted_type = get_default_promoted_type(arg_type);
7020 if (!types_compatible(expected_type_skip, promoted_type) &&
7021 !types_compatible(expected_type_skip, type_void_ptr) &&
7022 !types_compatible(type_void_ptr, promoted_type)) {
7023 /* Deliberately show the skipped types in this warning */
7024 position_t const *const apos = &arg_expr->base.pos;
7025 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7031 * Handle the semantic restrictions of builtin calls
7033 static void handle_builtin_argument_restrictions(call_expression_t *call)
7035 entity_t *entity = call->function->reference.entity;
7036 switch (entity->function.btk) {
7038 switch (entity->function.b.firm_builtin_kind) {
7039 case ir_bk_return_address:
7040 case ir_bk_frame_address: {
7041 /* argument must be constant */
7042 call_argument_t *argument = call->arguments;
7044 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7045 errorf(&call->base.pos,
7046 "argument of '%Y' must be a constant expression",
7047 call->function->reference.entity->base.symbol);
7051 case ir_bk_prefetch:
7052 /* second and third argument must be constant if existent */
7053 if (call->arguments == NULL)
7055 call_argument_t *rw = call->arguments->next;
7056 call_argument_t *locality = NULL;
7059 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7060 errorf(&call->base.pos,
7061 "second argument of '%Y' must be a constant expression",
7062 call->function->reference.entity->base.symbol);
7064 locality = rw->next;
7066 if (locality != NULL) {
7067 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7068 errorf(&call->base.pos,
7069 "third argument of '%Y' must be a constant expression",
7070 call->function->reference.entity->base.symbol);
7078 case BUILTIN_OBJECT_SIZE:
7079 if (call->arguments == NULL)
7082 call_argument_t *arg = call->arguments->next;
7083 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7084 errorf(&call->base.pos,
7085 "second argument of '%Y' must be a constant expression",
7086 call->function->reference.entity->base.symbol);
7095 * Parse a call expression, i.e. expression '( ... )'.
7097 * @param expression the function address
7099 static expression_t *parse_call_expression(expression_t *expression)
7101 expression_t *result = allocate_expression_zero(EXPR_CALL);
7102 call_expression_t *call = &result->call;
7103 call->function = expression;
7105 type_t *const orig_type = expression->base.type;
7106 type_t *const type = skip_typeref(orig_type);
7108 function_type_t *function_type = NULL;
7109 if (is_type_pointer(type)) {
7110 type_t *const to_type = skip_typeref(type->pointer.points_to);
7112 if (is_type_function(to_type)) {
7113 function_type = &to_type->function;
7114 call->base.type = function_type->return_type;
7118 if (function_type == NULL && is_type_valid(type)) {
7120 "called object '%E' (type '%T') is not a pointer to a function",
7121 expression, orig_type);
7124 /* parse arguments */
7126 add_anchor_token(')');
7127 add_anchor_token(',');
7129 if (token.kind != ')') {
7130 call_argument_t **anchor = &call->arguments;
7132 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7133 argument->expression = parse_assignment_expression();
7136 anchor = &argument->next;
7137 } while (accept(','));
7139 rem_anchor_token(',');
7140 rem_anchor_token(')');
7143 if (function_type == NULL)
7146 /* check type and count of call arguments */
7147 function_parameter_t *parameter = function_type->parameters;
7148 call_argument_t *argument = call->arguments;
7149 if (!function_type->unspecified_parameters) {
7150 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7151 parameter = parameter->next, argument = argument->next) {
7152 check_call_argument(parameter->type, argument, ++pos);
7155 if (parameter != NULL) {
7156 errorf(&expression->base.pos, "too few arguments to function '%E'",
7158 } else if (argument != NULL && !function_type->variadic) {
7159 errorf(&argument->expression->base.pos,
7160 "too many arguments to function '%E'", expression);
7164 /* do default promotion for other arguments */
7165 for (; argument != NULL; argument = argument->next) {
7166 type_t *argument_type = argument->expression->base.type;
7167 if (!is_type_object(skip_typeref(argument_type))) {
7168 errorf(&argument->expression->base.pos,
7169 "call argument '%E' must not be void", argument->expression);
7172 argument_type = get_default_promoted_type(argument_type);
7174 argument->expression
7175 = create_implicit_cast(argument->expression, argument_type);
7180 if (is_type_compound(skip_typeref(function_type->return_type))) {
7181 position_t const *const pos = &expression->base.pos;
7182 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7185 if (expression->kind == EXPR_REFERENCE) {
7186 reference_expression_t *reference = &expression->reference;
7187 if (reference->entity->kind == ENTITY_FUNCTION &&
7188 reference->entity->function.btk != BUILTIN_NONE)
7189 handle_builtin_argument_restrictions(call);
7195 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7197 static bool same_compound_type(const type_t *type1, const type_t *type2)
7200 is_type_compound(type1) &&
7201 type1->kind == type2->kind &&
7202 type1->compound.compound == type2->compound.compound;
7205 static expression_t const *get_reference_address(expression_t const *expr)
7207 bool regular_take_address = true;
7209 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7210 expr = expr->unary.value;
7212 regular_take_address = false;
7215 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7218 expr = expr->unary.value;
7221 if (expr->kind != EXPR_REFERENCE)
7224 /* special case for functions which are automatically converted to a
7225 * pointer to function without an extra TAKE_ADDRESS operation */
7226 if (!regular_take_address &&
7227 expr->reference.entity->kind != ENTITY_FUNCTION) {
7234 static void warn_reference_address_as_bool(expression_t const* expr)
7236 expr = get_reference_address(expr);
7238 position_t const *const pos = &expr->base.pos;
7239 entity_t const *const ent = expr->reference.entity;
7240 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7244 static void warn_assignment_in_condition(const expression_t *const expr)
7246 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7248 if (expr->base.parenthesized)
7250 position_t const *const pos = &expr->base.pos;
7251 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7254 static void semantic_condition(expression_t const *const expr,
7255 char const *const context)
7257 type_t *const type = skip_typeref(expr->base.type);
7258 if (is_type_scalar(type)) {
7259 warn_reference_address_as_bool(expr);
7260 warn_assignment_in_condition(expr);
7261 } else if (is_type_valid(type)) {
7262 errorf(&expr->base.pos, "%s must have scalar type", context);
7267 * Parse a conditional expression, i.e. 'expression ? ... : ...'.
7269 * @param expression the conditional expression
7271 static expression_t *parse_conditional_expression(expression_t *expression)
7273 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7275 conditional_expression_t *conditional = &result->conditional;
7276 conditional->condition = expression;
7279 add_anchor_token(':');
7281 /* §6.5.15:2 The first operand shall have scalar type. */
7282 semantic_condition(expression, "condition of conditional operator");
7284 expression_t *true_expression = expression;
7285 bool gnu_cond = false;
7286 if (GNU_MODE && token.kind == ':') {
7289 true_expression = parse_expression();
7291 rem_anchor_token(':');
7293 expression_t *false_expression =
7294 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7296 type_t *const orig_true_type = true_expression->base.type;
7297 type_t *const orig_false_type = false_expression->base.type;
7298 type_t *const true_type = skip_typeref(orig_true_type);
7299 type_t *const false_type = skip_typeref(orig_false_type);
7302 position_t const *const pos = &conditional->base.pos;
7303 type_t *result_type;
7304 if (is_type_void(true_type) || is_type_void(false_type)) {
7305 /* ISO/IEC 14882:1998(E) §5.16:2 */
7306 if (true_expression->kind == EXPR_UNARY_THROW) {
7307 result_type = false_type;
7308 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7309 result_type = true_type;
7311 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7312 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7314 result_type = type_void;
7316 } else if (is_type_arithmetic(true_type)
7317 && is_type_arithmetic(false_type)) {
7318 result_type = semantic_arithmetic(true_type, false_type);
7319 } else if (same_compound_type(true_type, false_type)) {
7320 /* just take 1 of the 2 types */
7321 result_type = true_type;
7322 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7323 type_t *pointer_type;
7325 expression_t *other_expression;
7326 if (is_type_pointer(true_type) &&
7327 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7328 pointer_type = true_type;
7329 other_type = false_type;
7330 other_expression = false_expression;
7332 pointer_type = false_type;
7333 other_type = true_type;
7334 other_expression = true_expression;
7337 if (is_null_pointer_constant(other_expression)) {
7338 result_type = pointer_type;
7339 } else if (is_type_pointer(other_type)) {
7340 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7341 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7344 if (is_type_void(to1) || is_type_void(to2)) {
7346 } else if (types_compatible(get_unqualified_type(to1),
7347 get_unqualified_type(to2))) {
7350 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7354 type_t *const type =
7355 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7356 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7357 } else if (is_type_integer(other_type)) {
7358 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7359 result_type = pointer_type;
7361 goto types_incompatible;
7365 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7366 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7368 result_type = type_error_type;
7371 conditional->true_expression
7372 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7373 conditional->false_expression
7374 = create_implicit_cast(false_expression, result_type);
7375 conditional->base.type = result_type;
7380 * Parse an extension expression.
7382 static expression_t *parse_extension(void)
7385 expression_t *expression = parse_subexpression(PREC_UNARY);
7391 * Parse a __builtin_classify_type() expression.
7393 static expression_t *parse_builtin_classify_type(void)
7395 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7396 result->base.type = type_int;
7398 eat(T___builtin_classify_type);
7400 add_anchor_token(')');
7402 expression_t *expression = parse_expression();
7403 rem_anchor_token(')');
7405 result->classify_type.type_expression = expression;
7411 * Parse a delete expression
7412 * ISO/IEC 14882:1998(E) §5.3.5
7414 static expression_t *parse_delete(void)
7416 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7417 result->base.type = type_void;
7422 result->kind = EXPR_UNARY_DELETE_ARRAY;
7426 expression_t *const value = parse_subexpression(PREC_CAST);
7427 result->unary.value = value;
7429 type_t *const type = skip_typeref(value->base.type);
7430 if (!is_type_pointer(type)) {
7431 if (is_type_valid(type)) {
7432 errorf(&value->base.pos,
7433 "operand of delete must have pointer type");
7435 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7436 position_t const *const pos = &value->base.pos;
7437 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7444 * Parse a throw expression
7445 * ISO/IEC 14882:1998(E) §15:1
7447 static expression_t *parse_throw(void)
7449 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7450 result->base.type = type_void;
7454 expression_t *value = NULL;
7455 switch (token.kind) {
7457 value = parse_assignment_expression();
7458 /* ISO/IEC 14882:1998(E) §15.1:3 */
7459 type_t *const orig_type = value->base.type;
7460 type_t *const type = skip_typeref(orig_type);
7461 if (is_type_incomplete(type)) {
7462 errorf(&value->base.pos,
7463 "cannot throw object of incomplete type '%T'", orig_type);
7464 } else if (is_type_pointer(type)) {
7465 type_t *const points_to = skip_typeref(type->pointer.points_to);
7466 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7467 errorf(&value->base.pos,
7468 "cannot throw pointer to incomplete type '%T'", orig_type);
7476 result->unary.value = value;
7481 static bool check_pointer_arithmetic(const position_t *pos,
7482 type_t *pointer_type,
7483 type_t *orig_pointer_type)
7485 type_t *points_to = pointer_type->pointer.points_to;
7486 points_to = skip_typeref(points_to);
7488 if (is_type_incomplete(points_to)) {
7489 if (!GNU_MODE || !is_type_void(points_to)) {
7491 "arithmetic with pointer to incomplete type '%T' not allowed",
7495 warningf(WARN_POINTER_ARITH, pos, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7497 } else if (is_type_function(points_to)) {
7500 "arithmetic with pointer to function type '%T' not allowed",
7504 warningf(WARN_POINTER_ARITH, pos,
7505 "pointer to a function '%T' used in arithmetic",
7512 static bool is_lvalue(const expression_t *expression)
7514 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7515 switch (expression->kind) {
7516 case EXPR_ARRAY_ACCESS:
7517 case EXPR_COMPOUND_LITERAL:
7518 case EXPR_REFERENCE:
7520 case EXPR_UNARY_DEREFERENCE:
7524 type_t *type = skip_typeref(expression->base.type);
7526 /* ISO/IEC 14882:1998(E) §3.10:3 */
7527 is_type_reference(type) ||
7528 /* Claim it is an lvalue, if the type is invalid. There was a parse
7529 * error before, which maybe prevented properly recognizing it as
7531 !is_type_valid(type);
7536 static void semantic_incdec(unary_expression_t *expression)
7538 type_t *orig_type = expression->value->base.type;
7539 type_t *type = skip_typeref(orig_type);
7540 if (is_type_pointer(type)) {
7541 if (!check_pointer_arithmetic(&expression->base.pos, type, orig_type)) {
7544 } else if (!is_type_real(type) &&
7545 (!GNU_MODE || !is_type_complex(type)) && is_type_valid(type)) {
7546 /* TODO: improve error message */
7547 errorf(&expression->base.pos,
7548 "operation needs an arithmetic or pointer type");
7549 orig_type = type = type_error_type;
7551 if (!is_lvalue(expression->value)) {
7552 /* TODO: improve error message */
7553 errorf(&expression->base.pos, "lvalue required as operand");
7555 expression->base.type = orig_type;
7558 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7560 atomic_type_kind_t akind = get_arithmetic_akind(type);
7562 if (get_akind_rank(akind) < get_akind_rank(ATOMIC_TYPE_INT)) {
7563 if (type->kind == TYPE_COMPLEX)
7564 res_type = make_complex_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
7566 res_type = type_int;
7570 expr->base.type = res_type;
7571 expr->value = create_implicit_cast(expr->value, res_type);
7574 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7576 type_t *const orig_type = expression->value->base.type;
7577 type_t *const type = skip_typeref(orig_type);
7578 if (!is_type_arithmetic(type)) {
7579 if (is_type_valid(type)) {
7580 position_t const *const pos = &expression->base.pos;
7581 errorf(pos, "operand of unary expression must have arithmetic type, but is '%T'", orig_type);
7584 } else if (is_type_integer(type)) {
7585 promote_unary_int_expr(expression, type);
7587 expression->base.type = orig_type;
7591 static void semantic_unexpr_plus(unary_expression_t *expression)
7593 semantic_unexpr_arithmetic(expression);
7594 position_t const *const pos = &expression->base.pos;
7595 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7598 static void semantic_not(unary_expression_t *expression)
7600 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7601 semantic_condition(expression->value, "operand of !");
7602 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7605 static void semantic_complement(unary_expression_t *expression)
7607 type_t *const orig_type = expression->value->base.type;
7608 type_t *const type = skip_typeref(orig_type);
7609 if (!is_type_integer(type) && (!GNU_MODE || !is_type_complex(type))) {
7610 if (is_type_valid(type)) {
7611 errorf(&expression->base.pos, "operand of ~ must be of integer type");
7616 if (is_type_integer(type)) {
7617 promote_unary_int_expr(expression, type);
7619 expression->base.type = orig_type;
7623 static void semantic_dereference(unary_expression_t *expression)
7625 type_t *const orig_type = expression->value->base.type;
7626 type_t *const type = skip_typeref(orig_type);
7627 if (!is_type_pointer(type)) {
7628 if (is_type_valid(type)) {
7629 errorf(&expression->base.pos,
7630 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7635 type_t *result_type = type->pointer.points_to;
7636 result_type = automatic_type_conversion(result_type);
7637 expression->base.type = result_type;
7641 * Record that an address is taken (expression represents an lvalue).
7643 * @param expression the expression
7644 * @param may_be_register if true, the expression might be an register
7646 static void set_address_taken(expression_t *expression, bool may_be_register)
7648 if (expression->kind != EXPR_REFERENCE)
7651 entity_t *const entity = expression->reference.entity;
7653 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7656 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7657 && !may_be_register) {
7658 position_t const *const pos = &expression->base.pos;
7659 errorf(pos, "address of register '%N' requested", entity);
7662 entity->variable.address_taken = true;
7666 * Check the semantic of the address taken expression.
7668 static void semantic_take_addr(unary_expression_t *expression)
7670 expression_t *value = expression->value;
7671 value->base.type = revert_automatic_type_conversion(value);
7673 type_t *orig_type = value->base.type;
7674 type_t *type = skip_typeref(orig_type);
7675 if (!is_type_valid(type))
7679 if (!is_lvalue(value)) {
7680 errorf(&expression->base.pos, "'&' requires an lvalue");
7682 if (is_bitfield(value)) {
7683 errorf(&expression->base.pos, "'&' not allowed on bitfield");
7686 set_address_taken(value, false);
7688 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7691 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7692 static expression_t *parse_##unexpression_type(void) \
7694 expression_t *unary_expression \
7695 = allocate_expression_zero(unexpression_type); \
7697 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7699 sfunc(&unary_expression->unary); \
7701 return unary_expression; \
7704 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7705 semantic_unexpr_arithmetic)
7706 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7707 semantic_unexpr_plus)
7708 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7710 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7711 semantic_dereference)
7712 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7714 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_COMPLEMENT,
7715 semantic_complement)
7716 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7718 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7721 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7723 static expression_t *parse_##unexpression_type(expression_t *left) \
7725 expression_t *unary_expression \
7726 = allocate_expression_zero(unexpression_type); \
7728 unary_expression->unary.value = left; \
7730 sfunc(&unary_expression->unary); \
7732 return unary_expression; \
7735 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7736 EXPR_UNARY_POSTFIX_INCREMENT,
7738 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7739 EXPR_UNARY_POSTFIX_DECREMENT,
7742 static atomic_type_kind_t semantic_arithmetic_(atomic_type_kind_t kind_left,
7743 atomic_type_kind_t kind_right)
7745 /* §6.3.1.8 Usual arithmetic conversions */
7746 if (kind_left == ATOMIC_TYPE_LONG_DOUBLE
7747 || kind_right == ATOMIC_TYPE_LONG_DOUBLE) {
7748 return ATOMIC_TYPE_LONG_DOUBLE;
7749 } else if (kind_left == ATOMIC_TYPE_DOUBLE
7750 || kind_right == ATOMIC_TYPE_DOUBLE) {
7751 return ATOMIC_TYPE_DOUBLE;
7752 } else if (kind_left == ATOMIC_TYPE_FLOAT
7753 || kind_right == ATOMIC_TYPE_FLOAT) {
7754 return ATOMIC_TYPE_FLOAT;
7757 unsigned rank_left = get_akind_rank(kind_left);
7758 unsigned rank_right = get_akind_rank(kind_right);
7759 unsigned const rank_int = get_akind_rank(ATOMIC_TYPE_INT);
7760 if (rank_left < rank_int) {
7761 kind_left = ATOMIC_TYPE_INT;
7762 rank_left = rank_int;
7764 if (rank_right < rank_int) {
7765 kind_right = ATOMIC_TYPE_INT;
7766 rank_right = rank_int;
7768 if (kind_left == kind_right)
7771 bool const signed_left = is_akind_signed(kind_left);
7772 bool const signed_right = is_akind_signed(kind_right);
7773 if (signed_left == signed_right)
7774 return rank_left >= rank_right ? kind_left : kind_right;
7778 atomic_type_kind_t s_kind;
7779 atomic_type_kind_t u_kind;
7783 u_kind = kind_right;
7784 u_rank = rank_right;
7786 s_kind = kind_right;
7787 s_rank = rank_right;
7791 if (u_rank >= s_rank)
7793 if (get_atomic_type_size(s_kind) > get_atomic_type_size(u_kind))
7797 case ATOMIC_TYPE_INT: return ATOMIC_TYPE_UINT;
7798 case ATOMIC_TYPE_LONG: return ATOMIC_TYPE_ULONG;
7799 case ATOMIC_TYPE_LONGLONG: return ATOMIC_TYPE_ULONGLONG;
7800 default: panic("invalid atomic type");
7804 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7806 atomic_type_kind_t kind_left = get_arithmetic_akind(type_left);
7807 atomic_type_kind_t kind_right = get_arithmetic_akind(type_right);
7808 atomic_type_kind_t kind_res = semantic_arithmetic_(kind_left, kind_right);
7810 if (type_left->kind == TYPE_COMPLEX || type_right->kind == TYPE_COMPLEX) {
7811 return make_complex_type(kind_res, TYPE_QUALIFIER_NONE);
7813 return make_atomic_type(kind_res, TYPE_QUALIFIER_NONE);
7817 * Check the semantic restrictions for a binary expression.
7819 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7821 expression_t *const left = expression->left;
7822 expression_t *const right = expression->right;
7823 type_t *const orig_type_left = left->base.type;
7824 type_t *const orig_type_right = right->base.type;
7825 type_t *const type_left = skip_typeref(orig_type_left);
7826 type_t *const type_right = skip_typeref(orig_type_right);
7828 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7829 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7830 position_t const *const pos = &expression->base.pos;
7831 errorf(pos, "operands of binary expression must have arithmetic types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7836 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7837 expression->left = create_implicit_cast(left, arithmetic_type);
7838 expression->right = create_implicit_cast(right, arithmetic_type);
7839 expression->base.type = arithmetic_type;
7842 static void semantic_binexpr_integer(binary_expression_t *const expression)
7844 expression_t *const left = expression->left;
7845 expression_t *const right = expression->right;
7846 type_t *const orig_type_left = left->base.type;
7847 type_t *const orig_type_right = right->base.type;
7848 type_t *const type_left = skip_typeref(orig_type_left);
7849 type_t *const type_right = skip_typeref(orig_type_right);
7851 if (!is_type_integer(type_left) || !is_type_integer(type_right)
7852 || is_type_complex(type_left) || is_type_complex(type_right)) {
7853 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7854 position_t const *const pos = &expression->base.pos;
7855 errorf(pos, "operands of binary expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7860 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7861 expression->left = create_implicit_cast(left, result_type);
7862 expression->right = create_implicit_cast(right, result_type);
7863 expression->base.type = result_type;
7866 static void warn_div_by_zero(binary_expression_t const *const expression)
7868 if (!is_type_integer(expression->base.type))
7871 expression_t const *const right = expression->right;
7872 /* The type of the right operand can be different for /= */
7873 if (is_type_integer(skip_typeref(right->base.type)) &&
7874 is_constant_expression(right) >= EXPR_CLASS_CONSTANT &&
7875 !fold_constant_to_bool(right)) {
7876 position_t const *const pos = &expression->base.pos;
7877 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7882 * Check the semantic restrictions for a div expression.
7884 static void semantic_div(binary_expression_t *expression)
7886 semantic_binexpr_arithmetic(expression);
7887 warn_div_by_zero(expression);
7891 * Check the semantic restrictions for a mod expression.
7893 static void semantic_mod(binary_expression_t *expression)
7895 semantic_binexpr_integer(expression);
7896 warn_div_by_zero(expression);
7899 static void warn_addsub_in_shift(const expression_t *const expr)
7901 if (expr->base.parenthesized)
7905 switch (expr->kind) {
7906 case EXPR_BINARY_ADD: op = '+'; break;
7907 case EXPR_BINARY_SUB: op = '-'; break;
7911 position_t const *const pos = &expr->base.pos;
7912 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7915 static bool semantic_shift(binary_expression_t *expression)
7917 expression_t *const left = expression->left;
7918 expression_t *const right = expression->right;
7919 type_t *const orig_type_left = left->base.type;
7920 type_t *const orig_type_right = right->base.type;
7921 type_t * type_left = skip_typeref(orig_type_left);
7922 type_t * type_right = skip_typeref(orig_type_right);
7924 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7925 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7926 position_t const *const pos = &expression->base.pos;
7927 errorf(pos, "operands of shift expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7932 type_left = promote_integer(type_left);
7934 if (is_constant_expression(right) >= EXPR_CLASS_CONSTANT) {
7935 position_t const *const pos = &right->base.pos;
7936 long const count = fold_constant_to_int(right);
7938 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7939 } else if ((unsigned long)count >=
7940 get_atomic_type_size(type_left->atomic.akind) * 8) {
7941 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7945 type_right = promote_integer(type_right);
7946 expression->right = create_implicit_cast(right, type_right);
7951 static void semantic_shift_op(binary_expression_t *expression)
7953 expression_t *const left = expression->left;
7954 expression_t *const right = expression->right;
7956 if (!semantic_shift(expression))
7959 warn_addsub_in_shift(left);
7960 warn_addsub_in_shift(right);
7962 type_t *const orig_type_left = left->base.type;
7963 type_t * type_left = skip_typeref(orig_type_left);
7965 type_left = promote_integer(type_left);
7966 expression->left = create_implicit_cast(left, type_left);
7967 expression->base.type = type_left;
7970 static void semantic_add(binary_expression_t *expression)
7972 expression_t *const left = expression->left;
7973 expression_t *const right = expression->right;
7974 type_t *const orig_type_left = left->base.type;
7975 type_t *const orig_type_right = right->base.type;
7976 type_t *const type_left = skip_typeref(orig_type_left);
7977 type_t *const type_right = skip_typeref(orig_type_right);
7980 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7981 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7982 expression->left = create_implicit_cast(left, arithmetic_type);
7983 expression->right = create_implicit_cast(right, arithmetic_type);
7984 expression->base.type = arithmetic_type;
7985 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7986 check_pointer_arithmetic(&expression->base.pos, type_left,
7988 expression->base.type = type_left;
7989 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7990 check_pointer_arithmetic(&expression->base.pos, type_right,
7992 expression->base.type = type_right;
7993 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7994 errorf(&expression->base.pos,
7995 "invalid operands to binary + ('%T', '%T')",
7996 orig_type_left, orig_type_right);
8000 static void semantic_sub(binary_expression_t *expression)
8002 expression_t *const left = expression->left;
8003 expression_t *const right = expression->right;
8004 type_t *const orig_type_left = left->base.type;
8005 type_t *const orig_type_right = right->base.type;
8006 type_t *const type_left = skip_typeref(orig_type_left);
8007 type_t *const type_right = skip_typeref(orig_type_right);
8008 position_t const *const pos = &expression->base.pos;
8011 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8012 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8013 expression->left = create_implicit_cast(left, arithmetic_type);
8014 expression->right = create_implicit_cast(right, arithmetic_type);
8015 expression->base.type = arithmetic_type;
8016 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8017 check_pointer_arithmetic(&expression->base.pos, type_left,
8019 expression->base.type = type_left;
8020 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8021 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8022 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8023 if (!types_compatible(unqual_left, unqual_right)) {
8025 "subtracting pointers to incompatible types '%T' and '%T'",
8026 orig_type_left, orig_type_right);
8027 } else if (!is_type_object(unqual_left)) {
8028 if (!is_type_void(unqual_left)) {
8029 errorf(pos, "subtracting pointers to non-object types '%T'",
8032 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8035 expression->base.type = type_ptrdiff_t;
8036 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8037 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8038 orig_type_left, orig_type_right);
8042 static void warn_string_literal_address(expression_t const* expr)
8044 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8045 expr = expr->unary.value;
8046 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8048 expr = expr->unary.value;
8051 if (expr->kind == EXPR_STRING_LITERAL) {
8052 position_t const *const pos = &expr->base.pos;
8053 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8057 static bool maybe_negative(expression_t const *const expr)
8059 switch (is_constant_expression(expr)) {
8060 case EXPR_CLASS_VARIABLE: return true;
8061 case EXPR_CLASS_ERROR: return false;
8062 case EXPR_CLASS_CONSTANT:
8063 case EXPR_CLASS_INTEGER_CONSTANT: return constant_is_negative(expr);
8065 panic("invalid expression classification");
8068 static void warn_comparison(position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8070 warn_string_literal_address(expr);
8072 expression_t const* const ref = get_reference_address(expr);
8073 if (ref != NULL && is_null_pointer_constant(other)) {
8074 entity_t const *const ent = ref->reference.entity;
8075 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8078 if (!expr->base.parenthesized) {
8079 switch (expr->base.kind) {
8080 case EXPR_BINARY_LESS:
8081 case EXPR_BINARY_GREATER:
8082 case EXPR_BINARY_LESSEQUAL:
8083 case EXPR_BINARY_GREATEREQUAL:
8084 case EXPR_BINARY_NOTEQUAL:
8085 case EXPR_BINARY_EQUAL:
8086 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8095 * Check the semantics of comparison expressions.
8097 static void semantic_comparison(binary_expression_t *expression,
8100 position_t const *const pos = &expression->base.pos;
8101 expression_t *const left = expression->left;
8102 expression_t *const right = expression->right;
8104 warn_comparison(pos, left, right);
8105 warn_comparison(pos, right, left);
8107 type_t *orig_type_left = left->base.type;
8108 type_t *orig_type_right = right->base.type;
8109 type_t *type_left = skip_typeref(orig_type_left);
8110 type_t *type_right = skip_typeref(orig_type_right);
8112 /* TODO non-arithmetic types */
8113 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8114 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8116 /* test for signed vs unsigned compares */
8117 if (is_type_integer(arithmetic_type)) {
8118 bool const signed_left = is_type_signed(type_left);
8119 bool const signed_right = is_type_signed(type_right);
8120 if (signed_left != signed_right) {
8121 /* FIXME long long needs better const folding magic */
8122 /* TODO check whether constant value can be represented by other type */
8123 if ((signed_left && maybe_negative(left)) ||
8124 (signed_right && maybe_negative(right))) {
8125 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8130 expression->left = create_implicit_cast(left, arithmetic_type);
8131 expression->right = create_implicit_cast(right, arithmetic_type);
8132 expression->base.type = arithmetic_type;
8133 if (!is_relational && is_type_float(arithmetic_type)) {
8134 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8136 /* for relational ops we need real types, not just arithmetic */
8138 && (!is_type_real(type_left) || !is_type_real(type_right))) {
8139 type_error_incompatible("invalid operands for relational operator", pos, type_left, type_right);
8141 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8142 /* TODO check compatibility */
8143 } else if (is_type_pointer(type_left)) {
8144 expression->right = create_implicit_cast(right, type_left);
8145 } else if (is_type_pointer(type_right)) {
8146 expression->left = create_implicit_cast(left, type_right);
8147 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8148 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8150 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8153 static void semantic_relational(binary_expression_t *expression)
8155 semantic_comparison(expression, true);
8158 static void semantic_equality(binary_expression_t *expression)
8160 semantic_comparison(expression, false);
8164 * Checks if a compound type has constant fields.
8166 static bool has_const_fields(const compound_type_t *type)
8168 compound_t *compound = type->compound;
8169 entity_t *entry = compound->members.entities;
8171 for (; entry != NULL; entry = entry->base.next) {
8172 if (!is_declaration(entry))
8175 const type_t *decl_type = skip_typeref(entry->declaration.type);
8176 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8183 static bool is_valid_assignment_lhs(expression_t const* const left)
8185 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8186 type_t *const type_left = skip_typeref(orig_type_left);
8188 if (!is_lvalue(left)) {
8189 errorf(&left->base.pos,
8190 "left hand side '%E' of assignment is not an lvalue", left);
8194 if (left->kind == EXPR_REFERENCE
8195 && left->reference.entity->kind == ENTITY_FUNCTION) {
8196 errorf(&left->base.pos, "cannot assign to function '%E'", left);
8200 if (is_type_array(type_left)) {
8201 errorf(&left->base.pos, "cannot assign to array '%E'", left);
8204 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8205 errorf(&left->base.pos,
8206 "assignment to read-only location '%E' (type '%T')", left,
8210 if (is_type_incomplete(type_left)) {
8211 errorf(&left->base.pos, "left-hand side '%E' of assignment has incomplete type '%T'",
8212 left, orig_type_left);
8215 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8216 errorf(&left->base.pos, "cannot assign to '%E' because compound type '%T' has read-only fields",
8217 left, orig_type_left);
8224 static void semantic_arithmetic_assign(binary_expression_t *expression)
8226 expression_t *left = expression->left;
8227 expression_t *right = expression->right;
8228 type_t *orig_type_left = left->base.type;
8229 type_t *orig_type_right = right->base.type;
8231 if (!is_valid_assignment_lhs(left))
8234 type_t *type_left = skip_typeref(orig_type_left);
8235 type_t *type_right = skip_typeref(orig_type_right);
8237 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8238 /* TODO: improve error message */
8239 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8240 errorf(&expression->base.pos, "operation needs arithmetic types");
8245 /* combined instructions are tricky. We can't create an implicit cast on
8246 * the left side, because we need the uncasted form for the store.
8247 * The ast2firm pass has to know that left_type must be right_type
8248 * for the arithmetic operation and create a cast by itself */
8249 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8250 expression->right = create_implicit_cast(right, arithmetic_type);
8251 expression->base.type = type_left;
8254 static void semantic_divmod_assign(binary_expression_t *expression)
8256 semantic_arithmetic_assign(expression);
8257 warn_div_by_zero(expression);
8260 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8262 expression_t *const left = expression->left;
8263 expression_t *const right = expression->right;
8264 type_t *const orig_type_left = left->base.type;
8265 type_t *const orig_type_right = right->base.type;
8266 type_t *const type_left = skip_typeref(orig_type_left);
8267 type_t *const type_right = skip_typeref(orig_type_right);
8269 if (!is_valid_assignment_lhs(left))
8272 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8273 /* combined instructions are tricky. We can't create an implicit cast on
8274 * the left side, because we need the uncasted form for the store.
8275 * The ast2firm pass has to know that left_type must be right_type
8276 * for the arithmetic operation and create a cast by itself */
8277 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8278 expression->right = create_implicit_cast(right, arithmetic_type);
8279 expression->base.type = type_left;
8280 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8281 check_pointer_arithmetic(&expression->base.pos, type_left,
8283 expression->base.type = type_left;
8284 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8285 errorf(&expression->base.pos,
8286 "incompatible types '%T' and '%T' in assignment",
8287 orig_type_left, orig_type_right);
8291 static void semantic_integer_assign(binary_expression_t *expression)
8293 expression_t *left = expression->left;
8294 expression_t *right = expression->right;
8295 type_t *orig_type_left = left->base.type;
8296 type_t *orig_type_right = right->base.type;
8298 if (!is_valid_assignment_lhs(left))
8301 type_t *type_left = skip_typeref(orig_type_left);
8302 type_t *type_right = skip_typeref(orig_type_right);
8304 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8305 /* TODO: improve error message */
8306 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8307 errorf(&expression->base.pos, "operation needs integer types");
8312 /* combined instructions are tricky. We can't create an implicit cast on
8313 * the left side, because we need the uncasted form for the store.
8314 * The ast2firm pass has to know that left_type must be right_type
8315 * for the arithmetic operation and create a cast by itself */
8316 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8317 expression->right = create_implicit_cast(right, arithmetic_type);
8318 expression->base.type = type_left;
8321 static void semantic_shift_assign(binary_expression_t *expression)
8323 expression_t *left = expression->left;
8325 if (!is_valid_assignment_lhs(left))
8328 if (!semantic_shift(expression))
8331 expression->base.type = skip_typeref(left->base.type);
8334 static void warn_logical_and_within_or(const expression_t *const expr)
8336 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8338 if (expr->base.parenthesized)
8340 position_t const *const pos = &expr->base.pos;
8341 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8345 * Check the semantic restrictions of a logical expression.
8347 static void semantic_logical_op(binary_expression_t *expression)
8349 /* §6.5.13:2 Each of the operands shall have scalar type.
8350 * §6.5.14:2 Each of the operands shall have scalar type. */
8351 semantic_condition(expression->left, "left operand of logical operator");
8352 semantic_condition(expression->right, "right operand of logical operator");
8353 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8354 warn_logical_and_within_or(expression->left);
8355 warn_logical_and_within_or(expression->right);
8357 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8361 * Check the semantic restrictions of a binary assign expression.
8363 static void semantic_binexpr_assign(binary_expression_t *expression)
8365 expression_t *left = expression->left;
8366 type_t *orig_type_left = left->base.type;
8368 if (!is_valid_assignment_lhs(left))
8371 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8372 report_assign_error(error, orig_type_left, expression->right,
8373 "assignment", &left->base.pos);
8374 expression->right = create_implicit_cast(expression->right, orig_type_left);
8375 expression->base.type = orig_type_left;
8379 * Determine if the outermost operation (or parts thereof) of the given
8380 * expression has no effect in order to generate a warning about this fact.
8381 * Therefore in some cases this only examines some of the operands of the
8382 * expression (see comments in the function and examples below).
8384 * f() + 23; // warning, because + has no effect
8385 * x || f(); // no warning, because x controls execution of f()
8386 * x ? y : f(); // warning, because y has no effect
8387 * (void)x; // no warning to be able to suppress the warning
8388 * This function can NOT be used for an "expression has definitely no effect"-
8390 static bool expression_has_effect(const expression_t *const expr)
8392 switch (expr->kind) {
8393 case EXPR_ERROR: return true; /* do NOT warn */
8394 case EXPR_REFERENCE: return false;
8395 case EXPR_ENUM_CONSTANT: return false;
8396 case EXPR_LABEL_ADDRESS: return false;
8398 /* suppress the warning for microsoft __noop operations */
8399 case EXPR_LITERAL_MS_NOOP: return true;
8400 case EXPR_LITERAL_BOOLEAN:
8401 case EXPR_LITERAL_CHARACTER:
8402 case EXPR_LITERAL_INTEGER:
8403 case EXPR_LITERAL_FLOATINGPOINT:
8404 case EXPR_STRING_LITERAL: return false;
8407 const call_expression_t *const call = &expr->call;
8408 if (call->function->kind != EXPR_REFERENCE)
8411 switch (call->function->reference.entity->function.btk) {
8412 /* FIXME: which builtins have no effect? */
8413 default: return true;
8417 /* Generate the warning if either the left or right hand side of a
8418 * conditional expression has no effect */
8419 case EXPR_CONDITIONAL: {
8420 conditional_expression_t const *const cond = &expr->conditional;
8421 expression_t const *const t = cond->true_expression;
8423 (t == NULL || expression_has_effect(t)) &&
8424 expression_has_effect(cond->false_expression);
8427 case EXPR_SELECT: return false;
8428 case EXPR_ARRAY_ACCESS: return false;
8429 case EXPR_SIZEOF: return false;
8430 case EXPR_CLASSIFY_TYPE: return false;
8431 case EXPR_ALIGNOF: return false;
8433 case EXPR_FUNCNAME: return false;
8434 case EXPR_BUILTIN_CONSTANT_P: return false;
8435 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8436 case EXPR_OFFSETOF: return false;
8437 case EXPR_VA_START: return true;
8438 case EXPR_VA_ARG: return true;
8439 case EXPR_VA_COPY: return true;
8440 case EXPR_STATEMENT: return true; // TODO
8441 case EXPR_COMPOUND_LITERAL: return false;
8443 case EXPR_UNARY_NEGATE: return false;
8444 case EXPR_UNARY_PLUS: return false;
8445 case EXPR_UNARY_COMPLEMENT: return false;
8446 case EXPR_UNARY_NOT: return false;
8447 case EXPR_UNARY_DEREFERENCE: return false;
8448 case EXPR_UNARY_TAKE_ADDRESS: return false;
8449 case EXPR_UNARY_REAL: return false;
8450 case EXPR_UNARY_IMAG: return false;
8451 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8452 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8453 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8454 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8456 /* Treat void casts as if they have an effect in order to being able to
8457 * suppress the warning */
8458 case EXPR_UNARY_CAST: {
8459 type_t *const type = skip_typeref(expr->base.type);
8460 return is_type_void(type);
8463 case EXPR_UNARY_ASSUME: return true;
8464 case EXPR_UNARY_DELETE: return true;
8465 case EXPR_UNARY_DELETE_ARRAY: return true;
8466 case EXPR_UNARY_THROW: return true;
8468 case EXPR_BINARY_ADD: return false;
8469 case EXPR_BINARY_SUB: return false;
8470 case EXPR_BINARY_MUL: return false;
8471 case EXPR_BINARY_DIV: return false;
8472 case EXPR_BINARY_MOD: return false;
8473 case EXPR_BINARY_EQUAL: return false;
8474 case EXPR_BINARY_NOTEQUAL: return false;
8475 case EXPR_BINARY_LESS: return false;
8476 case EXPR_BINARY_LESSEQUAL: return false;
8477 case EXPR_BINARY_GREATER: return false;
8478 case EXPR_BINARY_GREATEREQUAL: return false;
8479 case EXPR_BINARY_BITWISE_AND: return false;
8480 case EXPR_BINARY_BITWISE_OR: return false;
8481 case EXPR_BINARY_BITWISE_XOR: return false;
8482 case EXPR_BINARY_SHIFTLEFT: return false;
8483 case EXPR_BINARY_SHIFTRIGHT: return false;
8484 case EXPR_BINARY_ASSIGN: return true;
8485 case EXPR_BINARY_MUL_ASSIGN: return true;
8486 case EXPR_BINARY_DIV_ASSIGN: return true;
8487 case EXPR_BINARY_MOD_ASSIGN: return true;
8488 case EXPR_BINARY_ADD_ASSIGN: return true;
8489 case EXPR_BINARY_SUB_ASSIGN: return true;
8490 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8491 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8492 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8493 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8494 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8496 /* Only examine the right hand side of && and ||, because the left hand
8497 * side already has the effect of controlling the execution of the right
8499 case EXPR_BINARY_LOGICAL_AND:
8500 case EXPR_BINARY_LOGICAL_OR:
8501 /* Only examine the right hand side of a comma expression, because the left
8502 * hand side has a separate warning */
8503 case EXPR_BINARY_COMMA:
8504 return expression_has_effect(expr->binary.right);
8506 case EXPR_BINARY_ISGREATER: return false;
8507 case EXPR_BINARY_ISGREATEREQUAL: return false;
8508 case EXPR_BINARY_ISLESS: return false;
8509 case EXPR_BINARY_ISLESSEQUAL: return false;
8510 case EXPR_BINARY_ISLESSGREATER: return false;
8511 case EXPR_BINARY_ISUNORDERED: return false;
8514 internal_errorf(HERE, "unexpected expression");
8517 static void semantic_comma(binary_expression_t *expression)
8519 const expression_t *const left = expression->left;
8520 if (!expression_has_effect(left)) {
8521 position_t const *const pos = &left->base.pos;
8522 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8524 expression->base.type = expression->right->base.type;
8528 * @param prec_r precedence of the right operand
8530 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8531 static expression_t *parse_##binexpression_type(expression_t *left) \
8533 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8534 binexpr->binary.left = left; \
8537 expression_t *right = parse_subexpression(prec_r); \
8539 binexpr->binary.right = right; \
8540 sfunc(&binexpr->binary); \
8545 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8546 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_div)
8547 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_mod)
8548 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8549 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8550 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8551 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8552 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_relational)
8553 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_relational)
8554 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_relational)
8555 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_relational)
8556 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_equality)
8557 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_equality)
8558 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8559 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8560 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8561 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8562 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8563 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8564 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8565 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8566 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8567 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8568 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8569 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8570 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8571 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8572 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8573 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8574 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8577 static expression_t *parse_subexpression(precedence_t precedence)
8579 expression_parser_function_t *parser
8580 = &expression_parsers[token.kind];
8583 if (parser->parser != NULL) {
8584 left = parser->parser();
8586 left = parse_primary_expression();
8588 assert(left != NULL);
8591 parser = &expression_parsers[token.kind];
8592 if (parser->infix_parser == NULL)
8594 if (parser->infix_precedence < precedence)
8597 left = parser->infix_parser(left);
8599 assert(left != NULL);
8606 * Parse an expression.
8608 static expression_t *parse_expression(void)
8610 return parse_subexpression(PREC_EXPRESSION);
8614 * Register a parser for a prefix-like operator.
8616 * @param parser the parser function
8617 * @param token_kind the token type of the prefix token
8619 static void register_expression_parser(parse_expression_function parser,
8622 expression_parser_function_t *entry = &expression_parsers[token_kind];
8624 assert(!entry->parser);
8625 entry->parser = parser;
8629 * Register a parser for an infix operator with given precedence.
8631 * @param parser the parser function
8632 * @param token_kind the token type of the infix operator
8633 * @param precedence the precedence of the operator
8635 static void register_infix_parser(parse_expression_infix_function parser,
8636 int token_kind, precedence_t precedence)
8638 expression_parser_function_t *entry = &expression_parsers[token_kind];
8640 assert(!entry->infix_parser);
8641 entry->infix_parser = parser;
8642 entry->infix_precedence = precedence;
8646 * Initialize the expression parsers.
8648 static void init_expression_parsers(void)
8650 memset(&expression_parsers, 0, sizeof(expression_parsers));
8652 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8653 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8654 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8655 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8656 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8657 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8658 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8659 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8660 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8661 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8662 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8663 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8664 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8665 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8666 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8667 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8668 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8669 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8670 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8671 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8672 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8673 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8674 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8675 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8676 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8677 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8678 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8679 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8680 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8681 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8682 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8683 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8684 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8685 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8686 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8687 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8688 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8690 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8691 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8692 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8693 register_expression_parser(parse_EXPR_UNARY_COMPLEMENT, '~');
8694 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8695 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8696 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8697 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8698 register_expression_parser(parse_sizeof, T_sizeof);
8699 register_expression_parser(parse_alignof, T__Alignof);
8700 register_expression_parser(parse_extension, T___extension__);
8701 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8702 register_expression_parser(parse_delete, T_delete);
8703 register_expression_parser(parse_throw, T_throw);
8707 * Parse a asm statement arguments specification.
8709 static void parse_asm_arguments(asm_argument_t **anchor, bool const is_out)
8711 if (token.kind == T_STRING_LITERAL || token.kind == '[') {
8712 add_anchor_token(',');
8714 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8716 add_anchor_token(')');
8717 add_anchor_token('(');
8718 add_anchor_token(T_STRING_LITERAL);
8721 add_anchor_token(']');
8722 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8723 rem_anchor_token(']');
8727 rem_anchor_token(T_STRING_LITERAL);
8728 argument->constraints = parse_string_literals("asm argument");
8729 rem_anchor_token('(');
8731 expression_t *expression = parse_expression();
8733 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8734 * change size or type representation (e.g. int -> long is ok, but
8735 * int -> float is not) */
8736 if (expression->kind == EXPR_UNARY_CAST) {
8737 type_t *const type = expression->base.type;
8738 type_kind_t const kind = type->kind;
8739 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8742 if (kind == TYPE_ATOMIC) {
8743 atomic_type_kind_t const akind = type->atomic.akind;
8744 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8745 size = get_atomic_type_size(akind);
8747 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8748 size = get_type_size(type_void_ptr);
8752 expression_t *const value = expression->unary.value;
8753 type_t *const value_type = value->base.type;
8754 type_kind_t const value_kind = value_type->kind;
8756 unsigned value_flags;
8757 unsigned value_size;
8758 if (value_kind == TYPE_ATOMIC) {
8759 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8760 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8761 value_size = get_atomic_type_size(value_akind);
8762 } else if (value_kind == TYPE_POINTER) {
8763 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8764 value_size = get_type_size(type_void_ptr);
8769 if (value_flags != flags || value_size != size)
8773 } while (expression->kind == EXPR_UNARY_CAST);
8777 if (!is_lvalue(expression))
8778 errorf(&expression->base.pos,
8779 "asm output argument is not an lvalue");
8781 if (argument->constraints.begin[0] == '=')
8782 determine_lhs_ent(expression, NULL);
8784 mark_vars_read(expression, NULL);
8786 mark_vars_read(expression, NULL);
8788 argument->expression = expression;
8789 rem_anchor_token(')');
8792 set_address_taken(expression, true);
8795 anchor = &argument->next;
8796 } while (accept(','));
8797 rem_anchor_token(',');
8802 * Parse a asm statement clobber specification.
8804 static void parse_asm_clobbers(asm_clobber_t **anchor)
8806 if (token.kind == T_STRING_LITERAL) {
8807 add_anchor_token(',');
8809 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8810 clobber->clobber = parse_string_literals(NULL);
8813 anchor = &clobber->next;
8814 } while (accept(','));
8815 rem_anchor_token(',');
8819 static void parse_asm_labels(asm_label_t **anchor)
8821 if (token.kind == T_IDENTIFIER) {
8822 add_anchor_token(',');
8824 label_t *const label = get_label("while parsing 'asm goto' labels");
8826 asm_label_t *const asm_label = allocate_ast_zero(sizeof(*asm_label));
8827 asm_label->label = label;
8829 *anchor = asm_label;
8830 anchor = &asm_label->next;
8832 } while (accept(','));
8833 rem_anchor_token(',');
8838 * Parse an asm statement.
8840 static statement_t *parse_asm_statement(void)
8842 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8843 asm_statement_t *asm_statement = &statement->asms;
8846 add_anchor_token(')');
8847 add_anchor_token(':');
8848 add_anchor_token(T_STRING_LITERAL);
8850 if (accept(T_volatile))
8851 asm_statement->is_volatile = true;
8853 bool const asm_goto = accept(T_goto);
8856 rem_anchor_token(T_STRING_LITERAL);
8857 asm_statement->asm_text = parse_string_literals("asm statement");
8859 if (accept(':')) parse_asm_arguments(&asm_statement->outputs, true);
8860 if (accept(':')) parse_asm_arguments(&asm_statement->inputs, false);
8861 if (accept(':')) parse_asm_clobbers( &asm_statement->clobbers);
8863 rem_anchor_token(':');
8866 warningf(WARN_OTHER, &statement->base.pos, "assembler statement with labels should be 'asm goto'");
8867 parse_asm_labels(&asm_statement->labels);
8868 if (asm_statement->labels)
8869 errorf(&statement->base.pos, "'asm goto' not supported");
8872 warningf(WARN_OTHER, &statement->base.pos, "'asm goto' without labels");
8875 rem_anchor_token(')');
8879 if (asm_statement->outputs == NULL) {
8880 /* GCC: An 'asm' instruction without any output operands will be treated
8881 * identically to a volatile 'asm' instruction. */
8882 asm_statement->is_volatile = true;
8888 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8890 statement_t *inner_stmt;
8891 switch (token.kind) {
8893 errorf(&label->base.pos, "%s at end of compound statement", label_kind);
8894 inner_stmt = create_error_statement();
8898 if (label->kind == STATEMENT_LABEL) {
8899 /* Eat an empty statement here, to avoid the warning about an empty
8900 * statement after a label. label:; is commonly used to have a label
8901 * before a closing brace. */
8902 inner_stmt = create_empty_statement();
8909 inner_stmt = parse_statement();
8910 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8911 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8912 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8913 errorf(&inner_stmt->base.pos, "declaration after %s", label_kind);
8921 * Parse a case statement.
8923 static statement_t *parse_case_statement(void)
8925 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8926 position_t *const pos = &statement->base.pos;
8929 add_anchor_token(':');
8931 expression_t *expression = parse_expression();
8932 type_t *expression_type = expression->base.type;
8933 type_t *skipped = skip_typeref(expression_type);
8934 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8935 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8936 expression, expression_type);
8939 type_t *type = expression_type;
8940 if (current_switch != NULL) {
8941 type_t *switch_type = current_switch->expression->base.type;
8942 if (is_type_valid(skip_typeref(switch_type))) {
8943 expression = create_implicit_cast(expression, switch_type);
8947 statement->case_label.expression = expression;
8948 expression_classification_t const expr_class = is_constant_expression(expression);
8949 if (expr_class < EXPR_CLASS_CONSTANT) {
8950 if (expr_class != EXPR_CLASS_ERROR) {
8951 errorf(pos, "case label does not reduce to an integer constant");
8953 statement->case_label.is_bad = true;
8955 ir_tarval *val = fold_constant_to_tarval(expression);
8956 statement->case_label.first_case = val;
8957 statement->case_label.last_case = val;
8961 if (accept(T_DOTDOTDOT)) {
8962 expression_t *end_range = parse_expression();
8963 expression_type = expression->base.type;
8964 skipped = skip_typeref(expression_type);
8965 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8966 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8967 expression, expression_type);
8970 end_range = create_implicit_cast(end_range, type);
8971 statement->case_label.end_range = end_range;
8972 expression_classification_t const end_class = is_constant_expression(end_range);
8973 if (end_class < EXPR_CLASS_CONSTANT) {
8974 if (end_class != EXPR_CLASS_ERROR) {
8975 errorf(pos, "case range does not reduce to an integer constant");
8977 statement->case_label.is_bad = true;
8979 ir_tarval *val = fold_constant_to_tarval(end_range);
8980 statement->case_label.last_case = val;
8982 if (tarval_cmp(val, statement->case_label.first_case)
8983 == ir_relation_less) {
8984 statement->case_label.is_empty_range = true;
8985 warningf(WARN_OTHER, pos, "empty range specified");
8991 PUSH_PARENT(statement);
8993 rem_anchor_token(':');
8996 if (current_switch != NULL) {
8997 if (! statement->case_label.is_bad) {
8998 /* Check for duplicate case values */
8999 case_label_statement_t *c = &statement->case_label;
9000 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9001 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9004 if (c->last_case < l->first_case || c->first_case > l->last_case)
9007 errorf(pos, "duplicate case value (previously used %P)",
9012 /* link all cases into the switch statement */
9013 if (current_switch->last_case == NULL) {
9014 current_switch->first_case = &statement->case_label;
9016 current_switch->last_case->next = &statement->case_label;
9018 current_switch->last_case = &statement->case_label;
9020 errorf(pos, "case label not within a switch statement");
9023 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9030 * Parse a default statement.
9032 static statement_t *parse_default_statement(void)
9034 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9038 PUSH_PARENT(statement);
9042 if (current_switch != NULL) {
9043 const case_label_statement_t *def_label = current_switch->default_label;
9044 if (def_label != NULL) {
9045 errorf(&statement->base.pos, "multiple default labels in one switch (previous declared %P)", &def_label->base.pos);
9047 current_switch->default_label = &statement->case_label;
9049 /* link all cases into the switch statement */
9050 if (current_switch->last_case == NULL) {
9051 current_switch->first_case = &statement->case_label;
9053 current_switch->last_case->next = &statement->case_label;
9055 current_switch->last_case = &statement->case_label;
9058 errorf(&statement->base.pos,
9059 "'default' label not within a switch statement");
9062 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9069 * Parse a label statement.
9071 static statement_t *parse_label_statement(void)
9073 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9074 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9075 statement->label.label = label;
9077 PUSH_PARENT(statement);
9079 /* if statement is already set then the label is defined twice,
9080 * otherwise it was just mentioned in a goto/local label declaration so far
9082 position_t const* const pos = &statement->base.pos;
9083 if (label->statement != NULL) {
9084 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.pos);
9086 label->base.pos = *pos;
9087 label->statement = statement;
9088 label->n_users += 1;
9093 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9094 parse_attributes(NULL); // TODO process attributes
9097 statement->label.statement = parse_label_inner_statement(statement, "label");
9099 /* remember the labels in a list for later checking */
9100 *label_anchor = &statement->label;
9101 label_anchor = &statement->label.next;
9107 static statement_t *parse_inner_statement(void)
9109 statement_t *const stmt = parse_statement();
9110 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9111 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9112 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9113 errorf(&stmt->base.pos, "declaration as inner statement, use {}");
9119 * Parse an expression in parentheses and mark its variables as read.
9121 static expression_t *parse_condition(void)
9123 add_anchor_token(')');
9125 expression_t *const expr = parse_expression();
9126 mark_vars_read(expr, NULL);
9127 rem_anchor_token(')');
9133 * Parse an if statement.
9135 static statement_t *parse_if(void)
9137 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9141 PUSH_PARENT(statement);
9142 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9144 add_anchor_token(T_else);
9146 expression_t *const expr = parse_condition();
9147 statement->ifs.condition = expr;
9148 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9150 semantic_condition(expr, "condition of 'if'-statment");
9152 statement_t *const true_stmt = parse_inner_statement();
9153 statement->ifs.true_statement = true_stmt;
9154 rem_anchor_token(T_else);
9156 if (true_stmt->kind == STATEMENT_EMPTY) {
9157 warningf(WARN_EMPTY_BODY, HERE,
9158 "suggest braces around empty body in an ‘if’ statement");
9161 if (accept(T_else)) {
9162 statement->ifs.false_statement = parse_inner_statement();
9164 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9165 warningf(WARN_EMPTY_BODY, HERE,
9166 "suggest braces around empty body in an ‘if’ statement");
9168 } else if (true_stmt->kind == STATEMENT_IF &&
9169 true_stmt->ifs.false_statement != NULL) {
9170 position_t const *const pos = &true_stmt->base.pos;
9171 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9180 * Check that all enums are handled in a switch.
9182 * @param statement the switch statement to check
9184 static void check_enum_cases(const switch_statement_t *statement)
9186 if (!is_warn_on(WARN_SWITCH_ENUM))
9188 type_t *type = skip_typeref(statement->expression->base.type);
9189 if (! is_type_enum(type))
9191 enum_type_t *enumt = &type->enumt;
9193 /* if we have a default, no warnings */
9194 if (statement->default_label != NULL)
9197 determine_enum_values(enumt);
9199 /* FIXME: calculation of value should be done while parsing */
9200 /* TODO: quadratic algorithm here. Change to an n log n one */
9201 const entity_t *entry = enumt->enume->base.next;
9202 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9203 entry = entry->base.next) {
9204 ir_tarval *value = entry->enum_value.tv;
9206 for (const case_label_statement_t *l = statement->first_case; l != NULL;
9208 if (l->expression == NULL)
9210 if (l->first_case == l->last_case && l->first_case != value)
9212 if ((tarval_cmp(l->first_case, value) & ir_relation_less_equal)
9213 && (tarval_cmp(value, l->last_case) & ir_relation_less_equal)) {
9219 position_t const *const pos = &statement->base.pos;
9220 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9226 * Parse a switch statement.
9228 static statement_t *parse_switch(void)
9230 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9234 PUSH_PARENT(statement);
9235 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9237 expression_t *const expr = parse_condition();
9238 type_t * type = skip_typeref(expr->base.type);
9239 if (is_type_integer(type)) {
9240 type = promote_integer(type);
9241 if (get_akind_rank(get_arithmetic_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9242 warningf(WARN_TRADITIONAL, &expr->base.pos,
9243 "'%T' switch expression not converted to '%T' in ISO C",
9246 } else if (is_type_valid(type)) {
9247 errorf(&expr->base.pos, "switch quantity is not an integer, but '%T'",
9249 type = type_error_type;
9251 statement->switchs.expression = create_implicit_cast(expr, type);
9253 switch_statement_t *rem = current_switch;
9254 current_switch = &statement->switchs;
9255 statement->switchs.body = parse_inner_statement();
9256 current_switch = rem;
9258 if (statement->switchs.default_label == NULL) {
9259 warningf(WARN_SWITCH_DEFAULT, &statement->base.pos, "switch has no default case");
9261 check_enum_cases(&statement->switchs);
9268 static statement_t *parse_loop_body(statement_t *const loop)
9270 statement_t *const rem = current_loop;
9271 current_loop = loop;
9273 statement_t *const body = parse_inner_statement();
9280 * Parse a while statement.
9282 static statement_t *parse_while(void)
9284 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9288 PUSH_PARENT(statement);
9289 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9291 expression_t *const cond = parse_condition();
9292 statement->fors.condition = cond;
9293 /* §6.8.5:2 The controlling expression of an iteration statement shall
9294 * have scalar type. */
9295 semantic_condition(cond, "condition of 'while'-statement");
9297 statement->fors.body = parse_loop_body(statement);
9305 * Parse a do statement.
9307 static statement_t *parse_do(void)
9309 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9313 PUSH_PARENT(statement);
9314 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9316 add_anchor_token(T_while);
9317 statement->do_while.body = parse_loop_body(statement);
9318 rem_anchor_token(T_while);
9321 expression_t *const cond = parse_condition();
9322 statement->do_while.condition = cond;
9323 /* §6.8.5:2 The controlling expression of an iteration statement shall
9324 * have scalar type. */
9325 semantic_condition(cond, "condition of 'do-while'-statement");
9334 * Parse a for statement.
9336 static statement_t *parse_for(void)
9338 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9342 PUSH_PARENT(statement);
9343 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9345 add_anchor_token(')');
9351 } else if (is_declaration_specifier(&token)) {
9352 parse_declaration(record_entity, DECL_FLAGS_NONE);
9354 add_anchor_token(';');
9355 expression_t *const init = parse_expression();
9356 statement->fors.initialisation = init;
9357 mark_vars_read(init, ENT_ANY);
9358 if (!expression_has_effect(init)) {
9359 warningf(WARN_UNUSED_VALUE, &init->base.pos, "initialisation of 'for'-statement has no effect");
9361 rem_anchor_token(';');
9367 if (token.kind != ';') {
9368 add_anchor_token(';');
9369 expression_t *const cond = parse_expression();
9370 statement->fors.condition = cond;
9371 /* §6.8.5:2 The controlling expression of an iteration statement
9372 * shall have scalar type. */
9373 semantic_condition(cond, "condition of 'for'-statement");
9374 mark_vars_read(cond, NULL);
9375 rem_anchor_token(';');
9378 if (token.kind != ')') {
9379 expression_t *const step = parse_expression();
9380 statement->fors.step = step;
9381 mark_vars_read(step, ENT_ANY);
9382 if (!expression_has_effect(step)) {
9383 warningf(WARN_UNUSED_VALUE, &step->base.pos, "step of 'for'-statement has no effect");
9386 rem_anchor_token(')');
9388 statement->fors.body = parse_loop_body(statement);
9396 * Parse a goto statement.
9398 static statement_t *parse_goto(void)
9400 statement_t *statement;
9401 if (GNU_MODE && look_ahead(1)->kind == '*') {
9402 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9406 expression_t *expression = parse_expression();
9407 mark_vars_read(expression, NULL);
9409 /* Argh: although documentation says the expression must be of type void*,
9410 * gcc accepts anything that can be casted into void* without error */
9411 type_t *type = expression->base.type;
9413 if (type != type_error_type) {
9414 if (!is_type_pointer(type) && !is_type_integer(type)) {
9415 errorf(&expression->base.pos, "cannot convert to a pointer type");
9416 } else if (type != type_void_ptr) {
9417 warningf(WARN_OTHER, &expression->base.pos, "type of computed goto expression should be 'void*' not '%T'", type);
9419 expression = create_implicit_cast(expression, type_void_ptr);
9422 statement->computed_goto.expression = expression;
9424 statement = allocate_statement_zero(STATEMENT_GOTO);
9427 label_t *const label = get_label("while parsing goto");
9429 label->n_users += 1;
9431 statement->gotos.label = label;
9433 /* remember the goto's in a list for later checking */
9434 *goto_anchor = &statement->gotos;
9435 goto_anchor = &statement->gotos.next;
9437 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_position)->label;
9446 * Parse a continue statement.
9448 static statement_t *parse_continue(void)
9450 if (current_loop == NULL) {
9451 errorf(HERE, "continue statement not within loop");
9454 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9462 * Parse a break statement.
9464 static statement_t *parse_break(void)
9466 if (current_switch == NULL && current_loop == NULL) {
9467 errorf(HERE, "break statement not within loop or switch");
9470 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9478 * Parse a __leave statement.
9480 static statement_t *parse_leave_statement(void)
9482 if (current_try == NULL) {
9483 errorf(HERE, "__leave statement not within __try");
9486 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9494 * Check if a given entity represents a local variable.
9496 static bool is_local_variable(const entity_t *entity)
9498 if (entity->kind != ENTITY_VARIABLE)
9501 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9502 case STORAGE_CLASS_AUTO:
9503 case STORAGE_CLASS_REGISTER: {
9504 const type_t *type = skip_typeref(entity->declaration.type);
9505 if (is_type_function(type)) {
9517 * Check if a given expression represents a local variable.
9519 static bool expression_is_local_variable(const expression_t *expression)
9521 if (expression->base.kind != EXPR_REFERENCE) {
9524 const entity_t *entity = expression->reference.entity;
9525 return is_local_variable(entity);
9528 static void err_or_warn(position_t const *const pos, char const *const msg)
9530 if (c_mode & _CXX || strict_mode) {
9533 warningf(WARN_OTHER, pos, msg);
9538 * Parse a return statement.
9540 static statement_t *parse_return(void)
9542 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9545 expression_t *return_value = NULL;
9546 if (token.kind != ';') {
9547 return_value = parse_expression();
9548 mark_vars_read(return_value, NULL);
9551 const type_t *const func_type = skip_typeref(current_function->base.type);
9552 assert(is_type_function(func_type));
9553 type_t *const return_type = skip_typeref(func_type->function.return_type);
9555 position_t const *const pos = &statement->base.pos;
9556 if (return_value != NULL) {
9557 type_t *return_value_type = skip_typeref(return_value->base.type);
9559 if (is_type_void(return_type)) {
9560 if (!is_type_void(return_value_type)) {
9561 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9562 /* Only warn in C mode, because GCC does the same */
9563 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9564 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9565 /* Only warn in C mode, because GCC does the same */
9566 err_or_warn(pos, "'return' with expression in function returning 'void'");
9569 assign_error_t error = semantic_assign(return_type, return_value);
9570 report_assign_error(error, return_type, return_value, "'return'",
9573 return_value = create_implicit_cast(return_value, return_type);
9574 /* check for returning address of a local var */
9575 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9576 const expression_t *expression = return_value->unary.value;
9577 if (expression_is_local_variable(expression)) {
9578 warningf(WARN_OTHER, pos, "function returns address of local variable");
9581 } else if (!is_type_void(return_type)) {
9582 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9583 err_or_warn(pos, "'return' without value, in function returning non-void");
9585 statement->returns.value = return_value;
9592 * Parse a declaration statement.
9594 static statement_t *parse_declaration_statement(void)
9596 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9598 entity_t *before = current_scope->last_entity;
9600 parse_external_declaration();
9602 parse_declaration(record_entity, DECL_FLAGS_NONE);
9605 declaration_statement_t *const decl = &statement->declaration;
9606 entity_t *const begin =
9607 before != NULL ? before->base.next : current_scope->entities;
9608 decl->declarations_begin = begin;
9609 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9615 * Parse an expression statement, i.e. expr ';'.
9617 static statement_t *parse_expression_statement(void)
9619 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9621 expression_t *const expr = parse_expression();
9622 statement->expression.expression = expr;
9623 mark_vars_read(expr, ENT_ANY);
9630 * Parse a microsoft __try { } __finally { } or
9631 * __try{ } __except() { }
9633 static statement_t *parse_ms_try_statment(void)
9635 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9638 PUSH_PARENT(statement);
9640 ms_try_statement_t *rem = current_try;
9641 current_try = &statement->ms_try;
9642 statement->ms_try.try_statement = parse_compound_statement(false);
9647 if (accept(T___except)) {
9648 expression_t *const expr = parse_condition();
9649 type_t * type = skip_typeref(expr->base.type);
9650 if (is_type_integer(type)) {
9651 type = promote_integer(type);
9652 } else if (is_type_valid(type)) {
9653 errorf(&expr->base.pos,
9654 "__expect expression is not an integer, but '%T'", type);
9655 type = type_error_type;
9657 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9658 } else if (!accept(T__finally)) {
9659 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9661 statement->ms_try.final_statement = parse_compound_statement(false);
9665 static statement_t *parse_empty_statement(void)
9667 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9668 statement_t *const statement = create_empty_statement();
9673 static statement_t *parse_local_label_declaration(void)
9675 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9679 entity_t *begin = NULL;
9680 entity_t *end = NULL;
9681 entity_t **anchor = &begin;
9682 add_anchor_token(';');
9683 add_anchor_token(',');
9686 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9688 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9689 if (entity != NULL && entity->base.parent_scope == current_scope) {
9690 position_t const *const ppos = &entity->base.pos;
9691 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9693 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9694 entity->base.parent_scope = current_scope;
9697 anchor = &entity->base.next;
9700 environment_push(entity);
9703 } while (accept(','));
9704 rem_anchor_token(',');
9705 rem_anchor_token(';');
9707 statement->declaration.declarations_begin = begin;
9708 statement->declaration.declarations_end = end;
9712 static void parse_namespace_definition(void)
9716 entity_t *entity = NULL;
9717 symbol_t *symbol = NULL;
9719 if (token.kind == T_IDENTIFIER) {
9720 symbol = token.base.symbol;
9721 entity = get_entity(symbol, NAMESPACE_NORMAL);
9722 if (entity && entity->kind != ENTITY_NAMESPACE) {
9724 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9725 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9731 if (entity == NULL) {
9732 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9733 entity->base.parent_scope = current_scope;
9736 if (token.kind == '=') {
9737 /* TODO: parse namespace alias */
9738 panic("namespace alias definition not supported yet");
9741 environment_push(entity);
9742 append_entity(current_scope, entity);
9744 PUSH_SCOPE(&entity->namespacee.members);
9745 PUSH_CURRENT_ENTITY(entity);
9747 add_anchor_token('}');
9750 rem_anchor_token('}');
9753 POP_CURRENT_ENTITY();
9758 * Parse a statement.
9759 * There's also parse_statement() which additionally checks for
9760 * "statement has no effect" warnings
9762 static statement_t *intern_parse_statement(void)
9764 /* declaration or statement */
9765 statement_t *statement;
9766 switch (token.kind) {
9767 case T_IDENTIFIER: {
9768 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9769 if (la1_type == ':') {
9770 statement = parse_label_statement();
9771 } else if (is_typedef_symbol(token.base.symbol)) {
9772 statement = parse_declaration_statement();
9774 /* it's an identifier, the grammar says this must be an
9775 * expression statement. However it is common that users mistype
9776 * declaration types, so we guess a bit here to improve robustness
9777 * for incorrect programs */
9781 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9783 statement = parse_expression_statement();
9787 statement = parse_declaration_statement();
9795 case T___extension__: {
9796 /* This can be a prefix to a declaration or an expression statement.
9797 * We simply eat it now and parse the rest with tail recursion. */
9799 statement = intern_parse_statement();
9805 statement = parse_declaration_statement();
9809 statement = parse_local_label_declaration();
9812 case ';': statement = parse_empty_statement(); break;
9813 case '{': statement = parse_compound_statement(false); break;
9814 case T___leave: statement = parse_leave_statement(); break;
9815 case T___try: statement = parse_ms_try_statment(); break;
9816 case T_asm: statement = parse_asm_statement(); break;
9817 case T_break: statement = parse_break(); break;
9818 case T_case: statement = parse_case_statement(); break;
9819 case T_continue: statement = parse_continue(); break;
9820 case T_default: statement = parse_default_statement(); break;
9821 case T_do: statement = parse_do(); break;
9822 case T_for: statement = parse_for(); break;
9823 case T_goto: statement = parse_goto(); break;
9824 case T_if: statement = parse_if(); break;
9825 case T_return: statement = parse_return(); break;
9826 case T_switch: statement = parse_switch(); break;
9827 case T_while: statement = parse_while(); break;
9830 statement = parse_expression_statement();
9834 errorf(HERE, "unexpected token %K while parsing statement", &token);
9835 statement = create_error_statement();
9844 * parse a statement and emits "statement has no effect" warning if needed
9845 * (This is really a wrapper around intern_parse_statement with check for 1
9846 * single warning. It is needed, because for statement expressions we have
9847 * to avoid the warning on the last statement)
9849 static statement_t *parse_statement(void)
9851 statement_t *statement = intern_parse_statement();
9853 if (statement->kind == STATEMENT_EXPRESSION) {
9854 expression_t *expression = statement->expression.expression;
9855 if (!expression_has_effect(expression)) {
9856 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
9857 "statement has no effect");
9865 * Parse a compound statement.
9867 static statement_t *parse_compound_statement(bool inside_expression_statement)
9869 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9871 PUSH_PARENT(statement);
9872 PUSH_SCOPE(&statement->compound.scope);
9875 add_anchor_token('}');
9876 /* tokens, which can start a statement */
9877 /* TODO MS, __builtin_FOO */
9878 add_anchor_token('!');
9879 add_anchor_token('&');
9880 add_anchor_token('(');
9881 add_anchor_token('*');
9882 add_anchor_token('+');
9883 add_anchor_token('-');
9884 add_anchor_token(';');
9885 add_anchor_token('{');
9886 add_anchor_token('~');
9887 add_anchor_token(T_CHARACTER_CONSTANT);
9888 add_anchor_token(T_COLONCOLON);
9889 add_anchor_token(T_IDENTIFIER);
9890 add_anchor_token(T_MINUSMINUS);
9891 add_anchor_token(T_NUMBER);
9892 add_anchor_token(T_PLUSPLUS);
9893 add_anchor_token(T_STRING_LITERAL);
9894 add_anchor_token(T__Alignof);
9895 add_anchor_token(T__Bool);
9896 add_anchor_token(T__Complex);
9897 add_anchor_token(T__Imaginary);
9898 add_anchor_token(T__Thread_local);
9899 add_anchor_token(T___PRETTY_FUNCTION__);
9900 add_anchor_token(T___attribute__);
9901 add_anchor_token(T___builtin_va_start);
9902 add_anchor_token(T___extension__);
9903 add_anchor_token(T___func__);
9904 add_anchor_token(T___imag__);
9905 add_anchor_token(T___label__);
9906 add_anchor_token(T___real__);
9907 add_anchor_token(T_asm);
9908 add_anchor_token(T_auto);
9909 add_anchor_token(T_bool);
9910 add_anchor_token(T_break);
9911 add_anchor_token(T_case);
9912 add_anchor_token(T_char);
9913 add_anchor_token(T_class);
9914 add_anchor_token(T_const);
9915 add_anchor_token(T_const_cast);
9916 add_anchor_token(T_continue);
9917 add_anchor_token(T_default);
9918 add_anchor_token(T_delete);
9919 add_anchor_token(T_double);
9920 add_anchor_token(T_do);
9921 add_anchor_token(T_dynamic_cast);
9922 add_anchor_token(T_enum);
9923 add_anchor_token(T_extern);
9924 add_anchor_token(T_false);
9925 add_anchor_token(T_float);
9926 add_anchor_token(T_for);
9927 add_anchor_token(T_goto);
9928 add_anchor_token(T_if);
9929 add_anchor_token(T_inline);
9930 add_anchor_token(T_int);
9931 add_anchor_token(T_long);
9932 add_anchor_token(T_new);
9933 add_anchor_token(T_operator);
9934 add_anchor_token(T_register);
9935 add_anchor_token(T_reinterpret_cast);
9936 add_anchor_token(T_restrict);
9937 add_anchor_token(T_return);
9938 add_anchor_token(T_short);
9939 add_anchor_token(T_signed);
9940 add_anchor_token(T_sizeof);
9941 add_anchor_token(T_static);
9942 add_anchor_token(T_static_cast);
9943 add_anchor_token(T_struct);
9944 add_anchor_token(T_switch);
9945 add_anchor_token(T_template);
9946 add_anchor_token(T_this);
9947 add_anchor_token(T_throw);
9948 add_anchor_token(T_true);
9949 add_anchor_token(T_try);
9950 add_anchor_token(T_typedef);
9951 add_anchor_token(T_typeid);
9952 add_anchor_token(T_typename);
9953 add_anchor_token(T_typeof);
9954 add_anchor_token(T_union);
9955 add_anchor_token(T_unsigned);
9956 add_anchor_token(T_using);
9957 add_anchor_token(T_void);
9958 add_anchor_token(T_volatile);
9959 add_anchor_token(T_wchar_t);
9960 add_anchor_token(T_while);
9962 statement_t **anchor = &statement->compound.statements;
9963 bool only_decls_so_far = true;
9964 while (token.kind != '}' && token.kind != T_EOF) {
9965 statement_t *sub_statement = intern_parse_statement();
9966 if (sub_statement->kind == STATEMENT_ERROR) {
9970 if (sub_statement->kind != STATEMENT_DECLARATION) {
9971 only_decls_so_far = false;
9972 } else if (!only_decls_so_far) {
9973 position_t const *const pos = &sub_statement->base.pos;
9974 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9977 *anchor = sub_statement;
9978 anchor = &sub_statement->base.next;
9982 /* look over all statements again to produce no effect warnings */
9983 if (is_warn_on(WARN_UNUSED_VALUE)) {
9984 statement_t *sub_statement = statement->compound.statements;
9985 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9986 if (sub_statement->kind != STATEMENT_EXPRESSION)
9988 /* don't emit a warning for the last expression in an expression
9989 * statement as it has always an effect */
9990 if (inside_expression_statement && sub_statement->base.next == NULL)
9993 expression_t *expression = sub_statement->expression.expression;
9994 if (!expression_has_effect(expression)) {
9995 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
9996 "statement has no effect");
10001 rem_anchor_token(T_while);
10002 rem_anchor_token(T_wchar_t);
10003 rem_anchor_token(T_volatile);
10004 rem_anchor_token(T_void);
10005 rem_anchor_token(T_using);
10006 rem_anchor_token(T_unsigned);
10007 rem_anchor_token(T_union);
10008 rem_anchor_token(T_typeof);
10009 rem_anchor_token(T_typename);
10010 rem_anchor_token(T_typeid);
10011 rem_anchor_token(T_typedef);
10012 rem_anchor_token(T_try);
10013 rem_anchor_token(T_true);
10014 rem_anchor_token(T_throw);
10015 rem_anchor_token(T_this);
10016 rem_anchor_token(T_template);
10017 rem_anchor_token(T_switch);
10018 rem_anchor_token(T_struct);
10019 rem_anchor_token(T_static_cast);
10020 rem_anchor_token(T_static);
10021 rem_anchor_token(T_sizeof);
10022 rem_anchor_token(T_signed);
10023 rem_anchor_token(T_short);
10024 rem_anchor_token(T_return);
10025 rem_anchor_token(T_restrict);
10026 rem_anchor_token(T_reinterpret_cast);
10027 rem_anchor_token(T_register);
10028 rem_anchor_token(T_operator);
10029 rem_anchor_token(T_new);
10030 rem_anchor_token(T_long);
10031 rem_anchor_token(T_int);
10032 rem_anchor_token(T_inline);
10033 rem_anchor_token(T_if);
10034 rem_anchor_token(T_goto);
10035 rem_anchor_token(T_for);
10036 rem_anchor_token(T_float);
10037 rem_anchor_token(T_false);
10038 rem_anchor_token(T_extern);
10039 rem_anchor_token(T_enum);
10040 rem_anchor_token(T_dynamic_cast);
10041 rem_anchor_token(T_do);
10042 rem_anchor_token(T_double);
10043 rem_anchor_token(T_delete);
10044 rem_anchor_token(T_default);
10045 rem_anchor_token(T_continue);
10046 rem_anchor_token(T_const_cast);
10047 rem_anchor_token(T_const);
10048 rem_anchor_token(T_class);
10049 rem_anchor_token(T_char);
10050 rem_anchor_token(T_case);
10051 rem_anchor_token(T_break);
10052 rem_anchor_token(T_bool);
10053 rem_anchor_token(T_auto);
10054 rem_anchor_token(T_asm);
10055 rem_anchor_token(T___real__);
10056 rem_anchor_token(T___label__);
10057 rem_anchor_token(T___imag__);
10058 rem_anchor_token(T___func__);
10059 rem_anchor_token(T___extension__);
10060 rem_anchor_token(T___builtin_va_start);
10061 rem_anchor_token(T___attribute__);
10062 rem_anchor_token(T___PRETTY_FUNCTION__);
10063 rem_anchor_token(T__Thread_local);
10064 rem_anchor_token(T__Imaginary);
10065 rem_anchor_token(T__Complex);
10066 rem_anchor_token(T__Bool);
10067 rem_anchor_token(T__Alignof);
10068 rem_anchor_token(T_STRING_LITERAL);
10069 rem_anchor_token(T_PLUSPLUS);
10070 rem_anchor_token(T_NUMBER);
10071 rem_anchor_token(T_MINUSMINUS);
10072 rem_anchor_token(T_IDENTIFIER);
10073 rem_anchor_token(T_COLONCOLON);
10074 rem_anchor_token(T_CHARACTER_CONSTANT);
10075 rem_anchor_token('~');
10076 rem_anchor_token('{');
10077 rem_anchor_token(';');
10078 rem_anchor_token('-');
10079 rem_anchor_token('+');
10080 rem_anchor_token('*');
10081 rem_anchor_token('(');
10082 rem_anchor_token('&');
10083 rem_anchor_token('!');
10084 rem_anchor_token('}');
10092 * Check for unused global static functions and variables
10094 static void check_unused_globals(void)
10096 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10099 for (const entity_t *entity = file_scope->entities; entity != NULL;
10100 entity = entity->base.next) {
10101 if (!is_declaration(entity))
10104 const declaration_t *declaration = &entity->declaration;
10105 if (declaration->used ||
10106 declaration->modifiers & DM_UNUSED ||
10107 declaration->modifiers & DM_USED ||
10108 declaration->storage_class != STORAGE_CLASS_STATIC)
10113 if (entity->kind == ENTITY_FUNCTION) {
10114 /* inhibit warning for static inline functions */
10115 if (entity->function.is_inline)
10118 why = WARN_UNUSED_FUNCTION;
10119 s = entity->function.body != NULL ? "defined" : "declared";
10121 why = WARN_UNUSED_VARIABLE;
10125 warningf(why, &declaration->base.pos, "'%#N' %s but not used", entity, s);
10129 static void parse_global_asm(void)
10131 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10134 add_anchor_token(';');
10135 add_anchor_token(')');
10136 add_anchor_token(T_STRING_LITERAL);
10139 rem_anchor_token(T_STRING_LITERAL);
10140 statement->asms.asm_text = parse_string_literals("global asm");
10141 statement->base.next = unit->global_asm;
10142 unit->global_asm = statement;
10144 rem_anchor_token(')');
10146 rem_anchor_token(';');
10150 static void parse_linkage_specification(void)
10154 position_t const pos = *HERE;
10155 char const *const linkage = parse_string_literals(NULL).begin;
10157 linkage_kind_t old_linkage = current_linkage;
10158 linkage_kind_t new_linkage;
10159 if (streq(linkage, "C")) {
10160 new_linkage = LINKAGE_C;
10161 } else if (streq(linkage, "C++")) {
10162 new_linkage = LINKAGE_CXX;
10164 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10165 new_linkage = LINKAGE_C;
10167 current_linkage = new_linkage;
10176 assert(current_linkage == new_linkage);
10177 current_linkage = old_linkage;
10180 static void parse_external(void)
10182 switch (token.kind) {
10184 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10185 parse_linkage_specification();
10187 DECLARATION_START_NO_EXTERN
10189 case T___extension__:
10190 /* tokens below are for implicit int */
10191 case '&': /* & x; -> int& x; (and error later, because C++ has no
10193 case '*': /* * x; -> int* x; */
10194 case '(': /* (x); -> int (x); */
10196 parse_external_declaration();
10202 parse_global_asm();
10206 parse_namespace_definition();
10210 if (!strict_mode) {
10211 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10218 errorf(HERE, "stray %K outside of function", &token);
10219 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10220 eat_until_matching_token(token.kind);
10226 static void parse_externals(void)
10228 add_anchor_token('}');
10229 add_anchor_token(T_EOF);
10232 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10233 unsigned short token_anchor_copy[T_LAST_TOKEN];
10234 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10237 while (token.kind != T_EOF && token.kind != '}') {
10239 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10240 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10242 /* the anchor set and its copy differs */
10243 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10246 if (in_gcc_extension) {
10247 /* an gcc extension scope was not closed */
10248 internal_errorf(HERE, "Leaked __extension__");
10255 rem_anchor_token(T_EOF);
10256 rem_anchor_token('}');
10260 * Parse a translation unit.
10262 static void parse_translation_unit(void)
10264 add_anchor_token(T_EOF);
10269 if (token.kind == T_EOF)
10272 errorf(HERE, "stray %K outside of function", &token);
10273 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10274 eat_until_matching_token(token.kind);
10279 void set_default_visibility(elf_visibility_tag_t visibility)
10281 default_visibility = visibility;
10287 * @return the translation unit or NULL if errors occurred.
10289 void start_parsing(void)
10291 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10292 label_stack = NEW_ARR_F(stack_entry_t, 0);
10294 print_to_file(stderr);
10296 assert(unit == NULL);
10297 unit = allocate_ast_zero(sizeof(unit[0]));
10299 assert(file_scope == NULL);
10300 file_scope = &unit->scope;
10302 assert(current_scope == NULL);
10303 scope_push(&unit->scope);
10305 create_gnu_builtins();
10307 create_microsoft_intrinsics();
10310 translation_unit_t *finish_parsing(void)
10312 assert(current_scope == &unit->scope);
10315 assert(file_scope == &unit->scope);
10316 check_unused_globals();
10319 DEL_ARR_F(environment_stack);
10320 DEL_ARR_F(label_stack);
10322 translation_unit_t *result = unit;
10327 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10328 * are given length one. */
10329 static void complete_incomplete_arrays(void)
10331 size_t n = ARR_LEN(incomplete_arrays);
10332 for (size_t i = 0; i != n; ++i) {
10333 declaration_t *const decl = incomplete_arrays[i];
10334 type_t *const type = skip_typeref(decl->type);
10336 if (!is_type_incomplete(type))
10339 position_t const *const pos = &decl->base.pos;
10340 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10342 type_t *const new_type = duplicate_type(type);
10343 new_type->array.size_constant = true;
10344 new_type->array.has_implicit_size = true;
10345 new_type->array.size = 1;
10347 type_t *const result = identify_new_type(new_type);
10349 decl->type = result;
10353 static void prepare_main_collect2(entity_t *const entity)
10355 PUSH_SCOPE(&entity->function.body->compound.scope);
10357 // create call to __main
10358 symbol_t *symbol = symbol_table_insert("__main");
10359 entity_t *subsubmain_ent
10360 = create_implicit_function(symbol, &builtin_position);
10362 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10363 type_t *ftype = subsubmain_ent->declaration.type;
10364 ref->base.pos = builtin_position;
10365 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10366 ref->reference.entity = subsubmain_ent;
10368 expression_t *call = allocate_expression_zero(EXPR_CALL);
10369 call->base.pos = builtin_position;
10370 call->base.type = type_void;
10371 call->call.function = ref;
10373 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10374 expr_statement->base.pos = builtin_position;
10375 expr_statement->expression.expression = call;
10377 statement_t *const body = entity->function.body;
10378 assert(body->kind == STATEMENT_COMPOUND);
10379 compound_statement_t *compounds = &body->compound;
10381 expr_statement->base.next = compounds->statements;
10382 compounds->statements = expr_statement;
10389 lookahead_bufpos = 0;
10390 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10393 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10394 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10395 parse_translation_unit();
10396 complete_incomplete_arrays();
10397 DEL_ARR_F(incomplete_arrays);
10398 incomplete_arrays = NULL;
10402 * Initialize the parser.
10404 void init_parser(void)
10406 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10408 init_expression_parsers();
10409 obstack_init(&temp_obst);
10413 * Terminate the parser.
10415 void exit_parser(void)
10417 obstack_free(&temp_obst, NULL);