2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "adt/strutil.h"
29 #include "diagnostic.h"
30 #include "format_check.h"
36 #include "type_hash.h"
39 #include "attribute_t.h"
40 #include "lang_features.h"
44 #include "adt/bitfiddle.h"
45 #include "adt/error.h"
46 #include "adt/array.h"
48 //#define PRINT_TOKENS
49 #define MAX_LOOKAHEAD 1
54 entity_namespace_t namespc;
57 typedef struct declaration_specifiers_t declaration_specifiers_t;
58 struct declaration_specifiers_t {
59 source_position_t source_position;
60 storage_class_t storage_class;
61 unsigned char alignment; /**< Alignment, 0 if not set. */
63 bool thread_local : 1; /**< GCC __thread */
64 attribute_t *attributes; /**< list of attributes */
69 * An environment for parsing initializers (and compound literals).
71 typedef struct parse_initializer_env_t {
72 type_t *type; /**< the type of the initializer. In case of an
73 array type with unspecified size this gets
74 adjusted to the actual size. */
75 entity_t *entity; /**< the variable that is initialized if any */
76 bool must_be_constant;
77 } parse_initializer_env_t;
79 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
81 /** The current token. */
83 /** The lookahead ring-buffer. */
84 static token_t lookahead_buffer[MAX_LOOKAHEAD];
85 /** Position of the next token in the lookahead buffer. */
86 static size_t lookahead_bufpos;
87 static stack_entry_t *environment_stack = NULL;
88 static stack_entry_t *label_stack = NULL;
89 static scope_t *file_scope = NULL;
90 static scope_t *current_scope = NULL;
91 /** Point to the current function declaration if inside a function. */
92 static function_t *current_function = NULL;
93 static entity_t *current_entity = NULL;
94 static switch_statement_t *current_switch = NULL;
95 static statement_t *current_loop = NULL;
96 static statement_t *current_parent = NULL;
97 static ms_try_statement_t *current_try = NULL;
98 static linkage_kind_t current_linkage;
99 static goto_statement_t *goto_first = NULL;
100 static goto_statement_t **goto_anchor = NULL;
101 static label_statement_t *label_first = NULL;
102 static label_statement_t **label_anchor = NULL;
103 /** current translation unit. */
104 static translation_unit_t *unit = NULL;
105 /** true if we are in an __extension__ context. */
106 static bool in_gcc_extension = false;
107 static struct obstack temp_obst;
108 static entity_t *anonymous_entity;
109 static declaration_t **incomplete_arrays;
110 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
113 #define PUSH_CURRENT_ENTITY(entity) \
114 entity_t *const new_current_entity = (entity); \
115 entity_t *const old_current_entity = current_entity; \
116 ((void)(current_entity = new_current_entity))
117 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
119 #define PUSH_PARENT(stmt) \
120 statement_t *const new_parent = (stmt); \
121 statement_t *const old_parent = current_parent; \
122 ((void)(current_parent = new_parent))
123 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
125 #define PUSH_SCOPE(scope) \
126 size_t const top = environment_top(); \
127 scope_t *const new_scope = (scope); \
128 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
129 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
130 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
132 #define PUSH_EXTENSION() \
134 bool const old_gcc_extension = in_gcc_extension; \
135 while (next_if(T___extension__)) { \
136 in_gcc_extension = true; \
139 #define POP_EXTENSION() \
140 ((void)(in_gcc_extension = old_gcc_extension))
142 /** special symbol used for anonymous entities. */
143 static symbol_t *sym_anonymous = NULL;
145 /** The token anchor set */
146 static unsigned short token_anchor_set[T_LAST_TOKEN];
148 /** The current source position. */
149 #define HERE (&token.base.source_position)
151 /** true if we are in GCC mode. */
152 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
154 static statement_t *parse_compound_statement(bool inside_expression_statement);
155 static statement_t *parse_statement(void);
157 static expression_t *parse_subexpression(precedence_t);
158 static expression_t *parse_expression(void);
159 static type_t *parse_typename(void);
160 static void parse_externals(void);
161 static void parse_external(void);
163 static void parse_compound_type_entries(compound_t *compound_declaration);
165 static void check_call_argument(type_t *expected_type,
166 call_argument_t *argument, unsigned pos);
168 typedef enum declarator_flags_t {
170 DECL_MAY_BE_ABSTRACT = 1U << 0,
171 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
172 DECL_IS_PARAMETER = 1U << 2
173 } declarator_flags_t;
175 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
176 declarator_flags_t flags);
178 static void semantic_comparison(binary_expression_t *expression);
180 #define STORAGE_CLASSES \
181 STORAGE_CLASSES_NO_EXTERN \
184 #define STORAGE_CLASSES_NO_EXTERN \
191 #define TYPE_QUALIFIERS \
196 case T__forceinline: \
197 case T___attribute__:
199 #define COMPLEX_SPECIFIERS \
201 #define IMAGINARY_SPECIFIERS \
204 #define TYPE_SPECIFIERS \
206 case T___builtin_va_list: \
231 #define DECLARATION_START \
236 #define DECLARATION_START_NO_EXTERN \
237 STORAGE_CLASSES_NO_EXTERN \
241 #define EXPRESSION_START \
250 case T_CHARACTER_CONSTANT: \
254 case T_STRING_LITERAL: \
255 case T___FUNCDNAME__: \
256 case T___FUNCSIG__: \
257 case T___PRETTY_FUNCTION__: \
258 case T___alignof__: \
259 case T___builtin_classify_type: \
260 case T___builtin_constant_p: \
261 case T___builtin_isgreater: \
262 case T___builtin_isgreaterequal: \
263 case T___builtin_isless: \
264 case T___builtin_islessequal: \
265 case T___builtin_islessgreater: \
266 case T___builtin_isunordered: \
267 case T___builtin_offsetof: \
268 case T___builtin_va_arg: \
269 case T___builtin_va_copy: \
270 case T___builtin_va_start: \
281 * Returns the size of a statement node.
283 * @param kind the statement kind
285 static size_t get_statement_struct_size(statement_kind_t kind)
287 static const size_t sizes[] = {
288 [STATEMENT_ERROR] = sizeof(statement_base_t),
289 [STATEMENT_EMPTY] = sizeof(statement_base_t),
290 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
291 [STATEMENT_RETURN] = sizeof(return_statement_t),
292 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
293 [STATEMENT_IF] = sizeof(if_statement_t),
294 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
295 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
296 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
297 [STATEMENT_BREAK] = sizeof(statement_base_t),
298 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
299 [STATEMENT_GOTO] = sizeof(goto_statement_t),
300 [STATEMENT_LABEL] = sizeof(label_statement_t),
301 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
302 [STATEMENT_WHILE] = sizeof(while_statement_t),
303 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
304 [STATEMENT_FOR] = sizeof(for_statement_t),
305 [STATEMENT_ASM] = sizeof(asm_statement_t),
306 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
307 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
309 assert((size_t)kind < lengthof(sizes));
310 assert(sizes[kind] != 0);
315 * Returns the size of an expression node.
317 * @param kind the expression kind
319 static size_t get_expression_struct_size(expression_kind_t kind)
321 static const size_t sizes[] = {
322 [EXPR_ERROR] = sizeof(expression_base_t),
323 [EXPR_REFERENCE] = sizeof(reference_expression_t),
324 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
325 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_CHARACTER] = sizeof(string_literal_expression_t),
329 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
330 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
331 [EXPR_CALL] = sizeof(call_expression_t),
332 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
333 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
334 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
335 [EXPR_SELECT] = sizeof(select_expression_t),
336 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
337 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
338 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
339 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
340 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
341 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
342 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
343 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
344 [EXPR_VA_START] = sizeof(va_start_expression_t),
345 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
346 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
347 [EXPR_STATEMENT] = sizeof(statement_expression_t),
348 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
350 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
351 return sizes[EXPR_UNARY_FIRST];
353 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
354 return sizes[EXPR_BINARY_FIRST];
356 assert((size_t)kind < lengthof(sizes));
357 assert(sizes[kind] != 0);
362 * Allocate a statement node of given kind and initialize all
363 * fields with zero. Sets its source position to the position
364 * of the current token.
366 static statement_t *allocate_statement_zero(statement_kind_t kind)
368 size_t size = get_statement_struct_size(kind);
369 statement_t *res = allocate_ast_zero(size);
371 res->base.kind = kind;
372 res->base.parent = current_parent;
373 res->base.source_position = *HERE;
378 * Allocate an expression node of given kind and initialize all
381 * @param kind the kind of the expression to allocate
383 static expression_t *allocate_expression_zero(expression_kind_t kind)
385 size_t size = get_expression_struct_size(kind);
386 expression_t *res = allocate_ast_zero(size);
388 res->base.kind = kind;
389 res->base.type = type_error_type;
390 res->base.source_position = *HERE;
395 * Creates a new invalid expression at the source position
396 * of the current token.
398 static expression_t *create_error_expression(void)
400 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
401 expression->base.type = type_error_type;
406 * Creates a new invalid statement.
408 static statement_t *create_error_statement(void)
410 return allocate_statement_zero(STATEMENT_ERROR);
414 * Allocate a new empty statement.
416 static statement_t *create_empty_statement(void)
418 return allocate_statement_zero(STATEMENT_EMPTY);
422 * Returns the size of an initializer node.
424 * @param kind the initializer kind
426 static size_t get_initializer_size(initializer_kind_t kind)
428 static const size_t sizes[] = {
429 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
430 [INITIALIZER_STRING] = sizeof(initializer_value_t),
431 [INITIALIZER_LIST] = sizeof(initializer_list_t),
432 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
434 assert((size_t)kind < lengthof(sizes));
435 assert(sizes[kind] != 0);
440 * Allocate an initializer node of given kind and initialize all
443 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
445 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
452 * Returns the index of the top element of the environment stack.
454 static size_t environment_top(void)
456 return ARR_LEN(environment_stack);
460 * Returns the index of the top element of the global label stack.
462 static size_t label_top(void)
464 return ARR_LEN(label_stack);
468 * Return the next token.
470 static inline void next_token(void)
472 token = lookahead_buffer[lookahead_bufpos];
473 lookahead_buffer[lookahead_bufpos] = lexer_token;
476 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
479 print_token(stderr, &token);
480 fprintf(stderr, "\n");
484 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
486 static inline bool next_if(token_kind_t const type)
488 if (token.kind == type) {
497 * Return the next token with a given lookahead.
499 static inline const token_t *look_ahead(size_t num)
501 assert(0 < num && num <= MAX_LOOKAHEAD);
502 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
503 return &lookahead_buffer[pos];
507 * Adds a token type to the token type anchor set (a multi-set).
509 static void add_anchor_token(token_kind_t const token_kind)
511 assert(token_kind < T_LAST_TOKEN);
512 ++token_anchor_set[token_kind];
516 * Remove a token type from the token type anchor set (a multi-set).
518 static void rem_anchor_token(token_kind_t const token_kind)
520 assert(token_kind < T_LAST_TOKEN);
521 assert(token_anchor_set[token_kind] != 0);
522 --token_anchor_set[token_kind];
526 * Eat tokens until a matching token type is found.
528 static void eat_until_matching_token(token_kind_t const type)
530 token_kind_t end_token;
532 case '(': end_token = ')'; break;
533 case '{': end_token = '}'; break;
534 case '[': end_token = ']'; break;
535 default: end_token = type; break;
538 unsigned parenthesis_count = 0;
539 unsigned brace_count = 0;
540 unsigned bracket_count = 0;
541 while (token.kind != end_token ||
542 parenthesis_count != 0 ||
544 bracket_count != 0) {
545 switch (token.kind) {
547 case '(': ++parenthesis_count; break;
548 case '{': ++brace_count; break;
549 case '[': ++bracket_count; break;
552 if (parenthesis_count > 0)
562 if (bracket_count > 0)
565 if (token.kind == end_token &&
566 parenthesis_count == 0 &&
580 * Eat input tokens until an anchor is found.
582 static void eat_until_anchor(void)
584 while (token_anchor_set[token.kind] == 0) {
585 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
586 eat_until_matching_token(token.kind);
592 * Eat a whole block from input tokens.
594 static void eat_block(void)
596 eat_until_matching_token('{');
601 * Report a parse error because an expected token was not found.
604 #if defined __GNUC__ && __GNUC__ >= 4
605 __attribute__((sentinel))
607 void parse_error_expected(const char *message, ...)
609 if (message != NULL) {
610 errorf(HERE, "%s", message);
613 va_start(ap, message);
614 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
619 * Report an incompatible type.
621 static void type_error_incompatible(const char *msg,
622 const source_position_t *source_position, type_t *type1, type_t *type2)
624 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
628 static bool skip_till(token_kind_t const expected, char const *const context)
630 if (UNLIKELY(token.kind != expected)) {
631 parse_error_expected(context, expected, NULL);
632 add_anchor_token(expected);
634 rem_anchor_token(expected);
635 if (token.kind != expected)
642 * Expect the current token is the expected token.
643 * If not, generate an error and skip until the next anchor.
645 static void expect(token_kind_t const expected)
647 if (skip_till(expected, NULL))
651 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
653 if (!skip_till(T_IDENTIFIER, context))
655 symbol_t *const sym = token.base.symbol;
663 * Push a given scope on the scope stack and make it the
666 static scope_t *scope_push(scope_t *new_scope)
668 if (current_scope != NULL) {
669 new_scope->depth = current_scope->depth + 1;
672 scope_t *old_scope = current_scope;
673 current_scope = new_scope;
678 * Pop the current scope from the scope stack.
680 static void scope_pop(scope_t *old_scope)
682 current_scope = old_scope;
686 * Search an entity by its symbol in a given namespace.
688 static entity_t *get_entity(const symbol_t *const symbol,
689 namespace_tag_t namespc)
691 entity_t *entity = symbol->entity;
692 for (; entity != NULL; entity = entity->base.symbol_next) {
693 if ((namespace_tag_t)entity->base.namespc == namespc)
700 /* §6.2.3:1 24) There is only one name space for tags even though three are
702 static entity_t *get_tag(symbol_t const *const symbol,
703 entity_kind_tag_t const kind)
705 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
706 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
708 "'%Y' defined as wrong kind of tag (previous definition %P)",
709 symbol, &entity->base.source_position);
716 * pushs an entity on the environment stack and links the corresponding symbol
719 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
721 symbol_t *symbol = entity->base.symbol;
722 entity_namespace_t namespc = entity->base.namespc;
723 assert(namespc != 0);
725 /* replace/add entity into entity list of the symbol */
728 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
733 /* replace an entry? */
734 if (iter->base.namespc == namespc) {
735 entity->base.symbol_next = iter->base.symbol_next;
741 /* remember old declaration */
743 entry.symbol = symbol;
744 entry.old_entity = iter;
745 entry.namespc = namespc;
746 ARR_APP1(stack_entry_t, *stack_ptr, entry);
750 * Push an entity on the environment stack.
752 static void environment_push(entity_t *entity)
754 assert(entity->base.source_position.input_name != NULL);
755 assert(entity->base.parent_scope != NULL);
756 stack_push(&environment_stack, entity);
760 * Push a declaration on the global label stack.
762 * @param declaration the declaration
764 static void label_push(entity_t *label)
766 /* we abuse the parameters scope as parent for the labels */
767 label->base.parent_scope = ¤t_function->parameters;
768 stack_push(&label_stack, label);
772 * pops symbols from the environment stack until @p new_top is the top element
774 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
776 stack_entry_t *stack = *stack_ptr;
777 size_t top = ARR_LEN(stack);
780 assert(new_top <= top);
784 for (i = top; i > new_top; --i) {
785 stack_entry_t *entry = &stack[i - 1];
787 entity_t *old_entity = entry->old_entity;
788 symbol_t *symbol = entry->symbol;
789 entity_namespace_t namespc = entry->namespc;
791 /* replace with old_entity/remove */
794 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
796 assert(iter != NULL);
797 /* replace an entry? */
798 if (iter->base.namespc == namespc)
802 /* restore definition from outer scopes (if there was one) */
803 if (old_entity != NULL) {
804 old_entity->base.symbol_next = iter->base.symbol_next;
805 *anchor = old_entity;
807 /* remove entry from list */
808 *anchor = iter->base.symbol_next;
812 ARR_SHRINKLEN(*stack_ptr, new_top);
816 * Pop all entries from the environment stack until the new_top
819 * @param new_top the new stack top
821 static void environment_pop_to(size_t new_top)
823 stack_pop_to(&environment_stack, new_top);
827 * Pop all entries from the global label stack until the new_top
830 * @param new_top the new stack top
832 static void label_pop_to(size_t new_top)
834 stack_pop_to(&label_stack, new_top);
837 static atomic_type_kind_t get_akind(const type_t *type)
839 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
840 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
841 return type->atomic.akind;
845 * §6.3.1.1:2 Do integer promotion for a given type.
847 * @param type the type to promote
848 * @return the promoted type
850 static type_t *promote_integer(type_t *type)
852 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
859 * Check if a given expression represents a null pointer constant.
861 * @param expression the expression to check
863 static bool is_null_pointer_constant(const expression_t *expression)
865 /* skip void* cast */
866 if (expression->kind == EXPR_UNARY_CAST) {
867 type_t *const type = skip_typeref(expression->base.type);
868 if (types_compatible(type, type_void_ptr))
869 expression = expression->unary.value;
872 type_t *const type = skip_typeref(expression->base.type);
873 if (!is_type_integer(type))
875 switch (is_constant_expression(expression)) {
876 case EXPR_CLASS_ERROR: return true;
877 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
878 default: return false;
883 * Create an implicit cast expression.
885 * @param expression the expression to cast
886 * @param dest_type the destination type
888 static expression_t *create_implicit_cast(expression_t *expression,
891 type_t *const source_type = expression->base.type;
893 if (source_type == dest_type)
896 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
897 cast->unary.value = expression;
898 cast->base.type = dest_type;
899 cast->base.implicit = true;
904 typedef enum assign_error_t {
906 ASSIGN_ERROR_INCOMPATIBLE,
907 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
908 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
909 ASSIGN_WARNING_POINTER_FROM_INT,
910 ASSIGN_WARNING_INT_FROM_POINTER
913 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, source_position_t const *const pos)
915 type_t *const orig_type_right = right->base.type;
916 type_t *const type_left = skip_typeref(orig_type_left);
917 type_t *const type_right = skip_typeref(orig_type_right);
922 case ASSIGN_ERROR_INCOMPATIBLE:
923 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
926 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
927 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
928 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
930 /* the left type has all qualifiers from the right type */
931 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
932 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);
936 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
937 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
940 case ASSIGN_WARNING_POINTER_FROM_INT:
941 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
944 case ASSIGN_WARNING_INT_FROM_POINTER:
945 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
949 panic("invalid error value");
953 /** Implements the rules from §6.5.16.1 */
954 static assign_error_t semantic_assign(type_t *orig_type_left,
955 const expression_t *const right)
957 type_t *const orig_type_right = right->base.type;
958 type_t *const type_left = skip_typeref(orig_type_left);
959 type_t *const type_right = skip_typeref(orig_type_right);
961 if (is_type_pointer(type_left)) {
962 if (is_null_pointer_constant(right)) {
963 return ASSIGN_SUCCESS;
964 } else if (is_type_pointer(type_right)) {
965 type_t *points_to_left
966 = skip_typeref(type_left->pointer.points_to);
967 type_t *points_to_right
968 = skip_typeref(type_right->pointer.points_to);
969 assign_error_t res = ASSIGN_SUCCESS;
971 /* the left type has all qualifiers from the right type */
972 unsigned missing_qualifiers
973 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
974 if (missing_qualifiers != 0) {
975 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
978 points_to_left = get_unqualified_type(points_to_left);
979 points_to_right = get_unqualified_type(points_to_right);
981 if (is_type_void(points_to_left))
984 if (is_type_void(points_to_right)) {
985 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
986 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
989 if (!types_compatible(points_to_left, points_to_right)) {
990 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
994 } else if (is_type_integer(type_right)) {
995 return ASSIGN_WARNING_POINTER_FROM_INT;
997 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
998 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
999 && is_type_pointer(type_right))) {
1000 return ASSIGN_SUCCESS;
1001 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1002 type_t *const unqual_type_left = get_unqualified_type(type_left);
1003 type_t *const unqual_type_right = get_unqualified_type(type_right);
1004 if (types_compatible(unqual_type_left, unqual_type_right)) {
1005 return ASSIGN_SUCCESS;
1007 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1008 return ASSIGN_WARNING_INT_FROM_POINTER;
1011 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1012 return ASSIGN_SUCCESS;
1014 return ASSIGN_ERROR_INCOMPATIBLE;
1017 static expression_t *parse_constant_expression(void)
1019 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1021 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1022 errorf(&result->base.source_position,
1023 "expression '%E' is not constant", result);
1029 static expression_t *parse_assignment_expression(void)
1031 return parse_subexpression(PREC_ASSIGNMENT);
1034 static void append_string(string_t const *const s)
1036 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1037 * possible, because other tokens are grown there alongside. */
1038 obstack_grow(&ast_obstack, s->begin, s->size);
1041 static string_t finish_string(string_encoding_t const enc)
1043 obstack_1grow(&ast_obstack, '\0');
1044 size_t const size = obstack_object_size(&ast_obstack) - 1;
1045 char const *const string = obstack_finish(&ast_obstack);
1046 return (string_t){ string, size, enc };
1049 static string_t concat_string_literals(void)
1051 assert(token.kind == T_STRING_LITERAL);
1054 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1055 append_string(&token.literal.string);
1056 eat(T_STRING_LITERAL);
1057 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1058 string_encoding_t enc = token.literal.string.encoding;
1060 if (token.literal.string.encoding != STRING_ENCODING_CHAR) {
1061 enc = token.literal.string.encoding;
1063 append_string(&token.literal.string);
1064 eat(T_STRING_LITERAL);
1065 } while (token.kind == T_STRING_LITERAL);
1066 result = finish_string(enc);
1068 result = token.literal.string;
1069 eat(T_STRING_LITERAL);
1075 static string_t parse_string_literals(char const *const context)
1077 if (!skip_till(T_STRING_LITERAL, context))
1078 return (string_t){ "", 0, STRING_ENCODING_CHAR };
1080 source_position_t const pos = *HERE;
1081 string_t const res = concat_string_literals();
1083 if (res.encoding != STRING_ENCODING_CHAR) {
1084 errorf(&pos, "expected plain string literal, got wide string literal");
1090 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1092 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1093 attribute->kind = kind;
1094 attribute->source_position = *HERE;
1099 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1102 * __attribute__ ( ( attribute-list ) )
1106 * attribute_list , attrib
1111 * any-word ( identifier )
1112 * any-word ( identifier , nonempty-expr-list )
1113 * any-word ( expr-list )
1115 * where the "identifier" must not be declared as a type, and
1116 * "any-word" may be any identifier (including one declared as a
1117 * type), a reserved word storage class specifier, type specifier or
1118 * type qualifier. ??? This still leaves out most reserved keywords
1119 * (following the old parser), shouldn't we include them, and why not
1120 * allow identifiers declared as types to start the arguments?
1122 * Matze: this all looks confusing and little systematic, so we're even less
1123 * strict and parse any list of things which are identifiers or
1124 * (assignment-)expressions.
1126 static attribute_argument_t *parse_attribute_arguments(void)
1128 attribute_argument_t *first = NULL;
1129 attribute_argument_t **anchor = &first;
1130 if (token.kind != ')') do {
1131 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1133 /* is it an identifier */
1134 if (token.kind == T_IDENTIFIER
1135 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1136 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1137 argument->v.symbol = token.base.symbol;
1140 /* must be an expression */
1141 expression_t *expression = parse_assignment_expression();
1143 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1144 argument->v.expression = expression;
1147 /* append argument */
1149 anchor = &argument->next;
1150 } while (next_if(','));
1155 static attribute_t *parse_attribute_asm(void)
1157 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1160 attribute->a.arguments = parse_attribute_arguments();
1164 static attribute_t *parse_attribute_gnu_single(void)
1166 /* parse "any-word" */
1167 symbol_t *const symbol = token.base.symbol;
1168 if (symbol == NULL) {
1169 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1173 attribute_kind_t kind;
1174 char const *const name = symbol->string;
1175 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1176 if (kind > ATTRIBUTE_GNU_LAST) {
1177 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1178 /* TODO: we should still save the attribute in the list... */
1179 kind = ATTRIBUTE_UNKNOWN;
1183 const char *attribute_name = get_attribute_name(kind);
1184 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1188 attribute_t *attribute = allocate_attribute_zero(kind);
1191 /* parse arguments */
1193 attribute->a.arguments = parse_attribute_arguments();
1198 static attribute_t *parse_attribute_gnu(void)
1200 attribute_t *first = NULL;
1201 attribute_t **anchor = &first;
1203 eat(T___attribute__);
1204 add_anchor_token(')');
1205 add_anchor_token(',');
1209 if (token.kind != ')') do {
1210 attribute_t *attribute = parse_attribute_gnu_single();
1212 *anchor = attribute;
1213 anchor = &attribute->next;
1215 } while (next_if(','));
1216 rem_anchor_token(',');
1217 rem_anchor_token(')');
1224 /** Parse attributes. */
1225 static attribute_t *parse_attributes(attribute_t *first)
1227 attribute_t **anchor = &first;
1229 while (*anchor != NULL)
1230 anchor = &(*anchor)->next;
1232 attribute_t *attribute;
1233 switch (token.kind) {
1234 case T___attribute__:
1235 attribute = parse_attribute_gnu();
1236 if (attribute == NULL)
1241 attribute = parse_attribute_asm();
1245 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1250 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1254 case T__forceinline:
1255 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1256 eat(T__forceinline);
1260 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1265 /* TODO record modifier */
1266 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1267 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1275 *anchor = attribute;
1276 anchor = &attribute->next;
1280 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1282 static entity_t *determine_lhs_ent(expression_t *const expr,
1285 switch (expr->kind) {
1286 case EXPR_REFERENCE: {
1287 entity_t *const entity = expr->reference.entity;
1288 /* we should only find variables as lvalues... */
1289 if (entity->base.kind != ENTITY_VARIABLE
1290 && entity->base.kind != ENTITY_PARAMETER)
1296 case EXPR_ARRAY_ACCESS: {
1297 expression_t *const ref = expr->array_access.array_ref;
1298 entity_t * ent = NULL;
1299 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1300 ent = determine_lhs_ent(ref, lhs_ent);
1303 mark_vars_read(ref, lhs_ent);
1305 mark_vars_read(expr->array_access.index, lhs_ent);
1310 mark_vars_read(expr->select.compound, lhs_ent);
1311 if (is_type_compound(skip_typeref(expr->base.type)))
1312 return determine_lhs_ent(expr->select.compound, lhs_ent);
1316 case EXPR_UNARY_DEREFERENCE: {
1317 expression_t *const val = expr->unary.value;
1318 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1320 return determine_lhs_ent(val->unary.value, lhs_ent);
1322 mark_vars_read(val, NULL);
1328 mark_vars_read(expr, NULL);
1333 #define ENT_ANY ((entity_t*)-1)
1336 * Mark declarations, which are read. This is used to detect variables, which
1340 * x is not marked as "read", because it is only read to calculate its own new
1344 * x and y are not detected as "not read", because multiple variables are
1347 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1349 switch (expr->kind) {
1350 case EXPR_REFERENCE: {
1351 entity_t *const entity = expr->reference.entity;
1352 if (entity->kind != ENTITY_VARIABLE
1353 && entity->kind != ENTITY_PARAMETER)
1356 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1357 entity->variable.read = true;
1363 // TODO respect pure/const
1364 mark_vars_read(expr->call.function, NULL);
1365 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1366 mark_vars_read(arg->expression, NULL);
1370 case EXPR_CONDITIONAL:
1371 // TODO lhs_decl should depend on whether true/false have an effect
1372 mark_vars_read(expr->conditional.condition, NULL);
1373 if (expr->conditional.true_expression != NULL)
1374 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1375 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1379 if (lhs_ent == ENT_ANY
1380 && !is_type_compound(skip_typeref(expr->base.type)))
1382 mark_vars_read(expr->select.compound, lhs_ent);
1385 case EXPR_ARRAY_ACCESS: {
1386 mark_vars_read(expr->array_access.index, lhs_ent);
1387 expression_t *const ref = expr->array_access.array_ref;
1388 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1389 if (lhs_ent == ENT_ANY)
1392 mark_vars_read(ref, lhs_ent);
1397 mark_vars_read(expr->va_arge.ap, lhs_ent);
1401 mark_vars_read(expr->va_copye.src, lhs_ent);
1404 case EXPR_UNARY_CAST:
1405 /* Special case: Use void cast to mark a variable as "read" */
1406 if (is_type_void(skip_typeref(expr->base.type)))
1411 case EXPR_UNARY_THROW:
1412 if (expr->unary.value == NULL)
1415 case EXPR_UNARY_DEREFERENCE:
1416 case EXPR_UNARY_DELETE:
1417 case EXPR_UNARY_DELETE_ARRAY:
1418 if (lhs_ent == ENT_ANY)
1422 case EXPR_UNARY_NEGATE:
1423 case EXPR_UNARY_PLUS:
1424 case EXPR_UNARY_BITWISE_NEGATE:
1425 case EXPR_UNARY_NOT:
1426 case EXPR_UNARY_TAKE_ADDRESS:
1427 case EXPR_UNARY_POSTFIX_INCREMENT:
1428 case EXPR_UNARY_POSTFIX_DECREMENT:
1429 case EXPR_UNARY_PREFIX_INCREMENT:
1430 case EXPR_UNARY_PREFIX_DECREMENT:
1431 case EXPR_UNARY_ASSUME:
1433 mark_vars_read(expr->unary.value, lhs_ent);
1436 case EXPR_BINARY_ADD:
1437 case EXPR_BINARY_SUB:
1438 case EXPR_BINARY_MUL:
1439 case EXPR_BINARY_DIV:
1440 case EXPR_BINARY_MOD:
1441 case EXPR_BINARY_EQUAL:
1442 case EXPR_BINARY_NOTEQUAL:
1443 case EXPR_BINARY_LESS:
1444 case EXPR_BINARY_LESSEQUAL:
1445 case EXPR_BINARY_GREATER:
1446 case EXPR_BINARY_GREATEREQUAL:
1447 case EXPR_BINARY_BITWISE_AND:
1448 case EXPR_BINARY_BITWISE_OR:
1449 case EXPR_BINARY_BITWISE_XOR:
1450 case EXPR_BINARY_LOGICAL_AND:
1451 case EXPR_BINARY_LOGICAL_OR:
1452 case EXPR_BINARY_SHIFTLEFT:
1453 case EXPR_BINARY_SHIFTRIGHT:
1454 case EXPR_BINARY_COMMA:
1455 case EXPR_BINARY_ISGREATER:
1456 case EXPR_BINARY_ISGREATEREQUAL:
1457 case EXPR_BINARY_ISLESS:
1458 case EXPR_BINARY_ISLESSEQUAL:
1459 case EXPR_BINARY_ISLESSGREATER:
1460 case EXPR_BINARY_ISUNORDERED:
1461 mark_vars_read(expr->binary.left, lhs_ent);
1462 mark_vars_read(expr->binary.right, lhs_ent);
1465 case EXPR_BINARY_ASSIGN:
1466 case EXPR_BINARY_MUL_ASSIGN:
1467 case EXPR_BINARY_DIV_ASSIGN:
1468 case EXPR_BINARY_MOD_ASSIGN:
1469 case EXPR_BINARY_ADD_ASSIGN:
1470 case EXPR_BINARY_SUB_ASSIGN:
1471 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1472 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1473 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1474 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1475 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1476 if (lhs_ent == ENT_ANY)
1478 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1479 mark_vars_read(expr->binary.right, lhs_ent);
1484 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1487 case EXPR_LITERAL_CASES:
1488 case EXPR_LITERAL_CHARACTER:
1490 case EXPR_STRING_LITERAL:
1491 case EXPR_COMPOUND_LITERAL: // TODO init?
1493 case EXPR_CLASSIFY_TYPE:
1496 case EXPR_BUILTIN_CONSTANT_P:
1497 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1499 case EXPR_STATEMENT: // TODO
1500 case EXPR_LABEL_ADDRESS:
1501 case EXPR_ENUM_CONSTANT:
1505 panic("unhandled expression");
1508 static designator_t *parse_designation(void)
1510 designator_t *result = NULL;
1511 designator_t **anchor = &result;
1514 designator_t *designator;
1515 switch (token.kind) {
1517 designator = allocate_ast_zero(sizeof(designator[0]));
1518 designator->source_position = *HERE;
1520 add_anchor_token(']');
1521 designator->array_index = parse_constant_expression();
1522 rem_anchor_token(']');
1526 designator = allocate_ast_zero(sizeof(designator[0]));
1527 designator->source_position = *HERE;
1529 designator->symbol = expect_identifier("while parsing designator", NULL);
1530 if (!designator->symbol)
1538 assert(designator != NULL);
1539 *anchor = designator;
1540 anchor = &designator->next;
1545 * Build an initializer from a given expression.
1547 static initializer_t *initializer_from_expression(type_t *orig_type,
1548 expression_t *expression)
1550 /* TODO check that expression is a constant expression */
1552 type_t *const type = skip_typeref(orig_type);
1554 /* §6.7.8.14/15 char array may be initialized by string literals */
1555 if (expression->kind == EXPR_STRING_LITERAL && is_type_array(type)) {
1556 array_type_t *const array_type = &type->array;
1557 type_t *const element_type = skip_typeref(array_type->element_type);
1558 switch (expression->string_literal.value.encoding) {
1559 case STRING_ENCODING_CHAR: {
1560 if (is_type_atomic(element_type, ATOMIC_TYPE_CHAR) ||
1561 is_type_atomic(element_type, ATOMIC_TYPE_SCHAR) ||
1562 is_type_atomic(element_type, ATOMIC_TYPE_UCHAR)) {
1563 goto make_string_init;
1568 case STRING_ENCODING_WIDE: {
1569 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1570 if (get_unqualified_type(element_type) == bare_wchar_type) {
1572 initializer_t *const init = allocate_initializer_zero(INITIALIZER_STRING);
1573 init->value.value = expression;
1581 assign_error_t error = semantic_assign(type, expression);
1582 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1584 report_assign_error(error, type, expression, "initializer",
1585 &expression->base.source_position);
1587 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1588 result->value.value = create_implicit_cast(expression, type);
1594 * Parses an scalar initializer.
1596 * §6.7.8.11; eat {} without warning
1598 static initializer_t *parse_scalar_initializer(type_t *type,
1599 bool must_be_constant)
1601 /* there might be extra {} hierarchies */
1603 if (token.kind == '{') {
1604 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1608 } while (token.kind == '{');
1611 expression_t *expression = parse_assignment_expression();
1612 mark_vars_read(expression, NULL);
1613 if (must_be_constant && !is_linker_constant(expression)) {
1614 errorf(&expression->base.source_position,
1615 "initialisation expression '%E' is not constant",
1619 initializer_t *initializer = initializer_from_expression(type, expression);
1621 if (initializer == NULL) {
1622 errorf(&expression->base.source_position,
1623 "expression '%E' (type '%T') doesn't match expected type '%T'",
1624 expression, expression->base.type, type);
1629 bool additional_warning_displayed = false;
1630 while (braces > 0) {
1632 if (token.kind != '}') {
1633 if (!additional_warning_displayed) {
1634 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1635 additional_warning_displayed = true;
1646 * An entry in the type path.
1648 typedef struct type_path_entry_t type_path_entry_t;
1649 struct type_path_entry_t {
1650 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1652 size_t index; /**< For array types: the current index. */
1653 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1658 * A type path expression a position inside compound or array types.
1660 typedef struct type_path_t type_path_t;
1661 struct type_path_t {
1662 type_path_entry_t *path; /**< An flexible array containing the current path. */
1663 type_t *top_type; /**< type of the element the path points */
1664 size_t max_index; /**< largest index in outermost array */
1668 * Prints a type path for debugging.
1670 static __attribute__((unused)) void debug_print_type_path(
1671 const type_path_t *path)
1673 size_t len = ARR_LEN(path->path);
1675 for (size_t i = 0; i < len; ++i) {
1676 const type_path_entry_t *entry = & path->path[i];
1678 type_t *type = skip_typeref(entry->type);
1679 if (is_type_compound(type)) {
1680 /* in gcc mode structs can have no members */
1681 if (entry->v.compound_entry == NULL) {
1685 fprintf(stderr, ".%s",
1686 entry->v.compound_entry->base.symbol->string);
1687 } else if (is_type_array(type)) {
1688 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1690 fprintf(stderr, "-INVALID-");
1693 if (path->top_type != NULL) {
1694 fprintf(stderr, " (");
1695 print_type(path->top_type);
1696 fprintf(stderr, ")");
1701 * Return the top type path entry, ie. in a path
1702 * (type).a.b returns the b.
1704 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1706 size_t len = ARR_LEN(path->path);
1708 return &path->path[len-1];
1712 * Enlarge the type path by an (empty) element.
1714 static type_path_entry_t *append_to_type_path(type_path_t *path)
1716 size_t len = ARR_LEN(path->path);
1717 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1719 type_path_entry_t *result = & path->path[len];
1720 memset(result, 0, sizeof(result[0]));
1725 * Descending into a sub-type. Enter the scope of the current top_type.
1727 static void descend_into_subtype(type_path_t *path)
1729 type_t *orig_top_type = path->top_type;
1730 type_t *top_type = skip_typeref(orig_top_type);
1732 type_path_entry_t *top = append_to_type_path(path);
1733 top->type = top_type;
1735 if (is_type_compound(top_type)) {
1736 compound_t *const compound = top_type->compound.compound;
1737 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1739 if (entry != NULL) {
1740 top->v.compound_entry = &entry->declaration;
1741 path->top_type = entry->declaration.type;
1743 path->top_type = NULL;
1745 } else if (is_type_array(top_type)) {
1747 path->top_type = top_type->array.element_type;
1749 assert(!is_type_valid(top_type));
1754 * Pop an entry from the given type path, ie. returning from
1755 * (type).a.b to (type).a
1757 static void ascend_from_subtype(type_path_t *path)
1759 type_path_entry_t *top = get_type_path_top(path);
1761 path->top_type = top->type;
1763 size_t len = ARR_LEN(path->path);
1764 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1768 * Pop entries from the given type path until the given
1769 * path level is reached.
1771 static void ascend_to(type_path_t *path, size_t top_path_level)
1773 size_t len = ARR_LEN(path->path);
1775 while (len > top_path_level) {
1776 ascend_from_subtype(path);
1777 len = ARR_LEN(path->path);
1781 static bool walk_designator(type_path_t *path, const designator_t *designator,
1782 bool used_in_offsetof)
1784 for (; designator != NULL; designator = designator->next) {
1785 type_path_entry_t *top = get_type_path_top(path);
1786 type_t *orig_type = top->type;
1788 type_t *type = skip_typeref(orig_type);
1790 if (designator->symbol != NULL) {
1791 symbol_t *symbol = designator->symbol;
1792 if (!is_type_compound(type)) {
1793 if (is_type_valid(type)) {
1794 errorf(&designator->source_position,
1795 "'.%Y' designator used for non-compound type '%T'",
1799 top->type = type_error_type;
1800 top->v.compound_entry = NULL;
1801 orig_type = type_error_type;
1803 compound_t *compound = type->compound.compound;
1804 entity_t *iter = compound->members.entities;
1805 for (; iter != NULL; iter = iter->base.next) {
1806 if (iter->base.symbol == symbol) {
1811 errorf(&designator->source_position,
1812 "'%T' has no member named '%Y'", orig_type, symbol);
1815 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1816 if (used_in_offsetof && iter->compound_member.bitfield) {
1817 errorf(&designator->source_position,
1818 "offsetof designator '%Y' must not specify bitfield",
1823 top->type = orig_type;
1824 top->v.compound_entry = &iter->declaration;
1825 orig_type = iter->declaration.type;
1828 expression_t *array_index = designator->array_index;
1829 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1832 if (!is_type_array(type)) {
1833 if (is_type_valid(type)) {
1834 errorf(&designator->source_position,
1835 "[%E] designator used for non-array type '%T'",
1836 array_index, orig_type);
1841 long index = fold_constant_to_int(array_index);
1842 if (!used_in_offsetof) {
1844 errorf(&designator->source_position,
1845 "array index [%E] must be positive", array_index);
1846 } else if (type->array.size_constant) {
1847 long array_size = type->array.size;
1848 if (index >= array_size) {
1849 errorf(&designator->source_position,
1850 "designator [%E] (%d) exceeds array size %d",
1851 array_index, index, array_size);
1856 top->type = orig_type;
1857 top->v.index = (size_t) index;
1858 orig_type = type->array.element_type;
1860 path->top_type = orig_type;
1862 if (designator->next != NULL) {
1863 descend_into_subtype(path);
1869 static void advance_current_object(type_path_t *path, size_t top_path_level)
1871 type_path_entry_t *top = get_type_path_top(path);
1873 type_t *type = skip_typeref(top->type);
1874 if (is_type_union(type)) {
1875 /* in unions only the first element is initialized */
1876 top->v.compound_entry = NULL;
1877 } else if (is_type_struct(type)) {
1878 declaration_t *entry = top->v.compound_entry;
1880 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1881 if (next_entity != NULL) {
1882 assert(is_declaration(next_entity));
1883 entry = &next_entity->declaration;
1888 top->v.compound_entry = entry;
1889 if (entry != NULL) {
1890 path->top_type = entry->type;
1893 } else if (is_type_array(type)) {
1894 assert(is_type_array(type));
1898 if (!type->array.size_constant || top->v.index < type->array.size) {
1902 assert(!is_type_valid(type));
1906 /* we're past the last member of the current sub-aggregate, try if we
1907 * can ascend in the type hierarchy and continue with another subobject */
1908 size_t len = ARR_LEN(path->path);
1910 if (len > top_path_level) {
1911 ascend_from_subtype(path);
1912 advance_current_object(path, top_path_level);
1914 path->top_type = NULL;
1919 * skip any {...} blocks until a closing bracket is reached.
1921 static void skip_initializers(void)
1925 while (token.kind != '}') {
1926 if (token.kind == T_EOF)
1928 if (token.kind == '{') {
1936 static initializer_t *create_empty_initializer(void)
1938 static initializer_t empty_initializer
1939 = { .list = { { INITIALIZER_LIST }, 0 } };
1940 return &empty_initializer;
1944 * Parse a part of an initialiser for a struct or union,
1946 static initializer_t *parse_sub_initializer(type_path_t *path,
1947 type_t *outer_type, size_t top_path_level,
1948 parse_initializer_env_t *env)
1950 if (token.kind == '}') {
1951 /* empty initializer */
1952 return create_empty_initializer();
1955 type_t *orig_type = path->top_type;
1956 type_t *type = NULL;
1958 if (orig_type == NULL) {
1959 /* We are initializing an empty compound. */
1961 type = skip_typeref(orig_type);
1964 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1967 designator_t *designator = NULL;
1968 if (token.kind == '.' || token.kind == '[') {
1969 designator = parse_designation();
1970 goto finish_designator;
1971 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1972 /* GNU-style designator ("identifier: value") */
1973 designator = allocate_ast_zero(sizeof(designator[0]));
1974 designator->source_position = *HERE;
1975 designator->symbol = token.base.symbol;
1980 /* reset path to toplevel, evaluate designator from there */
1981 ascend_to(path, top_path_level);
1982 if (!walk_designator(path, designator, false)) {
1983 /* can't continue after designation error */
1987 initializer_t *designator_initializer
1988 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1989 designator_initializer->designator.designator = designator;
1990 ARR_APP1(initializer_t*, initializers, designator_initializer);
1992 orig_type = path->top_type;
1993 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
1998 if (token.kind == '{') {
1999 if (type != NULL && is_type_scalar(type)) {
2000 sub = parse_scalar_initializer(type, env->must_be_constant);
2003 if (env->entity != NULL) {
2004 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2006 errorf(HERE, "extra brace group at end of initializer");
2011 descend_into_subtype(path);
2014 add_anchor_token('}');
2015 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2017 rem_anchor_token('}');
2022 goto error_parse_next;
2024 ascend_from_subtype(path);
2027 /* must be an expression */
2028 expression_t *expression = parse_assignment_expression();
2029 mark_vars_read(expression, NULL);
2031 if (env->must_be_constant && !is_linker_constant(expression)) {
2032 errorf(&expression->base.source_position,
2033 "Initialisation expression '%E' is not constant",
2038 /* we are already outside, ... */
2039 if (outer_type == NULL)
2040 goto error_parse_next;
2041 type_t *const outer_type_skip = skip_typeref(outer_type);
2042 if (is_type_compound(outer_type_skip) &&
2043 !outer_type_skip->compound.compound->complete) {
2044 goto error_parse_next;
2047 source_position_t const* const pos = &expression->base.source_position;
2048 if (env->entity != NULL) {
2049 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2051 warningf(WARN_OTHER, pos, "excess elements in initializer");
2053 goto error_parse_next;
2056 /* handle { "string" } special case */
2057 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2058 sub = initializer_from_expression(outer_type, expression);
2061 if (token.kind != '}') {
2062 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2064 /* TODO: eat , ... */
2069 /* descend into subtypes until expression matches type */
2071 orig_type = path->top_type;
2072 type = skip_typeref(orig_type);
2074 sub = initializer_from_expression(orig_type, expression);
2078 if (!is_type_valid(type)) {
2081 if (is_type_scalar(type)) {
2082 errorf(&expression->base.source_position,
2083 "expression '%E' doesn't match expected type '%T'",
2084 expression, orig_type);
2088 descend_into_subtype(path);
2092 /* update largest index of top array */
2093 const type_path_entry_t *first = &path->path[0];
2094 type_t *first_type = first->type;
2095 first_type = skip_typeref(first_type);
2096 if (is_type_array(first_type)) {
2097 size_t index = first->v.index;
2098 if (index > path->max_index)
2099 path->max_index = index;
2102 /* append to initializers list */
2103 ARR_APP1(initializer_t*, initializers, sub);
2106 if (token.kind == '}') {
2109 add_anchor_token('}');
2111 rem_anchor_token('}');
2112 if (token.kind == '}') {
2117 /* advance to the next declaration if we are not at the end */
2118 advance_current_object(path, top_path_level);
2119 orig_type = path->top_type;
2120 if (orig_type != NULL)
2121 type = skip_typeref(orig_type);
2127 size_t len = ARR_LEN(initializers);
2128 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2129 initializer_t *result = allocate_ast_zero(size);
2130 result->kind = INITIALIZER_LIST;
2131 result->list.len = len;
2132 memcpy(&result->list.initializers, initializers,
2133 len * sizeof(initializers[0]));
2135 DEL_ARR_F(initializers);
2136 ascend_to(path, top_path_level+1);
2141 skip_initializers();
2142 DEL_ARR_F(initializers);
2143 ascend_to(path, top_path_level+1);
2147 static expression_t *make_size_literal(size_t value)
2149 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2150 literal->base.type = type_size_t;
2153 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2154 literal->literal.value = make_string(buf);
2160 * Parses an initializer. Parsers either a compound literal
2161 * (env->declaration == NULL) or an initializer of a declaration.
2163 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2165 type_t *type = skip_typeref(env->type);
2166 size_t max_index = 0;
2167 initializer_t *result;
2169 if (is_type_scalar(type)) {
2170 result = parse_scalar_initializer(type, env->must_be_constant);
2171 } else if (token.kind == '{') {
2175 memset(&path, 0, sizeof(path));
2176 path.top_type = env->type;
2177 path.path = NEW_ARR_F(type_path_entry_t, 0);
2179 descend_into_subtype(&path);
2181 add_anchor_token('}');
2182 result = parse_sub_initializer(&path, env->type, 1, env);
2183 rem_anchor_token('}');
2185 max_index = path.max_index;
2186 DEL_ARR_F(path.path);
2190 /* parse_scalar_initializer() also works in this case: we simply
2191 * have an expression without {} around it */
2192 result = parse_scalar_initializer(type, env->must_be_constant);
2195 /* §6.7.8:22 array initializers for arrays with unknown size determine
2196 * the array type size */
2197 if (is_type_array(type) && type->array.size_expression == NULL
2198 && result != NULL) {
2200 switch (result->kind) {
2201 case INITIALIZER_LIST:
2202 assert(max_index != 0xdeadbeaf);
2203 size = max_index + 1;
2206 case INITIALIZER_STRING: {
2207 size = get_string_len(&get_init_string(result)->value) + 1;
2211 case INITIALIZER_DESIGNATOR:
2212 case INITIALIZER_VALUE:
2213 /* can happen for parse errors */
2218 internal_errorf(HERE, "invalid initializer type");
2221 type_t *new_type = duplicate_type(type);
2223 new_type->array.size_expression = make_size_literal(size);
2224 new_type->array.size_constant = true;
2225 new_type->array.has_implicit_size = true;
2226 new_type->array.size = size;
2227 env->type = new_type;
2233 static void append_entity(scope_t *scope, entity_t *entity)
2235 if (scope->last_entity != NULL) {
2236 scope->last_entity->base.next = entity;
2238 scope->entities = entity;
2240 entity->base.parent_entity = current_entity;
2241 scope->last_entity = entity;
2245 static compound_t *parse_compound_type_specifier(bool is_struct)
2247 source_position_t const pos = *HERE;
2248 eat(is_struct ? T_struct : T_union);
2250 symbol_t *symbol = NULL;
2251 entity_t *entity = NULL;
2252 attribute_t *attributes = NULL;
2254 if (token.kind == T___attribute__) {
2255 attributes = parse_attributes(NULL);
2258 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2259 if (token.kind == T_IDENTIFIER) {
2260 /* the compound has a name, check if we have seen it already */
2261 symbol = token.base.symbol;
2262 entity = get_tag(symbol, kind);
2265 if (entity != NULL) {
2266 if (entity->base.parent_scope != current_scope &&
2267 (token.kind == '{' || token.kind == ';')) {
2268 /* we're in an inner scope and have a definition. Shadow
2269 * existing definition in outer scope */
2271 } else if (entity->compound.complete && token.kind == '{') {
2272 source_position_t const *const ppos = &entity->base.source_position;
2273 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2274 /* clear members in the hope to avoid further errors */
2275 entity->compound.members.entities = NULL;
2278 } else if (token.kind != '{') {
2279 char const *const msg =
2280 is_struct ? "while parsing struct type specifier" :
2281 "while parsing union type specifier";
2282 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2287 if (entity == NULL) {
2288 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2289 entity->compound.alignment = 1;
2290 entity->base.parent_scope = current_scope;
2291 if (symbol != NULL) {
2292 environment_push(entity);
2294 append_entity(current_scope, entity);
2297 if (token.kind == '{') {
2298 parse_compound_type_entries(&entity->compound);
2300 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2301 if (symbol == NULL) {
2302 assert(anonymous_entity == NULL);
2303 anonymous_entity = entity;
2307 if (attributes != NULL) {
2308 handle_entity_attributes(attributes, entity);
2311 return &entity->compound;
2314 static void parse_enum_entries(type_t *const enum_type)
2318 if (token.kind == '}') {
2319 errorf(HERE, "empty enum not allowed");
2324 add_anchor_token('}');
2325 add_anchor_token(',');
2327 add_anchor_token('=');
2328 source_position_t pos;
2329 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2330 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2331 entity->enum_value.enum_type = enum_type;
2332 rem_anchor_token('=');
2335 expression_t *value = parse_constant_expression();
2337 value = create_implicit_cast(value, enum_type);
2338 entity->enum_value.value = value;
2343 record_entity(entity, false);
2344 } while (next_if(',') && token.kind != '}');
2345 rem_anchor_token(',');
2346 rem_anchor_token('}');
2351 static type_t *parse_enum_specifier(void)
2353 source_position_t const pos = *HERE;
2358 switch (token.kind) {
2360 symbol = token.base.symbol;
2361 entity = get_tag(symbol, ENTITY_ENUM);
2364 if (entity != NULL) {
2365 if (entity->base.parent_scope != current_scope &&
2366 (token.kind == '{' || token.kind == ';')) {
2367 /* we're in an inner scope and have a definition. Shadow
2368 * existing definition in outer scope */
2370 } else if (entity->enume.complete && token.kind == '{') {
2371 source_position_t const *const ppos = &entity->base.source_position;
2372 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2383 parse_error_expected("while parsing enum type specifier",
2384 T_IDENTIFIER, '{', NULL);
2388 if (entity == NULL) {
2389 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2390 entity->base.parent_scope = current_scope;
2393 type_t *const type = allocate_type_zero(TYPE_ENUM);
2394 type->enumt.enume = &entity->enume;
2395 type->enumt.base.akind = ATOMIC_TYPE_INT;
2397 if (token.kind == '{') {
2398 if (symbol != NULL) {
2399 environment_push(entity);
2401 append_entity(current_scope, entity);
2402 entity->enume.complete = true;
2404 parse_enum_entries(type);
2405 parse_attributes(NULL);
2407 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2408 if (symbol == NULL) {
2409 assert(anonymous_entity == NULL);
2410 anonymous_entity = entity;
2412 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2413 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2420 * if a symbol is a typedef to another type, return true
2422 static bool is_typedef_symbol(symbol_t *symbol)
2424 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2425 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2428 static type_t *parse_typeof(void)
2434 add_anchor_token(')');
2437 expression_t *expression = NULL;
2439 switch (token.kind) {
2441 if (is_typedef_symbol(token.base.symbol)) {
2443 type = parse_typename();
2446 expression = parse_expression();
2447 type = revert_automatic_type_conversion(expression);
2452 rem_anchor_token(')');
2455 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2456 typeof_type->typeoft.expression = expression;
2457 typeof_type->typeoft.typeof_type = type;
2462 typedef enum specifiers_t {
2464 SPECIFIER_SIGNED = 1 << 0,
2465 SPECIFIER_UNSIGNED = 1 << 1,
2466 SPECIFIER_LONG = 1 << 2,
2467 SPECIFIER_INT = 1 << 3,
2468 SPECIFIER_DOUBLE = 1 << 4,
2469 SPECIFIER_CHAR = 1 << 5,
2470 SPECIFIER_WCHAR_T = 1 << 6,
2471 SPECIFIER_SHORT = 1 << 7,
2472 SPECIFIER_LONG_LONG = 1 << 8,
2473 SPECIFIER_FLOAT = 1 << 9,
2474 SPECIFIER_BOOL = 1 << 10,
2475 SPECIFIER_VOID = 1 << 11,
2476 SPECIFIER_INT8 = 1 << 12,
2477 SPECIFIER_INT16 = 1 << 13,
2478 SPECIFIER_INT32 = 1 << 14,
2479 SPECIFIER_INT64 = 1 << 15,
2480 SPECIFIER_INT128 = 1 << 16,
2481 SPECIFIER_COMPLEX = 1 << 17,
2482 SPECIFIER_IMAGINARY = 1 << 18,
2485 static type_t *get_typedef_type(symbol_t *symbol)
2487 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2488 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2491 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2492 type->typedeft.typedefe = &entity->typedefe;
2497 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2499 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2501 add_anchor_token(')');
2502 add_anchor_token(',');
2506 add_anchor_token('=');
2507 source_position_t pos;
2508 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2509 rem_anchor_token('=');
2511 symbol_t **prop = NULL;
2513 if (streq(prop_sym->string, "put")) {
2514 prop = &property->put_symbol;
2515 } else if (streq(prop_sym->string, "get")) {
2516 prop = &property->get_symbol;
2518 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2522 add_anchor_token(T_IDENTIFIER);
2524 rem_anchor_token(T_IDENTIFIER);
2526 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2528 *prop = sym ? sym : sym_anonymous;
2529 } while (next_if(','));
2530 rem_anchor_token(',');
2531 rem_anchor_token(')');
2533 attribute->a.property = property;
2539 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2541 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2542 if (next_if(T_restrict)) {
2543 kind = ATTRIBUTE_MS_RESTRICT;
2544 } else if (token.kind == T_IDENTIFIER) {
2545 char const *const name = token.base.symbol->string;
2546 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2548 const char *attribute_name = get_attribute_name(k);
2549 if (attribute_name != NULL && streq(attribute_name, name)) {
2555 if (kind == ATTRIBUTE_UNKNOWN) {
2556 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2559 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2563 attribute_t *attribute = allocate_attribute_zero(kind);
2566 if (kind == ATTRIBUTE_MS_PROPERTY) {
2567 return parse_attribute_ms_property(attribute);
2570 /* parse arguments */
2572 attribute->a.arguments = parse_attribute_arguments();
2577 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2581 add_anchor_token(')');
2583 if (token.kind != ')') {
2584 attribute_t **anchor = &first;
2586 while (*anchor != NULL)
2587 anchor = &(*anchor)->next;
2589 attribute_t *attribute
2590 = parse_microsoft_extended_decl_modifier_single();
2591 if (attribute == NULL)
2594 *anchor = attribute;
2595 anchor = &attribute->next;
2596 } while (next_if(','));
2598 rem_anchor_token(')');
2603 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2605 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2606 if (is_declaration(entity)) {
2607 entity->declaration.type = type_error_type;
2608 entity->declaration.implicit = true;
2609 } else if (kind == ENTITY_TYPEDEF) {
2610 entity->typedefe.type = type_error_type;
2611 entity->typedefe.builtin = true;
2613 if (kind != ENTITY_COMPOUND_MEMBER)
2614 record_entity(entity, false);
2618 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2620 type_t *type = NULL;
2621 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2622 unsigned type_specifiers = 0;
2623 bool newtype = false;
2624 bool saw_error = false;
2626 memset(specifiers, 0, sizeof(*specifiers));
2627 specifiers->source_position = *HERE;
2630 specifiers->attributes = parse_attributes(specifiers->attributes);
2632 switch (token.kind) {
2634 #define MATCH_STORAGE_CLASS(token, class) \
2636 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2637 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2639 specifiers->storage_class = class; \
2640 if (specifiers->thread_local) \
2641 goto check_thread_storage_class; \
2645 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2646 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2647 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2648 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2649 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2652 specifiers->attributes
2653 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2657 if (specifiers->thread_local) {
2658 errorf(HERE, "duplicate '__thread'");
2660 specifiers->thread_local = true;
2661 check_thread_storage_class:
2662 switch (specifiers->storage_class) {
2663 case STORAGE_CLASS_EXTERN:
2664 case STORAGE_CLASS_NONE:
2665 case STORAGE_CLASS_STATIC:
2669 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2670 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2671 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2672 wrong_thread_storage_class:
2673 errorf(HERE, "'__thread' used with '%s'", wrong);
2680 /* type qualifiers */
2681 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2683 qualifiers |= qualifier; \
2687 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2688 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2689 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2690 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2691 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2692 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2693 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2694 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2696 /* type specifiers */
2697 #define MATCH_SPECIFIER(token, specifier, name) \
2699 if (type_specifiers & specifier) { \
2700 errorf(HERE, "multiple " name " type specifiers given"); \
2702 type_specifiers |= specifier; \
2707 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2708 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2709 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2710 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2711 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2712 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2713 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2714 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2715 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2716 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2717 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2718 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2719 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2720 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2721 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2722 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2723 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2724 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2728 specifiers->is_inline = true;
2732 case T__forceinline:
2733 eat(T__forceinline);
2734 specifiers->modifiers |= DM_FORCEINLINE;
2739 if (type_specifiers & SPECIFIER_LONG_LONG) {
2740 errorf(HERE, "too many long type specifiers given");
2741 } else if (type_specifiers & SPECIFIER_LONG) {
2742 type_specifiers |= SPECIFIER_LONG_LONG;
2744 type_specifiers |= SPECIFIER_LONG;
2749 #define CHECK_DOUBLE_TYPE() \
2750 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2753 CHECK_DOUBLE_TYPE();
2754 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2756 type->compound.compound = parse_compound_type_specifier(true);
2759 CHECK_DOUBLE_TYPE();
2760 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2761 type->compound.compound = parse_compound_type_specifier(false);
2764 CHECK_DOUBLE_TYPE();
2765 type = parse_enum_specifier();
2768 CHECK_DOUBLE_TYPE();
2769 type = parse_typeof();
2771 case T___builtin_va_list:
2772 CHECK_DOUBLE_TYPE();
2773 type = duplicate_type(type_valist);
2774 eat(T___builtin_va_list);
2777 case T_IDENTIFIER: {
2778 /* only parse identifier if we haven't found a type yet */
2779 if (type != NULL || type_specifiers != 0) {
2780 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2781 * declaration, so it doesn't generate errors about expecting '(' or
2783 switch (look_ahead(1)->kind) {
2790 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2794 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2799 goto finish_specifiers;
2803 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2804 if (typedef_type == NULL) {
2805 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2806 * declaration, so it doesn't generate 'implicit int' followed by more
2807 * errors later on. */
2808 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2814 errorf(HERE, "%K does not name a type", &token);
2816 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2818 type = allocate_type_zero(TYPE_TYPEDEF);
2819 type->typedeft.typedefe = &entity->typedefe;
2827 goto finish_specifiers;
2832 type = typedef_type;
2836 /* function specifier */
2838 goto finish_specifiers;
2843 specifiers->attributes = parse_attributes(specifiers->attributes);
2845 if (type == NULL || (saw_error && type_specifiers != 0)) {
2846 atomic_type_kind_t atomic_type;
2848 /* match valid basic types */
2849 switch (type_specifiers) {
2850 case SPECIFIER_VOID:
2851 atomic_type = ATOMIC_TYPE_VOID;
2853 case SPECIFIER_WCHAR_T:
2854 atomic_type = ATOMIC_TYPE_WCHAR_T;
2856 case SPECIFIER_CHAR:
2857 atomic_type = ATOMIC_TYPE_CHAR;
2859 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2860 atomic_type = ATOMIC_TYPE_SCHAR;
2862 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2863 atomic_type = ATOMIC_TYPE_UCHAR;
2865 case SPECIFIER_SHORT:
2866 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2867 case SPECIFIER_SHORT | SPECIFIER_INT:
2868 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2869 atomic_type = ATOMIC_TYPE_SHORT;
2871 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2872 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2873 atomic_type = ATOMIC_TYPE_USHORT;
2876 case SPECIFIER_SIGNED:
2877 case SPECIFIER_SIGNED | SPECIFIER_INT:
2878 atomic_type = ATOMIC_TYPE_INT;
2880 case SPECIFIER_UNSIGNED:
2881 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2882 atomic_type = ATOMIC_TYPE_UINT;
2884 case SPECIFIER_LONG:
2885 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2886 case SPECIFIER_LONG | SPECIFIER_INT:
2887 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2888 atomic_type = ATOMIC_TYPE_LONG;
2890 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2891 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2892 atomic_type = ATOMIC_TYPE_ULONG;
2895 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2896 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2897 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2898 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2900 atomic_type = ATOMIC_TYPE_LONGLONG;
2901 goto warn_about_long_long;
2903 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2904 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2906 atomic_type = ATOMIC_TYPE_ULONGLONG;
2907 warn_about_long_long:
2908 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2911 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2912 atomic_type = unsigned_int8_type_kind;
2915 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2916 atomic_type = unsigned_int16_type_kind;
2919 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2920 atomic_type = unsigned_int32_type_kind;
2923 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2924 atomic_type = unsigned_int64_type_kind;
2927 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2928 atomic_type = unsigned_int128_type_kind;
2931 case SPECIFIER_INT8:
2932 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2933 atomic_type = int8_type_kind;
2936 case SPECIFIER_INT16:
2937 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2938 atomic_type = int16_type_kind;
2941 case SPECIFIER_INT32:
2942 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2943 atomic_type = int32_type_kind;
2946 case SPECIFIER_INT64:
2947 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2948 atomic_type = int64_type_kind;
2951 case SPECIFIER_INT128:
2952 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2953 atomic_type = int128_type_kind;
2956 case SPECIFIER_FLOAT:
2957 atomic_type = ATOMIC_TYPE_FLOAT;
2959 case SPECIFIER_DOUBLE:
2960 atomic_type = ATOMIC_TYPE_DOUBLE;
2962 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2963 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2965 case SPECIFIER_BOOL:
2966 atomic_type = ATOMIC_TYPE_BOOL;
2968 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2969 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2970 atomic_type = ATOMIC_TYPE_FLOAT;
2972 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2973 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2974 atomic_type = ATOMIC_TYPE_DOUBLE;
2976 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2977 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2978 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2981 /* invalid specifier combination, give an error message */
2982 source_position_t const* const pos = &specifiers->source_position;
2983 if (type_specifiers == 0) {
2985 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
2986 if (!(c_mode & _CXX) && !strict_mode) {
2987 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
2988 atomic_type = ATOMIC_TYPE_INT;
2991 errorf(pos, "no type specifiers given in declaration");
2994 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
2995 (type_specifiers & SPECIFIER_UNSIGNED)) {
2996 errorf(pos, "signed and unsigned specifiers given");
2997 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2998 errorf(pos, "only integer types can be signed or unsigned");
3000 errorf(pos, "multiple datatypes in declaration");
3002 specifiers->type = type_error_type;
3007 if (type_specifiers & SPECIFIER_COMPLEX) {
3008 type = allocate_type_zero(TYPE_COMPLEX);
3009 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3010 type = allocate_type_zero(TYPE_IMAGINARY);
3012 type = allocate_type_zero(TYPE_ATOMIC);
3014 type->atomic.akind = atomic_type;
3016 } else if (type_specifiers != 0) {
3017 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3020 /* FIXME: check type qualifiers here */
3021 type->base.qualifiers = qualifiers;
3024 type = identify_new_type(type);
3026 type = typehash_insert(type);
3029 if (specifiers->attributes != NULL)
3030 type = handle_type_attributes(specifiers->attributes, type);
3031 specifiers->type = type;
3034 static type_qualifiers_t parse_type_qualifiers(void)
3036 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3039 switch (token.kind) {
3040 /* type qualifiers */
3041 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3042 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3043 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3044 /* microsoft extended type modifiers */
3045 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3046 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3047 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3048 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3049 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3058 * Parses an K&R identifier list
3060 static void parse_identifier_list(scope_t *scope)
3062 assert(token.kind == T_IDENTIFIER);
3064 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3065 /* a K&R parameter has no type, yet */
3069 append_entity(scope, entity);
3070 } while (next_if(',') && token.kind == T_IDENTIFIER);
3073 static entity_t *parse_parameter(void)
3075 declaration_specifiers_t specifiers;
3076 parse_declaration_specifiers(&specifiers);
3078 entity_t *entity = parse_declarator(&specifiers,
3079 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3080 anonymous_entity = NULL;
3084 static void semantic_parameter_incomplete(const entity_t *entity)
3086 assert(entity->kind == ENTITY_PARAMETER);
3088 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3089 * list in a function declarator that is part of a
3090 * definition of that function shall not have
3091 * incomplete type. */
3092 type_t *type = skip_typeref(entity->declaration.type);
3093 if (is_type_incomplete(type)) {
3094 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3098 static bool has_parameters(void)
3100 /* func(void) is not a parameter */
3101 if (look_ahead(1)->kind != ')')
3103 if (token.kind == T_IDENTIFIER) {
3104 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3107 if (entity->kind != ENTITY_TYPEDEF)
3109 type_t const *const type = skip_typeref(entity->typedefe.type);
3110 if (!is_type_void(type))
3112 if (c_mode & _CXX) {
3113 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3114 * is not allowed. */
3115 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3116 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3117 /* §6.7.5.3:10 Qualification is not allowed here. */
3118 errorf(HERE, "'void' as parameter must not have type qualifiers");
3120 } else if (token.kind != T_void) {
3128 * Parses function type parameters (and optionally creates variable_t entities
3129 * for them in a scope)
3131 static void parse_parameters(function_type_t *type, scope_t *scope)
3133 add_anchor_token(')');
3136 if (token.kind == T_IDENTIFIER &&
3137 !is_typedef_symbol(token.base.symbol) &&
3138 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3139 type->kr_style_parameters = true;
3140 parse_identifier_list(scope);
3141 } else if (token.kind == ')') {
3142 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3143 if (!(c_mode & _CXX))
3144 type->unspecified_parameters = true;
3145 } else if (has_parameters()) {
3146 function_parameter_t **anchor = &type->parameters;
3147 add_anchor_token(',');
3149 switch (token.kind) {
3152 type->variadic = true;
3153 goto parameters_finished;
3158 entity_t *entity = parse_parameter();
3159 if (entity->kind == ENTITY_TYPEDEF) {
3160 errorf(&entity->base.source_position,
3161 "typedef not allowed as function parameter");
3164 assert(is_declaration(entity));
3166 semantic_parameter_incomplete(entity);
3168 function_parameter_t *const parameter =
3169 allocate_parameter(entity->declaration.type);
3171 if (scope != NULL) {
3172 append_entity(scope, entity);
3175 *anchor = parameter;
3176 anchor = ¶meter->next;
3181 goto parameters_finished;
3183 } while (next_if(','));
3184 parameters_finished:
3185 rem_anchor_token(',');
3188 rem_anchor_token(')');
3192 typedef enum construct_type_kind_t {
3193 CONSTRUCT_POINTER = 1,
3194 CONSTRUCT_REFERENCE,
3197 } construct_type_kind_t;
3199 typedef union construct_type_t construct_type_t;
3201 typedef struct construct_type_base_t {
3202 construct_type_kind_t kind;
3203 source_position_t pos;
3204 construct_type_t *next;
3205 } construct_type_base_t;
3207 typedef struct parsed_pointer_t {
3208 construct_type_base_t base;
3209 type_qualifiers_t type_qualifiers;
3210 variable_t *base_variable; /**< MS __based extension. */
3213 typedef struct parsed_reference_t {
3214 construct_type_base_t base;
3215 } parsed_reference_t;
3217 typedef struct construct_function_type_t {
3218 construct_type_base_t base;
3219 type_t *function_type;
3220 } construct_function_type_t;
3222 typedef struct parsed_array_t {
3223 construct_type_base_t base;
3224 type_qualifiers_t type_qualifiers;
3230 union construct_type_t {
3231 construct_type_kind_t kind;
3232 construct_type_base_t base;
3233 parsed_pointer_t pointer;
3234 parsed_reference_t reference;
3235 construct_function_type_t function;
3236 parsed_array_t array;
3239 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3241 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3242 memset(cons, 0, size);
3244 cons->base.pos = *HERE;
3249 static construct_type_t *parse_pointer_declarator(void)
3251 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3253 cons->pointer.type_qualifiers = parse_type_qualifiers();
3254 //cons->pointer.base_variable = base_variable;
3259 /* ISO/IEC 14882:1998(E) §8.3.2 */
3260 static construct_type_t *parse_reference_declarator(void)
3262 if (!(c_mode & _CXX))
3263 errorf(HERE, "references are only available for C++");
3265 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3272 static construct_type_t *parse_array_declarator(void)
3274 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3275 parsed_array_t *const array = &cons->array;
3278 add_anchor_token(']');
3280 bool is_static = next_if(T_static);
3282 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3285 is_static = next_if(T_static);
3287 array->type_qualifiers = type_qualifiers;
3288 array->is_static = is_static;
3290 expression_t *size = NULL;
3291 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3292 array->is_variable = true;
3294 } else if (token.kind != ']') {
3295 size = parse_assignment_expression();
3297 /* §6.7.5.2:1 Array size must have integer type */
3298 type_t *const orig_type = size->base.type;
3299 type_t *const type = skip_typeref(orig_type);
3300 if (!is_type_integer(type) && is_type_valid(type)) {
3301 errorf(&size->base.source_position,
3302 "array size '%E' must have integer type but has type '%T'",
3307 mark_vars_read(size, NULL);
3310 if (is_static && size == NULL)
3311 errorf(&array->base.pos, "static array parameters require a size");
3313 rem_anchor_token(']');
3319 static construct_type_t *parse_function_declarator(scope_t *scope)
3321 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3323 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3324 function_type_t *ftype = &type->function;
3326 ftype->linkage = current_linkage;
3327 ftype->calling_convention = CC_DEFAULT;
3329 parse_parameters(ftype, scope);
3331 cons->function.function_type = type;
3336 typedef struct parse_declarator_env_t {
3337 bool may_be_abstract : 1;
3338 bool must_be_abstract : 1;
3339 decl_modifiers_t modifiers;
3341 source_position_t source_position;
3343 attribute_t *attributes;
3344 } parse_declarator_env_t;
3347 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3349 /* construct a single linked list of construct_type_t's which describe
3350 * how to construct the final declarator type */
3351 construct_type_t *first = NULL;
3352 construct_type_t **anchor = &first;
3354 env->attributes = parse_attributes(env->attributes);
3357 construct_type_t *type;
3358 //variable_t *based = NULL; /* MS __based extension */
3359 switch (token.kind) {
3361 type = parse_reference_declarator();
3365 panic("based not supported anymore");
3370 type = parse_pointer_declarator();
3374 goto ptr_operator_end;
3378 anchor = &type->base.next;
3380 /* TODO: find out if this is correct */
3381 env->attributes = parse_attributes(env->attributes);
3385 construct_type_t *inner_types = NULL;
3387 switch (token.kind) {
3389 if (env->must_be_abstract) {
3390 errorf(HERE, "no identifier expected in typename");
3392 env->symbol = token.base.symbol;
3393 env->source_position = *HERE;
3399 /* Parenthesized declarator or function declarator? */
3400 token_t const *const la1 = look_ahead(1);
3401 switch (la1->kind) {
3403 if (is_typedef_symbol(la1->base.symbol)) {
3405 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3406 * interpreted as ``function with no parameter specification'', rather
3407 * than redundant parentheses around the omitted identifier. */
3409 /* Function declarator. */
3410 if (!env->may_be_abstract) {
3411 errorf(HERE, "function declarator must have a name");
3418 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3419 /* Paranthesized declarator. */
3421 add_anchor_token(')');
3422 inner_types = parse_inner_declarator(env);
3423 if (inner_types != NULL) {
3424 /* All later declarators only modify the return type */
3425 env->must_be_abstract = true;
3427 rem_anchor_token(')');
3436 if (env->may_be_abstract)
3438 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3443 construct_type_t **const p = anchor;
3446 construct_type_t *type;
3447 switch (token.kind) {
3449 scope_t *scope = NULL;
3450 if (!env->must_be_abstract) {
3451 scope = &env->parameters;
3454 type = parse_function_declarator(scope);
3458 type = parse_array_declarator();
3461 goto declarator_finished;
3464 /* insert in the middle of the list (at p) */
3465 type->base.next = *p;
3468 anchor = &type->base.next;
3471 declarator_finished:
3472 /* append inner_types at the end of the list, we don't to set anchor anymore
3473 * as it's not needed anymore */
3474 *anchor = inner_types;
3479 static type_t *construct_declarator_type(construct_type_t *construct_list,
3482 construct_type_t *iter = construct_list;
3483 for (; iter != NULL; iter = iter->base.next) {
3484 source_position_t const* const pos = &iter->base.pos;
3485 switch (iter->kind) {
3486 case CONSTRUCT_FUNCTION: {
3487 construct_function_type_t *function = &iter->function;
3488 type_t *function_type = function->function_type;
3490 function_type->function.return_type = type;
3492 type_t *skipped_return_type = skip_typeref(type);
3494 if (is_type_function(skipped_return_type)) {
3495 errorf(pos, "function returning function is not allowed");
3496 } else if (is_type_array(skipped_return_type)) {
3497 errorf(pos, "function returning array is not allowed");
3499 if (skipped_return_type->base.qualifiers != 0) {
3500 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3504 /* The function type was constructed earlier. Freeing it here will
3505 * destroy other types. */
3506 type = typehash_insert(function_type);
3510 case CONSTRUCT_POINTER: {
3511 if (is_type_reference(skip_typeref(type)))
3512 errorf(pos, "cannot declare a pointer to reference");
3514 parsed_pointer_t *pointer = &iter->pointer;
3515 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3519 case CONSTRUCT_REFERENCE:
3520 if (is_type_reference(skip_typeref(type)))
3521 errorf(pos, "cannot declare a reference to reference");
3523 type = make_reference_type(type);
3526 case CONSTRUCT_ARRAY: {
3527 if (is_type_reference(skip_typeref(type)))
3528 errorf(pos, "cannot declare an array of references");
3530 parsed_array_t *array = &iter->array;
3531 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3533 expression_t *size_expression = array->size;
3534 if (size_expression != NULL) {
3536 = create_implicit_cast(size_expression, type_size_t);
3539 array_type->base.qualifiers = array->type_qualifiers;
3540 array_type->array.element_type = type;
3541 array_type->array.is_static = array->is_static;
3542 array_type->array.is_variable = array->is_variable;
3543 array_type->array.size_expression = size_expression;
3545 if (size_expression != NULL) {
3546 switch (is_constant_expression(size_expression)) {
3547 case EXPR_CLASS_CONSTANT: {
3548 long const size = fold_constant_to_int(size_expression);
3549 array_type->array.size = size;
3550 array_type->array.size_constant = true;
3551 /* §6.7.5.2:1 If the expression is a constant expression,
3552 * it shall have a value greater than zero. */
3554 errorf(&size_expression->base.source_position,
3555 "size of array must be greater than zero");
3556 } else if (size == 0 && !GNU_MODE) {
3557 errorf(&size_expression->base.source_position,
3558 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3563 case EXPR_CLASS_VARIABLE:
3564 array_type->array.is_vla = true;
3567 case EXPR_CLASS_ERROR:
3572 type_t *skipped_type = skip_typeref(type);
3574 if (is_type_incomplete(skipped_type)) {
3575 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3576 } else if (is_type_function(skipped_type)) {
3577 errorf(pos, "array of functions is not allowed");
3579 type = identify_new_type(array_type);
3583 internal_errorf(pos, "invalid type construction found");
3589 static type_t *automatic_type_conversion(type_t *orig_type);
3591 static type_t *semantic_parameter(const source_position_t *pos,
3593 const declaration_specifiers_t *specifiers,
3594 entity_t const *const param)
3596 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3597 * shall be adjusted to ``qualified pointer to type'',
3599 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3600 * type'' shall be adjusted to ``pointer to function
3601 * returning type'', as in 6.3.2.1. */
3602 type = automatic_type_conversion(type);
3604 if (specifiers->is_inline && is_type_valid(type)) {
3605 errorf(pos, "'%N' declared 'inline'", param);
3608 /* §6.9.1:6 The declarations in the declaration list shall contain
3609 * no storage-class specifier other than register and no
3610 * initializations. */
3611 if (specifiers->thread_local || (
3612 specifiers->storage_class != STORAGE_CLASS_NONE &&
3613 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3615 errorf(pos, "invalid storage class for '%N'", param);
3618 /* delay test for incomplete type, because we might have (void)
3619 * which is legal but incomplete... */
3624 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3625 declarator_flags_t flags)
3627 parse_declarator_env_t env;
3628 memset(&env, 0, sizeof(env));
3629 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3631 construct_type_t *construct_type = parse_inner_declarator(&env);
3633 construct_declarator_type(construct_type, specifiers->type);
3634 type_t *type = skip_typeref(orig_type);
3636 if (construct_type != NULL) {
3637 obstack_free(&temp_obst, construct_type);
3640 attribute_t *attributes = parse_attributes(env.attributes);
3641 /* append (shared) specifier attribute behind attributes of this
3643 attribute_t **anchor = &attributes;
3644 while (*anchor != NULL)
3645 anchor = &(*anchor)->next;
3646 *anchor = specifiers->attributes;
3649 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3650 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3651 entity->typedefe.type = orig_type;
3653 if (anonymous_entity != NULL) {
3654 if (is_type_compound(type)) {
3655 assert(anonymous_entity->compound.alias == NULL);
3656 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3657 anonymous_entity->kind == ENTITY_UNION);
3658 anonymous_entity->compound.alias = entity;
3659 anonymous_entity = NULL;
3660 } else if (is_type_enum(type)) {
3661 assert(anonymous_entity->enume.alias == NULL);
3662 assert(anonymous_entity->kind == ENTITY_ENUM);
3663 anonymous_entity->enume.alias = entity;
3664 anonymous_entity = NULL;
3668 /* create a declaration type entity */
3669 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3670 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3671 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3673 if (env.symbol != NULL) {
3674 if (specifiers->is_inline && is_type_valid(type)) {
3675 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3678 if (specifiers->thread_local ||
3679 specifiers->storage_class != STORAGE_CLASS_NONE) {
3680 errorf(&env.source_position, "'%N' must have no storage class", entity);
3683 } else if (flags & DECL_IS_PARAMETER) {
3684 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3685 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3686 } else if (is_type_function(type)) {
3687 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3688 entity->function.is_inline = specifiers->is_inline;
3689 entity->function.elf_visibility = default_visibility;
3690 entity->function.parameters = env.parameters;
3692 if (env.symbol != NULL) {
3693 /* this needs fixes for C++ */
3694 bool in_function_scope = current_function != NULL;
3696 if (specifiers->thread_local || (
3697 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3698 specifiers->storage_class != STORAGE_CLASS_NONE &&
3699 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3701 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3705 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3706 entity->variable.elf_visibility = default_visibility;
3707 entity->variable.thread_local = specifiers->thread_local;
3709 if (env.symbol != NULL) {
3710 if (specifiers->is_inline && is_type_valid(type)) {
3711 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3714 bool invalid_storage_class = false;
3715 if (current_scope == file_scope) {
3716 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3717 specifiers->storage_class != STORAGE_CLASS_NONE &&
3718 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3719 invalid_storage_class = true;
3722 if (specifiers->thread_local &&
3723 specifiers->storage_class == STORAGE_CLASS_NONE) {
3724 invalid_storage_class = true;
3727 if (invalid_storage_class) {
3728 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3733 entity->declaration.type = orig_type;
3734 entity->declaration.alignment = get_type_alignment(orig_type);
3735 entity->declaration.modifiers = env.modifiers;
3736 entity->declaration.attributes = attributes;
3738 storage_class_t storage_class = specifiers->storage_class;
3739 entity->declaration.declared_storage_class = storage_class;
3741 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3742 storage_class = STORAGE_CLASS_AUTO;
3743 entity->declaration.storage_class = storage_class;
3746 if (attributes != NULL) {
3747 handle_entity_attributes(attributes, entity);
3750 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3751 adapt_special_functions(&entity->function);
3757 static type_t *parse_abstract_declarator(type_t *base_type)
3759 parse_declarator_env_t env;
3760 memset(&env, 0, sizeof(env));
3761 env.may_be_abstract = true;
3762 env.must_be_abstract = true;
3764 construct_type_t *construct_type = parse_inner_declarator(&env);
3766 type_t *result = construct_declarator_type(construct_type, base_type);
3767 if (construct_type != NULL) {
3768 obstack_free(&temp_obst, construct_type);
3770 result = handle_type_attributes(env.attributes, result);
3776 * Check if the declaration of main is suspicious. main should be a
3777 * function with external linkage, returning int, taking either zero
3778 * arguments, two, or three arguments of appropriate types, ie.
3780 * int main([ int argc, char **argv [, char **env ] ]).
3782 * @param decl the declaration to check
3783 * @param type the function type of the declaration
3785 static void check_main(const entity_t *entity)
3787 const source_position_t *pos = &entity->base.source_position;
3788 if (entity->kind != ENTITY_FUNCTION) {
3789 warningf(WARN_MAIN, pos, "'main' is not a function");
3793 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3794 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3797 type_t *type = skip_typeref(entity->declaration.type);
3798 assert(is_type_function(type));
3800 function_type_t const *const func_type = &type->function;
3801 type_t *const ret_type = func_type->return_type;
3802 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3803 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3805 const function_parameter_t *parm = func_type->parameters;
3807 type_t *const first_type = skip_typeref(parm->type);
3808 type_t *const first_type_unqual = get_unqualified_type(first_type);
3809 if (!types_compatible(first_type_unqual, type_int)) {
3810 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3814 type_t *const second_type = skip_typeref(parm->type);
3815 type_t *const second_type_unqual
3816 = get_unqualified_type(second_type);
3817 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3818 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3822 type_t *const third_type = skip_typeref(parm->type);
3823 type_t *const third_type_unqual
3824 = get_unqualified_type(third_type);
3825 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3826 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3830 goto warn_arg_count;
3834 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3839 static void error_redefined_as_different_kind(const source_position_t *pos,
3840 const entity_t *old, entity_kind_t new_kind)
3842 char const *const what = get_entity_kind_name(new_kind);
3843 source_position_t const *const ppos = &old->base.source_position;
3844 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3847 static bool is_entity_valid(entity_t *const ent)
3849 if (is_declaration(ent)) {
3850 return is_type_valid(skip_typeref(ent->declaration.type));
3851 } else if (ent->kind == ENTITY_TYPEDEF) {
3852 return is_type_valid(skip_typeref(ent->typedefe.type));
3857 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3859 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3860 if (attributes_equal(tattr, attr))
3867 * test wether new_list contains any attributes not included in old_list
3869 static bool has_new_attributes(const attribute_t *old_list,
3870 const attribute_t *new_list)
3872 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3873 if (!contains_attribute(old_list, attr))
3880 * Merge in attributes from an attribute list (probably from a previous
3881 * declaration with the same name). Warning: destroys the old structure
3882 * of the attribute list - don't reuse attributes after this call.
3884 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3887 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3889 if (contains_attribute(decl->attributes, attr))
3892 /* move attribute to new declarations attributes list */
3893 attr->next = decl->attributes;
3894 decl->attributes = attr;
3898 static bool is_main(entity_t*);
3901 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3902 * for various problems that occur for multiple definitions
3904 entity_t *record_entity(entity_t *entity, const bool is_definition)
3906 const symbol_t *const symbol = entity->base.symbol;
3907 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3908 const source_position_t *pos = &entity->base.source_position;
3910 /* can happen in error cases */
3914 assert(!entity->base.parent_scope);
3915 assert(current_scope);
3916 entity->base.parent_scope = current_scope;
3918 entity_t *const previous_entity = get_entity(symbol, namespc);
3919 /* pushing the same entity twice will break the stack structure */
3920 assert(previous_entity != entity);
3922 if (entity->kind == ENTITY_FUNCTION) {
3923 type_t *const orig_type = entity->declaration.type;
3924 type_t *const type = skip_typeref(orig_type);
3926 assert(is_type_function(type));
3927 if (type->function.unspecified_parameters &&
3928 previous_entity == NULL &&
3929 !entity->declaration.implicit) {
3930 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3933 if (is_main(entity)) {
3938 if (is_declaration(entity) &&
3939 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3940 current_scope != file_scope &&
3941 !entity->declaration.implicit) {
3942 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3945 if (previous_entity != NULL) {
3946 source_position_t const *const ppos = &previous_entity->base.source_position;
3948 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3949 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3950 assert(previous_entity->kind == ENTITY_PARAMETER);
3951 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3955 if (previous_entity->base.parent_scope == current_scope) {
3956 if (previous_entity->kind != entity->kind) {
3957 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3958 error_redefined_as_different_kind(pos, previous_entity,
3963 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3964 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3967 if (previous_entity->kind == ENTITY_TYPEDEF) {
3968 type_t *const type = skip_typeref(entity->typedefe.type);
3969 type_t *const prev_type
3970 = skip_typeref(previous_entity->typedefe.type);
3971 if (c_mode & _CXX) {
3972 /* C++ allows double typedef if they are identical
3973 * (after skipping typedefs) */
3974 if (type == prev_type)
3977 /* GCC extension: redef in system headers is allowed */
3978 if ((pos->is_system_header || ppos->is_system_header) &&
3979 types_compatible(type, prev_type))
3982 errorf(pos, "redefinition of '%N' (declared %P)",
3987 /* at this point we should have only VARIABLES or FUNCTIONS */
3988 assert(is_declaration(previous_entity) && is_declaration(entity));
3990 declaration_t *const prev_decl = &previous_entity->declaration;
3991 declaration_t *const decl = &entity->declaration;
3993 /* can happen for K&R style declarations */
3994 if (prev_decl->type == NULL &&
3995 previous_entity->kind == ENTITY_PARAMETER &&
3996 entity->kind == ENTITY_PARAMETER) {
3997 prev_decl->type = decl->type;
3998 prev_decl->storage_class = decl->storage_class;
3999 prev_decl->declared_storage_class = decl->declared_storage_class;
4000 prev_decl->modifiers = decl->modifiers;
4001 return previous_entity;
4004 type_t *const type = skip_typeref(decl->type);
4005 type_t *const prev_type = skip_typeref(prev_decl->type);
4007 if (!types_compatible(type, prev_type)) {
4008 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4010 unsigned old_storage_class = prev_decl->storage_class;
4012 if (is_definition &&
4014 !(prev_decl->modifiers & DM_USED) &&
4015 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4016 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4019 storage_class_t new_storage_class = decl->storage_class;
4021 /* pretend no storage class means extern for function
4022 * declarations (except if the previous declaration is neither
4023 * none nor extern) */
4024 if (entity->kind == ENTITY_FUNCTION) {
4025 /* the previous declaration could have unspecified parameters or
4026 * be a typedef, so use the new type */
4027 if (prev_type->function.unspecified_parameters || is_definition)
4028 prev_decl->type = type;
4030 switch (old_storage_class) {
4031 case STORAGE_CLASS_NONE:
4032 old_storage_class = STORAGE_CLASS_EXTERN;
4035 case STORAGE_CLASS_EXTERN:
4036 if (is_definition) {
4037 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4038 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4040 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4041 new_storage_class = STORAGE_CLASS_EXTERN;
4048 } else if (is_type_incomplete(prev_type)) {
4049 prev_decl->type = type;
4052 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4053 new_storage_class == STORAGE_CLASS_EXTERN) {
4055 warn_redundant_declaration: ;
4057 = has_new_attributes(prev_decl->attributes,
4059 if (has_new_attrs) {
4060 merge_in_attributes(decl, prev_decl->attributes);
4061 } else if (!is_definition &&
4062 is_type_valid(prev_type) &&
4063 !pos->is_system_header) {
4064 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4066 } else if (current_function == NULL) {
4067 if (old_storage_class != STORAGE_CLASS_STATIC &&
4068 new_storage_class == STORAGE_CLASS_STATIC) {
4069 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4070 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4071 prev_decl->storage_class = STORAGE_CLASS_NONE;
4072 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4074 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4076 goto error_redeclaration;
4077 goto warn_redundant_declaration;
4079 } else if (is_type_valid(prev_type)) {
4080 if (old_storage_class == new_storage_class) {
4081 error_redeclaration:
4082 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4084 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4089 prev_decl->modifiers |= decl->modifiers;
4090 if (entity->kind == ENTITY_FUNCTION) {
4091 previous_entity->function.is_inline |= entity->function.is_inline;
4093 return previous_entity;
4097 if (is_warn_on(why = WARN_SHADOW) ||
4098 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4099 char const *const what = get_entity_kind_name(previous_entity->kind);
4100 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4104 if (entity->kind == ENTITY_FUNCTION) {
4105 if (is_definition &&
4106 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4108 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4109 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4111 goto warn_missing_declaration;
4114 } else if (entity->kind == ENTITY_VARIABLE) {
4115 if (current_scope == file_scope &&
4116 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4117 !entity->declaration.implicit) {
4118 warn_missing_declaration:
4119 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4124 environment_push(entity);
4125 append_entity(current_scope, entity);
4130 static void parser_error_multiple_definition(entity_t *entity,
4131 const source_position_t *source_position)
4133 errorf(source_position, "redefinition of '%N' (declared %P)", entity, &entity->base.source_position);
4136 static bool is_declaration_specifier(const token_t *token)
4138 switch (token->kind) {
4142 return is_typedef_symbol(token->base.symbol);
4149 static void parse_init_declarator_rest(entity_t *entity)
4151 type_t *orig_type = type_error_type;
4153 if (entity->base.kind == ENTITY_TYPEDEF) {
4154 source_position_t const *const pos = &entity->base.source_position;
4155 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4157 assert(is_declaration(entity));
4158 orig_type = entity->declaration.type;
4161 type_t *type = skip_typeref(orig_type);
4163 if (entity->kind == ENTITY_VARIABLE
4164 && entity->variable.initializer != NULL) {
4165 parser_error_multiple_definition(entity, HERE);
4169 declaration_t *const declaration = &entity->declaration;
4170 bool must_be_constant = false;
4171 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4172 entity->base.parent_scope == file_scope) {
4173 must_be_constant = true;
4176 if (is_type_function(type)) {
4177 source_position_t const *const pos = &entity->base.source_position;
4178 errorf(pos, "'%N' is initialized like a variable", entity);
4179 orig_type = type_error_type;
4182 parse_initializer_env_t env;
4183 env.type = orig_type;
4184 env.must_be_constant = must_be_constant;
4185 env.entity = entity;
4187 initializer_t *initializer = parse_initializer(&env);
4189 if (entity->kind == ENTITY_VARIABLE) {
4190 /* §6.7.5:22 array initializers for arrays with unknown size
4191 * determine the array type size */
4192 declaration->type = env.type;
4193 entity->variable.initializer = initializer;
4197 /* parse rest of a declaration without any declarator */
4198 static void parse_anonymous_declaration_rest(
4199 const declaration_specifiers_t *specifiers)
4202 anonymous_entity = NULL;
4204 source_position_t const *const pos = &specifiers->source_position;
4205 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4206 specifiers->thread_local) {
4207 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4210 type_t *type = specifiers->type;
4211 switch (type->kind) {
4212 case TYPE_COMPOUND_STRUCT:
4213 case TYPE_COMPOUND_UNION: {
4214 if (type->compound.compound->base.symbol == NULL) {
4215 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4224 warningf(WARN_OTHER, pos, "empty declaration");
4229 static void check_variable_type_complete(entity_t *ent)
4231 if (ent->kind != ENTITY_VARIABLE)
4234 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4235 * type for the object shall be complete [...] */
4236 declaration_t *decl = &ent->declaration;
4237 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4238 decl->storage_class == STORAGE_CLASS_STATIC)
4241 type_t *const type = skip_typeref(decl->type);
4242 if (!is_type_incomplete(type))
4245 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4246 * are given length one. */
4247 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4248 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4252 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4256 static void parse_declaration_rest(entity_t *ndeclaration,
4257 const declaration_specifiers_t *specifiers,
4258 parsed_declaration_func finished_declaration,
4259 declarator_flags_t flags)
4261 add_anchor_token(';');
4262 add_anchor_token(',');
4264 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4266 if (token.kind == '=') {
4267 parse_init_declarator_rest(entity);
4268 } else if (entity->kind == ENTITY_VARIABLE) {
4269 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4270 * [...] where the extern specifier is explicitly used. */
4271 declaration_t *decl = &entity->declaration;
4272 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4273 is_type_reference(skip_typeref(decl->type))) {
4274 source_position_t const *const pos = &entity->base.source_position;
4275 errorf(pos, "reference '%#N' must be initialized", entity);
4279 check_variable_type_complete(entity);
4284 add_anchor_token('=');
4285 ndeclaration = parse_declarator(specifiers, flags);
4286 rem_anchor_token('=');
4288 rem_anchor_token(',');
4289 rem_anchor_token(';');
4292 anonymous_entity = NULL;
4295 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4297 symbol_t *symbol = entity->base.symbol;
4301 assert(entity->base.namespc == NAMESPACE_NORMAL);
4302 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4303 if (previous_entity == NULL
4304 || previous_entity->base.parent_scope != current_scope) {
4305 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4310 if (is_definition) {
4311 errorf(HERE, "'%N' is initialised", entity);
4314 return record_entity(entity, false);
4317 static void parse_declaration(parsed_declaration_func finished_declaration,
4318 declarator_flags_t flags)
4320 add_anchor_token(';');
4321 declaration_specifiers_t specifiers;
4322 parse_declaration_specifiers(&specifiers);
4323 rem_anchor_token(';');
4325 if (token.kind == ';') {
4326 parse_anonymous_declaration_rest(&specifiers);
4328 entity_t *entity = parse_declarator(&specifiers, flags);
4329 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4334 static type_t *get_default_promoted_type(type_t *orig_type)
4336 type_t *result = orig_type;
4338 type_t *type = skip_typeref(orig_type);
4339 if (is_type_integer(type)) {
4340 result = promote_integer(type);
4341 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4342 result = type_double;
4348 static void parse_kr_declaration_list(entity_t *entity)
4350 if (entity->kind != ENTITY_FUNCTION)
4353 type_t *type = skip_typeref(entity->declaration.type);
4354 assert(is_type_function(type));
4355 if (!type->function.kr_style_parameters)
4358 add_anchor_token('{');
4360 PUSH_SCOPE(&entity->function.parameters);
4362 entity_t *parameter = entity->function.parameters.entities;
4363 for ( ; parameter != NULL; parameter = parameter->base.next) {
4364 assert(parameter->base.parent_scope == NULL);
4365 parameter->base.parent_scope = current_scope;
4366 environment_push(parameter);
4369 /* parse declaration list */
4371 switch (token.kind) {
4373 /* This covers symbols, which are no type, too, and results in
4374 * better error messages. The typical cases are misspelled type
4375 * names and missing includes. */
4377 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4387 /* update function type */
4388 type_t *new_type = duplicate_type(type);
4390 function_parameter_t *parameters = NULL;
4391 function_parameter_t **anchor = ¶meters;
4393 /* did we have an earlier prototype? */
4394 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4395 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4398 function_parameter_t *proto_parameter = NULL;
4399 if (proto_type != NULL) {
4400 type_t *proto_type_type = proto_type->declaration.type;
4401 proto_parameter = proto_type_type->function.parameters;
4402 /* If a K&R function definition has a variadic prototype earlier, then
4403 * make the function definition variadic, too. This should conform to
4404 * §6.7.5.3:15 and §6.9.1:8. */
4405 new_type->function.variadic = proto_type_type->function.variadic;
4407 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4409 new_type->function.unspecified_parameters = true;
4412 bool need_incompatible_warning = false;
4413 parameter = entity->function.parameters.entities;
4414 for (; parameter != NULL; parameter = parameter->base.next,
4416 proto_parameter == NULL ? NULL : proto_parameter->next) {
4417 if (parameter->kind != ENTITY_PARAMETER)
4420 type_t *parameter_type = parameter->declaration.type;
4421 if (parameter_type == NULL) {
4422 source_position_t const* const pos = ¶meter->base.source_position;
4424 errorf(pos, "no type specified for function '%N'", parameter);
4425 parameter_type = type_error_type;
4427 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4428 parameter_type = type_int;
4430 parameter->declaration.type = parameter_type;
4433 semantic_parameter_incomplete(parameter);
4435 /* we need the default promoted types for the function type */
4436 type_t *not_promoted = parameter_type;
4437 parameter_type = get_default_promoted_type(parameter_type);
4439 /* gcc special: if the type of the prototype matches the unpromoted
4440 * type don't promote */
4441 if (!strict_mode && proto_parameter != NULL) {
4442 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4443 type_t *promo_skip = skip_typeref(parameter_type);
4444 type_t *param_skip = skip_typeref(not_promoted);
4445 if (!types_compatible(proto_p_type, promo_skip)
4446 && types_compatible(proto_p_type, param_skip)) {
4448 need_incompatible_warning = true;
4449 parameter_type = not_promoted;
4452 function_parameter_t *const function_parameter
4453 = allocate_parameter(parameter_type);
4455 *anchor = function_parameter;
4456 anchor = &function_parameter->next;
4459 new_type->function.parameters = parameters;
4460 new_type = identify_new_type(new_type);
4462 if (need_incompatible_warning) {
4463 symbol_t const *const sym = entity->base.symbol;
4464 source_position_t const *const pos = &entity->base.source_position;
4465 source_position_t const *const ppos = &proto_type->base.source_position;
4466 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4468 entity->declaration.type = new_type;
4470 rem_anchor_token('{');
4473 static bool first_err = true;
4476 * When called with first_err set, prints the name of the current function,
4479 static void print_in_function(void)
4483 char const *const file = current_function->base.base.source_position.input_name;
4484 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4489 * Check if all labels are defined in the current function.
4490 * Check if all labels are used in the current function.
4492 static void check_labels(void)
4494 for (const goto_statement_t *goto_statement = goto_first;
4495 goto_statement != NULL;
4496 goto_statement = goto_statement->next) {
4497 label_t *label = goto_statement->label;
4498 if (label->base.source_position.input_name == NULL) {
4499 print_in_function();
4500 source_position_t const *const pos = &goto_statement->base.source_position;
4501 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4505 if (is_warn_on(WARN_UNUSED_LABEL)) {
4506 for (const label_statement_t *label_statement = label_first;
4507 label_statement != NULL;
4508 label_statement = label_statement->next) {
4509 label_t *label = label_statement->label;
4511 if (! label->used) {
4512 print_in_function();
4513 source_position_t const *const pos = &label_statement->base.source_position;
4514 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4520 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4522 entity_t const *const end = last != NULL ? last->base.next : NULL;
4523 for (; entity != end; entity = entity->base.next) {
4524 if (!is_declaration(entity))
4527 declaration_t *declaration = &entity->declaration;
4528 if (declaration->implicit)
4531 if (!declaration->used) {
4532 print_in_function();
4533 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4534 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4535 print_in_function();
4536 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4541 static void check_unused_variables(statement_t *const stmt, void *const env)
4545 switch (stmt->kind) {
4546 case STATEMENT_DECLARATION: {
4547 declaration_statement_t const *const decls = &stmt->declaration;
4548 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4553 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4562 * Check declarations of current_function for unused entities.
4564 static void check_declarations(void)
4566 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4567 const scope_t *scope = ¤t_function->parameters;
4568 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4570 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4571 walk_statements(current_function->statement, check_unused_variables,
4576 static int determine_truth(expression_t const* const cond)
4579 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4580 fold_constant_to_bool(cond) ? 1 :
4584 static void check_reachable(statement_t *);
4585 static bool reaches_end;
4587 static bool expression_returns(expression_t const *const expr)
4589 switch (expr->kind) {
4591 expression_t const *const func = expr->call.function;
4592 type_t const *const type = skip_typeref(func->base.type);
4593 if (type->kind == TYPE_POINTER) {
4594 type_t const *const points_to
4595 = skip_typeref(type->pointer.points_to);
4596 if (points_to->kind == TYPE_FUNCTION
4597 && points_to->function.modifiers & DM_NORETURN)
4601 if (!expression_returns(func))
4604 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4605 if (!expression_returns(arg->expression))
4612 case EXPR_REFERENCE:
4613 case EXPR_ENUM_CONSTANT:
4614 case EXPR_LITERAL_CASES:
4615 case EXPR_LITERAL_CHARACTER:
4616 case EXPR_STRING_LITERAL:
4617 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4618 case EXPR_LABEL_ADDRESS:
4619 case EXPR_CLASSIFY_TYPE:
4620 case EXPR_SIZEOF: // TODO handle obscure VLA case
4623 case EXPR_BUILTIN_CONSTANT_P:
4624 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4629 case EXPR_STATEMENT: {
4630 bool old_reaches_end = reaches_end;
4631 reaches_end = false;
4632 check_reachable(expr->statement.statement);
4633 bool returns = reaches_end;
4634 reaches_end = old_reaches_end;
4638 case EXPR_CONDITIONAL:
4639 // TODO handle constant expression
4641 if (!expression_returns(expr->conditional.condition))
4644 if (expr->conditional.true_expression != NULL
4645 && expression_returns(expr->conditional.true_expression))
4648 return expression_returns(expr->conditional.false_expression);
4651 return expression_returns(expr->select.compound);
4653 case EXPR_ARRAY_ACCESS:
4655 expression_returns(expr->array_access.array_ref) &&
4656 expression_returns(expr->array_access.index);
4659 return expression_returns(expr->va_starte.ap);
4662 return expression_returns(expr->va_arge.ap);
4665 return expression_returns(expr->va_copye.src);
4667 case EXPR_UNARY_CASES_MANDATORY:
4668 return expression_returns(expr->unary.value);
4670 case EXPR_UNARY_THROW:
4673 case EXPR_BINARY_CASES:
4674 // TODO handle constant lhs of && and ||
4676 expression_returns(expr->binary.left) &&
4677 expression_returns(expr->binary.right);
4680 panic("unhandled expression");
4683 static bool initializer_returns(initializer_t const *const init)
4685 switch (init->kind) {
4686 case INITIALIZER_VALUE:
4687 return expression_returns(init->value.value);
4689 case INITIALIZER_LIST: {
4690 initializer_t * const* i = init->list.initializers;
4691 initializer_t * const* const end = i + init->list.len;
4692 bool returns = true;
4693 for (; i != end; ++i) {
4694 if (!initializer_returns(*i))
4700 case INITIALIZER_STRING:
4701 case INITIALIZER_DESIGNATOR: // designators have no payload
4704 panic("unhandled initializer");
4707 static bool noreturn_candidate;
4709 static void check_reachable(statement_t *const stmt)
4711 if (stmt->base.reachable)
4713 if (stmt->kind != STATEMENT_DO_WHILE)
4714 stmt->base.reachable = true;
4716 statement_t *last = stmt;
4718 switch (stmt->kind) {
4719 case STATEMENT_ERROR:
4720 case STATEMENT_EMPTY:
4722 next = stmt->base.next;
4725 case STATEMENT_DECLARATION: {
4726 declaration_statement_t const *const decl = &stmt->declaration;
4727 entity_t const * ent = decl->declarations_begin;
4728 entity_t const *const last_decl = decl->declarations_end;
4730 for (;; ent = ent->base.next) {
4731 if (ent->kind == ENTITY_VARIABLE &&
4732 ent->variable.initializer != NULL &&
4733 !initializer_returns(ent->variable.initializer)) {
4736 if (ent == last_decl)
4740 next = stmt->base.next;
4744 case STATEMENT_COMPOUND:
4745 next = stmt->compound.statements;
4747 next = stmt->base.next;
4750 case STATEMENT_RETURN: {
4751 expression_t const *const val = stmt->returns.value;
4752 if (val == NULL || expression_returns(val))
4753 noreturn_candidate = false;
4757 case STATEMENT_IF: {
4758 if_statement_t const *const ifs = &stmt->ifs;
4759 expression_t const *const cond = ifs->condition;
4761 if (!expression_returns(cond))
4764 int const val = determine_truth(cond);
4767 check_reachable(ifs->true_statement);
4772 if (ifs->false_statement != NULL) {
4773 check_reachable(ifs->false_statement);
4777 next = stmt->base.next;
4781 case STATEMENT_SWITCH: {
4782 switch_statement_t const *const switchs = &stmt->switchs;
4783 expression_t const *const expr = switchs->expression;
4785 if (!expression_returns(expr))
4788 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4789 long const val = fold_constant_to_int(expr);
4790 case_label_statement_t * defaults = NULL;
4791 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4792 if (i->expression == NULL) {
4797 if (i->first_case <= val && val <= i->last_case) {
4798 check_reachable((statement_t*)i);
4803 if (defaults != NULL) {
4804 check_reachable((statement_t*)defaults);
4808 bool has_default = false;
4809 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4810 if (i->expression == NULL)
4813 check_reachable((statement_t*)i);
4820 next = stmt->base.next;
4824 case STATEMENT_EXPRESSION: {
4825 /* Check for noreturn function call */
4826 expression_t const *const expr = stmt->expression.expression;
4827 if (!expression_returns(expr))
4830 next = stmt->base.next;
4834 case STATEMENT_CONTINUE:
4835 for (statement_t *parent = stmt;;) {
4836 parent = parent->base.parent;
4837 if (parent == NULL) /* continue not within loop */
4841 switch (parent->kind) {
4842 case STATEMENT_WHILE: goto continue_while;
4843 case STATEMENT_DO_WHILE: goto continue_do_while;
4844 case STATEMENT_FOR: goto continue_for;
4850 case STATEMENT_BREAK:
4851 for (statement_t *parent = stmt;;) {
4852 parent = parent->base.parent;
4853 if (parent == NULL) /* break not within loop/switch */
4856 switch (parent->kind) {
4857 case STATEMENT_SWITCH:
4858 case STATEMENT_WHILE:
4859 case STATEMENT_DO_WHILE:
4862 next = parent->base.next;
4863 goto found_break_parent;
4871 case STATEMENT_COMPUTED_GOTO: {
4872 if (!expression_returns(stmt->computed_goto.expression))
4875 statement_t *parent = stmt->base.parent;
4876 if (parent == NULL) /* top level goto */
4882 case STATEMENT_GOTO:
4883 next = stmt->gotos.label->statement;
4884 if (next == NULL) /* missing label */
4888 case STATEMENT_LABEL:
4889 next = stmt->label.statement;
4892 case STATEMENT_CASE_LABEL:
4893 next = stmt->case_label.statement;
4896 case STATEMENT_WHILE: {
4897 while_statement_t const *const whiles = &stmt->whiles;
4898 expression_t const *const cond = whiles->condition;
4900 if (!expression_returns(cond))
4903 int const val = determine_truth(cond);
4906 check_reachable(whiles->body);
4911 next = stmt->base.next;
4915 case STATEMENT_DO_WHILE:
4916 next = stmt->do_while.body;
4919 case STATEMENT_FOR: {
4920 for_statement_t *const fors = &stmt->fors;
4922 if (fors->condition_reachable)
4924 fors->condition_reachable = true;
4926 expression_t const *const cond = fors->condition;
4931 } else if (expression_returns(cond)) {
4932 val = determine_truth(cond);
4938 check_reachable(fors->body);
4943 next = stmt->base.next;
4947 case STATEMENT_MS_TRY: {
4948 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4949 check_reachable(ms_try->try_statement);
4950 next = ms_try->final_statement;
4954 case STATEMENT_LEAVE: {
4955 statement_t *parent = stmt;
4957 parent = parent->base.parent;
4958 if (parent == NULL) /* __leave not within __try */
4961 if (parent->kind == STATEMENT_MS_TRY) {
4963 next = parent->ms_try.final_statement;
4971 panic("invalid statement kind");
4974 while (next == NULL) {
4975 next = last->base.parent;
4977 noreturn_candidate = false;
4979 type_t *const type = skip_typeref(current_function->base.type);
4980 assert(is_type_function(type));
4981 type_t *const ret = skip_typeref(type->function.return_type);
4982 if (!is_type_void(ret) &&
4983 is_type_valid(ret) &&
4984 !is_main(current_entity)) {
4985 source_position_t const *const pos = &stmt->base.source_position;
4986 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4991 switch (next->kind) {
4992 case STATEMENT_ERROR:
4993 case STATEMENT_EMPTY:
4994 case STATEMENT_DECLARATION:
4995 case STATEMENT_EXPRESSION:
4997 case STATEMENT_RETURN:
4998 case STATEMENT_CONTINUE:
4999 case STATEMENT_BREAK:
5000 case STATEMENT_COMPUTED_GOTO:
5001 case STATEMENT_GOTO:
5002 case STATEMENT_LEAVE:
5003 panic("invalid control flow in function");
5005 case STATEMENT_COMPOUND:
5006 if (next->compound.stmt_expr) {
5012 case STATEMENT_SWITCH:
5013 case STATEMENT_LABEL:
5014 case STATEMENT_CASE_LABEL:
5016 next = next->base.next;
5019 case STATEMENT_WHILE: {
5021 if (next->base.reachable)
5023 next->base.reachable = true;
5025 while_statement_t const *const whiles = &next->whiles;
5026 expression_t const *const cond = whiles->condition;
5028 if (!expression_returns(cond))
5031 int const val = determine_truth(cond);
5034 check_reachable(whiles->body);
5040 next = next->base.next;
5044 case STATEMENT_DO_WHILE: {
5046 if (next->base.reachable)
5048 next->base.reachable = true;
5050 do_while_statement_t const *const dw = &next->do_while;
5051 expression_t const *const cond = dw->condition;
5053 if (!expression_returns(cond))
5056 int const val = determine_truth(cond);
5059 check_reachable(dw->body);
5065 next = next->base.next;
5069 case STATEMENT_FOR: {
5071 for_statement_t *const fors = &next->fors;
5073 fors->step_reachable = true;
5075 if (fors->condition_reachable)
5077 fors->condition_reachable = true;
5079 expression_t const *const cond = fors->condition;
5084 } else if (expression_returns(cond)) {
5085 val = determine_truth(cond);
5091 check_reachable(fors->body);
5097 next = next->base.next;
5101 case STATEMENT_MS_TRY:
5103 next = next->ms_try.final_statement;
5108 check_reachable(next);
5111 static void check_unreachable(statement_t* const stmt, void *const env)
5115 switch (stmt->kind) {
5116 case STATEMENT_DO_WHILE:
5117 if (!stmt->base.reachable) {
5118 expression_t const *const cond = stmt->do_while.condition;
5119 if (determine_truth(cond) >= 0) {
5120 source_position_t const *const pos = &cond->base.source_position;
5121 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5126 case STATEMENT_FOR: {
5127 for_statement_t const* const fors = &stmt->fors;
5129 // if init and step are unreachable, cond is unreachable, too
5130 if (!stmt->base.reachable && !fors->step_reachable) {
5131 goto warn_unreachable;
5133 if (!stmt->base.reachable && fors->initialisation != NULL) {
5134 source_position_t const *const pos = &fors->initialisation->base.source_position;
5135 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5138 if (!fors->condition_reachable && fors->condition != NULL) {
5139 source_position_t const *const pos = &fors->condition->base.source_position;
5140 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5143 if (!fors->step_reachable && fors->step != NULL) {
5144 source_position_t const *const pos = &fors->step->base.source_position;
5145 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5151 case STATEMENT_COMPOUND:
5152 if (stmt->compound.statements != NULL)
5154 goto warn_unreachable;
5156 case STATEMENT_DECLARATION: {
5157 /* Only warn if there is at least one declarator with an initializer.
5158 * This typically occurs in switch statements. */
5159 declaration_statement_t const *const decl = &stmt->declaration;
5160 entity_t const * ent = decl->declarations_begin;
5161 entity_t const *const last = decl->declarations_end;
5163 for (;; ent = ent->base.next) {
5164 if (ent->kind == ENTITY_VARIABLE &&
5165 ent->variable.initializer != NULL) {
5166 goto warn_unreachable;
5176 if (!stmt->base.reachable) {
5177 source_position_t const *const pos = &stmt->base.source_position;
5178 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5184 static bool is_main(entity_t *entity)
5186 static symbol_t *sym_main = NULL;
5187 if (sym_main == NULL) {
5188 sym_main = symbol_table_insert("main");
5191 if (entity->base.symbol != sym_main)
5193 /* must be in outermost scope */
5194 if (entity->base.parent_scope != file_scope)
5200 static void prepare_main_collect2(entity_t*);
5202 static void parse_external_declaration(void)
5204 /* function-definitions and declarations both start with declaration
5206 add_anchor_token(';');
5207 declaration_specifiers_t specifiers;
5208 parse_declaration_specifiers(&specifiers);
5209 rem_anchor_token(';');
5211 /* must be a declaration */
5212 if (token.kind == ';') {
5213 parse_anonymous_declaration_rest(&specifiers);
5217 add_anchor_token(',');
5218 add_anchor_token('=');
5219 add_anchor_token(';');
5220 add_anchor_token('{');
5222 /* declarator is common to both function-definitions and declarations */
5223 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5225 rem_anchor_token('{');
5226 rem_anchor_token(';');
5227 rem_anchor_token('=');
5228 rem_anchor_token(',');
5230 /* must be a declaration */
5231 switch (token.kind) {
5235 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5240 /* must be a function definition */
5241 parse_kr_declaration_list(ndeclaration);
5243 if (token.kind != '{') {
5244 parse_error_expected("while parsing function definition", '{', NULL);
5245 eat_until_matching_token(';');
5249 assert(is_declaration(ndeclaration));
5250 type_t *const orig_type = ndeclaration->declaration.type;
5251 type_t * type = skip_typeref(orig_type);
5253 if (!is_type_function(type)) {
5254 if (is_type_valid(type)) {
5255 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5261 source_position_t const *const pos = &ndeclaration->base.source_position;
5262 if (is_typeref(orig_type)) {
5264 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5267 if (is_type_compound(skip_typeref(type->function.return_type))) {
5268 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5270 if (type->function.unspecified_parameters) {
5271 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5273 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5276 /* §6.7.5.3:14 a function definition with () means no
5277 * parameters (and not unspecified parameters) */
5278 if (type->function.unspecified_parameters &&
5279 type->function.parameters == NULL) {
5280 type_t *copy = duplicate_type(type);
5281 copy->function.unspecified_parameters = false;
5282 type = identify_new_type(copy);
5284 ndeclaration->declaration.type = type;
5287 entity_t *const entity = record_entity(ndeclaration, true);
5288 assert(entity->kind == ENTITY_FUNCTION);
5289 assert(ndeclaration->kind == ENTITY_FUNCTION);
5291 function_t *const function = &entity->function;
5292 if (ndeclaration != entity) {
5293 function->parameters = ndeclaration->function.parameters;
5296 PUSH_SCOPE(&function->parameters);
5298 entity_t *parameter = function->parameters.entities;
5299 for (; parameter != NULL; parameter = parameter->base.next) {
5300 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5301 parameter->base.parent_scope = current_scope;
5303 assert(parameter->base.parent_scope == NULL
5304 || parameter->base.parent_scope == current_scope);
5305 parameter->base.parent_scope = current_scope;
5306 if (parameter->base.symbol == NULL) {
5307 errorf(¶meter->base.source_position, "parameter name omitted");
5310 environment_push(parameter);
5313 if (function->statement != NULL) {
5314 parser_error_multiple_definition(entity, HERE);
5317 /* parse function body */
5318 int label_stack_top = label_top();
5319 function_t *old_current_function = current_function;
5320 current_function = function;
5321 PUSH_CURRENT_ENTITY(entity);
5325 goto_anchor = &goto_first;
5327 label_anchor = &label_first;
5329 statement_t *const body = parse_compound_statement(false);
5330 function->statement = body;
5333 check_declarations();
5334 if (is_warn_on(WARN_RETURN_TYPE) ||
5335 is_warn_on(WARN_UNREACHABLE_CODE) ||
5336 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5337 noreturn_candidate = true;
5338 check_reachable(body);
5339 if (is_warn_on(WARN_UNREACHABLE_CODE))
5340 walk_statements(body, check_unreachable, NULL);
5341 if (noreturn_candidate &&
5342 !(function->base.modifiers & DM_NORETURN)) {
5343 source_position_t const *const pos = &body->base.source_position;
5344 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5348 if (is_main(entity)) {
5349 /* Force main to C linkage. */
5350 type_t *const type = entity->declaration.type;
5351 assert(is_type_function(type));
5352 if (type->function.linkage != LINKAGE_C) {
5353 type_t *new_type = duplicate_type(type);
5354 new_type->function.linkage = LINKAGE_C;
5355 entity->declaration.type = identify_new_type(new_type);
5358 if (enable_main_collect2_hack)
5359 prepare_main_collect2(entity);
5362 POP_CURRENT_ENTITY();
5364 assert(current_function == function);
5365 current_function = old_current_function;
5366 label_pop_to(label_stack_top);
5372 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5374 entity_t *iter = compound->members.entities;
5375 for (; iter != NULL; iter = iter->base.next) {
5376 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5379 if (iter->base.symbol == symbol) {
5381 } else if (iter->base.symbol == NULL) {
5382 /* search in anonymous structs and unions */
5383 type_t *type = skip_typeref(iter->declaration.type);
5384 if (is_type_compound(type)) {
5385 if (find_compound_entry(type->compound.compound, symbol)
5396 static void check_deprecated(const source_position_t *source_position,
5397 const entity_t *entity)
5399 if (!is_declaration(entity))
5401 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5404 source_position_t const *const epos = &entity->base.source_position;
5405 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5407 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5409 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5414 static expression_t *create_select(const source_position_t *pos,
5416 type_qualifiers_t qualifiers,
5419 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5421 check_deprecated(pos, entry);
5423 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5424 select->select.compound = addr;
5425 select->select.compound_entry = entry;
5427 type_t *entry_type = entry->declaration.type;
5428 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5430 /* bitfields need special treatment */
5431 if (entry->compound_member.bitfield) {
5432 unsigned bit_size = entry->compound_member.bit_size;
5433 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5434 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5435 res_type = type_int;
5439 /* we always do the auto-type conversions; the & and sizeof parser contains
5440 * code to revert this! */
5441 select->base.type = automatic_type_conversion(res_type);
5448 * Find entry with symbol in compound. Search anonymous structs and unions and
5449 * creates implicit select expressions for them.
5450 * Returns the adress for the innermost compound.
5452 static expression_t *find_create_select(const source_position_t *pos,
5454 type_qualifiers_t qualifiers,
5455 compound_t *compound, symbol_t *symbol)
5457 entity_t *iter = compound->members.entities;
5458 for (; iter != NULL; iter = iter->base.next) {
5459 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5462 symbol_t *iter_symbol = iter->base.symbol;
5463 if (iter_symbol == NULL) {
5464 type_t *type = iter->declaration.type;
5465 if (!is_type_compound(type))
5468 compound_t *sub_compound = type->compound.compound;
5470 if (find_compound_entry(sub_compound, symbol) == NULL)
5473 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5474 sub_addr->base.source_position = *pos;
5475 sub_addr->base.implicit = true;
5476 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5480 if (iter_symbol == symbol) {
5481 return create_select(pos, addr, qualifiers, iter);
5488 static void parse_bitfield_member(entity_t *entity)
5492 expression_t *size = parse_constant_expression();
5495 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5496 type_t *type = entity->declaration.type;
5497 if (!is_type_integer(skip_typeref(type))) {
5498 errorf(HERE, "bitfield base type '%T' is not an integer type",
5502 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5503 /* error already reported by parse_constant_expression */
5504 size_long = get_type_size(type) * 8;
5506 size_long = fold_constant_to_int(size);
5508 const symbol_t *symbol = entity->base.symbol;
5509 const symbol_t *user_symbol
5510 = symbol == NULL ? sym_anonymous : symbol;
5511 unsigned bit_size = get_type_size(type) * 8;
5512 if (size_long < 0) {
5513 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5514 } else if (size_long == 0 && symbol != NULL) {
5515 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5516 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5517 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5520 /* hope that people don't invent crazy types with more bits
5521 * than our struct can hold */
5523 (1 << sizeof(entity->compound_member.bit_size)*8));
5527 entity->compound_member.bitfield = true;
5528 entity->compound_member.bit_size = (unsigned char)size_long;
5531 static void parse_compound_declarators(compound_t *compound,
5532 const declaration_specifiers_t *specifiers)
5534 add_anchor_token(';');
5535 add_anchor_token(',');
5539 if (token.kind == ':') {
5540 /* anonymous bitfield */
5541 type_t *type = specifiers->type;
5542 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5543 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5544 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5545 entity->declaration.type = type;
5547 parse_bitfield_member(entity);
5549 attribute_t *attributes = parse_attributes(NULL);
5550 attribute_t **anchor = &attributes;
5551 while (*anchor != NULL)
5552 anchor = &(*anchor)->next;
5553 *anchor = specifiers->attributes;
5554 if (attributes != NULL) {
5555 handle_entity_attributes(attributes, entity);
5557 entity->declaration.attributes = attributes;
5559 append_entity(&compound->members, entity);
5561 entity = parse_declarator(specifiers,
5562 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5563 source_position_t const *const pos = &entity->base.source_position;
5564 if (entity->kind == ENTITY_TYPEDEF) {
5565 errorf(pos, "typedef not allowed as compound member");
5567 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5569 /* make sure we don't define a symbol multiple times */
5570 symbol_t *symbol = entity->base.symbol;
5571 if (symbol != NULL) {
5572 entity_t *prev = find_compound_entry(compound, symbol);
5574 source_position_t const *const ppos = &prev->base.source_position;
5575 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5579 if (token.kind == ':') {
5580 parse_bitfield_member(entity);
5582 attribute_t *attributes = parse_attributes(NULL);
5583 handle_entity_attributes(attributes, entity);
5585 type_t *orig_type = entity->declaration.type;
5586 type_t *type = skip_typeref(orig_type);
5587 if (is_type_function(type)) {
5588 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5589 } else if (is_type_incomplete(type)) {
5590 /* §6.7.2.1:16 flexible array member */
5591 if (!is_type_array(type) ||
5592 token.kind != ';' ||
5593 look_ahead(1)->kind != '}') {
5594 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5595 } else if (compound->members.entities == NULL) {
5596 errorf(pos, "flexible array member in otherwise empty struct");
5601 append_entity(&compound->members, entity);
5604 } while (next_if(','));
5605 rem_anchor_token(',');
5606 rem_anchor_token(';');
5609 anonymous_entity = NULL;
5612 static void parse_compound_type_entries(compound_t *compound)
5615 add_anchor_token('}');
5618 switch (token.kind) {
5620 case T___extension__:
5621 case T_IDENTIFIER: {
5623 declaration_specifiers_t specifiers;
5624 parse_declaration_specifiers(&specifiers);
5625 parse_compound_declarators(compound, &specifiers);
5631 rem_anchor_token('}');
5634 compound->complete = true;
5640 static type_t *parse_typename(void)
5642 declaration_specifiers_t specifiers;
5643 parse_declaration_specifiers(&specifiers);
5644 if (specifiers.storage_class != STORAGE_CLASS_NONE
5645 || specifiers.thread_local) {
5646 /* TODO: improve error message, user does probably not know what a
5647 * storage class is...
5649 errorf(&specifiers.source_position, "typename must not have a storage class");
5652 type_t *result = parse_abstract_declarator(specifiers.type);
5660 typedef expression_t* (*parse_expression_function)(void);
5661 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5663 typedef struct expression_parser_function_t expression_parser_function_t;
5664 struct expression_parser_function_t {
5665 parse_expression_function parser;
5666 precedence_t infix_precedence;
5667 parse_expression_infix_function infix_parser;
5670 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5672 static type_t *get_string_type(string_encoding_t const enc)
5674 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5676 case STRING_ENCODING_CHAR: return warn ? type_const_char_ptr : type_char_ptr;
5677 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5679 panic("invalid string encoding");
5683 * Parse a string constant.
5685 static expression_t *parse_string_literal(void)
5687 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5688 expr->string_literal.value = concat_string_literals();
5689 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5694 * Parse a boolean constant.
5696 static expression_t *parse_boolean_literal(bool value)
5698 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5699 literal->base.type = type_bool;
5700 literal->literal.value.begin = value ? "true" : "false";
5701 literal->literal.value.size = value ? 4 : 5;
5703 eat(value ? T_true : T_false);
5707 static void warn_traditional_suffix(char const *const suffix)
5709 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5712 static void check_integer_suffix(expression_t *const expr, char const *const suffix)
5714 specifiers_t spec = SPECIFIER_NONE;
5715 char const *c = suffix;
5718 if (*c == 'L' || *c == 'l') {
5719 add = SPECIFIER_LONG;
5721 add |= SPECIFIER_LONG_LONG;
5724 } else if (*c == 'U' || *c == 'u') {
5725 add = SPECIFIER_UNSIGNED;
5738 case SPECIFIER_NONE: type = type_int; break;
5739 case SPECIFIER_LONG: type = type_long; break;
5740 case SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long; break;
5741 case SPECIFIER_UNSIGNED: type = type_unsigned_int; break;
5742 case SPECIFIER_UNSIGNED | SPECIFIER_LONG: type = type_unsigned_long; break;
5743 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5744 default: panic("inconsistent suffix");
5746 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG) {
5747 warn_traditional_suffix(suffix);
5749 expr->base.type = type;
5750 /* Integer type depends on the size of the number and the size
5751 * representable by the types. The backend/codegeneration has to
5752 * determine that. */
5753 determine_literal_type(&expr->literal);
5756 errorf(HERE, "invalid suffix '%s' on integer constant", suffix);
5760 static void check_floatingpoint_suffix(expression_t *const expr, char const *const suffix)
5763 char const *c = suffix;
5766 case 'f': type = type_float; ++c; break;
5768 case 'l': type = type_long_double; ++c; break;
5769 default: type = type_double; break;
5773 expr->base.type = type;
5774 if (suffix[0] != '\0') {
5775 warn_traditional_suffix(suffix);
5778 errorf(HERE, "invalid suffix '%s' on floatingpoint constant", suffix);
5782 static expression_t *parse_number_literal(void)
5784 string_t const *const str = &token.literal.string;
5785 char const * i = str->begin;
5786 unsigned digits = 0;
5787 bool is_float = false;
5789 /* Parse base prefix. */
5793 case 'B': case 'b': base = 2; ++i; break;
5794 case 'X': case 'x': base = 16; ++i; break;
5795 default: base = 8; digits |= 1U << 0; break;
5801 /* Parse mantissa. */
5807 errorf(HERE, "multiple decimal points in %K", &token);
5816 case '0': digit = 0; break;
5817 case '1': digit = 1; break;
5818 case '2': digit = 2; break;
5819 case '3': digit = 3; break;
5820 case '4': digit = 4; break;
5821 case '5': digit = 5; break;
5822 case '6': digit = 6; break;
5823 case '7': digit = 7; break;
5824 case '8': digit = 8; break;
5825 case '9': digit = 9; break;
5826 case 'A': case 'a': digit = 10; break;
5827 case 'B': case 'b': digit = 11; break;
5828 case 'C': case 'c': digit = 12; break;
5829 case 'D': case 'd': digit = 13; break;
5830 case 'E': case 'e': digit = 14; break;
5831 case 'F': case 'f': digit = 15; break;
5833 default: goto done_mantissa;
5836 if (digit >= 10 && base != 16)
5839 digits |= 1U << digit;
5843 /* Parse exponent. */
5847 errorf(HERE, "binary floating %K not allowed", &token);
5852 if (*i == 'E' || *i == 'e') {
5854 goto parse_exponent;
5859 if (*i == 'P' || *i == 'p') {
5864 if (*i == '-' || *i == '+')
5870 } while (isdigit(*i));
5872 errorf(HERE, "exponent of %K has no digits", &token);
5874 } else if (is_float) {
5875 errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5881 panic("invalid base");
5885 expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5886 expr->literal.value = *str;
5890 errorf(HERE, "%K has no digits", &token);
5891 } else if (digits & ~((1U << base) - 1)) {
5892 errorf(HERE, "invalid digit in %K", &token);
5894 expr->literal.suffix = i;
5896 check_floatingpoint_suffix(expr, i);
5898 check_integer_suffix(expr, i);
5908 * Parse a character constant.
5910 static expression_t *parse_character_constant(void)
5912 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5913 literal->string_literal.value = token.literal.string;
5915 size_t const size = get_string_len(&token.literal.string);
5916 switch (token.literal.string.encoding) {
5917 case STRING_ENCODING_CHAR:
5918 literal->base.type = c_mode & _CXX ? type_char : type_int;
5920 if (!GNU_MODE && !(c_mode & _C99)) {
5921 errorf(HERE, "more than 1 character in character constant");
5923 literal->base.type = type_int;
5924 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5929 case STRING_ENCODING_WIDE:
5930 literal->base.type = type_int;
5932 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5937 eat(T_CHARACTER_CONSTANT);
5941 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5943 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5944 ntype->function.return_type = type_int;
5945 ntype->function.unspecified_parameters = true;
5946 ntype->function.linkage = LINKAGE_C;
5947 type_t *type = identify_new_type(ntype);
5949 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5950 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5951 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5952 entity->declaration.type = type;
5953 entity->declaration.implicit = true;
5955 if (current_scope != NULL)
5956 record_entity(entity, false);
5962 * Performs automatic type cast as described in §6.3.2.1.
5964 * @param orig_type the original type
5966 static type_t *automatic_type_conversion(type_t *orig_type)
5968 type_t *type = skip_typeref(orig_type);
5969 if (is_type_array(type)) {
5970 array_type_t *array_type = &type->array;
5971 type_t *element_type = array_type->element_type;
5972 unsigned qualifiers = array_type->base.qualifiers;
5974 return make_pointer_type(element_type, qualifiers);
5977 if (is_type_function(type)) {
5978 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5985 * reverts the automatic casts of array to pointer types and function
5986 * to function-pointer types as defined §6.3.2.1
5988 type_t *revert_automatic_type_conversion(const expression_t *expression)
5990 switch (expression->kind) {
5991 case EXPR_REFERENCE: {
5992 entity_t *entity = expression->reference.entity;
5993 if (is_declaration(entity)) {
5994 return entity->declaration.type;
5995 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5996 return entity->enum_value.enum_type;
5998 panic("no declaration or enum in reference");
6003 entity_t *entity = expression->select.compound_entry;
6004 assert(is_declaration(entity));
6005 type_t *type = entity->declaration.type;
6006 return get_qualified_type(type, expression->base.type->base.qualifiers);
6009 case EXPR_UNARY_DEREFERENCE: {
6010 const expression_t *const value = expression->unary.value;
6011 type_t *const type = skip_typeref(value->base.type);
6012 if (!is_type_pointer(type))
6013 return type_error_type;
6014 return type->pointer.points_to;
6017 case EXPR_ARRAY_ACCESS: {
6018 const expression_t *array_ref = expression->array_access.array_ref;
6019 type_t *type_left = skip_typeref(array_ref->base.type);
6020 if (!is_type_pointer(type_left))
6021 return type_error_type;
6022 return type_left->pointer.points_to;
6025 case EXPR_STRING_LITERAL: {
6026 size_t const size = get_string_len(&expression->string_literal.value) + 1;
6027 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
6028 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
6031 case EXPR_COMPOUND_LITERAL:
6032 return expression->compound_literal.type;
6037 return expression->base.type;
6041 * Find an entity matching a symbol in a scope.
6042 * Uses current scope if scope is NULL
6044 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6045 namespace_tag_t namespc)
6047 if (scope == NULL) {
6048 return get_entity(symbol, namespc);
6051 /* we should optimize here, if scope grows above a certain size we should
6052 construct a hashmap here... */
6053 entity_t *entity = scope->entities;
6054 for ( ; entity != NULL; entity = entity->base.next) {
6055 if (entity->base.symbol == symbol
6056 && (namespace_tag_t)entity->base.namespc == namespc)
6063 static entity_t *parse_qualified_identifier(void)
6065 /* namespace containing the symbol */
6067 source_position_t pos;
6068 const scope_t *lookup_scope = NULL;
6070 if (next_if(T_COLONCOLON))
6071 lookup_scope = &unit->scope;
6075 symbol = expect_identifier("while parsing identifier", &pos);
6077 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6080 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6082 if (!next_if(T_COLONCOLON))
6085 switch (entity->kind) {
6086 case ENTITY_NAMESPACE:
6087 lookup_scope = &entity->namespacee.members;
6092 lookup_scope = &entity->compound.members;
6095 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6096 symbol, get_entity_kind_name(entity->kind));
6098 /* skip further qualifications */
6099 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6101 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6105 if (entity == NULL) {
6106 if (!strict_mode && token.kind == '(') {
6107 /* an implicitly declared function */
6108 entity = create_implicit_function(symbol, &pos);
6109 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6111 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6112 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6119 static expression_t *parse_reference(void)
6121 source_position_t const pos = *HERE;
6122 entity_t *const entity = parse_qualified_identifier();
6125 if (is_declaration(entity)) {
6126 orig_type = entity->declaration.type;
6127 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6128 orig_type = entity->enum_value.enum_type;
6130 panic("expected declaration or enum value in reference");
6133 /* we always do the auto-type conversions; the & and sizeof parser contains
6134 * code to revert this! */
6135 type_t *type = automatic_type_conversion(orig_type);
6137 expression_kind_t kind = EXPR_REFERENCE;
6138 if (entity->kind == ENTITY_ENUM_VALUE)
6139 kind = EXPR_ENUM_CONSTANT;
6141 expression_t *expression = allocate_expression_zero(kind);
6142 expression->base.source_position = pos;
6143 expression->base.type = type;
6144 expression->reference.entity = entity;
6146 /* this declaration is used */
6147 if (is_declaration(entity)) {
6148 entity->declaration.used = true;
6151 if (entity->base.parent_scope != file_scope
6152 && (current_function != NULL
6153 && entity->base.parent_scope->depth < current_function->parameters.depth)
6154 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6155 /* access of a variable from an outer function */
6156 entity->variable.address_taken = true;
6157 current_function->need_closure = true;
6160 check_deprecated(&pos, entity);
6165 static bool semantic_cast(expression_t *cast)
6167 expression_t *expression = cast->unary.value;
6168 type_t *orig_dest_type = cast->base.type;
6169 type_t *orig_type_right = expression->base.type;
6170 type_t const *dst_type = skip_typeref(orig_dest_type);
6171 type_t const *src_type = skip_typeref(orig_type_right);
6172 source_position_t const *pos = &cast->base.source_position;
6174 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6175 if (is_type_void(dst_type))
6178 /* only integer and pointer can be casted to pointer */
6179 if (is_type_pointer(dst_type) &&
6180 !is_type_pointer(src_type) &&
6181 !is_type_integer(src_type) &&
6182 is_type_valid(src_type)) {
6183 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6187 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6188 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6192 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6193 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6197 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6198 type_t *src = skip_typeref(src_type->pointer.points_to);
6199 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6200 unsigned missing_qualifiers =
6201 src->base.qualifiers & ~dst->base.qualifiers;
6202 if (missing_qualifiers != 0) {
6203 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6209 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6211 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6212 expression->base.source_position = *pos;
6214 parse_initializer_env_t env;
6217 env.must_be_constant = false;
6218 initializer_t *initializer = parse_initializer(&env);
6221 expression->compound_literal.initializer = initializer;
6222 expression->compound_literal.type = type;
6223 expression->base.type = automatic_type_conversion(type);
6229 * Parse a cast expression.
6231 static expression_t *parse_cast(void)
6233 source_position_t const pos = *HERE;
6236 add_anchor_token(')');
6238 type_t *type = parse_typename();
6240 rem_anchor_token(')');
6243 if (token.kind == '{') {
6244 return parse_compound_literal(&pos, type);
6247 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6248 cast->base.source_position = pos;
6250 expression_t *value = parse_subexpression(PREC_CAST);
6251 cast->base.type = type;
6252 cast->unary.value = value;
6254 if (! semantic_cast(cast)) {
6255 /* TODO: record the error in the AST. else it is impossible to detect it */
6262 * Parse a statement expression.
6264 static expression_t *parse_statement_expression(void)
6266 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6269 add_anchor_token(')');
6271 statement_t *statement = parse_compound_statement(true);
6272 statement->compound.stmt_expr = true;
6273 expression->statement.statement = statement;
6275 /* find last statement and use its type */
6276 type_t *type = type_void;
6277 const statement_t *stmt = statement->compound.statements;
6279 while (stmt->base.next != NULL)
6280 stmt = stmt->base.next;
6282 if (stmt->kind == STATEMENT_EXPRESSION) {
6283 type = stmt->expression.expression->base.type;
6286 source_position_t const *const pos = &expression->base.source_position;
6287 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6289 expression->base.type = type;
6291 rem_anchor_token(')');
6297 * Parse a parenthesized expression.
6299 static expression_t *parse_parenthesized_expression(void)
6301 token_t const* const la1 = look_ahead(1);
6302 switch (la1->kind) {
6304 /* gcc extension: a statement expression */
6305 return parse_statement_expression();
6308 if (is_typedef_symbol(la1->base.symbol)) {
6310 return parse_cast();
6315 add_anchor_token(')');
6316 expression_t *result = parse_expression();
6317 result->base.parenthesized = true;
6318 rem_anchor_token(')');
6324 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6326 if (current_function == NULL) {
6327 errorf(HERE, "'%K' used outside of a function", &token);
6330 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6331 expression->base.type = type_char_ptr;
6332 expression->funcname.kind = kind;
6339 static designator_t *parse_designator(void)
6341 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6342 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6343 if (!result->symbol)
6346 designator_t *last_designator = result;
6349 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6350 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6351 if (!designator->symbol)
6354 last_designator->next = designator;
6355 last_designator = designator;
6359 add_anchor_token(']');
6360 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6361 designator->source_position = *HERE;
6362 designator->array_index = parse_expression();
6363 rem_anchor_token(']');
6365 if (designator->array_index == NULL) {
6369 last_designator->next = designator;
6370 last_designator = designator;
6380 * Parse the __builtin_offsetof() expression.
6382 static expression_t *parse_offsetof(void)
6384 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6385 expression->base.type = type_size_t;
6387 eat(T___builtin_offsetof);
6389 add_anchor_token(')');
6390 add_anchor_token(',');
6392 type_t *type = parse_typename();
6393 rem_anchor_token(',');
6395 designator_t *designator = parse_designator();
6396 rem_anchor_token(')');
6399 expression->offsetofe.type = type;
6400 expression->offsetofe.designator = designator;
6403 memset(&path, 0, sizeof(path));
6404 path.top_type = type;
6405 path.path = NEW_ARR_F(type_path_entry_t, 0);
6407 descend_into_subtype(&path);
6409 if (!walk_designator(&path, designator, true)) {
6410 return create_error_expression();
6413 DEL_ARR_F(path.path);
6418 static bool is_last_parameter(expression_t *const param)
6420 if (param->kind == EXPR_REFERENCE) {
6421 entity_t *const entity = param->reference.entity;
6422 if (entity->kind == ENTITY_PARAMETER &&
6423 !entity->base.next &&
6424 entity->base.parent_scope == ¤t_function->parameters) {
6429 if (!is_type_valid(skip_typeref(param->base.type)))
6436 * Parses a __builtin_va_start() expression.
6438 static expression_t *parse_va_start(void)
6440 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6442 eat(T___builtin_va_start);
6444 add_anchor_token(')');
6445 add_anchor_token(',');
6447 expression->va_starte.ap = parse_assignment_expression();
6448 rem_anchor_token(',');
6450 expression_t *const param = parse_assignment_expression();
6451 expression->va_starte.parameter = param;
6452 rem_anchor_token(')');
6455 if (!current_function) {
6456 errorf(&expression->base.source_position, "'va_start' used outside of function");
6457 } else if (!current_function->base.type->function.variadic) {
6458 errorf(&expression->base.source_position, "'va_start' used in non-variadic function");
6459 } else if (!is_last_parameter(param)) {
6460 errorf(¶m->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
6467 * Parses a __builtin_va_arg() expression.
6469 static expression_t *parse_va_arg(void)
6471 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6473 eat(T___builtin_va_arg);
6475 add_anchor_token(')');
6476 add_anchor_token(',');
6479 ap.expression = parse_assignment_expression();
6480 expression->va_arge.ap = ap.expression;
6481 check_call_argument(type_valist, &ap, 1);
6483 rem_anchor_token(',');
6485 expression->base.type = parse_typename();
6486 rem_anchor_token(')');
6493 * Parses a __builtin_va_copy() expression.
6495 static expression_t *parse_va_copy(void)
6497 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6499 eat(T___builtin_va_copy);
6501 add_anchor_token(')');
6502 add_anchor_token(',');
6504 expression_t *dst = parse_assignment_expression();
6505 assign_error_t error = semantic_assign(type_valist, dst);
6506 report_assign_error(error, type_valist, dst, "call argument 1",
6507 &dst->base.source_position);
6508 expression->va_copye.dst = dst;
6510 rem_anchor_token(',');
6513 call_argument_t src;
6514 src.expression = parse_assignment_expression();
6515 check_call_argument(type_valist, &src, 2);
6516 expression->va_copye.src = src.expression;
6517 rem_anchor_token(')');
6524 * Parses a __builtin_constant_p() expression.
6526 static expression_t *parse_builtin_constant(void)
6528 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6530 eat(T___builtin_constant_p);
6532 add_anchor_token(')');
6534 expression->builtin_constant.value = parse_assignment_expression();
6535 rem_anchor_token(')');
6537 expression->base.type = type_int;
6543 * Parses a __builtin_types_compatible_p() expression.
6545 static expression_t *parse_builtin_types_compatible(void)
6547 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6549 eat(T___builtin_types_compatible_p);
6551 add_anchor_token(')');
6552 add_anchor_token(',');
6554 expression->builtin_types_compatible.left = parse_typename();
6555 rem_anchor_token(',');
6557 expression->builtin_types_compatible.right = parse_typename();
6558 rem_anchor_token(')');
6560 expression->base.type = type_int;
6566 * Parses a __builtin_is_*() compare expression.
6568 static expression_t *parse_compare_builtin(void)
6570 expression_kind_t kind;
6571 switch (token.kind) {
6572 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6573 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6574 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6575 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6576 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6577 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6578 default: internal_errorf(HERE, "invalid compare builtin found");
6580 expression_t *const expression = allocate_expression_zero(kind);
6583 add_anchor_token(')');
6584 add_anchor_token(',');
6586 expression->binary.left = parse_assignment_expression();
6587 rem_anchor_token(',');
6589 expression->binary.right = parse_assignment_expression();
6590 rem_anchor_token(')');
6593 type_t *const orig_type_left = expression->binary.left->base.type;
6594 type_t *const orig_type_right = expression->binary.right->base.type;
6596 type_t *const type_left = skip_typeref(orig_type_left);
6597 type_t *const type_right = skip_typeref(orig_type_right);
6598 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6599 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6600 type_error_incompatible("invalid operands in comparison",
6601 &expression->base.source_position, orig_type_left, orig_type_right);
6604 semantic_comparison(&expression->binary);
6611 * Parses a MS assume() expression.
6613 static expression_t *parse_assume(void)
6615 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6619 add_anchor_token(')');
6621 expression->unary.value = parse_assignment_expression();
6622 rem_anchor_token(')');
6625 expression->base.type = type_void;
6630 * Return the label for the current symbol or create a new one.
6632 static label_t *get_label(char const *const context)
6634 assert(current_function != NULL);
6636 symbol_t *const sym = expect_identifier(context, NULL);
6640 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6641 /* If we find a local label, we already created the declaration. */
6642 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6643 if (label->base.parent_scope != current_scope) {
6644 assert(label->base.parent_scope->depth < current_scope->depth);
6645 current_function->goto_to_outer = true;
6647 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6648 /* There is no matching label in the same function, so create a new one. */
6649 source_position_t const nowhere = { NULL, 0, 0, false };
6650 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6654 return &label->label;
6658 * Parses a GNU && label address expression.
6660 static expression_t *parse_label_address(void)
6662 source_position_t const source_position = *HERE;
6665 label_t *const label = get_label("while parsing label address");
6667 return create_error_expression();
6670 label->address_taken = true;
6672 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6673 expression->base.source_position = source_position;
6675 /* label address is treated as a void pointer */
6676 expression->base.type = type_void_ptr;
6677 expression->label_address.label = label;
6682 * Parse a microsoft __noop expression.
6684 static expression_t *parse_noop_expression(void)
6686 /* the result is a (int)0 */
6687 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6688 literal->base.type = type_int;
6689 literal->literal.value.begin = "__noop";
6690 literal->literal.value.size = 6;
6694 if (token.kind == '(') {
6695 /* parse arguments */
6697 add_anchor_token(')');
6698 add_anchor_token(',');
6700 if (token.kind != ')') do {
6701 (void)parse_assignment_expression();
6702 } while (next_if(','));
6704 rem_anchor_token(',');
6705 rem_anchor_token(')');
6713 * Parses a primary expression.
6715 static expression_t *parse_primary_expression(void)
6717 switch (token.kind) {
6718 case T_false: return parse_boolean_literal(false);
6719 case T_true: return parse_boolean_literal(true);
6720 case T_NUMBER: return parse_number_literal();
6721 case T_CHARACTER_CONSTANT: return parse_character_constant();
6722 case T_STRING_LITERAL: return parse_string_literal();
6723 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6724 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6725 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6726 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6727 case T___builtin_offsetof: return parse_offsetof();
6728 case T___builtin_va_start: return parse_va_start();
6729 case T___builtin_va_arg: return parse_va_arg();
6730 case T___builtin_va_copy: return parse_va_copy();
6731 case T___builtin_isgreater:
6732 case T___builtin_isgreaterequal:
6733 case T___builtin_isless:
6734 case T___builtin_islessequal:
6735 case T___builtin_islessgreater:
6736 case T___builtin_isunordered: return parse_compare_builtin();
6737 case T___builtin_constant_p: return parse_builtin_constant();
6738 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6739 case T__assume: return parse_assume();
6742 return parse_label_address();
6745 case '(': return parse_parenthesized_expression();
6746 case T___noop: return parse_noop_expression();
6748 /* Gracefully handle type names while parsing expressions. */
6750 return parse_reference();
6752 if (!is_typedef_symbol(token.base.symbol)) {
6753 return parse_reference();
6757 source_position_t const pos = *HERE;
6758 declaration_specifiers_t specifiers;
6759 parse_declaration_specifiers(&specifiers);
6760 type_t const *const type = parse_abstract_declarator(specifiers.type);
6761 errorf(&pos, "encountered type '%T' while parsing expression", type);
6762 return create_error_expression();
6766 errorf(HERE, "unexpected token %K, expected an expression", &token);
6768 return create_error_expression();
6771 static expression_t *parse_array_expression(expression_t *left)
6773 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6774 array_access_expression_t *const arr = &expr->array_access;
6777 add_anchor_token(']');
6779 expression_t *const inside = parse_expression();
6781 type_t *const orig_type_left = left->base.type;
6782 type_t *const orig_type_inside = inside->base.type;
6784 type_t *const type_left = skip_typeref(orig_type_left);
6785 type_t *const type_inside = skip_typeref(orig_type_inside);
6791 if (is_type_pointer(type_left)) {
6794 idx_type = type_inside;
6795 res_type = type_left->pointer.points_to;
6797 } else if (is_type_pointer(type_inside)) {
6798 arr->flipped = true;
6801 idx_type = type_left;
6802 res_type = type_inside->pointer.points_to;
6804 res_type = automatic_type_conversion(res_type);
6805 if (!is_type_integer(idx_type)) {
6806 errorf(&idx->base.source_position, "array subscript must have integer type");
6807 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6808 source_position_t const *const pos = &idx->base.source_position;
6809 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6812 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6813 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6815 res_type = type_error_type;
6820 arr->array_ref = ref;
6822 arr->base.type = res_type;
6824 rem_anchor_token(']');
6829 static bool is_bitfield(const expression_t *expression)
6831 return expression->kind == EXPR_SELECT
6832 && expression->select.compound_entry->compound_member.bitfield;
6835 static expression_t *parse_typeprop(expression_kind_t const kind)
6837 expression_t *tp_expression = allocate_expression_zero(kind);
6838 tp_expression->base.type = type_size_t;
6840 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6843 expression_t *expression;
6844 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6845 source_position_t const pos = *HERE;
6847 add_anchor_token(')');
6848 orig_type = parse_typename();
6849 rem_anchor_token(')');
6852 if (token.kind == '{') {
6853 /* It was not sizeof(type) after all. It is sizeof of an expression
6854 * starting with a compound literal */
6855 expression = parse_compound_literal(&pos, orig_type);
6856 goto typeprop_expression;
6859 expression = parse_subexpression(PREC_UNARY);
6861 typeprop_expression:
6862 if (is_bitfield(expression)) {
6863 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6864 errorf(&tp_expression->base.source_position,
6865 "operand of %s expression must not be a bitfield", what);
6868 tp_expression->typeprop.tp_expression = expression;
6870 orig_type = revert_automatic_type_conversion(expression);
6871 expression->base.type = orig_type;
6874 tp_expression->typeprop.type = orig_type;
6875 type_t const* const type = skip_typeref(orig_type);
6876 char const* wrong_type = NULL;
6877 if (is_type_incomplete(type)) {
6878 if (!is_type_void(type) || !GNU_MODE)
6879 wrong_type = "incomplete";
6880 } else if (type->kind == TYPE_FUNCTION) {
6882 /* function types are allowed (and return 1) */
6883 source_position_t const *const pos = &tp_expression->base.source_position;
6884 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6885 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6887 wrong_type = "function";
6891 if (wrong_type != NULL) {
6892 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6893 errorf(&tp_expression->base.source_position,
6894 "operand of %s expression must not be of %s type '%T'",
6895 what, wrong_type, orig_type);
6898 return tp_expression;
6901 static expression_t *parse_sizeof(void)
6903 return parse_typeprop(EXPR_SIZEOF);
6906 static expression_t *parse_alignof(void)
6908 return parse_typeprop(EXPR_ALIGNOF);
6911 static expression_t *parse_select_expression(expression_t *addr)
6913 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6914 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6915 source_position_t const pos = *HERE;
6918 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6920 return create_error_expression();
6922 type_t *const orig_type = addr->base.type;
6923 type_t *const type = skip_typeref(orig_type);
6926 bool saw_error = false;
6927 if (is_type_pointer(type)) {
6928 if (!select_left_arrow) {
6930 "request for member '%Y' in something not a struct or union, but '%T'",
6934 type_left = skip_typeref(type->pointer.points_to);
6936 if (select_left_arrow && is_type_valid(type)) {
6937 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6943 if (!is_type_compound(type_left)) {
6944 if (is_type_valid(type_left) && !saw_error) {
6946 "request for member '%Y' in something not a struct or union, but '%T'",
6949 return create_error_expression();
6952 compound_t *compound = type_left->compound.compound;
6953 if (!compound->complete) {
6954 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6956 return create_error_expression();
6959 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6960 expression_t *result =
6961 find_create_select(&pos, addr, qualifiers, compound, symbol);
6963 if (result == NULL) {
6964 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6965 return create_error_expression();
6971 static void check_call_argument(type_t *expected_type,
6972 call_argument_t *argument, unsigned pos)
6974 type_t *expected_type_skip = skip_typeref(expected_type);
6975 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6976 expression_t *arg_expr = argument->expression;
6977 type_t *arg_type = skip_typeref(arg_expr->base.type);
6979 /* handle transparent union gnu extension */
6980 if (is_type_union(expected_type_skip)
6981 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6982 compound_t *union_decl = expected_type_skip->compound.compound;
6983 type_t *best_type = NULL;
6984 entity_t *entry = union_decl->members.entities;
6985 for ( ; entry != NULL; entry = entry->base.next) {
6986 assert(is_declaration(entry));
6987 type_t *decl_type = entry->declaration.type;
6988 error = semantic_assign(decl_type, arg_expr);
6989 if (error == ASSIGN_ERROR_INCOMPATIBLE
6990 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6993 if (error == ASSIGN_SUCCESS) {
6994 best_type = decl_type;
6995 } else if (best_type == NULL) {
6996 best_type = decl_type;
7000 if (best_type != NULL) {
7001 expected_type = best_type;
7005 error = semantic_assign(expected_type, arg_expr);
7006 argument->expression = create_implicit_cast(arg_expr, expected_type);
7008 if (error != ASSIGN_SUCCESS) {
7009 /* report exact scope in error messages (like "in argument 3") */
7011 snprintf(buf, sizeof(buf), "call argument %u", pos);
7012 report_assign_error(error, expected_type, arg_expr, buf,
7013 &arg_expr->base.source_position);
7015 type_t *const promoted_type = get_default_promoted_type(arg_type);
7016 if (!types_compatible(expected_type_skip, promoted_type) &&
7017 !types_compatible(expected_type_skip, type_void_ptr) &&
7018 !types_compatible(type_void_ptr, promoted_type)) {
7019 /* Deliberately show the skipped types in this warning */
7020 source_position_t const *const apos = &arg_expr->base.source_position;
7021 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7027 * Handle the semantic restrictions of builtin calls
7029 static void handle_builtin_argument_restrictions(call_expression_t *call)
7031 entity_t *entity = call->function->reference.entity;
7032 switch (entity->function.btk) {
7034 switch (entity->function.b.firm_builtin_kind) {
7035 case ir_bk_return_address:
7036 case ir_bk_frame_address: {
7037 /* argument must be constant */
7038 call_argument_t *argument = call->arguments;
7040 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7041 errorf(&call->base.source_position,
7042 "argument of '%Y' must be a constant expression",
7043 call->function->reference.entity->base.symbol);
7047 case ir_bk_prefetch:
7048 /* second and third argument must be constant if existent */
7049 if (call->arguments == NULL)
7051 call_argument_t *rw = call->arguments->next;
7052 call_argument_t *locality = NULL;
7055 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7056 errorf(&call->base.source_position,
7057 "second argument of '%Y' must be a constant expression",
7058 call->function->reference.entity->base.symbol);
7060 locality = rw->next;
7062 if (locality != NULL) {
7063 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7064 errorf(&call->base.source_position,
7065 "third argument of '%Y' must be a constant expression",
7066 call->function->reference.entity->base.symbol);
7068 locality = rw->next;
7075 case BUILTIN_OBJECT_SIZE:
7076 if (call->arguments == NULL)
7079 call_argument_t *arg = call->arguments->next;
7080 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7081 errorf(&call->base.source_position,
7082 "second argument of '%Y' must be a constant expression",
7083 call->function->reference.entity->base.symbol);
7092 * Parse a call expression, ie. expression '( ... )'.
7094 * @param expression the function address
7096 static expression_t *parse_call_expression(expression_t *expression)
7098 expression_t *result = allocate_expression_zero(EXPR_CALL);
7099 call_expression_t *call = &result->call;
7100 call->function = expression;
7102 type_t *const orig_type = expression->base.type;
7103 type_t *const type = skip_typeref(orig_type);
7105 function_type_t *function_type = NULL;
7106 if (is_type_pointer(type)) {
7107 type_t *const to_type = skip_typeref(type->pointer.points_to);
7109 if (is_type_function(to_type)) {
7110 function_type = &to_type->function;
7111 call->base.type = function_type->return_type;
7115 if (function_type == NULL && is_type_valid(type)) {
7117 "called object '%E' (type '%T') is not a pointer to a function",
7118 expression, orig_type);
7121 /* parse arguments */
7123 add_anchor_token(')');
7124 add_anchor_token(',');
7126 if (token.kind != ')') {
7127 call_argument_t **anchor = &call->arguments;
7129 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7130 argument->expression = parse_assignment_expression();
7133 anchor = &argument->next;
7134 } while (next_if(','));
7136 rem_anchor_token(',');
7137 rem_anchor_token(')');
7140 if (function_type == NULL)
7143 /* check type and count of call arguments */
7144 function_parameter_t *parameter = function_type->parameters;
7145 call_argument_t *argument = call->arguments;
7146 if (!function_type->unspecified_parameters) {
7147 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7148 parameter = parameter->next, argument = argument->next) {
7149 check_call_argument(parameter->type, argument, ++pos);
7152 if (parameter != NULL) {
7153 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7154 } else if (argument != NULL && !function_type->variadic) {
7155 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7159 /* do default promotion for other arguments */
7160 for (; argument != NULL; argument = argument->next) {
7161 type_t *argument_type = argument->expression->base.type;
7162 if (!is_type_object(skip_typeref(argument_type))) {
7163 errorf(&argument->expression->base.source_position,
7164 "call argument '%E' must not be void", argument->expression);
7167 argument_type = get_default_promoted_type(argument_type);
7169 argument->expression
7170 = create_implicit_cast(argument->expression, argument_type);
7175 if (is_type_compound(skip_typeref(function_type->return_type))) {
7176 source_position_t const *const pos = &expression->base.source_position;
7177 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7180 if (expression->kind == EXPR_REFERENCE) {
7181 reference_expression_t *reference = &expression->reference;
7182 if (reference->entity->kind == ENTITY_FUNCTION &&
7183 reference->entity->function.btk != BUILTIN_NONE)
7184 handle_builtin_argument_restrictions(call);
7190 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7192 static bool same_compound_type(const type_t *type1, const type_t *type2)
7195 is_type_compound(type1) &&
7196 type1->kind == type2->kind &&
7197 type1->compound.compound == type2->compound.compound;
7200 static expression_t const *get_reference_address(expression_t const *expr)
7202 bool regular_take_address = true;
7204 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7205 expr = expr->unary.value;
7207 regular_take_address = false;
7210 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7213 expr = expr->unary.value;
7216 if (expr->kind != EXPR_REFERENCE)
7219 /* special case for functions which are automatically converted to a
7220 * pointer to function without an extra TAKE_ADDRESS operation */
7221 if (!regular_take_address &&
7222 expr->reference.entity->kind != ENTITY_FUNCTION) {
7229 static void warn_reference_address_as_bool(expression_t const* expr)
7231 expr = get_reference_address(expr);
7233 source_position_t const *const pos = &expr->base.source_position;
7234 entity_t const *const ent = expr->reference.entity;
7235 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7239 static void warn_assignment_in_condition(const expression_t *const expr)
7241 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7243 if (expr->base.parenthesized)
7245 source_position_t const *const pos = &expr->base.source_position;
7246 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7249 static void semantic_condition(expression_t const *const expr,
7250 char const *const context)
7252 type_t *const type = skip_typeref(expr->base.type);
7253 if (is_type_scalar(type)) {
7254 warn_reference_address_as_bool(expr);
7255 warn_assignment_in_condition(expr);
7256 } else if (is_type_valid(type)) {
7257 errorf(&expr->base.source_position,
7258 "%s must have scalar type", context);
7263 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7265 * @param expression the conditional expression
7267 static expression_t *parse_conditional_expression(expression_t *expression)
7269 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7271 conditional_expression_t *conditional = &result->conditional;
7272 conditional->condition = expression;
7275 add_anchor_token(':');
7277 /* §6.5.15:2 The first operand shall have scalar type. */
7278 semantic_condition(expression, "condition of conditional operator");
7280 expression_t *true_expression = expression;
7281 bool gnu_cond = false;
7282 if (GNU_MODE && token.kind == ':') {
7285 true_expression = parse_expression();
7287 rem_anchor_token(':');
7289 expression_t *false_expression =
7290 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7292 type_t *const orig_true_type = true_expression->base.type;
7293 type_t *const orig_false_type = false_expression->base.type;
7294 type_t *const true_type = skip_typeref(orig_true_type);
7295 type_t *const false_type = skip_typeref(orig_false_type);
7298 source_position_t const *const pos = &conditional->base.source_position;
7299 type_t *result_type;
7300 if (is_type_void(true_type) || is_type_void(false_type)) {
7301 /* ISO/IEC 14882:1998(E) §5.16:2 */
7302 if (true_expression->kind == EXPR_UNARY_THROW) {
7303 result_type = false_type;
7304 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7305 result_type = true_type;
7307 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7308 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7310 result_type = type_void;
7312 } else if (is_type_arithmetic(true_type)
7313 && is_type_arithmetic(false_type)) {
7314 result_type = semantic_arithmetic(true_type, false_type);
7315 } else if (same_compound_type(true_type, false_type)) {
7316 /* just take 1 of the 2 types */
7317 result_type = true_type;
7318 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7319 type_t *pointer_type;
7321 expression_t *other_expression;
7322 if (is_type_pointer(true_type) &&
7323 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7324 pointer_type = true_type;
7325 other_type = false_type;
7326 other_expression = false_expression;
7328 pointer_type = false_type;
7329 other_type = true_type;
7330 other_expression = true_expression;
7333 if (is_null_pointer_constant(other_expression)) {
7334 result_type = pointer_type;
7335 } else if (is_type_pointer(other_type)) {
7336 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7337 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7340 if (is_type_void(to1) || is_type_void(to2)) {
7342 } else if (types_compatible(get_unqualified_type(to1),
7343 get_unqualified_type(to2))) {
7346 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7350 type_t *const type =
7351 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7352 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7353 } else if (is_type_integer(other_type)) {
7354 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7355 result_type = pointer_type;
7357 goto types_incompatible;
7361 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7362 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7364 result_type = type_error_type;
7367 conditional->true_expression
7368 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7369 conditional->false_expression
7370 = create_implicit_cast(false_expression, result_type);
7371 conditional->base.type = result_type;
7376 * Parse an extension expression.
7378 static expression_t *parse_extension(void)
7381 expression_t *expression = parse_subexpression(PREC_UNARY);
7387 * Parse a __builtin_classify_type() expression.
7389 static expression_t *parse_builtin_classify_type(void)
7391 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7392 result->base.type = type_int;
7394 eat(T___builtin_classify_type);
7396 add_anchor_token(')');
7398 expression_t *expression = parse_expression();
7399 rem_anchor_token(')');
7401 result->classify_type.type_expression = expression;
7407 * Parse a delete expression
7408 * ISO/IEC 14882:1998(E) §5.3.5
7410 static expression_t *parse_delete(void)
7412 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7413 result->base.type = type_void;
7418 result->kind = EXPR_UNARY_DELETE_ARRAY;
7422 expression_t *const value = parse_subexpression(PREC_CAST);
7423 result->unary.value = value;
7425 type_t *const type = skip_typeref(value->base.type);
7426 if (!is_type_pointer(type)) {
7427 if (is_type_valid(type)) {
7428 errorf(&value->base.source_position,
7429 "operand of delete must have pointer type");
7431 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7432 source_position_t const *const pos = &value->base.source_position;
7433 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7440 * Parse a throw expression
7441 * ISO/IEC 14882:1998(E) §15:1
7443 static expression_t *parse_throw(void)
7445 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7446 result->base.type = type_void;
7450 expression_t *value = NULL;
7451 switch (token.kind) {
7453 value = parse_assignment_expression();
7454 /* ISO/IEC 14882:1998(E) §15.1:3 */
7455 type_t *const orig_type = value->base.type;
7456 type_t *const type = skip_typeref(orig_type);
7457 if (is_type_incomplete(type)) {
7458 errorf(&value->base.source_position,
7459 "cannot throw object of incomplete type '%T'", orig_type);
7460 } else if (is_type_pointer(type)) {
7461 type_t *const points_to = skip_typeref(type->pointer.points_to);
7462 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7463 errorf(&value->base.source_position,
7464 "cannot throw pointer to incomplete type '%T'", orig_type);
7472 result->unary.value = value;
7477 static bool check_pointer_arithmetic(const source_position_t *source_position,
7478 type_t *pointer_type,
7479 type_t *orig_pointer_type)
7481 type_t *points_to = pointer_type->pointer.points_to;
7482 points_to = skip_typeref(points_to);
7484 if (is_type_incomplete(points_to)) {
7485 if (!GNU_MODE || !is_type_void(points_to)) {
7486 errorf(source_position,
7487 "arithmetic with pointer to incomplete type '%T' not allowed",
7491 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7493 } else if (is_type_function(points_to)) {
7495 errorf(source_position,
7496 "arithmetic with pointer to function type '%T' not allowed",
7500 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7506 static bool is_lvalue(const expression_t *expression)
7508 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7509 switch (expression->kind) {
7510 case EXPR_ARRAY_ACCESS:
7511 case EXPR_COMPOUND_LITERAL:
7512 case EXPR_REFERENCE:
7514 case EXPR_UNARY_DEREFERENCE:
7518 type_t *type = skip_typeref(expression->base.type);
7520 /* ISO/IEC 14882:1998(E) §3.10:3 */
7521 is_type_reference(type) ||
7522 /* Claim it is an lvalue, if the type is invalid. There was a parse
7523 * error before, which maybe prevented properly recognizing it as
7525 !is_type_valid(type);
7530 static void semantic_incdec(unary_expression_t *expression)
7532 type_t *const orig_type = expression->value->base.type;
7533 type_t *const type = skip_typeref(orig_type);
7534 if (is_type_pointer(type)) {
7535 if (!check_pointer_arithmetic(&expression->base.source_position,
7539 } else if (!is_type_real(type) && is_type_valid(type)) {
7540 /* TODO: improve error message */
7541 errorf(&expression->base.source_position,
7542 "operation needs an arithmetic or pointer type");
7545 if (!is_lvalue(expression->value)) {
7546 /* TODO: improve error message */
7547 errorf(&expression->base.source_position, "lvalue required as operand");
7549 expression->base.type = orig_type;
7552 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7554 type_t *const res_type = promote_integer(type);
7555 expr->base.type = res_type;
7556 expr->value = create_implicit_cast(expr->value, res_type);
7559 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7561 type_t *const orig_type = expression->value->base.type;
7562 type_t *const type = skip_typeref(orig_type);
7563 if (!is_type_arithmetic(type)) {
7564 if (is_type_valid(type)) {
7565 /* TODO: improve error message */
7566 errorf(&expression->base.source_position,
7567 "operation needs an arithmetic type");
7570 } else if (is_type_integer(type)) {
7571 promote_unary_int_expr(expression, type);
7573 expression->base.type = orig_type;
7577 static void semantic_unexpr_plus(unary_expression_t *expression)
7579 semantic_unexpr_arithmetic(expression);
7580 source_position_t const *const pos = &expression->base.source_position;
7581 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7584 static void semantic_not(unary_expression_t *expression)
7586 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7587 semantic_condition(expression->value, "operand of !");
7588 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7591 static void semantic_unexpr_integer(unary_expression_t *expression)
7593 type_t *const orig_type = expression->value->base.type;
7594 type_t *const type = skip_typeref(orig_type);
7595 if (!is_type_integer(type)) {
7596 if (is_type_valid(type)) {
7597 errorf(&expression->base.source_position,
7598 "operand of ~ must be of integer type");
7603 promote_unary_int_expr(expression, type);
7606 static void semantic_dereference(unary_expression_t *expression)
7608 type_t *const orig_type = expression->value->base.type;
7609 type_t *const type = skip_typeref(orig_type);
7610 if (!is_type_pointer(type)) {
7611 if (is_type_valid(type)) {
7612 errorf(&expression->base.source_position,
7613 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7618 type_t *result_type = type->pointer.points_to;
7619 result_type = automatic_type_conversion(result_type);
7620 expression->base.type = result_type;
7624 * Record that an address is taken (expression represents an lvalue).
7626 * @param expression the expression
7627 * @param may_be_register if true, the expression might be an register
7629 static void set_address_taken(expression_t *expression, bool may_be_register)
7631 if (expression->kind != EXPR_REFERENCE)
7634 entity_t *const entity = expression->reference.entity;
7636 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7639 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7640 && !may_be_register) {
7641 source_position_t const *const pos = &expression->base.source_position;
7642 errorf(pos, "address of register '%N' requested", entity);
7645 entity->variable.address_taken = true;
7649 * Check the semantic of the address taken expression.
7651 static void semantic_take_addr(unary_expression_t *expression)
7653 expression_t *value = expression->value;
7654 value->base.type = revert_automatic_type_conversion(value);
7656 type_t *orig_type = value->base.type;
7657 type_t *type = skip_typeref(orig_type);
7658 if (!is_type_valid(type))
7662 if (!is_lvalue(value)) {
7663 errorf(&expression->base.source_position, "'&' requires an lvalue");
7665 if (is_bitfield(value)) {
7666 errorf(&expression->base.source_position,
7667 "'&' not allowed on bitfield");
7670 set_address_taken(value, false);
7672 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7675 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7676 static expression_t *parse_##unexpression_type(void) \
7678 expression_t *unary_expression \
7679 = allocate_expression_zero(unexpression_type); \
7681 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7683 sfunc(&unary_expression->unary); \
7685 return unary_expression; \
7688 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7689 semantic_unexpr_arithmetic)
7690 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7691 semantic_unexpr_plus)
7692 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7694 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7695 semantic_dereference)
7696 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7698 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7699 semantic_unexpr_integer)
7700 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7702 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7705 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7707 static expression_t *parse_##unexpression_type(expression_t *left) \
7709 expression_t *unary_expression \
7710 = allocate_expression_zero(unexpression_type); \
7712 unary_expression->unary.value = left; \
7714 sfunc(&unary_expression->unary); \
7716 return unary_expression; \
7719 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7720 EXPR_UNARY_POSTFIX_INCREMENT,
7722 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7723 EXPR_UNARY_POSTFIX_DECREMENT,
7726 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7728 /* TODO: handle complex + imaginary types */
7730 type_left = get_unqualified_type(type_left);
7731 type_right = get_unqualified_type(type_right);
7733 /* §6.3.1.8 Usual arithmetic conversions */
7734 if (type_left == type_long_double || type_right == type_long_double) {
7735 return type_long_double;
7736 } else if (type_left == type_double || type_right == type_double) {
7738 } else if (type_left == type_float || type_right == type_float) {
7742 type_left = promote_integer(type_left);
7743 type_right = promote_integer(type_right);
7745 if (type_left == type_right)
7748 bool const signed_left = is_type_signed(type_left);
7749 bool const signed_right = is_type_signed(type_right);
7750 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7751 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7753 if (signed_left == signed_right)
7754 return rank_left >= rank_right ? type_left : type_right;
7758 atomic_type_kind_t s_akind;
7759 atomic_type_kind_t u_akind;
7764 u_type = type_right;
7766 s_type = type_right;
7769 s_akind = get_akind(s_type);
7770 u_akind = get_akind(u_type);
7771 s_rank = get_akind_rank(s_akind);
7772 u_rank = get_akind_rank(u_akind);
7774 if (u_rank >= s_rank)
7777 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7781 case ATOMIC_TYPE_INT: return type_unsigned_int;
7782 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7783 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7785 default: panic("invalid atomic type");
7790 * Check the semantic restrictions for a binary expression.
7792 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7794 expression_t *const left = expression->left;
7795 expression_t *const right = expression->right;
7796 type_t *const orig_type_left = left->base.type;
7797 type_t *const orig_type_right = right->base.type;
7798 type_t *const type_left = skip_typeref(orig_type_left);
7799 type_t *const type_right = skip_typeref(orig_type_right);
7801 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7802 /* TODO: improve error message */
7803 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7804 errorf(&expression->base.source_position,
7805 "operation needs arithmetic types");
7810 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7811 expression->left = create_implicit_cast(left, arithmetic_type);
7812 expression->right = create_implicit_cast(right, arithmetic_type);
7813 expression->base.type = arithmetic_type;
7816 static void semantic_binexpr_integer(binary_expression_t *const expression)
7818 expression_t *const left = expression->left;
7819 expression_t *const right = expression->right;
7820 type_t *const orig_type_left = left->base.type;
7821 type_t *const orig_type_right = right->base.type;
7822 type_t *const type_left = skip_typeref(orig_type_left);
7823 type_t *const type_right = skip_typeref(orig_type_right);
7825 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7826 /* TODO: improve error message */
7827 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7828 errorf(&expression->base.source_position,
7829 "operation needs integer types");
7834 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7835 expression->left = create_implicit_cast(left, result_type);
7836 expression->right = create_implicit_cast(right, result_type);
7837 expression->base.type = result_type;
7840 static void warn_div_by_zero(binary_expression_t const *const expression)
7842 if (!is_type_integer(expression->base.type))
7845 expression_t const *const right = expression->right;
7846 /* The type of the right operand can be different for /= */
7847 if (is_type_integer(right->base.type) &&
7848 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7849 !fold_constant_to_bool(right)) {
7850 source_position_t const *const pos = &expression->base.source_position;
7851 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7856 * Check the semantic restrictions for a div/mod expression.
7858 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7860 semantic_binexpr_arithmetic(expression);
7861 warn_div_by_zero(expression);
7864 static void warn_addsub_in_shift(const expression_t *const expr)
7866 if (expr->base.parenthesized)
7870 switch (expr->kind) {
7871 case EXPR_BINARY_ADD: op = '+'; break;
7872 case EXPR_BINARY_SUB: op = '-'; break;
7876 source_position_t const *const pos = &expr->base.source_position;
7877 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7880 static bool semantic_shift(binary_expression_t *expression)
7882 expression_t *const left = expression->left;
7883 expression_t *const right = expression->right;
7884 type_t *const orig_type_left = left->base.type;
7885 type_t *const orig_type_right = right->base.type;
7886 type_t * type_left = skip_typeref(orig_type_left);
7887 type_t * type_right = skip_typeref(orig_type_right);
7889 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7890 /* TODO: improve error message */
7891 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7892 errorf(&expression->base.source_position,
7893 "operands of shift operation must have integer types");
7898 type_left = promote_integer(type_left);
7900 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7901 source_position_t const *const pos = &right->base.source_position;
7902 long const count = fold_constant_to_int(right);
7904 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7905 } else if ((unsigned long)count >=
7906 get_atomic_type_size(type_left->atomic.akind) * 8) {
7907 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7911 type_right = promote_integer(type_right);
7912 expression->right = create_implicit_cast(right, type_right);
7917 static void semantic_shift_op(binary_expression_t *expression)
7919 expression_t *const left = expression->left;
7920 expression_t *const right = expression->right;
7922 if (!semantic_shift(expression))
7925 warn_addsub_in_shift(left);
7926 warn_addsub_in_shift(right);
7928 type_t *const orig_type_left = left->base.type;
7929 type_t * type_left = skip_typeref(orig_type_left);
7931 type_left = promote_integer(type_left);
7932 expression->left = create_implicit_cast(left, type_left);
7933 expression->base.type = type_left;
7936 static void semantic_add(binary_expression_t *expression)
7938 expression_t *const left = expression->left;
7939 expression_t *const right = expression->right;
7940 type_t *const orig_type_left = left->base.type;
7941 type_t *const orig_type_right = right->base.type;
7942 type_t *const type_left = skip_typeref(orig_type_left);
7943 type_t *const type_right = skip_typeref(orig_type_right);
7946 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7947 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7948 expression->left = create_implicit_cast(left, arithmetic_type);
7949 expression->right = create_implicit_cast(right, arithmetic_type);
7950 expression->base.type = arithmetic_type;
7951 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7952 check_pointer_arithmetic(&expression->base.source_position,
7953 type_left, orig_type_left);
7954 expression->base.type = type_left;
7955 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7956 check_pointer_arithmetic(&expression->base.source_position,
7957 type_right, orig_type_right);
7958 expression->base.type = type_right;
7959 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7960 errorf(&expression->base.source_position,
7961 "invalid operands to binary + ('%T', '%T')",
7962 orig_type_left, orig_type_right);
7966 static void semantic_sub(binary_expression_t *expression)
7968 expression_t *const left = expression->left;
7969 expression_t *const right = expression->right;
7970 type_t *const orig_type_left = left->base.type;
7971 type_t *const orig_type_right = right->base.type;
7972 type_t *const type_left = skip_typeref(orig_type_left);
7973 type_t *const type_right = skip_typeref(orig_type_right);
7974 source_position_t const *const pos = &expression->base.source_position;
7977 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7978 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7979 expression->left = create_implicit_cast(left, arithmetic_type);
7980 expression->right = create_implicit_cast(right, arithmetic_type);
7981 expression->base.type = arithmetic_type;
7982 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7983 check_pointer_arithmetic(&expression->base.source_position,
7984 type_left, orig_type_left);
7985 expression->base.type = type_left;
7986 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7987 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7988 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7989 if (!types_compatible(unqual_left, unqual_right)) {
7991 "subtracting pointers to incompatible types '%T' and '%T'",
7992 orig_type_left, orig_type_right);
7993 } else if (!is_type_object(unqual_left)) {
7994 if (!is_type_void(unqual_left)) {
7995 errorf(pos, "subtracting pointers to non-object types '%T'",
7998 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8001 expression->base.type = type_ptrdiff_t;
8002 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8003 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8004 orig_type_left, orig_type_right);
8008 static void warn_string_literal_address(expression_t const* expr)
8010 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8011 expr = expr->unary.value;
8012 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8014 expr = expr->unary.value;
8017 if (expr->kind == EXPR_STRING_LITERAL) {
8018 source_position_t const *const pos = &expr->base.source_position;
8019 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8023 static bool maybe_negative(expression_t const *const expr)
8025 switch (is_constant_expression(expr)) {
8026 case EXPR_CLASS_ERROR: return false;
8027 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8028 default: return true;
8032 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8034 warn_string_literal_address(expr);
8036 expression_t const* const ref = get_reference_address(expr);
8037 if (ref != NULL && is_null_pointer_constant(other)) {
8038 entity_t const *const ent = ref->reference.entity;
8039 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8042 if (!expr->base.parenthesized) {
8043 switch (expr->base.kind) {
8044 case EXPR_BINARY_LESS:
8045 case EXPR_BINARY_GREATER:
8046 case EXPR_BINARY_LESSEQUAL:
8047 case EXPR_BINARY_GREATEREQUAL:
8048 case EXPR_BINARY_NOTEQUAL:
8049 case EXPR_BINARY_EQUAL:
8050 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8059 * Check the semantics of comparison expressions.
8061 * @param expression The expression to check.
8063 static void semantic_comparison(binary_expression_t *expression)
8065 source_position_t const *const pos = &expression->base.source_position;
8066 expression_t *const left = expression->left;
8067 expression_t *const right = expression->right;
8069 warn_comparison(pos, left, right);
8070 warn_comparison(pos, right, left);
8072 type_t *orig_type_left = left->base.type;
8073 type_t *orig_type_right = right->base.type;
8074 type_t *type_left = skip_typeref(orig_type_left);
8075 type_t *type_right = skip_typeref(orig_type_right);
8077 /* TODO non-arithmetic types */
8078 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8079 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8081 /* test for signed vs unsigned compares */
8082 if (is_type_integer(arithmetic_type)) {
8083 bool const signed_left = is_type_signed(type_left);
8084 bool const signed_right = is_type_signed(type_right);
8085 if (signed_left != signed_right) {
8086 /* FIXME long long needs better const folding magic */
8087 /* TODO check whether constant value can be represented by other type */
8088 if ((signed_left && maybe_negative(left)) ||
8089 (signed_right && maybe_negative(right))) {
8090 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8095 expression->left = create_implicit_cast(left, arithmetic_type);
8096 expression->right = create_implicit_cast(right, arithmetic_type);
8097 expression->base.type = arithmetic_type;
8098 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8099 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8100 is_type_float(arithmetic_type)) {
8101 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8103 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8104 /* TODO check compatibility */
8105 } else if (is_type_pointer(type_left)) {
8106 expression->right = create_implicit_cast(right, type_left);
8107 } else if (is_type_pointer(type_right)) {
8108 expression->left = create_implicit_cast(left, type_right);
8109 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8110 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8112 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8116 * Checks if a compound type has constant fields.
8118 static bool has_const_fields(const compound_type_t *type)
8120 compound_t *compound = type->compound;
8121 entity_t *entry = compound->members.entities;
8123 for (; entry != NULL; entry = entry->base.next) {
8124 if (!is_declaration(entry))
8127 const type_t *decl_type = skip_typeref(entry->declaration.type);
8128 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8135 static bool is_valid_assignment_lhs(expression_t const* const left)
8137 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8138 type_t *const type_left = skip_typeref(orig_type_left);
8140 if (!is_lvalue(left)) {
8141 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8146 if (left->kind == EXPR_REFERENCE
8147 && left->reference.entity->kind == ENTITY_FUNCTION) {
8148 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8152 if (is_type_array(type_left)) {
8153 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8156 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8157 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8161 if (is_type_incomplete(type_left)) {
8162 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8163 left, orig_type_left);
8166 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8167 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8168 left, orig_type_left);
8175 static void semantic_arithmetic_assign(binary_expression_t *expression)
8177 expression_t *left = expression->left;
8178 expression_t *right = expression->right;
8179 type_t *orig_type_left = left->base.type;
8180 type_t *orig_type_right = right->base.type;
8182 if (!is_valid_assignment_lhs(left))
8185 type_t *type_left = skip_typeref(orig_type_left);
8186 type_t *type_right = skip_typeref(orig_type_right);
8188 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8189 /* TODO: improve error message */
8190 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8191 errorf(&expression->base.source_position,
8192 "operation needs arithmetic types");
8197 /* combined instructions are tricky. We can't create an implicit cast on
8198 * the left side, because we need the uncasted form for the store.
8199 * The ast2firm pass has to know that left_type must be right_type
8200 * for the arithmetic operation and create a cast by itself */
8201 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8202 expression->right = create_implicit_cast(right, arithmetic_type);
8203 expression->base.type = type_left;
8206 static void semantic_divmod_assign(binary_expression_t *expression)
8208 semantic_arithmetic_assign(expression);
8209 warn_div_by_zero(expression);
8212 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8214 expression_t *const left = expression->left;
8215 expression_t *const right = expression->right;
8216 type_t *const orig_type_left = left->base.type;
8217 type_t *const orig_type_right = right->base.type;
8218 type_t *const type_left = skip_typeref(orig_type_left);
8219 type_t *const type_right = skip_typeref(orig_type_right);
8221 if (!is_valid_assignment_lhs(left))
8224 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8225 /* combined instructions are tricky. We can't create an implicit cast on
8226 * the left side, because we need the uncasted form for the store.
8227 * The ast2firm pass has to know that left_type must be right_type
8228 * for the arithmetic operation and create a cast by itself */
8229 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8230 expression->right = create_implicit_cast(right, arithmetic_type);
8231 expression->base.type = type_left;
8232 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8233 check_pointer_arithmetic(&expression->base.source_position,
8234 type_left, orig_type_left);
8235 expression->base.type = type_left;
8236 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8237 errorf(&expression->base.source_position,
8238 "incompatible types '%T' and '%T' in assignment",
8239 orig_type_left, orig_type_right);
8243 static void semantic_integer_assign(binary_expression_t *expression)
8245 expression_t *left = expression->left;
8246 expression_t *right = expression->right;
8247 type_t *orig_type_left = left->base.type;
8248 type_t *orig_type_right = right->base.type;
8250 if (!is_valid_assignment_lhs(left))
8253 type_t *type_left = skip_typeref(orig_type_left);
8254 type_t *type_right = skip_typeref(orig_type_right);
8256 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8257 /* TODO: improve error message */
8258 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8259 errorf(&expression->base.source_position,
8260 "operation needs integer types");
8265 /* combined instructions are tricky. We can't create an implicit cast on
8266 * the left side, because we need the uncasted form for the store.
8267 * The ast2firm pass has to know that left_type must be right_type
8268 * for the arithmetic operation and create a cast by itself */
8269 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8270 expression->right = create_implicit_cast(right, arithmetic_type);
8271 expression->base.type = type_left;
8274 static void semantic_shift_assign(binary_expression_t *expression)
8276 expression_t *left = expression->left;
8278 if (!is_valid_assignment_lhs(left))
8281 if (!semantic_shift(expression))
8284 expression->base.type = skip_typeref(left->base.type);
8287 static void warn_logical_and_within_or(const expression_t *const expr)
8289 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8291 if (expr->base.parenthesized)
8293 source_position_t const *const pos = &expr->base.source_position;
8294 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8298 * Check the semantic restrictions of a logical expression.
8300 static void semantic_logical_op(binary_expression_t *expression)
8302 /* §6.5.13:2 Each of the operands shall have scalar type.
8303 * §6.5.14:2 Each of the operands shall have scalar type. */
8304 semantic_condition(expression->left, "left operand of logical operator");
8305 semantic_condition(expression->right, "right operand of logical operator");
8306 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8307 warn_logical_and_within_or(expression->left);
8308 warn_logical_and_within_or(expression->right);
8310 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8314 * Check the semantic restrictions of a binary assign expression.
8316 static void semantic_binexpr_assign(binary_expression_t *expression)
8318 expression_t *left = expression->left;
8319 type_t *orig_type_left = left->base.type;
8321 if (!is_valid_assignment_lhs(left))
8324 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8325 report_assign_error(error, orig_type_left, expression->right,
8326 "assignment", &left->base.source_position);
8327 expression->right = create_implicit_cast(expression->right, orig_type_left);
8328 expression->base.type = orig_type_left;
8332 * Determine if the outermost operation (or parts thereof) of the given
8333 * expression has no effect in order to generate a warning about this fact.
8334 * Therefore in some cases this only examines some of the operands of the
8335 * expression (see comments in the function and examples below).
8337 * f() + 23; // warning, because + has no effect
8338 * x || f(); // no warning, because x controls execution of f()
8339 * x ? y : f(); // warning, because y has no effect
8340 * (void)x; // no warning to be able to suppress the warning
8341 * This function can NOT be used for an "expression has definitely no effect"-
8343 static bool expression_has_effect(const expression_t *const expr)
8345 switch (expr->kind) {
8346 case EXPR_ERROR: return true; /* do NOT warn */
8347 case EXPR_REFERENCE: return false;
8348 case EXPR_ENUM_CONSTANT: return false;
8349 case EXPR_LABEL_ADDRESS: return false;
8351 /* suppress the warning for microsoft __noop operations */
8352 case EXPR_LITERAL_MS_NOOP: return true;
8353 case EXPR_LITERAL_BOOLEAN:
8354 case EXPR_LITERAL_CHARACTER:
8355 case EXPR_LITERAL_INTEGER:
8356 case EXPR_LITERAL_FLOATINGPOINT:
8357 case EXPR_STRING_LITERAL: return false;
8360 const call_expression_t *const call = &expr->call;
8361 if (call->function->kind != EXPR_REFERENCE)
8364 switch (call->function->reference.entity->function.btk) {
8365 /* FIXME: which builtins have no effect? */
8366 default: return true;
8370 /* Generate the warning if either the left or right hand side of a
8371 * conditional expression has no effect */
8372 case EXPR_CONDITIONAL: {
8373 conditional_expression_t const *const cond = &expr->conditional;
8374 expression_t const *const t = cond->true_expression;
8376 (t == NULL || expression_has_effect(t)) &&
8377 expression_has_effect(cond->false_expression);
8380 case EXPR_SELECT: return false;
8381 case EXPR_ARRAY_ACCESS: return false;
8382 case EXPR_SIZEOF: return false;
8383 case EXPR_CLASSIFY_TYPE: return false;
8384 case EXPR_ALIGNOF: return false;
8386 case EXPR_FUNCNAME: return false;
8387 case EXPR_BUILTIN_CONSTANT_P: return false;
8388 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8389 case EXPR_OFFSETOF: return false;
8390 case EXPR_VA_START: return true;
8391 case EXPR_VA_ARG: return true;
8392 case EXPR_VA_COPY: return true;
8393 case EXPR_STATEMENT: return true; // TODO
8394 case EXPR_COMPOUND_LITERAL: return false;
8396 case EXPR_UNARY_NEGATE: return false;
8397 case EXPR_UNARY_PLUS: return false;
8398 case EXPR_UNARY_BITWISE_NEGATE: return false;
8399 case EXPR_UNARY_NOT: return false;
8400 case EXPR_UNARY_DEREFERENCE: return false;
8401 case EXPR_UNARY_TAKE_ADDRESS: return false;
8402 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8403 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8404 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8405 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8407 /* Treat void casts as if they have an effect in order to being able to
8408 * suppress the warning */
8409 case EXPR_UNARY_CAST: {
8410 type_t *const type = skip_typeref(expr->base.type);
8411 return is_type_void(type);
8414 case EXPR_UNARY_ASSUME: return true;
8415 case EXPR_UNARY_DELETE: return true;
8416 case EXPR_UNARY_DELETE_ARRAY: return true;
8417 case EXPR_UNARY_THROW: return true;
8419 case EXPR_BINARY_ADD: return false;
8420 case EXPR_BINARY_SUB: return false;
8421 case EXPR_BINARY_MUL: return false;
8422 case EXPR_BINARY_DIV: return false;
8423 case EXPR_BINARY_MOD: return false;
8424 case EXPR_BINARY_EQUAL: return false;
8425 case EXPR_BINARY_NOTEQUAL: return false;
8426 case EXPR_BINARY_LESS: return false;
8427 case EXPR_BINARY_LESSEQUAL: return false;
8428 case EXPR_BINARY_GREATER: return false;
8429 case EXPR_BINARY_GREATEREQUAL: return false;
8430 case EXPR_BINARY_BITWISE_AND: return false;
8431 case EXPR_BINARY_BITWISE_OR: return false;
8432 case EXPR_BINARY_BITWISE_XOR: return false;
8433 case EXPR_BINARY_SHIFTLEFT: return false;
8434 case EXPR_BINARY_SHIFTRIGHT: return false;
8435 case EXPR_BINARY_ASSIGN: return true;
8436 case EXPR_BINARY_MUL_ASSIGN: return true;
8437 case EXPR_BINARY_DIV_ASSIGN: return true;
8438 case EXPR_BINARY_MOD_ASSIGN: return true;
8439 case EXPR_BINARY_ADD_ASSIGN: return true;
8440 case EXPR_BINARY_SUB_ASSIGN: return true;
8441 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8442 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8443 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8444 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8445 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8447 /* Only examine the right hand side of && and ||, because the left hand
8448 * side already has the effect of controlling the execution of the right
8450 case EXPR_BINARY_LOGICAL_AND:
8451 case EXPR_BINARY_LOGICAL_OR:
8452 /* Only examine the right hand side of a comma expression, because the left
8453 * hand side has a separate warning */
8454 case EXPR_BINARY_COMMA:
8455 return expression_has_effect(expr->binary.right);
8457 case EXPR_BINARY_ISGREATER: return false;
8458 case EXPR_BINARY_ISGREATEREQUAL: return false;
8459 case EXPR_BINARY_ISLESS: return false;
8460 case EXPR_BINARY_ISLESSEQUAL: return false;
8461 case EXPR_BINARY_ISLESSGREATER: return false;
8462 case EXPR_BINARY_ISUNORDERED: return false;
8465 internal_errorf(HERE, "unexpected expression");
8468 static void semantic_comma(binary_expression_t *expression)
8470 const expression_t *const left = expression->left;
8471 if (!expression_has_effect(left)) {
8472 source_position_t const *const pos = &left->base.source_position;
8473 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8475 expression->base.type = expression->right->base.type;
8479 * @param prec_r precedence of the right operand
8481 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8482 static expression_t *parse_##binexpression_type(expression_t *left) \
8484 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8485 binexpr->binary.left = left; \
8488 expression_t *right = parse_subexpression(prec_r); \
8490 binexpr->binary.right = right; \
8491 sfunc(&binexpr->binary); \
8496 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8497 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8498 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8499 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8500 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8501 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8502 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8503 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8504 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8505 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8506 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8507 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8508 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8509 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8510 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8511 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8512 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8513 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8514 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8515 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8516 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8517 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8518 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8519 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8520 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8521 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8522 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8523 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8524 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8525 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8528 static expression_t *parse_subexpression(precedence_t precedence)
8530 expression_parser_function_t *parser
8531 = &expression_parsers[token.kind];
8534 if (parser->parser != NULL) {
8535 left = parser->parser();
8537 left = parse_primary_expression();
8539 assert(left != NULL);
8542 parser = &expression_parsers[token.kind];
8543 if (parser->infix_parser == NULL)
8545 if (parser->infix_precedence < precedence)
8548 left = parser->infix_parser(left);
8550 assert(left != NULL);
8557 * Parse an expression.
8559 static expression_t *parse_expression(void)
8561 return parse_subexpression(PREC_EXPRESSION);
8565 * Register a parser for a prefix-like operator.
8567 * @param parser the parser function
8568 * @param token_kind the token type of the prefix token
8570 static void register_expression_parser(parse_expression_function parser,
8573 expression_parser_function_t *entry = &expression_parsers[token_kind];
8575 assert(!entry->parser);
8576 entry->parser = parser;
8580 * Register a parser for an infix operator with given precedence.
8582 * @param parser the parser function
8583 * @param token_kind the token type of the infix operator
8584 * @param precedence the precedence of the operator
8586 static void register_infix_parser(parse_expression_infix_function parser,
8587 int token_kind, precedence_t precedence)
8589 expression_parser_function_t *entry = &expression_parsers[token_kind];
8591 assert(!entry->infix_parser);
8592 entry->infix_parser = parser;
8593 entry->infix_precedence = precedence;
8597 * Initialize the expression parsers.
8599 static void init_expression_parsers(void)
8601 memset(&expression_parsers, 0, sizeof(expression_parsers));
8603 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8604 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8605 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8606 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8607 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8608 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8609 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8610 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8611 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8612 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8613 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8614 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8615 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8616 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8617 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8618 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8619 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8620 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8621 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8622 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8623 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8624 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8625 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8626 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8627 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8628 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8629 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8630 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8631 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8632 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8633 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8634 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8635 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8636 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8637 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8638 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8639 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8641 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8642 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8643 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8644 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8645 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8646 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8647 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8648 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8649 register_expression_parser(parse_sizeof, T_sizeof);
8650 register_expression_parser(parse_alignof, T___alignof__);
8651 register_expression_parser(parse_extension, T___extension__);
8652 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8653 register_expression_parser(parse_delete, T_delete);
8654 register_expression_parser(parse_throw, T_throw);
8658 * Parse a asm statement arguments specification.
8660 static asm_argument_t *parse_asm_arguments(bool is_out)
8662 asm_argument_t *result = NULL;
8663 asm_argument_t **anchor = &result;
8665 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8666 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8669 add_anchor_token(']');
8670 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8671 rem_anchor_token(']');
8673 if (!argument->symbol)
8677 argument->constraints = parse_string_literals("asm argument");
8678 add_anchor_token(')');
8680 expression_t *expression = parse_expression();
8681 rem_anchor_token(')');
8683 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8684 * change size or type representation (e.g. int -> long is ok, but
8685 * int -> float is not) */
8686 if (expression->kind == EXPR_UNARY_CAST) {
8687 type_t *const type = expression->base.type;
8688 type_kind_t const kind = type->kind;
8689 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8692 if (kind == TYPE_ATOMIC) {
8693 atomic_type_kind_t const akind = type->atomic.akind;
8694 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8695 size = get_atomic_type_size(akind);
8697 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8698 size = get_type_size(type_void_ptr);
8702 expression_t *const value = expression->unary.value;
8703 type_t *const value_type = value->base.type;
8704 type_kind_t const value_kind = value_type->kind;
8706 unsigned value_flags;
8707 unsigned value_size;
8708 if (value_kind == TYPE_ATOMIC) {
8709 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8710 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8711 value_size = get_atomic_type_size(value_akind);
8712 } else if (value_kind == TYPE_POINTER) {
8713 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8714 value_size = get_type_size(type_void_ptr);
8719 if (value_flags != flags || value_size != size)
8723 } while (expression->kind == EXPR_UNARY_CAST);
8727 if (!is_lvalue(expression)) {
8728 errorf(&expression->base.source_position,
8729 "asm output argument is not an lvalue");
8732 if (argument->constraints.begin[0] == '=')
8733 determine_lhs_ent(expression, NULL);
8735 mark_vars_read(expression, NULL);
8737 mark_vars_read(expression, NULL);
8739 argument->expression = expression;
8742 set_address_taken(expression, true);
8745 anchor = &argument->next;
8755 * Parse a asm statement clobber specification.
8757 static asm_clobber_t *parse_asm_clobbers(void)
8759 asm_clobber_t *result = NULL;
8760 asm_clobber_t **anchor = &result;
8762 while (token.kind == T_STRING_LITERAL) {
8763 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8764 clobber->clobber = parse_string_literals(NULL);
8767 anchor = &clobber->next;
8777 * Parse an asm statement.
8779 static statement_t *parse_asm_statement(void)
8781 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8782 asm_statement_t *asm_statement = &statement->asms;
8785 add_anchor_token(')');
8786 add_anchor_token(':');
8787 add_anchor_token(T_STRING_LITERAL);
8789 if (next_if(T_volatile))
8790 asm_statement->is_volatile = true;
8793 rem_anchor_token(T_STRING_LITERAL);
8794 asm_statement->asm_text = parse_string_literals("asm statement");
8797 asm_statement->outputs = parse_asm_arguments(true);
8800 asm_statement->inputs = parse_asm_arguments(false);
8802 rem_anchor_token(':');
8804 asm_statement->clobbers = parse_asm_clobbers();
8806 rem_anchor_token(')');
8810 if (asm_statement->outputs == NULL) {
8811 /* GCC: An 'asm' instruction without any output operands will be treated
8812 * identically to a volatile 'asm' instruction. */
8813 asm_statement->is_volatile = true;
8819 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8821 statement_t *inner_stmt;
8822 switch (token.kind) {
8824 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8825 inner_stmt = create_error_statement();
8829 if (label->kind == STATEMENT_LABEL) {
8830 /* Eat an empty statement here, to avoid the warning about an empty
8831 * statement after a label. label:; is commonly used to have a label
8832 * before a closing brace. */
8833 inner_stmt = create_empty_statement();
8840 inner_stmt = parse_statement();
8841 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8842 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8843 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8844 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8852 * Parse a case statement.
8854 static statement_t *parse_case_statement(void)
8856 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8857 source_position_t *const pos = &statement->base.source_position;
8860 add_anchor_token(':');
8862 expression_t *expression = parse_expression();
8863 type_t *expression_type = expression->base.type;
8864 type_t *skipped = skip_typeref(expression_type);
8865 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8866 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8867 expression, expression_type);
8870 type_t *type = expression_type;
8871 if (current_switch != NULL) {
8872 type_t *switch_type = current_switch->expression->base.type;
8873 if (is_type_valid(switch_type)) {
8874 expression = create_implicit_cast(expression, switch_type);
8878 statement->case_label.expression = expression;
8879 expression_classification_t const expr_class = is_constant_expression(expression);
8880 if (expr_class != EXPR_CLASS_CONSTANT) {
8881 if (expr_class != EXPR_CLASS_ERROR) {
8882 errorf(pos, "case label does not reduce to an integer constant");
8884 statement->case_label.is_bad = true;
8886 long const val = fold_constant_to_int(expression);
8887 statement->case_label.first_case = val;
8888 statement->case_label.last_case = val;
8892 if (next_if(T_DOTDOTDOT)) {
8893 expression_t *end_range = parse_expression();
8894 expression_type = expression->base.type;
8895 skipped = skip_typeref(expression_type);
8896 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8897 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8898 expression, expression_type);
8901 end_range = create_implicit_cast(end_range, type);
8902 statement->case_label.end_range = end_range;
8903 expression_classification_t const end_class = is_constant_expression(end_range);
8904 if (end_class != EXPR_CLASS_CONSTANT) {
8905 if (end_class != EXPR_CLASS_ERROR) {
8906 errorf(pos, "case range does not reduce to an integer constant");
8908 statement->case_label.is_bad = true;
8910 long const val = fold_constant_to_int(end_range);
8911 statement->case_label.last_case = val;
8913 if (val < statement->case_label.first_case) {
8914 statement->case_label.is_empty_range = true;
8915 warningf(WARN_OTHER, pos, "empty range specified");
8921 PUSH_PARENT(statement);
8923 rem_anchor_token(':');
8926 if (current_switch != NULL) {
8927 if (! statement->case_label.is_bad) {
8928 /* Check for duplicate case values */
8929 case_label_statement_t *c = &statement->case_label;
8930 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8931 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8934 if (c->last_case < l->first_case || c->first_case > l->last_case)
8937 errorf(pos, "duplicate case value (previously used %P)",
8938 &l->base.source_position);
8942 /* link all cases into the switch statement */
8943 if (current_switch->last_case == NULL) {
8944 current_switch->first_case = &statement->case_label;
8946 current_switch->last_case->next = &statement->case_label;
8948 current_switch->last_case = &statement->case_label;
8950 errorf(pos, "case label not within a switch statement");
8953 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
8960 * Parse a default statement.
8962 static statement_t *parse_default_statement(void)
8964 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8968 PUSH_PARENT(statement);
8972 if (current_switch != NULL) {
8973 const case_label_statement_t *def_label = current_switch->default_label;
8974 if (def_label != NULL) {
8975 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
8977 current_switch->default_label = &statement->case_label;
8979 /* link all cases into the switch statement */
8980 if (current_switch->last_case == NULL) {
8981 current_switch->first_case = &statement->case_label;
8983 current_switch->last_case->next = &statement->case_label;
8985 current_switch->last_case = &statement->case_label;
8988 errorf(&statement->base.source_position,
8989 "'default' label not within a switch statement");
8992 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
8999 * Parse a label statement.
9001 static statement_t *parse_label_statement(void)
9003 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9004 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9005 statement->label.label = label;
9007 PUSH_PARENT(statement);
9009 /* if statement is already set then the label is defined twice,
9010 * otherwise it was just mentioned in a goto/local label declaration so far
9012 source_position_t const* const pos = &statement->base.source_position;
9013 if (label->statement != NULL) {
9014 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9016 label->base.source_position = *pos;
9017 label->statement = statement;
9022 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9023 parse_attributes(NULL); // TODO process attributes
9026 statement->label.statement = parse_label_inner_statement(statement, "label");
9028 /* remember the labels in a list for later checking */
9029 *label_anchor = &statement->label;
9030 label_anchor = &statement->label.next;
9036 static statement_t *parse_inner_statement(void)
9038 statement_t *const stmt = parse_statement();
9039 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9040 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9041 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9042 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9048 * Parse an expression in parentheses and mark its variables as read.
9050 static expression_t *parse_condition(void)
9052 add_anchor_token(')');
9054 expression_t *const expr = parse_expression();
9055 mark_vars_read(expr, NULL);
9056 rem_anchor_token(')');
9062 * Parse an if statement.
9064 static statement_t *parse_if(void)
9066 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9070 PUSH_PARENT(statement);
9071 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9073 add_anchor_token(T_else);
9075 expression_t *const expr = parse_condition();
9076 statement->ifs.condition = expr;
9077 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9079 semantic_condition(expr, "condition of 'if'-statment");
9081 statement_t *const true_stmt = parse_inner_statement();
9082 statement->ifs.true_statement = true_stmt;
9083 rem_anchor_token(T_else);
9085 if (true_stmt->kind == STATEMENT_EMPTY) {
9086 warningf(WARN_EMPTY_BODY, HERE,
9087 "suggest braces around empty body in an ‘if’ statement");
9090 if (next_if(T_else)) {
9091 statement->ifs.false_statement = parse_inner_statement();
9093 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9094 warningf(WARN_EMPTY_BODY, HERE,
9095 "suggest braces around empty body in an ‘if’ statement");
9097 } else if (true_stmt->kind == STATEMENT_IF &&
9098 true_stmt->ifs.false_statement != NULL) {
9099 source_position_t const *const pos = &true_stmt->base.source_position;
9100 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9109 * Check that all enums are handled in a switch.
9111 * @param statement the switch statement to check
9113 static void check_enum_cases(const switch_statement_t *statement)
9115 if (!is_warn_on(WARN_SWITCH_ENUM))
9117 const type_t *type = skip_typeref(statement->expression->base.type);
9118 if (! is_type_enum(type))
9120 const enum_type_t *enumt = &type->enumt;
9122 /* if we have a default, no warnings */
9123 if (statement->default_label != NULL)
9126 /* FIXME: calculation of value should be done while parsing */
9127 /* TODO: quadratic algorithm here. Change to an n log n one */
9128 long last_value = -1;
9129 const entity_t *entry = enumt->enume->base.next;
9130 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9131 entry = entry->base.next) {
9132 const expression_t *expression = entry->enum_value.value;
9133 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9135 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9136 if (l->expression == NULL)
9138 if (l->first_case <= value && value <= l->last_case) {
9144 source_position_t const *const pos = &statement->base.source_position;
9145 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9152 * Parse a switch statement.
9154 static statement_t *parse_switch(void)
9156 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9160 PUSH_PARENT(statement);
9161 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9163 expression_t *const expr = parse_condition();
9164 type_t * type = skip_typeref(expr->base.type);
9165 if (is_type_integer(type)) {
9166 type = promote_integer(type);
9167 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9168 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9170 } else if (is_type_valid(type)) {
9171 errorf(&expr->base.source_position,
9172 "switch quantity is not an integer, but '%T'", type);
9173 type = type_error_type;
9175 statement->switchs.expression = create_implicit_cast(expr, type);
9177 switch_statement_t *rem = current_switch;
9178 current_switch = &statement->switchs;
9179 statement->switchs.body = parse_inner_statement();
9180 current_switch = rem;
9182 if (statement->switchs.default_label == NULL) {
9183 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9185 check_enum_cases(&statement->switchs);
9192 static statement_t *parse_loop_body(statement_t *const loop)
9194 statement_t *const rem = current_loop;
9195 current_loop = loop;
9197 statement_t *const body = parse_inner_statement();
9204 * Parse a while statement.
9206 static statement_t *parse_while(void)
9208 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9212 PUSH_PARENT(statement);
9213 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9215 expression_t *const cond = parse_condition();
9216 statement->whiles.condition = cond;
9217 /* §6.8.5:2 The controlling expression of an iteration statement shall
9218 * have scalar type. */
9219 semantic_condition(cond, "condition of 'while'-statement");
9221 statement->whiles.body = parse_loop_body(statement);
9229 * Parse a do statement.
9231 static statement_t *parse_do(void)
9233 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9237 PUSH_PARENT(statement);
9238 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9240 add_anchor_token(T_while);
9241 statement->do_while.body = parse_loop_body(statement);
9242 rem_anchor_token(T_while);
9245 expression_t *const cond = parse_condition();
9246 statement->do_while.condition = cond;
9247 /* §6.8.5:2 The controlling expression of an iteration statement shall
9248 * have scalar type. */
9249 semantic_condition(cond, "condition of 'do-while'-statement");
9258 * Parse a for statement.
9260 static statement_t *parse_for(void)
9262 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9266 PUSH_PARENT(statement);
9267 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9269 add_anchor_token(')');
9275 } else if (is_declaration_specifier(&token)) {
9276 parse_declaration(record_entity, DECL_FLAGS_NONE);
9278 add_anchor_token(';');
9279 expression_t *const init = parse_expression();
9280 statement->fors.initialisation = init;
9281 mark_vars_read(init, ENT_ANY);
9282 if (!expression_has_effect(init)) {
9283 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9285 rem_anchor_token(';');
9291 if (token.kind != ';') {
9292 add_anchor_token(';');
9293 expression_t *const cond = parse_expression();
9294 statement->fors.condition = cond;
9295 /* §6.8.5:2 The controlling expression of an iteration statement
9296 * shall have scalar type. */
9297 semantic_condition(cond, "condition of 'for'-statement");
9298 mark_vars_read(cond, NULL);
9299 rem_anchor_token(';');
9302 if (token.kind != ')') {
9303 expression_t *const step = parse_expression();
9304 statement->fors.step = step;
9305 mark_vars_read(step, ENT_ANY);
9306 if (!expression_has_effect(step)) {
9307 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9310 rem_anchor_token(')');
9312 statement->fors.body = parse_loop_body(statement);
9320 * Parse a goto statement.
9322 static statement_t *parse_goto(void)
9324 statement_t *statement;
9325 if (GNU_MODE && look_ahead(1)->kind == '*') {
9326 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9330 expression_t *expression = parse_expression();
9331 mark_vars_read(expression, NULL);
9333 /* Argh: although documentation says the expression must be of type void*,
9334 * gcc accepts anything that can be casted into void* without error */
9335 type_t *type = expression->base.type;
9337 if (type != type_error_type) {
9338 if (!is_type_pointer(type) && !is_type_integer(type)) {
9339 errorf(&expression->base.source_position,
9340 "cannot convert to a pointer type");
9341 } else if (type != type_void_ptr) {
9342 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9344 expression = create_implicit_cast(expression, type_void_ptr);
9347 statement->computed_goto.expression = expression;
9349 statement = allocate_statement_zero(STATEMENT_GOTO);
9352 label_t *const label = get_label("while parsing goto");
9355 statement->gotos.label = label;
9357 /* remember the goto's in a list for later checking */
9358 *goto_anchor = &statement->gotos;
9359 goto_anchor = &statement->gotos.next;
9361 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9370 * Parse a continue statement.
9372 static statement_t *parse_continue(void)
9374 if (current_loop == NULL) {
9375 errorf(HERE, "continue statement not within loop");
9378 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9386 * Parse a break statement.
9388 static statement_t *parse_break(void)
9390 if (current_switch == NULL && current_loop == NULL) {
9391 errorf(HERE, "break statement not within loop or switch");
9394 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9402 * Parse a __leave statement.
9404 static statement_t *parse_leave_statement(void)
9406 if (current_try == NULL) {
9407 errorf(HERE, "__leave statement not within __try");
9410 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9418 * Check if a given entity represents a local variable.
9420 static bool is_local_variable(const entity_t *entity)
9422 if (entity->kind != ENTITY_VARIABLE)
9425 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9426 case STORAGE_CLASS_AUTO:
9427 case STORAGE_CLASS_REGISTER: {
9428 const type_t *type = skip_typeref(entity->declaration.type);
9429 if (is_type_function(type)) {
9441 * Check if a given expression represents a local variable.
9443 static bool expression_is_local_variable(const expression_t *expression)
9445 if (expression->base.kind != EXPR_REFERENCE) {
9448 const entity_t *entity = expression->reference.entity;
9449 return is_local_variable(entity);
9452 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9454 if (c_mode & _CXX || strict_mode) {
9457 warningf(WARN_OTHER, pos, msg);
9462 * Parse a return statement.
9464 static statement_t *parse_return(void)
9466 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9469 expression_t *return_value = NULL;
9470 if (token.kind != ';') {
9471 return_value = parse_expression();
9472 mark_vars_read(return_value, NULL);
9475 const type_t *const func_type = skip_typeref(current_function->base.type);
9476 assert(is_type_function(func_type));
9477 type_t *const return_type = skip_typeref(func_type->function.return_type);
9479 source_position_t const *const pos = &statement->base.source_position;
9480 if (return_value != NULL) {
9481 type_t *return_value_type = skip_typeref(return_value->base.type);
9483 if (is_type_void(return_type)) {
9484 if (!is_type_void(return_value_type)) {
9485 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9486 /* Only warn in C mode, because GCC does the same */
9487 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9488 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9489 /* Only warn in C mode, because GCC does the same */
9490 err_or_warn(pos, "'return' with expression in function returning 'void'");
9493 assign_error_t error = semantic_assign(return_type, return_value);
9494 report_assign_error(error, return_type, return_value, "'return'",
9497 return_value = create_implicit_cast(return_value, return_type);
9498 /* check for returning address of a local var */
9499 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9500 const expression_t *expression = return_value->unary.value;
9501 if (expression_is_local_variable(expression)) {
9502 warningf(WARN_OTHER, pos, "function returns address of local variable");
9505 } else if (!is_type_void(return_type)) {
9506 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9507 err_or_warn(pos, "'return' without value, in function returning non-void");
9509 statement->returns.value = return_value;
9516 * Parse a declaration statement.
9518 static statement_t *parse_declaration_statement(void)
9520 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9522 entity_t *before = current_scope->last_entity;
9524 parse_external_declaration();
9526 parse_declaration(record_entity, DECL_FLAGS_NONE);
9529 declaration_statement_t *const decl = &statement->declaration;
9530 entity_t *const begin =
9531 before != NULL ? before->base.next : current_scope->entities;
9532 decl->declarations_begin = begin;
9533 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9539 * Parse an expression statement, ie. expr ';'.
9541 static statement_t *parse_expression_statement(void)
9543 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9545 expression_t *const expr = parse_expression();
9546 statement->expression.expression = expr;
9547 mark_vars_read(expr, ENT_ANY);
9554 * Parse a microsoft __try { } __finally { } or
9555 * __try{ } __except() { }
9557 static statement_t *parse_ms_try_statment(void)
9559 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9562 PUSH_PARENT(statement);
9564 ms_try_statement_t *rem = current_try;
9565 current_try = &statement->ms_try;
9566 statement->ms_try.try_statement = parse_compound_statement(false);
9571 if (next_if(T___except)) {
9572 expression_t *const expr = parse_condition();
9573 type_t * type = skip_typeref(expr->base.type);
9574 if (is_type_integer(type)) {
9575 type = promote_integer(type);
9576 } else if (is_type_valid(type)) {
9577 errorf(&expr->base.source_position,
9578 "__expect expression is not an integer, but '%T'", type);
9579 type = type_error_type;
9581 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9582 } else if (!next_if(T__finally)) {
9583 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9585 statement->ms_try.final_statement = parse_compound_statement(false);
9589 static statement_t *parse_empty_statement(void)
9591 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9592 statement_t *const statement = create_empty_statement();
9597 static statement_t *parse_local_label_declaration(void)
9599 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9603 entity_t *begin = NULL;
9604 entity_t *end = NULL;
9605 entity_t **anchor = &begin;
9606 add_anchor_token(';');
9607 add_anchor_token(',');
9609 source_position_t pos;
9610 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9612 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9613 if (entity != NULL && entity->base.parent_scope == current_scope) {
9614 source_position_t const *const ppos = &entity->base.source_position;
9615 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9617 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9618 entity->base.parent_scope = current_scope;
9621 anchor = &entity->base.next;
9624 environment_push(entity);
9627 } while (next_if(','));
9628 rem_anchor_token(',');
9629 rem_anchor_token(';');
9631 statement->declaration.declarations_begin = begin;
9632 statement->declaration.declarations_end = end;
9636 static void parse_namespace_definition(void)
9640 entity_t *entity = NULL;
9641 symbol_t *symbol = NULL;
9643 if (token.kind == T_IDENTIFIER) {
9644 symbol = token.base.symbol;
9645 entity = get_entity(symbol, NAMESPACE_NORMAL);
9646 if (entity && entity->kind != ENTITY_NAMESPACE) {
9648 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9649 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9655 if (entity == NULL) {
9656 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9657 entity->base.parent_scope = current_scope;
9660 if (token.kind == '=') {
9661 /* TODO: parse namespace alias */
9662 panic("namespace alias definition not supported yet");
9665 environment_push(entity);
9666 append_entity(current_scope, entity);
9668 PUSH_SCOPE(&entity->namespacee.members);
9669 PUSH_CURRENT_ENTITY(entity);
9671 add_anchor_token('}');
9674 rem_anchor_token('}');
9677 POP_CURRENT_ENTITY();
9682 * Parse a statement.
9683 * There's also parse_statement() which additionally checks for
9684 * "statement has no effect" warnings
9686 static statement_t *intern_parse_statement(void)
9688 /* declaration or statement */
9689 statement_t *statement;
9690 switch (token.kind) {
9691 case T_IDENTIFIER: {
9692 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9693 if (la1_type == ':') {
9694 statement = parse_label_statement();
9695 } else if (is_typedef_symbol(token.base.symbol)) {
9696 statement = parse_declaration_statement();
9698 /* it's an identifier, the grammar says this must be an
9699 * expression statement. However it is common that users mistype
9700 * declaration types, so we guess a bit here to improve robustness
9701 * for incorrect programs */
9705 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9707 statement = parse_expression_statement();
9711 statement = parse_declaration_statement();
9719 case T___extension__: {
9720 /* This can be a prefix to a declaration or an expression statement.
9721 * We simply eat it now and parse the rest with tail recursion. */
9723 statement = intern_parse_statement();
9729 statement = parse_declaration_statement();
9733 statement = parse_local_label_declaration();
9736 case ';': statement = parse_empty_statement(); break;
9737 case '{': statement = parse_compound_statement(false); break;
9738 case T___leave: statement = parse_leave_statement(); break;
9739 case T___try: statement = parse_ms_try_statment(); break;
9740 case T_asm: statement = parse_asm_statement(); break;
9741 case T_break: statement = parse_break(); break;
9742 case T_case: statement = parse_case_statement(); break;
9743 case T_continue: statement = parse_continue(); break;
9744 case T_default: statement = parse_default_statement(); break;
9745 case T_do: statement = parse_do(); break;
9746 case T_for: statement = parse_for(); break;
9747 case T_goto: statement = parse_goto(); break;
9748 case T_if: statement = parse_if(); break;
9749 case T_return: statement = parse_return(); break;
9750 case T_switch: statement = parse_switch(); break;
9751 case T_while: statement = parse_while(); break;
9754 statement = parse_expression_statement();
9758 errorf(HERE, "unexpected token %K while parsing statement", &token);
9759 statement = create_error_statement();
9768 * parse a statement and emits "statement has no effect" warning if needed
9769 * (This is really a wrapper around intern_parse_statement with check for 1
9770 * single warning. It is needed, because for statement expressions we have
9771 * to avoid the warning on the last statement)
9773 static statement_t *parse_statement(void)
9775 statement_t *statement = intern_parse_statement();
9777 if (statement->kind == STATEMENT_EXPRESSION) {
9778 expression_t *expression = statement->expression.expression;
9779 if (!expression_has_effect(expression)) {
9780 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9788 * Parse a compound statement.
9790 static statement_t *parse_compound_statement(bool inside_expression_statement)
9792 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9794 PUSH_PARENT(statement);
9795 PUSH_SCOPE(&statement->compound.scope);
9798 add_anchor_token('}');
9799 /* tokens, which can start a statement */
9800 /* TODO MS, __builtin_FOO */
9801 add_anchor_token('!');
9802 add_anchor_token('&');
9803 add_anchor_token('(');
9804 add_anchor_token('*');
9805 add_anchor_token('+');
9806 add_anchor_token('-');
9807 add_anchor_token(';');
9808 add_anchor_token('{');
9809 add_anchor_token('~');
9810 add_anchor_token(T_CHARACTER_CONSTANT);
9811 add_anchor_token(T_COLONCOLON);
9812 add_anchor_token(T_IDENTIFIER);
9813 add_anchor_token(T_MINUSMINUS);
9814 add_anchor_token(T_NUMBER);
9815 add_anchor_token(T_PLUSPLUS);
9816 add_anchor_token(T_STRING_LITERAL);
9817 add_anchor_token(T__Bool);
9818 add_anchor_token(T__Complex);
9819 add_anchor_token(T__Imaginary);
9820 add_anchor_token(T___PRETTY_FUNCTION__);
9821 add_anchor_token(T___alignof__);
9822 add_anchor_token(T___attribute__);
9823 add_anchor_token(T___builtin_va_start);
9824 add_anchor_token(T___extension__);
9825 add_anchor_token(T___func__);
9826 add_anchor_token(T___imag__);
9827 add_anchor_token(T___label__);
9828 add_anchor_token(T___real__);
9829 add_anchor_token(T___thread);
9830 add_anchor_token(T_asm);
9831 add_anchor_token(T_auto);
9832 add_anchor_token(T_bool);
9833 add_anchor_token(T_break);
9834 add_anchor_token(T_case);
9835 add_anchor_token(T_char);
9836 add_anchor_token(T_class);
9837 add_anchor_token(T_const);
9838 add_anchor_token(T_const_cast);
9839 add_anchor_token(T_continue);
9840 add_anchor_token(T_default);
9841 add_anchor_token(T_delete);
9842 add_anchor_token(T_double);
9843 add_anchor_token(T_do);
9844 add_anchor_token(T_dynamic_cast);
9845 add_anchor_token(T_enum);
9846 add_anchor_token(T_extern);
9847 add_anchor_token(T_false);
9848 add_anchor_token(T_float);
9849 add_anchor_token(T_for);
9850 add_anchor_token(T_goto);
9851 add_anchor_token(T_if);
9852 add_anchor_token(T_inline);
9853 add_anchor_token(T_int);
9854 add_anchor_token(T_long);
9855 add_anchor_token(T_new);
9856 add_anchor_token(T_operator);
9857 add_anchor_token(T_register);
9858 add_anchor_token(T_reinterpret_cast);
9859 add_anchor_token(T_restrict);
9860 add_anchor_token(T_return);
9861 add_anchor_token(T_short);
9862 add_anchor_token(T_signed);
9863 add_anchor_token(T_sizeof);
9864 add_anchor_token(T_static);
9865 add_anchor_token(T_static_cast);
9866 add_anchor_token(T_struct);
9867 add_anchor_token(T_switch);
9868 add_anchor_token(T_template);
9869 add_anchor_token(T_this);
9870 add_anchor_token(T_throw);
9871 add_anchor_token(T_true);
9872 add_anchor_token(T_try);
9873 add_anchor_token(T_typedef);
9874 add_anchor_token(T_typeid);
9875 add_anchor_token(T_typename);
9876 add_anchor_token(T_typeof);
9877 add_anchor_token(T_union);
9878 add_anchor_token(T_unsigned);
9879 add_anchor_token(T_using);
9880 add_anchor_token(T_void);
9881 add_anchor_token(T_volatile);
9882 add_anchor_token(T_wchar_t);
9883 add_anchor_token(T_while);
9885 statement_t **anchor = &statement->compound.statements;
9886 bool only_decls_so_far = true;
9887 while (token.kind != '}' && token.kind != T_EOF) {
9888 statement_t *sub_statement = intern_parse_statement();
9889 if (sub_statement->kind == STATEMENT_ERROR) {
9893 if (sub_statement->kind != STATEMENT_DECLARATION) {
9894 only_decls_so_far = false;
9895 } else if (!only_decls_so_far) {
9896 source_position_t const *const pos = &sub_statement->base.source_position;
9897 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9900 *anchor = sub_statement;
9901 anchor = &sub_statement->base.next;
9905 /* look over all statements again to produce no effect warnings */
9906 if (is_warn_on(WARN_UNUSED_VALUE)) {
9907 statement_t *sub_statement = statement->compound.statements;
9908 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9909 if (sub_statement->kind != STATEMENT_EXPRESSION)
9911 /* don't emit a warning for the last expression in an expression
9912 * statement as it has always an effect */
9913 if (inside_expression_statement && sub_statement->base.next == NULL)
9916 expression_t *expression = sub_statement->expression.expression;
9917 if (!expression_has_effect(expression)) {
9918 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9923 rem_anchor_token(T_while);
9924 rem_anchor_token(T_wchar_t);
9925 rem_anchor_token(T_volatile);
9926 rem_anchor_token(T_void);
9927 rem_anchor_token(T_using);
9928 rem_anchor_token(T_unsigned);
9929 rem_anchor_token(T_union);
9930 rem_anchor_token(T_typeof);
9931 rem_anchor_token(T_typename);
9932 rem_anchor_token(T_typeid);
9933 rem_anchor_token(T_typedef);
9934 rem_anchor_token(T_try);
9935 rem_anchor_token(T_true);
9936 rem_anchor_token(T_throw);
9937 rem_anchor_token(T_this);
9938 rem_anchor_token(T_template);
9939 rem_anchor_token(T_switch);
9940 rem_anchor_token(T_struct);
9941 rem_anchor_token(T_static_cast);
9942 rem_anchor_token(T_static);
9943 rem_anchor_token(T_sizeof);
9944 rem_anchor_token(T_signed);
9945 rem_anchor_token(T_short);
9946 rem_anchor_token(T_return);
9947 rem_anchor_token(T_restrict);
9948 rem_anchor_token(T_reinterpret_cast);
9949 rem_anchor_token(T_register);
9950 rem_anchor_token(T_operator);
9951 rem_anchor_token(T_new);
9952 rem_anchor_token(T_long);
9953 rem_anchor_token(T_int);
9954 rem_anchor_token(T_inline);
9955 rem_anchor_token(T_if);
9956 rem_anchor_token(T_goto);
9957 rem_anchor_token(T_for);
9958 rem_anchor_token(T_float);
9959 rem_anchor_token(T_false);
9960 rem_anchor_token(T_extern);
9961 rem_anchor_token(T_enum);
9962 rem_anchor_token(T_dynamic_cast);
9963 rem_anchor_token(T_do);
9964 rem_anchor_token(T_double);
9965 rem_anchor_token(T_delete);
9966 rem_anchor_token(T_default);
9967 rem_anchor_token(T_continue);
9968 rem_anchor_token(T_const_cast);
9969 rem_anchor_token(T_const);
9970 rem_anchor_token(T_class);
9971 rem_anchor_token(T_char);
9972 rem_anchor_token(T_case);
9973 rem_anchor_token(T_break);
9974 rem_anchor_token(T_bool);
9975 rem_anchor_token(T_auto);
9976 rem_anchor_token(T_asm);
9977 rem_anchor_token(T___thread);
9978 rem_anchor_token(T___real__);
9979 rem_anchor_token(T___label__);
9980 rem_anchor_token(T___imag__);
9981 rem_anchor_token(T___func__);
9982 rem_anchor_token(T___extension__);
9983 rem_anchor_token(T___builtin_va_start);
9984 rem_anchor_token(T___attribute__);
9985 rem_anchor_token(T___alignof__);
9986 rem_anchor_token(T___PRETTY_FUNCTION__);
9987 rem_anchor_token(T__Imaginary);
9988 rem_anchor_token(T__Complex);
9989 rem_anchor_token(T__Bool);
9990 rem_anchor_token(T_STRING_LITERAL);
9991 rem_anchor_token(T_PLUSPLUS);
9992 rem_anchor_token(T_NUMBER);
9993 rem_anchor_token(T_MINUSMINUS);
9994 rem_anchor_token(T_IDENTIFIER);
9995 rem_anchor_token(T_COLONCOLON);
9996 rem_anchor_token(T_CHARACTER_CONSTANT);
9997 rem_anchor_token('~');
9998 rem_anchor_token('{');
9999 rem_anchor_token(';');
10000 rem_anchor_token('-');
10001 rem_anchor_token('+');
10002 rem_anchor_token('*');
10003 rem_anchor_token('(');
10004 rem_anchor_token('&');
10005 rem_anchor_token('!');
10006 rem_anchor_token('}');
10014 * Check for unused global static functions and variables
10016 static void check_unused_globals(void)
10018 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10021 for (const entity_t *entity = file_scope->entities; entity != NULL;
10022 entity = entity->base.next) {
10023 if (!is_declaration(entity))
10026 const declaration_t *declaration = &entity->declaration;
10027 if (declaration->used ||
10028 declaration->modifiers & DM_UNUSED ||
10029 declaration->modifiers & DM_USED ||
10030 declaration->storage_class != STORAGE_CLASS_STATIC)
10035 if (entity->kind == ENTITY_FUNCTION) {
10036 /* inhibit warning for static inline functions */
10037 if (entity->function.is_inline)
10040 why = WARN_UNUSED_FUNCTION;
10041 s = entity->function.statement != NULL ? "defined" : "declared";
10043 why = WARN_UNUSED_VARIABLE;
10047 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10051 static void parse_global_asm(void)
10053 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10056 add_anchor_token(';');
10057 add_anchor_token(')');
10058 add_anchor_token(T_STRING_LITERAL);
10061 rem_anchor_token(T_STRING_LITERAL);
10062 statement->asms.asm_text = parse_string_literals("global asm");
10063 statement->base.next = unit->global_asm;
10064 unit->global_asm = statement;
10066 rem_anchor_token(')');
10068 rem_anchor_token(';');
10072 static void parse_linkage_specification(void)
10076 source_position_t const pos = *HERE;
10077 char const *const linkage = parse_string_literals(NULL).begin;
10079 linkage_kind_t old_linkage = current_linkage;
10080 linkage_kind_t new_linkage;
10081 if (streq(linkage, "C")) {
10082 new_linkage = LINKAGE_C;
10083 } else if (streq(linkage, "C++")) {
10084 new_linkage = LINKAGE_CXX;
10086 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10087 new_linkage = LINKAGE_C;
10089 current_linkage = new_linkage;
10091 if (next_if('{')) {
10098 assert(current_linkage == new_linkage);
10099 current_linkage = old_linkage;
10102 static void parse_external(void)
10104 switch (token.kind) {
10106 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10107 parse_linkage_specification();
10109 DECLARATION_START_NO_EXTERN
10111 case T___extension__:
10112 /* tokens below are for implicit int */
10113 case '&': /* & x; -> int& x; (and error later, because C++ has no
10115 case '*': /* * x; -> int* x; */
10116 case '(': /* (x); -> int (x); */
10118 parse_external_declaration();
10124 parse_global_asm();
10128 parse_namespace_definition();
10132 if (!strict_mode) {
10133 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10140 errorf(HERE, "stray %K outside of function", &token);
10141 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10142 eat_until_matching_token(token.kind);
10148 static void parse_externals(void)
10150 add_anchor_token('}');
10151 add_anchor_token(T_EOF);
10154 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10155 unsigned short token_anchor_copy[T_LAST_TOKEN];
10156 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10159 while (token.kind != T_EOF && token.kind != '}') {
10161 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10162 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10164 /* the anchor set and its copy differs */
10165 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10168 if (in_gcc_extension) {
10169 /* an gcc extension scope was not closed */
10170 internal_errorf(HERE, "Leaked __extension__");
10177 rem_anchor_token(T_EOF);
10178 rem_anchor_token('}');
10182 * Parse a translation unit.
10184 static void parse_translation_unit(void)
10186 add_anchor_token(T_EOF);
10191 if (token.kind == T_EOF)
10194 errorf(HERE, "stray %K outside of function", &token);
10195 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10196 eat_until_matching_token(token.kind);
10201 void set_default_visibility(elf_visibility_tag_t visibility)
10203 default_visibility = visibility;
10209 * @return the translation unit or NULL if errors occurred.
10211 void start_parsing(void)
10213 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10214 label_stack = NEW_ARR_F(stack_entry_t, 0);
10218 print_to_file(stderr);
10220 assert(unit == NULL);
10221 unit = allocate_ast_zero(sizeof(unit[0]));
10223 assert(file_scope == NULL);
10224 file_scope = &unit->scope;
10226 assert(current_scope == NULL);
10227 scope_push(&unit->scope);
10229 create_gnu_builtins();
10231 create_microsoft_intrinsics();
10234 translation_unit_t *finish_parsing(void)
10236 assert(current_scope == &unit->scope);
10239 assert(file_scope == &unit->scope);
10240 check_unused_globals();
10243 DEL_ARR_F(environment_stack);
10244 DEL_ARR_F(label_stack);
10246 translation_unit_t *result = unit;
10251 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10252 * are given length one. */
10253 static void complete_incomplete_arrays(void)
10255 size_t n = ARR_LEN(incomplete_arrays);
10256 for (size_t i = 0; i != n; ++i) {
10257 declaration_t *const decl = incomplete_arrays[i];
10258 type_t *const type = skip_typeref(decl->type);
10260 if (!is_type_incomplete(type))
10263 source_position_t const *const pos = &decl->base.source_position;
10264 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10266 type_t *const new_type = duplicate_type(type);
10267 new_type->array.size_constant = true;
10268 new_type->array.has_implicit_size = true;
10269 new_type->array.size = 1;
10271 type_t *const result = identify_new_type(new_type);
10273 decl->type = result;
10277 static void prepare_main_collect2(entity_t *const entity)
10279 PUSH_SCOPE(&entity->function.statement->compound.scope);
10281 // create call to __main
10282 symbol_t *symbol = symbol_table_insert("__main");
10283 entity_t *subsubmain_ent
10284 = create_implicit_function(symbol, &builtin_source_position);
10286 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10287 type_t *ftype = subsubmain_ent->declaration.type;
10288 ref->base.source_position = builtin_source_position;
10289 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10290 ref->reference.entity = subsubmain_ent;
10292 expression_t *call = allocate_expression_zero(EXPR_CALL);
10293 call->base.source_position = builtin_source_position;
10294 call->base.type = type_void;
10295 call->call.function = ref;
10297 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10298 expr_statement->base.source_position = builtin_source_position;
10299 expr_statement->expression.expression = call;
10301 statement_t *statement = entity->function.statement;
10302 assert(statement->kind == STATEMENT_COMPOUND);
10303 compound_statement_t *compounds = &statement->compound;
10305 expr_statement->base.next = compounds->statements;
10306 compounds->statements = expr_statement;
10313 lookahead_bufpos = 0;
10314 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10317 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10318 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10319 parse_translation_unit();
10320 complete_incomplete_arrays();
10321 DEL_ARR_F(incomplete_arrays);
10322 incomplete_arrays = NULL;
10326 * Initialize the parser.
10328 void init_parser(void)
10330 sym_anonymous = symbol_table_insert("<anonymous>");
10332 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10334 init_expression_parsers();
10335 obstack_init(&temp_obst);
10339 * Terminate the parser.
10341 void exit_parser(void)
10343 obstack_free(&temp_obst, NULL);