2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "adt/strutil.h"
29 #include "diagnostic.h"
30 #include "format_check.h"
31 #include "preprocessor.h"
36 #include "type_hash.h"
39 #include "attribute_t.h"
40 #include "lang_features.h"
45 #include "adt/bitfiddle.h"
46 #include "adt/error.h"
47 #include "adt/array.h"
49 //#define PRINT_TOKENS
50 #define MAX_LOOKAHEAD 1
55 entity_namespace_t namespc;
58 typedef struct declaration_specifiers_t declaration_specifiers_t;
59 struct declaration_specifiers_t {
60 source_position_t source_position;
61 storage_class_t storage_class;
62 unsigned char alignment; /**< Alignment, 0 if not set. */
64 bool thread_local : 1;
65 attribute_t *attributes; /**< list of attributes */
70 * An environment for parsing initializers (and compound literals).
72 typedef struct parse_initializer_env_t {
73 type_t *type; /**< the type of the initializer. In case of an
74 array type with unspecified size this gets
75 adjusted to the actual size. */
76 entity_t *entity; /**< the variable that is initialized if any */
77 bool must_be_constant;
78 } parse_initializer_env_t;
80 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
82 /** The current token. */
84 /** The lookahead ring-buffer. */
85 static token_t lookahead_buffer[MAX_LOOKAHEAD];
86 /** Position of the next token in the lookahead buffer. */
87 static size_t lookahead_bufpos;
88 static stack_entry_t *environment_stack = NULL;
89 static stack_entry_t *label_stack = NULL;
90 static scope_t *file_scope = NULL;
91 static scope_t *current_scope = NULL;
92 /** Point to the current function declaration if inside a function. */
93 static function_t *current_function = NULL;
94 static entity_t *current_entity = NULL;
95 static switch_statement_t *current_switch = NULL;
96 static statement_t *current_loop = NULL;
97 static statement_t *current_parent = NULL;
98 static ms_try_statement_t *current_try = NULL;
99 static linkage_kind_t current_linkage;
100 static goto_statement_t *goto_first = NULL;
101 static goto_statement_t **goto_anchor = NULL;
102 static label_statement_t *label_first = NULL;
103 static label_statement_t **label_anchor = NULL;
104 /** current translation unit. */
105 static translation_unit_t *unit = NULL;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_CURRENT_ENTITY(entity) \
115 entity_t *const new_current_entity = (entity); \
116 entity_t *const old_current_entity = current_entity; \
117 ((void)(current_entity = new_current_entity))
118 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
120 #define PUSH_PARENT(stmt) \
121 statement_t *const new_parent = (stmt); \
122 statement_t *const old_parent = current_parent; \
123 ((void)(current_parent = new_parent))
124 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
126 #define PUSH_SCOPE(scope) \
127 size_t const top = environment_top(); \
128 scope_t *const new_scope = (scope); \
129 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
130 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
131 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
133 #define PUSH_EXTENSION() \
135 bool const old_gcc_extension = in_gcc_extension; \
136 while (next_if(T___extension__)) { \
137 in_gcc_extension = true; \
140 #define POP_EXTENSION() \
141 ((void)(in_gcc_extension = old_gcc_extension))
143 /** The token anchor set */
144 static unsigned short token_anchor_set[T_LAST_TOKEN];
146 /** The current source position. */
147 #define HERE (&token.base.source_position)
149 /** true if we are in GCC mode. */
150 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
152 static statement_t *parse_compound_statement(bool inside_expression_statement);
153 static statement_t *parse_statement(void);
155 static expression_t *parse_subexpression(precedence_t);
156 static expression_t *parse_expression(void);
157 static type_t *parse_typename(void);
158 static void parse_externals(void);
159 static void parse_external(void);
161 static void parse_compound_type_entries(compound_t *compound_declaration);
163 static void check_call_argument(type_t *expected_type,
164 call_argument_t *argument, unsigned pos);
166 typedef enum declarator_flags_t {
168 DECL_MAY_BE_ABSTRACT = 1U << 0,
169 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
170 DECL_IS_PARAMETER = 1U << 2
171 } declarator_flags_t;
173 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
174 declarator_flags_t flags);
176 static void semantic_comparison(binary_expression_t *expression);
178 #define STORAGE_CLASSES \
179 STORAGE_CLASSES_NO_EXTERN \
182 #define STORAGE_CLASSES_NO_EXTERN \
187 case T__Thread_local:
189 #define TYPE_QUALIFIERS \
194 case T__forceinline: \
195 case T___attribute__:
197 #define COMPLEX_SPECIFIERS \
199 #define IMAGINARY_SPECIFIERS \
202 #define TYPE_SPECIFIERS \
204 case T___builtin_va_list: \
229 #define DECLARATION_START \
234 #define DECLARATION_START_NO_EXTERN \
235 STORAGE_CLASSES_NO_EXTERN \
239 #define EXPRESSION_START \
248 case T_CHARACTER_CONSTANT: \
252 case T_STRING_LITERAL: \
254 case T___FUNCDNAME__: \
255 case T___FUNCSIG__: \
256 case T___PRETTY_FUNCTION__: \
257 case T___builtin_classify_type: \
258 case T___builtin_constant_p: \
259 case T___builtin_isgreater: \
260 case T___builtin_isgreaterequal: \
261 case T___builtin_isless: \
262 case T___builtin_islessequal: \
263 case T___builtin_islessgreater: \
264 case T___builtin_isunordered: \
265 case T___builtin_offsetof: \
266 case T___builtin_va_arg: \
267 case T___builtin_va_copy: \
268 case T___builtin_va_start: \
279 * Returns the size of a statement node.
281 * @param kind the statement kind
283 static size_t get_statement_struct_size(statement_kind_t kind)
285 static const size_t sizes[] = {
286 [STATEMENT_ERROR] = sizeof(statement_base_t),
287 [STATEMENT_EMPTY] = sizeof(statement_base_t),
288 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
289 [STATEMENT_RETURN] = sizeof(return_statement_t),
290 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
291 [STATEMENT_IF] = sizeof(if_statement_t),
292 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
293 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
294 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
295 [STATEMENT_BREAK] = sizeof(statement_base_t),
296 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
297 [STATEMENT_GOTO] = sizeof(goto_statement_t),
298 [STATEMENT_LABEL] = sizeof(label_statement_t),
299 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
300 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
301 [STATEMENT_FOR] = sizeof(for_statement_t),
302 [STATEMENT_ASM] = sizeof(asm_statement_t),
303 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
304 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
306 assert((size_t)kind < lengthof(sizes));
307 assert(sizes[kind] != 0);
312 * Returns the size of an expression node.
314 * @param kind the expression kind
316 static size_t get_expression_struct_size(expression_kind_t kind)
318 static const size_t sizes[] = {
319 [EXPR_ERROR] = sizeof(expression_base_t),
320 [EXPR_REFERENCE] = sizeof(reference_expression_t),
321 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
322 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
323 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
324 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_CHARACTER] = sizeof(string_literal_expression_t),
326 [EXPR_LITERAL_MS_NOOP] = sizeof(literal_expression_t),
327 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
328 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
329 [EXPR_CALL] = sizeof(call_expression_t),
330 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
331 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
332 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
333 [EXPR_SELECT] = sizeof(select_expression_t),
334 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
335 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
336 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
337 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
338 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
339 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
340 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
341 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
342 [EXPR_VA_START] = sizeof(va_start_expression_t),
343 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
344 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
345 [EXPR_STATEMENT] = sizeof(statement_expression_t),
346 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
348 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
349 return sizes[EXPR_UNARY_FIRST];
351 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
352 return sizes[EXPR_BINARY_FIRST];
354 assert((size_t)kind < lengthof(sizes));
355 assert(sizes[kind] != 0);
360 * Allocate a statement node of given kind and initialize all
361 * fields with zero. Sets its source position to the position
362 * of the current token.
364 static statement_t *allocate_statement_zero(statement_kind_t kind)
366 size_t size = get_statement_struct_size(kind);
367 statement_t *res = allocate_ast_zero(size);
369 res->base.kind = kind;
370 res->base.parent = current_parent;
371 res->base.source_position = *HERE;
376 * Allocate an expression node of given kind and initialize all
379 * @param kind the kind of the expression to allocate
381 static expression_t *allocate_expression_zero(expression_kind_t kind)
383 size_t size = get_expression_struct_size(kind);
384 expression_t *res = allocate_ast_zero(size);
386 res->base.kind = kind;
387 res->base.type = type_error_type;
388 res->base.source_position = *HERE;
393 * Creates a new invalid expression at the source position
394 * of the current token.
396 static expression_t *create_error_expression(void)
398 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
399 expression->base.type = type_error_type;
404 * Creates a new invalid statement.
406 static statement_t *create_error_statement(void)
408 return allocate_statement_zero(STATEMENT_ERROR);
412 * Allocate a new empty statement.
414 static statement_t *create_empty_statement(void)
416 return allocate_statement_zero(STATEMENT_EMPTY);
420 * Returns the size of an initializer node.
422 * @param kind the initializer kind
424 static size_t get_initializer_size(initializer_kind_t kind)
426 static const size_t sizes[] = {
427 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
428 [INITIALIZER_STRING] = sizeof(initializer_value_t),
429 [INITIALIZER_LIST] = sizeof(initializer_list_t),
430 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
432 assert((size_t)kind < lengthof(sizes));
433 assert(sizes[kind] != 0);
438 * Allocate an initializer node of given kind and initialize all
441 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
443 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
450 * Returns the index of the top element of the environment stack.
452 static size_t environment_top(void)
454 return ARR_LEN(environment_stack);
458 * Returns the index of the top element of the global label stack.
460 static size_t label_top(void)
462 return ARR_LEN(label_stack);
466 * Return the next token.
468 static inline void next_token(void)
470 token = lookahead_buffer[lookahead_bufpos];
471 lookahead_buffer[lookahead_bufpos] = pp_token;
472 next_preprocessing_token();
474 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
477 print_token(stderr, &token);
478 fprintf(stderr, "\n");
482 static inline void eat(token_kind_t const kind)
484 assert(token.kind == kind);
489 static inline bool next_if(token_kind_t const kind)
491 if (token.kind == kind) {
500 * Return the next token with a given lookahead.
502 static inline const token_t *look_ahead(size_t num)
504 assert(0 < num && num <= MAX_LOOKAHEAD);
505 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
506 return &lookahead_buffer[pos];
510 * Adds a token type to the token type anchor set (a multi-set).
512 static void add_anchor_token(token_kind_t const token_kind)
514 assert(token_kind < T_LAST_TOKEN);
515 ++token_anchor_set[token_kind];
519 * Remove a token type from the token type anchor set (a multi-set).
521 static void rem_anchor_token(token_kind_t const token_kind)
523 assert(token_kind < T_LAST_TOKEN);
524 assert(token_anchor_set[token_kind] != 0);
525 --token_anchor_set[token_kind];
529 * Eat tokens until a matching token type is found.
531 static void eat_until_matching_token(token_kind_t const type)
533 token_kind_t end_token;
535 case '(': end_token = ')'; break;
536 case '{': end_token = '}'; break;
537 case '[': end_token = ']'; break;
538 default: end_token = type; break;
541 unsigned parenthesis_count = 0;
542 unsigned brace_count = 0;
543 unsigned bracket_count = 0;
544 while (token.kind != end_token ||
545 parenthesis_count != 0 ||
547 bracket_count != 0) {
548 switch (token.kind) {
550 case '(': ++parenthesis_count; break;
551 case '{': ++brace_count; break;
552 case '[': ++bracket_count; break;
555 if (parenthesis_count > 0)
565 if (bracket_count > 0)
568 if (token.kind == end_token &&
569 parenthesis_count == 0 &&
583 * Eat input tokens until an anchor is found.
585 static void eat_until_anchor(void)
587 while (token_anchor_set[token.kind] == 0) {
588 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
589 eat_until_matching_token(token.kind);
595 * Eat a whole block from input tokens.
597 static void eat_block(void)
599 eat_until_matching_token('{');
604 * Report a parse error because an expected token was not found.
607 #if defined __GNUC__ && __GNUC__ >= 4
608 __attribute__((sentinel))
610 void parse_error_expected(const char *message, ...)
612 if (message != NULL) {
613 errorf(HERE, "%s", message);
616 va_start(ap, message);
617 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
622 * Report an incompatible type.
624 static void type_error_incompatible(const char *msg,
625 const source_position_t *source_position, type_t *type1, type_t *type2)
627 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
631 static bool skip_till(token_kind_t const expected, char const *const context)
633 if (UNLIKELY(token.kind != expected)) {
634 parse_error_expected(context, expected, NULL);
635 add_anchor_token(expected);
637 rem_anchor_token(expected);
638 if (token.kind != expected)
645 * Expect the current token is the expected token.
646 * If not, generate an error and skip until the next anchor.
648 static void expect(token_kind_t const expected)
650 if (skip_till(expected, NULL))
654 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
656 if (!skip_till(T_IDENTIFIER, context))
658 symbol_t *const sym = token.base.symbol;
666 * Push a given scope on the scope stack and make it the
669 static scope_t *scope_push(scope_t *new_scope)
671 if (current_scope != NULL) {
672 new_scope->depth = current_scope->depth + 1;
675 scope_t *old_scope = current_scope;
676 current_scope = new_scope;
681 * Pop the current scope from the scope stack.
683 static void scope_pop(scope_t *old_scope)
685 current_scope = old_scope;
689 * Search an entity by its symbol in a given namespace.
691 static entity_t *get_entity(const symbol_t *const symbol,
692 namespace_tag_t namespc)
694 entity_t *entity = symbol->entity;
695 for (; entity != NULL; entity = entity->base.symbol_next) {
696 if ((namespace_tag_t)entity->base.namespc == namespc)
703 /* §6.2.3:1 24) There is only one name space for tags even though three are
705 static entity_t *get_tag(symbol_t const *const symbol,
706 entity_kind_tag_t const kind)
708 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
709 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
711 "'%Y' defined as wrong kind of tag (previous definition %P)",
712 symbol, &entity->base.source_position);
719 * pushs an entity on the environment stack and links the corresponding symbol
722 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
724 symbol_t *symbol = entity->base.symbol;
725 entity_namespace_t namespc = entity->base.namespc;
726 assert(namespc != 0);
728 /* replace/add entity into entity list of the symbol */
731 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
736 /* replace an entry? */
737 if (iter->base.namespc == namespc) {
738 entity->base.symbol_next = iter->base.symbol_next;
744 /* remember old declaration */
746 entry.symbol = symbol;
747 entry.old_entity = iter;
748 entry.namespc = namespc;
749 ARR_APP1(stack_entry_t, *stack_ptr, entry);
753 * Push an entity on the environment stack.
755 static void environment_push(entity_t *entity)
757 assert(entity->base.source_position.input_name != NULL);
758 assert(entity->base.parent_scope != NULL);
759 stack_push(&environment_stack, entity);
763 * Push a declaration on the global label stack.
765 * @param declaration the declaration
767 static void label_push(entity_t *label)
769 /* we abuse the parameters scope as parent for the labels */
770 label->base.parent_scope = ¤t_function->parameters;
771 stack_push(&label_stack, label);
775 * pops symbols from the environment stack until @p new_top is the top element
777 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
779 stack_entry_t *stack = *stack_ptr;
780 size_t top = ARR_LEN(stack);
783 assert(new_top <= top);
787 for (i = top; i > new_top; --i) {
788 stack_entry_t *entry = &stack[i - 1];
790 entity_t *old_entity = entry->old_entity;
791 symbol_t *symbol = entry->symbol;
792 entity_namespace_t namespc = entry->namespc;
794 /* replace with old_entity/remove */
797 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
799 assert(iter != NULL);
800 /* replace an entry? */
801 if (iter->base.namespc == namespc)
805 /* restore definition from outer scopes (if there was one) */
806 if (old_entity != NULL) {
807 old_entity->base.symbol_next = iter->base.symbol_next;
808 *anchor = old_entity;
810 /* remove entry from list */
811 *anchor = iter->base.symbol_next;
815 ARR_SHRINKLEN(*stack_ptr, new_top);
819 * Pop all entries from the environment stack until the new_top
822 * @param new_top the new stack top
824 static void environment_pop_to(size_t new_top)
826 stack_pop_to(&environment_stack, new_top);
830 * Pop all entries from the global label stack until the new_top
833 * @param new_top the new stack top
835 static void label_pop_to(size_t new_top)
837 stack_pop_to(&label_stack, new_top);
840 static atomic_type_kind_t get_akind(const type_t *type)
842 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
843 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
844 return type->atomic.akind;
848 * §6.3.1.1:2 Do integer promotion for a given type.
850 * @param type the type to promote
851 * @return the promoted type
853 static type_t *promote_integer(type_t *type)
855 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
862 * Check if a given expression represents a null pointer constant.
864 * @param expression the expression to check
866 static bool is_null_pointer_constant(const expression_t *expression)
868 /* skip void* cast */
869 if (expression->kind == EXPR_UNARY_CAST) {
870 type_t *const type = skip_typeref(expression->base.type);
871 if (types_compatible(type, type_void_ptr))
872 expression = expression->unary.value;
875 type_t *const type = skip_typeref(expression->base.type);
876 if (!is_type_integer(type))
878 switch (is_constant_expression(expression)) {
879 case EXPR_CLASS_ERROR: return true;
880 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
881 default: return false;
886 * Create an implicit cast expression.
888 * @param expression the expression to cast
889 * @param dest_type the destination type
891 static expression_t *create_implicit_cast(expression_t *expression,
894 type_t *const source_type = expression->base.type;
896 if (source_type == dest_type)
899 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
900 cast->unary.value = expression;
901 cast->base.type = dest_type;
902 cast->base.implicit = true;
907 typedef enum assign_error_t {
909 ASSIGN_ERROR_INCOMPATIBLE,
910 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
911 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
912 ASSIGN_WARNING_POINTER_FROM_INT,
913 ASSIGN_WARNING_INT_FROM_POINTER
916 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)
918 type_t *const orig_type_right = right->base.type;
919 type_t *const type_left = skip_typeref(orig_type_left);
920 type_t *const type_right = skip_typeref(orig_type_right);
925 case ASSIGN_ERROR_INCOMPATIBLE:
926 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
929 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
930 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
931 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
933 /* the left type has all qualifiers from the right type */
934 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
935 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);
939 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
940 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
943 case ASSIGN_WARNING_POINTER_FROM_INT:
944 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
947 case ASSIGN_WARNING_INT_FROM_POINTER:
948 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
952 panic("invalid error value");
956 /** Implements the rules from §6.5.16.1 */
957 static assign_error_t semantic_assign(type_t *orig_type_left,
958 const expression_t *const right)
960 type_t *const orig_type_right = right->base.type;
961 type_t *const type_left = skip_typeref(orig_type_left);
962 type_t *const type_right = skip_typeref(orig_type_right);
964 if (is_type_pointer(type_left)) {
965 if (is_null_pointer_constant(right)) {
966 return ASSIGN_SUCCESS;
967 } else if (is_type_pointer(type_right)) {
968 type_t *points_to_left
969 = skip_typeref(type_left->pointer.points_to);
970 type_t *points_to_right
971 = skip_typeref(type_right->pointer.points_to);
972 assign_error_t res = ASSIGN_SUCCESS;
974 /* the left type has all qualifiers from the right type */
975 unsigned missing_qualifiers
976 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
977 if (missing_qualifiers != 0) {
978 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
981 points_to_left = get_unqualified_type(points_to_left);
982 points_to_right = get_unqualified_type(points_to_right);
984 if (is_type_void(points_to_left))
987 if (is_type_void(points_to_right)) {
988 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
989 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
992 if (!types_compatible(points_to_left, points_to_right)) {
993 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
997 } else if (is_type_integer(type_right)) {
998 return ASSIGN_WARNING_POINTER_FROM_INT;
1000 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1001 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1002 && is_type_pointer(type_right))) {
1003 return ASSIGN_SUCCESS;
1004 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1005 type_t *const unqual_type_left = get_unqualified_type(type_left);
1006 type_t *const unqual_type_right = get_unqualified_type(type_right);
1007 if (types_compatible(unqual_type_left, unqual_type_right)) {
1008 return ASSIGN_SUCCESS;
1010 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1011 return ASSIGN_WARNING_INT_FROM_POINTER;
1014 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1015 return ASSIGN_SUCCESS;
1017 return ASSIGN_ERROR_INCOMPATIBLE;
1020 static expression_t *parse_constant_expression(void)
1022 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1024 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1025 errorf(&result->base.source_position,
1026 "expression '%E' is not constant", result);
1032 static expression_t *parse_assignment_expression(void)
1034 return parse_subexpression(PREC_ASSIGNMENT);
1037 static void append_string(string_t const *const s)
1039 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1040 * possible, because other tokens are grown there alongside. */
1041 obstack_grow(&ast_obstack, s->begin, s->size);
1044 static string_t finish_string(string_encoding_t const enc)
1046 obstack_1grow(&ast_obstack, '\0');
1047 size_t const size = obstack_object_size(&ast_obstack) - 1;
1048 char const *const string = obstack_finish(&ast_obstack);
1049 return (string_t){ string, size, enc };
1052 static string_t concat_string_literals(void)
1054 assert(token.kind == T_STRING_LITERAL);
1057 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1058 append_string(&token.literal.string);
1059 eat(T_STRING_LITERAL);
1060 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1061 string_encoding_t enc = token.literal.string.encoding;
1063 string_encoding_t const new_enc = token.literal.string.encoding;
1064 if (new_enc != enc && new_enc != STRING_ENCODING_CHAR) {
1065 if (enc == STRING_ENCODING_CHAR) {
1068 errorf(HERE, "concatenating string literals with encodings %s and %s", get_string_encoding_prefix(enc), get_string_encoding_prefix(new_enc));
1071 append_string(&token.literal.string);
1072 eat(T_STRING_LITERAL);
1073 } while (token.kind == T_STRING_LITERAL);
1074 result = finish_string(enc);
1076 result = token.literal.string;
1077 eat(T_STRING_LITERAL);
1083 static string_t parse_string_literals(char const *const context)
1085 if (!skip_till(T_STRING_LITERAL, context))
1086 return (string_t){ "", 0, STRING_ENCODING_CHAR };
1088 source_position_t const pos = *HERE;
1089 string_t const res = concat_string_literals();
1091 if (res.encoding != STRING_ENCODING_CHAR) {
1092 errorf(&pos, "expected plain string literal, got %s string literal", get_string_encoding_prefix(res.encoding));
1098 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1100 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1101 attribute->kind = kind;
1102 attribute->source_position = *HERE;
1107 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1110 * __attribute__ ( ( attribute-list ) )
1114 * attribute_list , attrib
1119 * any-word ( identifier )
1120 * any-word ( identifier , nonempty-expr-list )
1121 * any-word ( expr-list )
1123 * where the "identifier" must not be declared as a type, and
1124 * "any-word" may be any identifier (including one declared as a
1125 * type), a reserved word storage class specifier, type specifier or
1126 * type qualifier. ??? This still leaves out most reserved keywords
1127 * (following the old parser), shouldn't we include them, and why not
1128 * allow identifiers declared as types to start the arguments?
1130 * Matze: this all looks confusing and little systematic, so we're even less
1131 * strict and parse any list of things which are identifiers or
1132 * (assignment-)expressions.
1134 static attribute_argument_t *parse_attribute_arguments(void)
1136 attribute_argument_t *first = NULL;
1137 attribute_argument_t **anchor = &first;
1138 if (token.kind != ')') do {
1139 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1141 /* is it an identifier */
1142 if (token.kind == T_IDENTIFIER
1143 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1144 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1145 argument->v.symbol = token.base.symbol;
1148 /* must be an expression */
1149 expression_t *expression = parse_assignment_expression();
1151 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1152 argument->v.expression = expression;
1155 /* append argument */
1157 anchor = &argument->next;
1158 } while (next_if(','));
1163 static attribute_t *parse_attribute_asm(void)
1165 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1168 attribute->a.arguments = parse_attribute_arguments();
1172 static attribute_t *parse_attribute_gnu_single(void)
1174 /* parse "any-word" */
1175 symbol_t *const symbol = token.base.symbol;
1176 if (symbol == NULL) {
1177 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1181 attribute_kind_t kind;
1182 char const *const name = symbol->string;
1183 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1184 if (kind > ATTRIBUTE_GNU_LAST) {
1185 /* special case for "__const" */
1186 if (token.kind == T_const) {
1187 kind = ATTRIBUTE_GNU_CONST;
1191 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1192 /* TODO: we should still save the attribute in the list... */
1193 kind = ATTRIBUTE_UNKNOWN;
1197 const char *attribute_name = get_attribute_name(kind);
1198 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1202 attribute_t *attribute = allocate_attribute_zero(kind);
1205 /* parse arguments */
1207 attribute->a.arguments = parse_attribute_arguments();
1212 static attribute_t *parse_attribute_gnu(void)
1214 attribute_t *first = NULL;
1215 attribute_t **anchor = &first;
1217 eat(T___attribute__);
1218 add_anchor_token(')');
1219 add_anchor_token(',');
1223 if (token.kind != ')') do {
1224 attribute_t *attribute = parse_attribute_gnu_single();
1226 *anchor = attribute;
1227 anchor = &attribute->next;
1229 } while (next_if(','));
1230 rem_anchor_token(',');
1231 rem_anchor_token(')');
1238 /** Parse attributes. */
1239 static attribute_t *parse_attributes(attribute_t *first)
1241 attribute_t **anchor = &first;
1243 while (*anchor != NULL)
1244 anchor = &(*anchor)->next;
1246 attribute_t *attribute;
1247 switch (token.kind) {
1248 case T___attribute__:
1249 attribute = parse_attribute_gnu();
1250 if (attribute == NULL)
1255 attribute = parse_attribute_asm();
1259 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1264 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1268 case T__forceinline:
1269 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1270 eat(T__forceinline);
1274 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1279 /* TODO record modifier */
1280 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1281 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1289 *anchor = attribute;
1290 anchor = &attribute->next;
1294 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1296 static entity_t *determine_lhs_ent(expression_t *const expr,
1299 switch (expr->kind) {
1300 case EXPR_REFERENCE: {
1301 entity_t *const entity = expr->reference.entity;
1302 /* we should only find variables as lvalues... */
1303 if (entity->base.kind != ENTITY_VARIABLE
1304 && entity->base.kind != ENTITY_PARAMETER)
1310 case EXPR_ARRAY_ACCESS: {
1311 expression_t *const ref = expr->array_access.array_ref;
1312 entity_t * ent = NULL;
1313 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1314 ent = determine_lhs_ent(ref, lhs_ent);
1317 mark_vars_read(ref, lhs_ent);
1319 mark_vars_read(expr->array_access.index, lhs_ent);
1324 mark_vars_read(expr->select.compound, lhs_ent);
1325 if (is_type_compound(skip_typeref(expr->base.type)))
1326 return determine_lhs_ent(expr->select.compound, lhs_ent);
1330 case EXPR_UNARY_DEREFERENCE: {
1331 expression_t *const val = expr->unary.value;
1332 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1334 return determine_lhs_ent(val->unary.value, lhs_ent);
1336 mark_vars_read(val, NULL);
1342 mark_vars_read(expr, NULL);
1347 #define ENT_ANY ((entity_t*)-1)
1350 * Mark declarations, which are read. This is used to detect variables, which
1354 * x is not marked as "read", because it is only read to calculate its own new
1358 * x and y are not detected as "not read", because multiple variables are
1361 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1363 switch (expr->kind) {
1364 case EXPR_REFERENCE: {
1365 entity_t *const entity = expr->reference.entity;
1366 if (entity->kind != ENTITY_VARIABLE
1367 && entity->kind != ENTITY_PARAMETER)
1370 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1371 entity->variable.read = true;
1377 // TODO respect pure/const
1378 mark_vars_read(expr->call.function, NULL);
1379 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1380 mark_vars_read(arg->expression, NULL);
1384 case EXPR_CONDITIONAL:
1385 // TODO lhs_decl should depend on whether true/false have an effect
1386 mark_vars_read(expr->conditional.condition, NULL);
1387 if (expr->conditional.true_expression != NULL)
1388 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1389 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1393 if (lhs_ent == ENT_ANY
1394 && !is_type_compound(skip_typeref(expr->base.type)))
1396 mark_vars_read(expr->select.compound, lhs_ent);
1399 case EXPR_ARRAY_ACCESS: {
1400 mark_vars_read(expr->array_access.index, lhs_ent);
1401 expression_t *const ref = expr->array_access.array_ref;
1402 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1403 if (lhs_ent == ENT_ANY)
1406 mark_vars_read(ref, lhs_ent);
1411 mark_vars_read(expr->va_arge.ap, lhs_ent);
1415 mark_vars_read(expr->va_copye.src, lhs_ent);
1418 case EXPR_UNARY_CAST:
1419 /* Special case: Use void cast to mark a variable as "read" */
1420 if (is_type_void(skip_typeref(expr->base.type)))
1425 case EXPR_UNARY_THROW:
1426 if (expr->unary.value == NULL)
1429 case EXPR_UNARY_DEREFERENCE:
1430 case EXPR_UNARY_DELETE:
1431 case EXPR_UNARY_DELETE_ARRAY:
1432 if (lhs_ent == ENT_ANY)
1436 case EXPR_UNARY_NEGATE:
1437 case EXPR_UNARY_PLUS:
1438 case EXPR_UNARY_BITWISE_NEGATE:
1439 case EXPR_UNARY_NOT:
1440 case EXPR_UNARY_TAKE_ADDRESS:
1441 case EXPR_UNARY_POSTFIX_INCREMENT:
1442 case EXPR_UNARY_POSTFIX_DECREMENT:
1443 case EXPR_UNARY_PREFIX_INCREMENT:
1444 case EXPR_UNARY_PREFIX_DECREMENT:
1445 case EXPR_UNARY_ASSUME:
1447 mark_vars_read(expr->unary.value, lhs_ent);
1450 case EXPR_BINARY_ADD:
1451 case EXPR_BINARY_SUB:
1452 case EXPR_BINARY_MUL:
1453 case EXPR_BINARY_DIV:
1454 case EXPR_BINARY_MOD:
1455 case EXPR_BINARY_EQUAL:
1456 case EXPR_BINARY_NOTEQUAL:
1457 case EXPR_BINARY_LESS:
1458 case EXPR_BINARY_LESSEQUAL:
1459 case EXPR_BINARY_GREATER:
1460 case EXPR_BINARY_GREATEREQUAL:
1461 case EXPR_BINARY_BITWISE_AND:
1462 case EXPR_BINARY_BITWISE_OR:
1463 case EXPR_BINARY_BITWISE_XOR:
1464 case EXPR_BINARY_LOGICAL_AND:
1465 case EXPR_BINARY_LOGICAL_OR:
1466 case EXPR_BINARY_SHIFTLEFT:
1467 case EXPR_BINARY_SHIFTRIGHT:
1468 case EXPR_BINARY_COMMA:
1469 case EXPR_BINARY_ISGREATER:
1470 case EXPR_BINARY_ISGREATEREQUAL:
1471 case EXPR_BINARY_ISLESS:
1472 case EXPR_BINARY_ISLESSEQUAL:
1473 case EXPR_BINARY_ISLESSGREATER:
1474 case EXPR_BINARY_ISUNORDERED:
1475 mark_vars_read(expr->binary.left, lhs_ent);
1476 mark_vars_read(expr->binary.right, lhs_ent);
1479 case EXPR_BINARY_ASSIGN:
1480 case EXPR_BINARY_MUL_ASSIGN:
1481 case EXPR_BINARY_DIV_ASSIGN:
1482 case EXPR_BINARY_MOD_ASSIGN:
1483 case EXPR_BINARY_ADD_ASSIGN:
1484 case EXPR_BINARY_SUB_ASSIGN:
1485 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1486 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1487 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1488 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1489 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1490 if (lhs_ent == ENT_ANY)
1492 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1493 mark_vars_read(expr->binary.right, lhs_ent);
1498 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1501 case EXPR_LITERAL_CASES:
1502 case EXPR_LITERAL_CHARACTER:
1504 case EXPR_STRING_LITERAL:
1505 case EXPR_COMPOUND_LITERAL: // TODO init?
1507 case EXPR_CLASSIFY_TYPE:
1510 case EXPR_BUILTIN_CONSTANT_P:
1511 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1513 case EXPR_STATEMENT: // TODO
1514 case EXPR_LABEL_ADDRESS:
1515 case EXPR_ENUM_CONSTANT:
1519 panic("unhandled expression");
1522 static designator_t *parse_designation(void)
1524 designator_t *result = NULL;
1525 designator_t **anchor = &result;
1528 designator_t *designator;
1529 switch (token.kind) {
1531 designator = allocate_ast_zero(sizeof(designator[0]));
1532 designator->source_position = *HERE;
1534 add_anchor_token(']');
1535 designator->array_index = parse_constant_expression();
1536 rem_anchor_token(']');
1540 designator = allocate_ast_zero(sizeof(designator[0]));
1541 designator->source_position = *HERE;
1543 designator->symbol = expect_identifier("while parsing designator", NULL);
1544 if (!designator->symbol)
1552 assert(designator != NULL);
1553 *anchor = designator;
1554 anchor = &designator->next;
1559 * Build an initializer from a given expression.
1561 static initializer_t *initializer_from_expression(type_t *orig_type,
1562 expression_t *expression)
1564 /* TODO check that expression is a constant expression */
1566 type_t *const type = skip_typeref(orig_type);
1568 /* §6.7.8.14/15 char array may be initialized by string literals */
1569 if (expression->kind == EXPR_STRING_LITERAL && is_type_array(type)) {
1570 array_type_t *const array_type = &type->array;
1571 type_t *const element_type = skip_typeref(array_type->element_type);
1572 switch (expression->string_literal.value.encoding) {
1573 case STRING_ENCODING_CHAR:
1574 case STRING_ENCODING_UTF8: {
1575 if (is_type_atomic(element_type, ATOMIC_TYPE_CHAR) ||
1576 is_type_atomic(element_type, ATOMIC_TYPE_SCHAR) ||
1577 is_type_atomic(element_type, ATOMIC_TYPE_UCHAR)) {
1578 goto make_string_init;
1583 case STRING_ENCODING_CHAR16:
1584 case STRING_ENCODING_CHAR32:
1585 case STRING_ENCODING_WIDE: {
1586 assert(is_type_pointer(expression->base.type));
1587 type_t *const init_type = get_unqualified_type(expression->base.type->pointer.points_to);
1588 if (types_compatible(get_unqualified_type(element_type), init_type)) {
1590 initializer_t *const init = allocate_initializer_zero(INITIALIZER_STRING);
1591 init->value.value = expression;
1599 assign_error_t error = semantic_assign(type, expression);
1600 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1602 report_assign_error(error, type, expression, "initializer",
1603 &expression->base.source_position);
1605 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1606 result->value.value = create_implicit_cast(expression, type);
1612 * Parses an scalar initializer.
1614 * §6.7.8.11; eat {} without warning
1616 static initializer_t *parse_scalar_initializer(type_t *type,
1617 bool must_be_constant)
1619 /* there might be extra {} hierarchies */
1621 if (token.kind == '{') {
1622 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1626 } while (token.kind == '{');
1629 expression_t *expression = parse_assignment_expression();
1630 mark_vars_read(expression, NULL);
1631 if (must_be_constant && !is_linker_constant(expression)) {
1632 errorf(&expression->base.source_position,
1633 "initialisation expression '%E' is not constant",
1637 initializer_t *initializer = initializer_from_expression(type, expression);
1639 if (initializer == NULL) {
1640 errorf(&expression->base.source_position,
1641 "expression '%E' (type '%T') doesn't match expected type '%T'",
1642 expression, expression->base.type, type);
1647 bool additional_warning_displayed = false;
1648 while (braces > 0) {
1650 if (token.kind != '}') {
1651 if (!additional_warning_displayed) {
1652 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1653 additional_warning_displayed = true;
1664 * An entry in the type path.
1666 typedef struct type_path_entry_t type_path_entry_t;
1667 struct type_path_entry_t {
1668 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1670 size_t index; /**< For array types: the current index. */
1671 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1676 * A type path expression a position inside compound or array types.
1678 typedef struct type_path_t type_path_t;
1679 struct type_path_t {
1680 type_path_entry_t *path; /**< An flexible array containing the current path. */
1681 type_t *top_type; /**< type of the element the path points */
1682 size_t max_index; /**< largest index in outermost array */
1686 * Prints a type path for debugging.
1688 static __attribute__((unused)) void debug_print_type_path(
1689 const type_path_t *path)
1691 size_t len = ARR_LEN(path->path);
1693 for (size_t i = 0; i < len; ++i) {
1694 const type_path_entry_t *entry = & path->path[i];
1696 type_t *type = skip_typeref(entry->type);
1697 if (is_type_compound(type)) {
1698 /* in gcc mode structs can have no members */
1699 if (entry->v.compound_entry == NULL) {
1703 fprintf(stderr, ".%s",
1704 entry->v.compound_entry->base.symbol->string);
1705 } else if (is_type_array(type)) {
1706 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1708 fprintf(stderr, "-INVALID-");
1711 if (path->top_type != NULL) {
1712 fprintf(stderr, " (");
1713 print_type(path->top_type);
1714 fprintf(stderr, ")");
1719 * Return the top type path entry, ie. in a path
1720 * (type).a.b returns the b.
1722 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1724 size_t len = ARR_LEN(path->path);
1726 return &path->path[len-1];
1730 * Enlarge the type path by an (empty) element.
1732 static type_path_entry_t *append_to_type_path(type_path_t *path)
1734 size_t len = ARR_LEN(path->path);
1735 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1737 type_path_entry_t *result = & path->path[len];
1738 memset(result, 0, sizeof(result[0]));
1743 * Descending into a sub-type. Enter the scope of the current top_type.
1745 static void descend_into_subtype(type_path_t *path)
1747 type_t *orig_top_type = path->top_type;
1748 type_t *top_type = skip_typeref(orig_top_type);
1750 type_path_entry_t *top = append_to_type_path(path);
1751 top->type = top_type;
1753 if (is_type_compound(top_type)) {
1754 compound_t *const compound = top_type->compound.compound;
1755 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1757 if (entry != NULL) {
1758 top->v.compound_entry = &entry->declaration;
1759 path->top_type = entry->declaration.type;
1761 path->top_type = NULL;
1763 } else if (is_type_array(top_type)) {
1765 path->top_type = top_type->array.element_type;
1767 assert(!is_type_valid(top_type));
1772 * Pop an entry from the given type path, ie. returning from
1773 * (type).a.b to (type).a
1775 static void ascend_from_subtype(type_path_t *path)
1777 type_path_entry_t *top = get_type_path_top(path);
1779 path->top_type = top->type;
1781 size_t len = ARR_LEN(path->path);
1782 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1786 * Pop entries from the given type path until the given
1787 * path level is reached.
1789 static void ascend_to(type_path_t *path, size_t top_path_level)
1791 size_t len = ARR_LEN(path->path);
1793 while (len > top_path_level) {
1794 ascend_from_subtype(path);
1795 len = ARR_LEN(path->path);
1799 static bool walk_designator(type_path_t *path, const designator_t *designator,
1800 bool used_in_offsetof)
1802 for (; designator != NULL; designator = designator->next) {
1803 type_path_entry_t *top = get_type_path_top(path);
1804 type_t *orig_type = top->type;
1806 type_t *type = skip_typeref(orig_type);
1808 if (designator->symbol != NULL) {
1809 symbol_t *symbol = designator->symbol;
1810 if (!is_type_compound(type)) {
1811 if (is_type_valid(type)) {
1812 errorf(&designator->source_position,
1813 "'.%Y' designator used for non-compound type '%T'",
1817 top->type = type_error_type;
1818 top->v.compound_entry = NULL;
1819 orig_type = type_error_type;
1821 compound_t *compound = type->compound.compound;
1822 entity_t *iter = compound->members.entities;
1823 for (; iter != NULL; iter = iter->base.next) {
1824 if (iter->base.symbol == symbol) {
1829 errorf(&designator->source_position,
1830 "'%T' has no member named '%Y'", orig_type, symbol);
1833 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1834 if (used_in_offsetof && iter->compound_member.bitfield) {
1835 errorf(&designator->source_position,
1836 "offsetof designator '%Y' must not specify bitfield",
1841 top->type = orig_type;
1842 top->v.compound_entry = &iter->declaration;
1843 orig_type = iter->declaration.type;
1846 expression_t *array_index = designator->array_index;
1847 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1850 if (!is_type_array(type)) {
1851 if (is_type_valid(type)) {
1852 errorf(&designator->source_position,
1853 "[%E] designator used for non-array type '%T'",
1854 array_index, orig_type);
1859 long index = fold_constant_to_int(array_index);
1860 if (!used_in_offsetof) {
1862 errorf(&designator->source_position,
1863 "array index [%E] must be positive", array_index);
1864 } else if (type->array.size_constant) {
1865 long array_size = type->array.size;
1866 if (index >= array_size) {
1867 errorf(&designator->source_position,
1868 "designator [%E] (%d) exceeds array size %d",
1869 array_index, index, array_size);
1874 top->type = orig_type;
1875 top->v.index = (size_t) index;
1876 orig_type = type->array.element_type;
1878 path->top_type = orig_type;
1880 if (designator->next != NULL) {
1881 descend_into_subtype(path);
1887 static void advance_current_object(type_path_t *path, size_t top_path_level)
1889 type_path_entry_t *top = get_type_path_top(path);
1891 type_t *type = skip_typeref(top->type);
1892 if (is_type_union(type)) {
1893 /* in unions only the first element is initialized */
1894 top->v.compound_entry = NULL;
1895 } else if (is_type_struct(type)) {
1896 declaration_t *entry = top->v.compound_entry;
1898 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1899 if (next_entity != NULL) {
1900 assert(is_declaration(next_entity));
1901 entry = &next_entity->declaration;
1906 top->v.compound_entry = entry;
1907 if (entry != NULL) {
1908 path->top_type = entry->type;
1911 } else if (is_type_array(type)) {
1912 assert(is_type_array(type));
1916 if (!type->array.size_constant || top->v.index < type->array.size) {
1920 assert(!is_type_valid(type));
1924 /* we're past the last member of the current sub-aggregate, try if we
1925 * can ascend in the type hierarchy and continue with another subobject */
1926 size_t len = ARR_LEN(path->path);
1928 if (len > top_path_level) {
1929 ascend_from_subtype(path);
1930 advance_current_object(path, top_path_level);
1932 path->top_type = NULL;
1937 * skip any {...} blocks until a closing bracket is reached.
1939 static void skip_initializers(void)
1943 while (token.kind != '}') {
1944 if (token.kind == T_EOF)
1946 if (token.kind == '{') {
1954 static initializer_t *create_empty_initializer(void)
1956 static initializer_t empty_initializer
1957 = { .list = { { INITIALIZER_LIST }, 0 } };
1958 return &empty_initializer;
1962 * Parse a part of an initialiser for a struct or union,
1964 static initializer_t *parse_sub_initializer(type_path_t *path,
1965 type_t *outer_type, size_t top_path_level,
1966 parse_initializer_env_t *env)
1968 if (token.kind == '}') {
1969 /* empty initializer */
1970 return create_empty_initializer();
1973 initializer_t *result = NULL;
1975 type_t *orig_type = path->top_type;
1976 type_t *type = NULL;
1978 if (orig_type == NULL) {
1979 /* We are initializing an empty compound. */
1981 type = skip_typeref(orig_type);
1984 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1987 designator_t *designator = NULL;
1988 if (token.kind == '.' || token.kind == '[') {
1989 designator = parse_designation();
1990 goto finish_designator;
1991 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1992 /* GNU-style designator ("identifier: value") */
1993 designator = allocate_ast_zero(sizeof(designator[0]));
1994 designator->source_position = *HERE;
1995 designator->symbol = token.base.symbol;
2000 /* reset path to toplevel, evaluate designator from there */
2001 ascend_to(path, top_path_level);
2002 if (!walk_designator(path, designator, false)) {
2003 /* can't continue after designation error */
2007 initializer_t *designator_initializer
2008 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2009 designator_initializer->designator.designator = designator;
2010 ARR_APP1(initializer_t*, initializers, designator_initializer);
2012 orig_type = path->top_type;
2013 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2018 if (token.kind == '{') {
2019 if (type != NULL && is_type_scalar(type)) {
2020 sub = parse_scalar_initializer(type, env->must_be_constant);
2023 if (env->entity != NULL) {
2024 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2026 errorf(HERE, "extra brace group at end of initializer");
2031 descend_into_subtype(path);
2034 add_anchor_token('}');
2035 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2037 rem_anchor_token('}');
2042 goto error_parse_next;
2044 ascend_from_subtype(path);
2047 /* must be an expression */
2048 expression_t *expression = parse_assignment_expression();
2049 mark_vars_read(expression, NULL);
2051 if (env->must_be_constant && !is_linker_constant(expression)) {
2052 errorf(&expression->base.source_position,
2053 "Initialisation expression '%E' is not constant",
2058 /* we are already outside, ... */
2059 if (outer_type == NULL)
2060 goto error_parse_next;
2061 type_t *const outer_type_skip = skip_typeref(outer_type);
2062 if (is_type_compound(outer_type_skip) &&
2063 !outer_type_skip->compound.compound->complete) {
2064 goto error_parse_next;
2067 source_position_t const* const pos = &expression->base.source_position;
2068 if (env->entity != NULL) {
2069 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2071 warningf(WARN_OTHER, pos, "excess elements in initializer");
2073 goto error_parse_next;
2076 /* handle { "string" } special case */
2077 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2078 result = initializer_from_expression(outer_type, expression);
2079 if (result != NULL) {
2081 if (token.kind != '}') {
2082 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", outer_type);
2084 /* TODO: eat , ... */
2089 /* descend into subtypes until expression matches type */
2091 orig_type = path->top_type;
2092 type = skip_typeref(orig_type);
2094 sub = initializer_from_expression(orig_type, expression);
2098 if (!is_type_valid(type)) {
2101 if (is_type_scalar(type)) {
2102 errorf(&expression->base.source_position,
2103 "expression '%E' doesn't match expected type '%T'",
2104 expression, orig_type);
2108 descend_into_subtype(path);
2112 /* update largest index of top array */
2113 const type_path_entry_t *first = &path->path[0];
2114 type_t *first_type = first->type;
2115 first_type = skip_typeref(first_type);
2116 if (is_type_array(first_type)) {
2117 size_t index = first->v.index;
2118 if (index > path->max_index)
2119 path->max_index = index;
2122 /* append to initializers list */
2123 ARR_APP1(initializer_t*, initializers, sub);
2128 if (token.kind == '}') {
2133 /* advance to the next declaration if we are not at the end */
2134 advance_current_object(path, top_path_level);
2135 orig_type = path->top_type;
2136 if (orig_type != NULL)
2137 type = skip_typeref(orig_type);
2143 size_t len = ARR_LEN(initializers);
2144 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2145 result = allocate_ast_zero(size);
2146 result->kind = INITIALIZER_LIST;
2147 result->list.len = len;
2148 memcpy(&result->list.initializers, initializers,
2149 len * sizeof(initializers[0]));
2153 skip_initializers();
2155 DEL_ARR_F(initializers);
2156 ascend_to(path, top_path_level+1);
2160 static expression_t *make_size_literal(size_t value)
2162 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2163 literal->base.type = type_size_t;
2166 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2167 literal->literal.value = make_string(buf);
2173 * Parses an initializer. Parsers either a compound literal
2174 * (env->declaration == NULL) or an initializer of a declaration.
2176 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2178 type_t *type = skip_typeref(env->type);
2179 size_t max_index = 0;
2180 initializer_t *result;
2182 if (is_type_scalar(type)) {
2183 result = parse_scalar_initializer(type, env->must_be_constant);
2184 } else if (token.kind == '{') {
2188 memset(&path, 0, sizeof(path));
2189 path.top_type = env->type;
2190 path.path = NEW_ARR_F(type_path_entry_t, 0);
2192 descend_into_subtype(&path);
2194 add_anchor_token('}');
2195 result = parse_sub_initializer(&path, env->type, 1, env);
2196 rem_anchor_token('}');
2198 max_index = path.max_index;
2199 DEL_ARR_F(path.path);
2203 /* parse_scalar_initializer() also works in this case: we simply
2204 * have an expression without {} around it */
2205 result = parse_scalar_initializer(type, env->must_be_constant);
2208 /* §6.7.8:22 array initializers for arrays with unknown size determine
2209 * the array type size */
2210 if (is_type_array(type) && type->array.size_expression == NULL
2211 && result != NULL) {
2213 switch (result->kind) {
2214 case INITIALIZER_LIST:
2215 assert(max_index != 0xdeadbeaf);
2216 size = max_index + 1;
2219 case INITIALIZER_STRING: {
2220 size = get_string_len(&get_init_string(result)->value) + 1;
2224 case INITIALIZER_DESIGNATOR:
2225 case INITIALIZER_VALUE:
2226 /* can happen for parse errors */
2231 internal_errorf(HERE, "invalid initializer type");
2234 type_t *new_type = duplicate_type(type);
2236 new_type->array.size_expression = make_size_literal(size);
2237 new_type->array.size_constant = true;
2238 new_type->array.has_implicit_size = true;
2239 new_type->array.size = size;
2240 env->type = new_type;
2246 static void append_entity(scope_t *scope, entity_t *entity)
2248 if (scope->last_entity != NULL) {
2249 scope->last_entity->base.next = entity;
2251 scope->entities = entity;
2253 entity->base.parent_entity = current_entity;
2254 scope->last_entity = entity;
2258 static compound_t *parse_compound_type_specifier(bool is_struct)
2260 source_position_t const pos = *HERE;
2261 eat(is_struct ? T_struct : T_union);
2263 symbol_t *symbol = NULL;
2264 entity_t *entity = NULL;
2265 attribute_t *attributes = NULL;
2267 if (token.kind == T___attribute__) {
2268 attributes = parse_attributes(NULL);
2271 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2272 if (token.kind == T_IDENTIFIER) {
2273 /* the compound has a name, check if we have seen it already */
2274 symbol = token.base.symbol;
2275 entity = get_tag(symbol, kind);
2278 if (entity != NULL) {
2279 if (entity->base.parent_scope != current_scope &&
2280 (token.kind == '{' || token.kind == ';')) {
2281 /* we're in an inner scope and have a definition. Shadow
2282 * existing definition in outer scope */
2284 } else if (entity->compound.complete && token.kind == '{') {
2285 source_position_t const *const ppos = &entity->base.source_position;
2286 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2287 /* clear members in the hope to avoid further errors */
2288 entity->compound.members.entities = NULL;
2291 } else if (token.kind != '{') {
2292 char const *const msg =
2293 is_struct ? "while parsing struct type specifier" :
2294 "while parsing union type specifier";
2295 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2300 if (entity == NULL) {
2301 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2302 entity->compound.alignment = 1;
2303 entity->base.parent_scope = current_scope;
2304 if (symbol != NULL) {
2305 environment_push(entity);
2307 append_entity(current_scope, entity);
2310 if (token.kind == '{') {
2311 parse_compound_type_entries(&entity->compound);
2313 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2314 if (symbol == NULL) {
2315 assert(anonymous_entity == NULL);
2316 anonymous_entity = entity;
2320 if (attributes != NULL) {
2321 entity->compound.attributes = attributes;
2322 handle_entity_attributes(attributes, entity);
2325 return &entity->compound;
2328 static void parse_enum_entries(type_t *const enum_type)
2332 if (token.kind == '}') {
2333 errorf(HERE, "empty enum not allowed");
2338 add_anchor_token('}');
2339 add_anchor_token(',');
2341 add_anchor_token('=');
2342 source_position_t pos;
2343 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2344 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2345 entity->enum_value.enum_type = enum_type;
2346 rem_anchor_token('=');
2349 expression_t *value = parse_constant_expression();
2351 value = create_implicit_cast(value, enum_type);
2352 entity->enum_value.value = value;
2357 record_entity(entity, false);
2358 } while (next_if(',') && token.kind != '}');
2359 rem_anchor_token(',');
2360 rem_anchor_token('}');
2365 static type_t *parse_enum_specifier(void)
2367 source_position_t const pos = *HERE;
2372 switch (token.kind) {
2374 symbol = token.base.symbol;
2375 entity = get_tag(symbol, ENTITY_ENUM);
2378 if (entity != NULL) {
2379 if (entity->base.parent_scope != current_scope &&
2380 (token.kind == '{' || token.kind == ';')) {
2381 /* we're in an inner scope and have a definition. Shadow
2382 * existing definition in outer scope */
2384 } else if (entity->enume.complete && token.kind == '{') {
2385 source_position_t const *const ppos = &entity->base.source_position;
2386 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2397 parse_error_expected("while parsing enum type specifier",
2398 T_IDENTIFIER, '{', NULL);
2402 if (entity == NULL) {
2403 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2404 entity->base.parent_scope = current_scope;
2407 type_t *const type = allocate_type_zero(TYPE_ENUM);
2408 type->enumt.enume = &entity->enume;
2409 type->enumt.base.akind = ATOMIC_TYPE_INT;
2411 if (token.kind == '{') {
2412 if (symbol != NULL) {
2413 environment_push(entity);
2415 append_entity(current_scope, entity);
2416 entity->enume.complete = true;
2418 parse_enum_entries(type);
2419 parse_attributes(NULL);
2421 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2422 if (symbol == NULL) {
2423 assert(anonymous_entity == NULL);
2424 anonymous_entity = entity;
2426 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2427 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2434 * if a symbol is a typedef to another type, return true
2436 static bool is_typedef_symbol(symbol_t *symbol)
2438 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2439 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2442 static type_t *parse_typeof(void)
2448 add_anchor_token(')');
2451 expression_t *expression = NULL;
2453 switch (token.kind) {
2455 if (is_typedef_symbol(token.base.symbol)) {
2457 type = parse_typename();
2460 expression = parse_expression();
2461 type = revert_automatic_type_conversion(expression);
2466 rem_anchor_token(')');
2469 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2470 typeof_type->typeoft.expression = expression;
2471 typeof_type->typeoft.typeof_type = type;
2476 typedef enum specifiers_t {
2478 SPECIFIER_SIGNED = 1 << 0,
2479 SPECIFIER_UNSIGNED = 1 << 1,
2480 SPECIFIER_LONG = 1 << 2,
2481 SPECIFIER_INT = 1 << 3,
2482 SPECIFIER_DOUBLE = 1 << 4,
2483 SPECIFIER_CHAR = 1 << 5,
2484 SPECIFIER_WCHAR_T = 1 << 6,
2485 SPECIFIER_SHORT = 1 << 7,
2486 SPECIFIER_LONG_LONG = 1 << 8,
2487 SPECIFIER_FLOAT = 1 << 9,
2488 SPECIFIER_BOOL = 1 << 10,
2489 SPECIFIER_VOID = 1 << 11,
2490 SPECIFIER_INT8 = 1 << 12,
2491 SPECIFIER_INT16 = 1 << 13,
2492 SPECIFIER_INT32 = 1 << 14,
2493 SPECIFIER_INT64 = 1 << 15,
2494 SPECIFIER_INT128 = 1 << 16,
2495 SPECIFIER_COMPLEX = 1 << 17,
2496 SPECIFIER_IMAGINARY = 1 << 18,
2499 static type_t *get_typedef_type(symbol_t *symbol)
2501 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2502 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2505 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2506 type->typedeft.typedefe = &entity->typedefe;
2511 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2513 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2515 add_anchor_token(')');
2516 add_anchor_token(',');
2520 add_anchor_token('=');
2521 source_position_t pos;
2522 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2523 rem_anchor_token('=');
2525 symbol_t **prop = NULL;
2527 if (streq(prop_sym->string, "put")) {
2528 prop = &property->put_symbol;
2529 } else if (streq(prop_sym->string, "get")) {
2530 prop = &property->get_symbol;
2532 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2536 add_anchor_token(T_IDENTIFIER);
2538 rem_anchor_token(T_IDENTIFIER);
2540 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2542 *prop = sym ? sym : sym_anonymous;
2543 } while (next_if(','));
2544 rem_anchor_token(',');
2545 rem_anchor_token(')');
2547 attribute->a.property = property;
2553 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2555 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2556 if (next_if(T_restrict)) {
2557 kind = ATTRIBUTE_MS_RESTRICT;
2558 } else if (token.kind == T_IDENTIFIER) {
2559 char const *const name = token.base.symbol->string;
2560 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2562 const char *attribute_name = get_attribute_name(k);
2563 if (attribute_name != NULL && streq(attribute_name, name)) {
2569 if (kind == ATTRIBUTE_UNKNOWN) {
2570 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2573 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2577 attribute_t *attribute = allocate_attribute_zero(kind);
2580 if (kind == ATTRIBUTE_MS_PROPERTY) {
2581 return parse_attribute_ms_property(attribute);
2584 /* parse arguments */
2586 attribute->a.arguments = parse_attribute_arguments();
2591 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2595 add_anchor_token(')');
2597 if (token.kind != ')') {
2598 attribute_t **anchor = &first;
2600 while (*anchor != NULL)
2601 anchor = &(*anchor)->next;
2603 attribute_t *attribute
2604 = parse_microsoft_extended_decl_modifier_single();
2605 if (attribute == NULL)
2608 *anchor = attribute;
2609 anchor = &attribute->next;
2610 } while (next_if(','));
2612 rem_anchor_token(')');
2617 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2619 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2620 if (is_declaration(entity)) {
2621 entity->declaration.type = type_error_type;
2622 entity->declaration.implicit = true;
2623 } else if (kind == ENTITY_TYPEDEF) {
2624 entity->typedefe.type = type_error_type;
2625 entity->typedefe.builtin = true;
2627 if (kind != ENTITY_COMPOUND_MEMBER)
2628 record_entity(entity, false);
2632 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2634 type_t *type = NULL;
2635 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2636 unsigned type_specifiers = 0;
2637 bool newtype = false;
2638 bool saw_error = false;
2640 memset(specifiers, 0, sizeof(*specifiers));
2641 specifiers->source_position = *HERE;
2644 specifiers->attributes = parse_attributes(specifiers->attributes);
2646 switch (token.kind) {
2648 #define MATCH_STORAGE_CLASS(token, class) \
2650 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2651 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2653 specifiers->storage_class = class; \
2654 if (specifiers->thread_local) \
2655 goto check_thread_storage_class; \
2659 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2660 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2661 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2662 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2663 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2666 specifiers->attributes
2667 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2670 case T__Thread_local:
2671 if (specifiers->thread_local) {
2672 errorf(HERE, "duplicate %K", &token);
2674 specifiers->thread_local = true;
2675 check_thread_storage_class:
2676 switch (specifiers->storage_class) {
2677 case STORAGE_CLASS_EXTERN:
2678 case STORAGE_CLASS_NONE:
2679 case STORAGE_CLASS_STATIC:
2683 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2684 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2685 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2686 wrong_thread_storage_class:
2687 errorf(HERE, "%K used with '%s'", &token, wrong);
2694 /* type qualifiers */
2695 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2697 qualifiers |= qualifier; \
2701 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2702 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2703 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2704 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2705 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2706 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2707 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2708 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2710 /* type specifiers */
2711 #define MATCH_SPECIFIER(token, specifier, name) \
2713 if (type_specifiers & specifier) { \
2714 errorf(HERE, "multiple " name " type specifiers given"); \
2716 type_specifiers |= specifier; \
2721 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2722 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2723 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2724 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2725 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2726 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2727 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2728 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2729 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2730 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2731 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2732 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2733 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2734 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2735 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2736 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2737 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2738 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2742 specifiers->is_inline = true;
2746 case T__forceinline:
2747 eat(T__forceinline);
2748 specifiers->modifiers |= DM_FORCEINLINE;
2753 if (type_specifiers & SPECIFIER_LONG_LONG) {
2754 errorf(HERE, "too many long type specifiers given");
2755 } else if (type_specifiers & SPECIFIER_LONG) {
2756 type_specifiers |= SPECIFIER_LONG_LONG;
2758 type_specifiers |= SPECIFIER_LONG;
2763 #define CHECK_DOUBLE_TYPE() \
2764 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2767 CHECK_DOUBLE_TYPE();
2768 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2770 type->compound.compound = parse_compound_type_specifier(true);
2773 CHECK_DOUBLE_TYPE();
2774 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2775 type->compound.compound = parse_compound_type_specifier(false);
2778 CHECK_DOUBLE_TYPE();
2779 type = parse_enum_specifier();
2782 CHECK_DOUBLE_TYPE();
2783 type = parse_typeof();
2785 case T___builtin_va_list:
2786 CHECK_DOUBLE_TYPE();
2787 type = duplicate_type(type_valist);
2788 eat(T___builtin_va_list);
2791 case T_IDENTIFIER: {
2792 /* only parse identifier if we haven't found a type yet */
2793 if (type != NULL || type_specifiers != 0) {
2794 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2795 * declaration, so it doesn't generate errors about expecting '(' or
2797 switch (look_ahead(1)->kind) {
2804 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2808 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2813 goto finish_specifiers;
2817 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2818 if (typedef_type == NULL) {
2819 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2820 * declaration, so it doesn't generate 'implicit int' followed by more
2821 * errors later on. */
2822 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2828 errorf(HERE, "%K does not name a type", &token);
2830 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2832 type = allocate_type_zero(TYPE_TYPEDEF);
2833 type->typedeft.typedefe = &entity->typedefe;
2841 goto finish_specifiers;
2846 type = typedef_type;
2850 /* function specifier */
2852 goto finish_specifiers;
2857 specifiers->attributes = parse_attributes(specifiers->attributes);
2859 if (type == NULL || (saw_error && type_specifiers != 0)) {
2860 atomic_type_kind_t atomic_type;
2862 /* match valid basic types */
2863 switch (type_specifiers) {
2864 case SPECIFIER_VOID:
2865 atomic_type = ATOMIC_TYPE_VOID;
2867 case SPECIFIER_WCHAR_T:
2868 atomic_type = ATOMIC_TYPE_WCHAR_T;
2870 case SPECIFIER_CHAR:
2871 atomic_type = ATOMIC_TYPE_CHAR;
2873 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2874 atomic_type = ATOMIC_TYPE_SCHAR;
2876 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2877 atomic_type = ATOMIC_TYPE_UCHAR;
2879 case SPECIFIER_SHORT:
2880 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2881 case SPECIFIER_SHORT | SPECIFIER_INT:
2882 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2883 atomic_type = ATOMIC_TYPE_SHORT;
2885 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2886 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2887 atomic_type = ATOMIC_TYPE_USHORT;
2890 case SPECIFIER_SIGNED:
2891 case SPECIFIER_SIGNED | SPECIFIER_INT:
2892 atomic_type = ATOMIC_TYPE_INT;
2894 case SPECIFIER_UNSIGNED:
2895 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2896 atomic_type = ATOMIC_TYPE_UINT;
2898 case SPECIFIER_LONG:
2899 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2900 case SPECIFIER_LONG | SPECIFIER_INT:
2901 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2902 atomic_type = ATOMIC_TYPE_LONG;
2904 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2905 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2906 atomic_type = ATOMIC_TYPE_ULONG;
2909 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2910 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2911 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2912 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2914 atomic_type = ATOMIC_TYPE_LONGLONG;
2915 goto warn_about_long_long;
2917 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2918 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2920 atomic_type = ATOMIC_TYPE_ULONGLONG;
2921 warn_about_long_long:
2922 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2925 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2926 atomic_type = unsigned_int8_type_kind;
2929 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2930 atomic_type = unsigned_int16_type_kind;
2933 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2934 atomic_type = unsigned_int32_type_kind;
2937 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2938 atomic_type = unsigned_int64_type_kind;
2941 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2942 atomic_type = unsigned_int128_type_kind;
2945 case SPECIFIER_INT8:
2946 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2947 atomic_type = int8_type_kind;
2950 case SPECIFIER_INT16:
2951 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2952 atomic_type = int16_type_kind;
2955 case SPECIFIER_INT32:
2956 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2957 atomic_type = int32_type_kind;
2960 case SPECIFIER_INT64:
2961 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2962 atomic_type = int64_type_kind;
2965 case SPECIFIER_INT128:
2966 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2967 atomic_type = int128_type_kind;
2970 case SPECIFIER_FLOAT:
2971 atomic_type = ATOMIC_TYPE_FLOAT;
2973 case SPECIFIER_DOUBLE:
2974 atomic_type = ATOMIC_TYPE_DOUBLE;
2976 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2977 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2979 case SPECIFIER_BOOL:
2980 atomic_type = ATOMIC_TYPE_BOOL;
2982 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2983 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2984 atomic_type = ATOMIC_TYPE_FLOAT;
2986 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2987 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2988 atomic_type = ATOMIC_TYPE_DOUBLE;
2990 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2991 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2992 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2995 /* invalid specifier combination, give an error message */
2996 source_position_t const* const pos = &specifiers->source_position;
2997 if (type_specifiers == 0) {
2999 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3000 if (!(c_mode & _CXX) && !strict_mode) {
3001 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3002 atomic_type = ATOMIC_TYPE_INT;
3005 errorf(pos, "no type specifiers given in declaration");
3008 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3009 (type_specifiers & SPECIFIER_UNSIGNED)) {
3010 errorf(pos, "signed and unsigned specifiers given");
3011 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3012 errorf(pos, "only integer types can be signed or unsigned");
3014 errorf(pos, "multiple datatypes in declaration");
3016 specifiers->type = type_error_type;
3021 if (type_specifiers & SPECIFIER_COMPLEX) {
3022 type = allocate_type_zero(TYPE_COMPLEX);
3023 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3024 type = allocate_type_zero(TYPE_IMAGINARY);
3026 type = allocate_type_zero(TYPE_ATOMIC);
3028 type->atomic.akind = atomic_type;
3030 } else if (type_specifiers != 0) {
3031 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3034 /* FIXME: check type qualifiers here */
3035 type->base.qualifiers = qualifiers;
3038 type = identify_new_type(type);
3040 type = typehash_insert(type);
3043 if (specifiers->attributes != NULL)
3044 type = handle_type_attributes(specifiers->attributes, type);
3045 specifiers->type = type;
3048 static type_qualifiers_t parse_type_qualifiers(void)
3050 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3053 switch (token.kind) {
3054 /* type qualifiers */
3055 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3056 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3057 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3058 /* microsoft extended type modifiers */
3059 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3060 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3061 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3062 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3063 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3072 * Parses an K&R identifier list
3074 static void parse_identifier_list(scope_t *scope)
3076 assert(token.kind == T_IDENTIFIER);
3078 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3079 /* a K&R parameter has no type, yet */
3083 append_entity(scope, entity);
3084 } while (next_if(',') && token.kind == T_IDENTIFIER);
3087 static entity_t *parse_parameter(void)
3089 declaration_specifiers_t specifiers;
3090 parse_declaration_specifiers(&specifiers);
3092 entity_t *entity = parse_declarator(&specifiers,
3093 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3094 anonymous_entity = NULL;
3098 static void semantic_parameter_incomplete(const entity_t *entity)
3100 assert(entity->kind == ENTITY_PARAMETER);
3102 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3103 * list in a function declarator that is part of a
3104 * definition of that function shall not have
3105 * incomplete type. */
3106 type_t *type = skip_typeref(entity->declaration.type);
3107 if (is_type_incomplete(type)) {
3108 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3112 static bool has_parameters(void)
3114 /* func(void) is not a parameter */
3115 if (look_ahead(1)->kind != ')')
3117 if (token.kind == T_IDENTIFIER) {
3118 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3121 if (entity->kind != ENTITY_TYPEDEF)
3123 type_t const *const type = skip_typeref(entity->typedefe.type);
3124 if (!is_type_void(type))
3126 if (c_mode & _CXX) {
3127 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3128 * is not allowed. */
3129 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3130 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3131 /* §6.7.5.3:10 Qualification is not allowed here. */
3132 errorf(HERE, "'void' as parameter must not have type qualifiers");
3134 } else if (token.kind != T_void) {
3142 * Parses function type parameters (and optionally creates variable_t entities
3143 * for them in a scope)
3145 static void parse_parameters(function_type_t *type, scope_t *scope)
3147 add_anchor_token(')');
3150 if (token.kind == T_IDENTIFIER &&
3151 !is_typedef_symbol(token.base.symbol) &&
3152 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3153 type->kr_style_parameters = true;
3154 parse_identifier_list(scope);
3155 } else if (token.kind == ')') {
3156 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3157 if (!(c_mode & _CXX))
3158 type->unspecified_parameters = true;
3159 } else if (has_parameters()) {
3160 function_parameter_t **anchor = &type->parameters;
3161 add_anchor_token(',');
3163 switch (token.kind) {
3166 type->variadic = true;
3167 goto parameters_finished;
3172 entity_t *entity = parse_parameter();
3173 if (entity->kind == ENTITY_TYPEDEF) {
3174 errorf(&entity->base.source_position,
3175 "typedef not allowed as function parameter");
3178 assert(is_declaration(entity));
3180 semantic_parameter_incomplete(entity);
3182 function_parameter_t *const parameter =
3183 allocate_parameter(entity->declaration.type);
3185 if (scope != NULL) {
3186 append_entity(scope, entity);
3189 *anchor = parameter;
3190 anchor = ¶meter->next;
3195 goto parameters_finished;
3197 } while (next_if(','));
3198 parameters_finished:
3199 rem_anchor_token(',');
3202 rem_anchor_token(')');
3206 typedef enum construct_type_kind_t {
3207 CONSTRUCT_POINTER = 1,
3208 CONSTRUCT_REFERENCE,
3211 } construct_type_kind_t;
3213 typedef union construct_type_t construct_type_t;
3215 typedef struct construct_type_base_t {
3216 construct_type_kind_t kind;
3217 source_position_t pos;
3218 construct_type_t *next;
3219 } construct_type_base_t;
3221 typedef struct parsed_pointer_t {
3222 construct_type_base_t base;
3223 type_qualifiers_t type_qualifiers;
3224 variable_t *base_variable; /**< MS __based extension. */
3227 typedef struct parsed_reference_t {
3228 construct_type_base_t base;
3229 } parsed_reference_t;
3231 typedef struct construct_function_type_t {
3232 construct_type_base_t base;
3233 type_t *function_type;
3234 } construct_function_type_t;
3236 typedef struct parsed_array_t {
3237 construct_type_base_t base;
3238 type_qualifiers_t type_qualifiers;
3244 union construct_type_t {
3245 construct_type_kind_t kind;
3246 construct_type_base_t base;
3247 parsed_pointer_t pointer;
3248 parsed_reference_t reference;
3249 construct_function_type_t function;
3250 parsed_array_t array;
3253 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3255 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3256 memset(cons, 0, size);
3258 cons->base.pos = *HERE;
3263 static construct_type_t *parse_pointer_declarator(void)
3265 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3267 cons->pointer.type_qualifiers = parse_type_qualifiers();
3268 //cons->pointer.base_variable = base_variable;
3273 /* ISO/IEC 14882:1998(E) §8.3.2 */
3274 static construct_type_t *parse_reference_declarator(void)
3276 if (!(c_mode & _CXX))
3277 errorf(HERE, "references are only available for C++");
3279 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3286 static construct_type_t *parse_array_declarator(void)
3288 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3289 parsed_array_t *const array = &cons->array;
3292 add_anchor_token(']');
3294 bool is_static = next_if(T_static);
3296 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3299 is_static = next_if(T_static);
3301 array->type_qualifiers = type_qualifiers;
3302 array->is_static = is_static;
3304 expression_t *size = NULL;
3305 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3306 array->is_variable = true;
3308 } else if (token.kind != ']') {
3309 size = parse_assignment_expression();
3311 /* §6.7.5.2:1 Array size must have integer type */
3312 type_t *const orig_type = size->base.type;
3313 type_t *const type = skip_typeref(orig_type);
3314 if (!is_type_integer(type) && is_type_valid(type)) {
3315 errorf(&size->base.source_position,
3316 "array size '%E' must have integer type but has type '%T'",
3321 mark_vars_read(size, NULL);
3324 if (is_static && size == NULL)
3325 errorf(&array->base.pos, "static array parameters require a size");
3327 rem_anchor_token(']');
3333 static construct_type_t *parse_function_declarator(scope_t *scope)
3335 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3337 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3338 function_type_t *ftype = &type->function;
3340 ftype->linkage = current_linkage;
3341 ftype->calling_convention = CC_DEFAULT;
3343 parse_parameters(ftype, scope);
3345 cons->function.function_type = type;
3350 typedef struct parse_declarator_env_t {
3351 bool may_be_abstract : 1;
3352 bool must_be_abstract : 1;
3353 decl_modifiers_t modifiers;
3355 source_position_t source_position;
3357 attribute_t *attributes;
3358 } parse_declarator_env_t;
3361 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3363 /* construct a single linked list of construct_type_t's which describe
3364 * how to construct the final declarator type */
3365 construct_type_t *first = NULL;
3366 construct_type_t **anchor = &first;
3368 env->attributes = parse_attributes(env->attributes);
3371 construct_type_t *type;
3372 //variable_t *based = NULL; /* MS __based extension */
3373 switch (token.kind) {
3375 type = parse_reference_declarator();
3379 panic("based not supported anymore");
3384 type = parse_pointer_declarator();
3388 goto ptr_operator_end;
3392 anchor = &type->base.next;
3394 /* TODO: find out if this is correct */
3395 env->attributes = parse_attributes(env->attributes);
3399 construct_type_t *inner_types = NULL;
3401 switch (token.kind) {
3403 if (env->must_be_abstract) {
3404 errorf(HERE, "no identifier expected in typename");
3406 env->symbol = token.base.symbol;
3407 env->source_position = *HERE;
3413 /* Parenthesized declarator or function declarator? */
3414 token_t const *const la1 = look_ahead(1);
3415 switch (la1->kind) {
3417 if (is_typedef_symbol(la1->base.symbol)) {
3419 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3420 * interpreted as ``function with no parameter specification'', rather
3421 * than redundant parentheses around the omitted identifier. */
3423 /* Function declarator. */
3424 if (!env->may_be_abstract) {
3425 errorf(HERE, "function declarator must have a name");
3432 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3433 /* Paranthesized declarator. */
3435 add_anchor_token(')');
3436 inner_types = parse_inner_declarator(env);
3437 if (inner_types != NULL) {
3438 /* All later declarators only modify the return type */
3439 env->must_be_abstract = true;
3441 rem_anchor_token(')');
3450 if (env->may_be_abstract)
3452 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3457 construct_type_t **const p = anchor;
3460 construct_type_t *type;
3461 switch (token.kind) {
3463 scope_t *scope = NULL;
3464 if (!env->must_be_abstract) {
3465 scope = &env->parameters;
3468 type = parse_function_declarator(scope);
3472 type = parse_array_declarator();
3475 goto declarator_finished;
3478 /* insert in the middle of the list (at p) */
3479 type->base.next = *p;
3482 anchor = &type->base.next;
3485 declarator_finished:
3486 /* append inner_types at the end of the list, we don't to set anchor anymore
3487 * as it's not needed anymore */
3488 *anchor = inner_types;
3493 static type_t *construct_declarator_type(construct_type_t *construct_list,
3496 construct_type_t *iter = construct_list;
3497 for (; iter != NULL; iter = iter->base.next) {
3498 source_position_t const* const pos = &iter->base.pos;
3499 switch (iter->kind) {
3500 case CONSTRUCT_FUNCTION: {
3501 construct_function_type_t *function = &iter->function;
3502 type_t *function_type = function->function_type;
3504 function_type->function.return_type = type;
3506 type_t *skipped_return_type = skip_typeref(type);
3508 if (is_type_function(skipped_return_type)) {
3509 errorf(pos, "function returning function is not allowed");
3510 } else if (is_type_array(skipped_return_type)) {
3511 errorf(pos, "function returning array is not allowed");
3513 if (skipped_return_type->base.qualifiers != 0) {
3514 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3518 /* The function type was constructed earlier. Freeing it here will
3519 * destroy other types. */
3520 type = typehash_insert(function_type);
3524 case CONSTRUCT_POINTER: {
3525 if (is_type_reference(skip_typeref(type)))
3526 errorf(pos, "cannot declare a pointer to reference");
3528 parsed_pointer_t *pointer = &iter->pointer;
3529 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3533 case CONSTRUCT_REFERENCE:
3534 if (is_type_reference(skip_typeref(type)))
3535 errorf(pos, "cannot declare a reference to reference");
3537 type = make_reference_type(type);
3540 case CONSTRUCT_ARRAY: {
3541 if (is_type_reference(skip_typeref(type)))
3542 errorf(pos, "cannot declare an array of references");
3544 parsed_array_t *array = &iter->array;
3545 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3547 expression_t *size_expression = array->size;
3548 if (size_expression != NULL) {
3550 = create_implicit_cast(size_expression, type_size_t);
3553 array_type->base.qualifiers = array->type_qualifiers;
3554 array_type->array.element_type = type;
3555 array_type->array.is_static = array->is_static;
3556 array_type->array.is_variable = array->is_variable;
3557 array_type->array.size_expression = size_expression;
3559 if (size_expression != NULL) {
3560 switch (is_constant_expression(size_expression)) {
3561 case EXPR_CLASS_CONSTANT: {
3562 long const size = fold_constant_to_int(size_expression);
3563 array_type->array.size = size;
3564 array_type->array.size_constant = true;
3565 /* §6.7.5.2:1 If the expression is a constant expression,
3566 * it shall have a value greater than zero. */
3568 errorf(&size_expression->base.source_position,
3569 "size of array must be greater than zero");
3570 } else if (size == 0 && !GNU_MODE) {
3571 errorf(&size_expression->base.source_position,
3572 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3577 case EXPR_CLASS_VARIABLE:
3578 array_type->array.is_vla = true;
3581 case EXPR_CLASS_ERROR:
3586 type_t *skipped_type = skip_typeref(type);
3588 if (is_type_incomplete(skipped_type)) {
3589 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3590 } else if (is_type_function(skipped_type)) {
3591 errorf(pos, "array of functions is not allowed");
3593 type = identify_new_type(array_type);
3597 internal_errorf(pos, "invalid type construction found");
3603 static type_t *automatic_type_conversion(type_t *orig_type);
3605 static type_t *semantic_parameter(const source_position_t *pos,
3607 const declaration_specifiers_t *specifiers,
3608 entity_t const *const param)
3610 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3611 * shall be adjusted to ``qualified pointer to type'',
3613 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3614 * type'' shall be adjusted to ``pointer to function
3615 * returning type'', as in 6.3.2.1. */
3616 type = automatic_type_conversion(type);
3618 if (specifiers->is_inline && is_type_valid(type)) {
3619 errorf(pos, "'%N' declared 'inline'", param);
3622 /* §6.9.1:6 The declarations in the declaration list shall contain
3623 * no storage-class specifier other than register and no
3624 * initializations. */
3625 if (specifiers->thread_local || (
3626 specifiers->storage_class != STORAGE_CLASS_NONE &&
3627 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3629 errorf(pos, "invalid storage class for '%N'", param);
3632 /* delay test for incomplete type, because we might have (void)
3633 * which is legal but incomplete... */
3638 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3639 declarator_flags_t flags)
3641 parse_declarator_env_t env;
3642 memset(&env, 0, sizeof(env));
3643 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3645 construct_type_t *construct_type = parse_inner_declarator(&env);
3647 construct_declarator_type(construct_type, specifiers->type);
3648 type_t *type = skip_typeref(orig_type);
3650 if (construct_type != NULL) {
3651 obstack_free(&temp_obst, construct_type);
3654 attribute_t *attributes = parse_attributes(env.attributes);
3655 /* append (shared) specifier attribute behind attributes of this
3657 attribute_t **anchor = &attributes;
3658 while (*anchor != NULL)
3659 anchor = &(*anchor)->next;
3660 *anchor = specifiers->attributes;
3663 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3664 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3665 entity->typedefe.type = orig_type;
3667 if (anonymous_entity != NULL) {
3668 if (is_type_compound(type)) {
3669 assert(anonymous_entity->compound.alias == NULL);
3670 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3671 anonymous_entity->kind == ENTITY_UNION);
3672 anonymous_entity->compound.alias = entity;
3673 anonymous_entity = NULL;
3674 } else if (is_type_enum(type)) {
3675 assert(anonymous_entity->enume.alias == NULL);
3676 assert(anonymous_entity->kind == ENTITY_ENUM);
3677 anonymous_entity->enume.alias = entity;
3678 anonymous_entity = NULL;
3682 /* create a declaration type entity */
3683 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3684 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3685 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3687 if (env.symbol != NULL) {
3688 if (specifiers->is_inline && is_type_valid(type)) {
3689 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3692 if (specifiers->thread_local ||
3693 specifiers->storage_class != STORAGE_CLASS_NONE) {
3694 errorf(&env.source_position, "'%N' must have no storage class", entity);
3697 } else if (flags & DECL_IS_PARAMETER) {
3698 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3699 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3700 } else if (is_type_function(type)) {
3701 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3702 entity->function.is_inline = specifiers->is_inline;
3703 entity->function.elf_visibility = default_visibility;
3704 entity->function.parameters = env.parameters;
3706 if (env.symbol != NULL) {
3707 /* this needs fixes for C++ */
3708 bool in_function_scope = current_function != NULL;
3710 if (specifiers->thread_local || (
3711 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3712 specifiers->storage_class != STORAGE_CLASS_NONE &&
3713 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3715 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3719 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3720 entity->variable.elf_visibility = default_visibility;
3721 entity->variable.thread_local = specifiers->thread_local;
3723 if (env.symbol != NULL) {
3724 if (specifiers->is_inline && is_type_valid(type)) {
3725 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3728 bool invalid_storage_class = false;
3729 if (current_scope == file_scope) {
3730 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3731 specifiers->storage_class != STORAGE_CLASS_NONE &&
3732 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3733 invalid_storage_class = true;
3736 if (specifiers->thread_local &&
3737 specifiers->storage_class == STORAGE_CLASS_NONE) {
3738 invalid_storage_class = true;
3741 if (invalid_storage_class) {
3742 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3747 entity->declaration.type = orig_type;
3748 entity->declaration.alignment = get_type_alignment(orig_type);
3749 entity->declaration.modifiers = env.modifiers;
3750 entity->declaration.attributes = attributes;
3752 storage_class_t storage_class = specifiers->storage_class;
3753 entity->declaration.declared_storage_class = storage_class;
3755 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3756 storage_class = STORAGE_CLASS_AUTO;
3757 entity->declaration.storage_class = storage_class;
3760 if (attributes != NULL) {
3761 handle_entity_attributes(attributes, entity);
3764 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3765 adapt_special_functions(&entity->function);
3771 static type_t *parse_abstract_declarator(type_t *base_type)
3773 parse_declarator_env_t env;
3774 memset(&env, 0, sizeof(env));
3775 env.may_be_abstract = true;
3776 env.must_be_abstract = true;
3778 construct_type_t *construct_type = parse_inner_declarator(&env);
3780 type_t *result = construct_declarator_type(construct_type, base_type);
3781 if (construct_type != NULL) {
3782 obstack_free(&temp_obst, construct_type);
3784 result = handle_type_attributes(env.attributes, result);
3790 * Check if the declaration of main is suspicious. main should be a
3791 * function with external linkage, returning int, taking either zero
3792 * arguments, two, or three arguments of appropriate types, ie.
3794 * int main([ int argc, char **argv [, char **env ] ]).
3796 * @param decl the declaration to check
3797 * @param type the function type of the declaration
3799 static void check_main(const entity_t *entity)
3801 const source_position_t *pos = &entity->base.source_position;
3802 if (entity->kind != ENTITY_FUNCTION) {
3803 warningf(WARN_MAIN, pos, "'main' is not a function");
3807 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3808 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3811 type_t *type = skip_typeref(entity->declaration.type);
3812 assert(is_type_function(type));
3814 function_type_t const *const func_type = &type->function;
3815 type_t *const ret_type = func_type->return_type;
3816 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3817 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3819 const function_parameter_t *parm = func_type->parameters;
3821 type_t *const first_type = skip_typeref(parm->type);
3822 type_t *const first_type_unqual = get_unqualified_type(first_type);
3823 if (!types_compatible(first_type_unqual, type_int)) {
3824 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3828 type_t *const second_type = skip_typeref(parm->type);
3829 type_t *const second_type_unqual
3830 = get_unqualified_type(second_type);
3831 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3832 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3836 type_t *const third_type = skip_typeref(parm->type);
3837 type_t *const third_type_unqual
3838 = get_unqualified_type(third_type);
3839 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3840 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3844 goto warn_arg_count;
3848 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3853 static void error_redefined_as_different_kind(const source_position_t *pos,
3854 const entity_t *old, entity_kind_t new_kind)
3856 char const *const what = get_entity_kind_name(new_kind);
3857 source_position_t const *const ppos = &old->base.source_position;
3858 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3861 static bool is_entity_valid(entity_t *const ent)
3863 if (is_declaration(ent)) {
3864 return is_type_valid(skip_typeref(ent->declaration.type));
3865 } else if (ent->kind == ENTITY_TYPEDEF) {
3866 return is_type_valid(skip_typeref(ent->typedefe.type));
3871 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3873 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3874 if (attributes_equal(tattr, attr))
3881 * test wether new_list contains any attributes not included in old_list
3883 static bool has_new_attributes(const attribute_t *old_list,
3884 const attribute_t *new_list)
3886 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3887 if (!contains_attribute(old_list, attr))
3894 * Merge in attributes from an attribute list (probably from a previous
3895 * declaration with the same name). Warning: destroys the old structure
3896 * of the attribute list - don't reuse attributes after this call.
3898 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3901 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3903 if (contains_attribute(decl->attributes, attr))
3906 /* move attribute to new declarations attributes list */
3907 attr->next = decl->attributes;
3908 decl->attributes = attr;
3912 static bool is_main(entity_t*);
3915 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3916 * for various problems that occur for multiple definitions
3918 entity_t *record_entity(entity_t *entity, const bool is_definition)
3920 const symbol_t *const symbol = entity->base.symbol;
3921 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3922 const source_position_t *pos = &entity->base.source_position;
3924 /* can happen in error cases */
3928 assert(!entity->base.parent_scope);
3929 assert(current_scope);
3930 entity->base.parent_scope = current_scope;
3932 entity_t *const previous_entity = get_entity(symbol, namespc);
3933 /* pushing the same entity twice will break the stack structure */
3934 assert(previous_entity != entity);
3936 if (entity->kind == ENTITY_FUNCTION) {
3937 type_t *const orig_type = entity->declaration.type;
3938 type_t *const type = skip_typeref(orig_type);
3940 assert(is_type_function(type));
3941 if (type->function.unspecified_parameters &&
3942 previous_entity == NULL &&
3943 !entity->declaration.implicit) {
3944 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3947 if (is_main(entity)) {
3952 if (is_declaration(entity) &&
3953 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3954 current_scope != file_scope &&
3955 !entity->declaration.implicit) {
3956 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3959 if (previous_entity != NULL) {
3960 source_position_t const *const ppos = &previous_entity->base.source_position;
3962 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3963 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3964 assert(previous_entity->kind == ENTITY_PARAMETER);
3965 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3969 if (previous_entity->base.parent_scope == current_scope) {
3970 if (previous_entity->kind != entity->kind) {
3971 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3972 error_redefined_as_different_kind(pos, previous_entity,
3977 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3978 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3981 if (previous_entity->kind == ENTITY_TYPEDEF) {
3982 type_t *const type = skip_typeref(entity->typedefe.type);
3983 type_t *const prev_type
3984 = skip_typeref(previous_entity->typedefe.type);
3985 if (c_mode & _CXX) {
3986 /* C++ allows double typedef if they are identical
3987 * (after skipping typedefs) */
3988 if (type == prev_type)
3991 /* GCC extension: redef in system headers is allowed */
3992 if ((pos->is_system_header || ppos->is_system_header) &&
3993 types_compatible(type, prev_type))
3996 errorf(pos, "redefinition of '%N' (declared %P)",
4001 /* at this point we should have only VARIABLES or FUNCTIONS */
4002 assert(is_declaration(previous_entity) && is_declaration(entity));
4004 declaration_t *const prev_decl = &previous_entity->declaration;
4005 declaration_t *const decl = &entity->declaration;
4007 /* can happen for K&R style declarations */
4008 if (prev_decl->type == NULL &&
4009 previous_entity->kind == ENTITY_PARAMETER &&
4010 entity->kind == ENTITY_PARAMETER) {
4011 prev_decl->type = decl->type;
4012 prev_decl->storage_class = decl->storage_class;
4013 prev_decl->declared_storage_class = decl->declared_storage_class;
4014 prev_decl->modifiers = decl->modifiers;
4015 return previous_entity;
4018 type_t *const type = skip_typeref(decl->type);
4019 type_t *const prev_type = skip_typeref(prev_decl->type);
4021 if (!types_compatible(type, prev_type)) {
4022 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4024 unsigned old_storage_class = prev_decl->storage_class;
4026 if (is_definition &&
4028 !(prev_decl->modifiers & DM_USED) &&
4029 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4030 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4033 storage_class_t new_storage_class = decl->storage_class;
4035 /* pretend no storage class means extern for function
4036 * declarations (except if the previous declaration is neither
4037 * none nor extern) */
4038 if (entity->kind == ENTITY_FUNCTION) {
4039 /* the previous declaration could have unspecified parameters or
4040 * be a typedef, so use the new type */
4041 if (prev_type->function.unspecified_parameters || is_definition)
4042 prev_decl->type = type;
4044 switch (old_storage_class) {
4045 case STORAGE_CLASS_NONE:
4046 old_storage_class = STORAGE_CLASS_EXTERN;
4049 case STORAGE_CLASS_EXTERN:
4050 if (is_definition) {
4051 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4052 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4054 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4055 new_storage_class = STORAGE_CLASS_EXTERN;
4062 } else if (is_type_incomplete(prev_type)) {
4063 prev_decl->type = type;
4066 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4067 new_storage_class == STORAGE_CLASS_EXTERN) {
4069 warn_redundant_declaration: ;
4071 = has_new_attributes(prev_decl->attributes,
4073 if (has_new_attrs) {
4074 merge_in_attributes(decl, prev_decl->attributes);
4075 } else if (!is_definition &&
4076 is_type_valid(prev_type) &&
4077 !pos->is_system_header) {
4078 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4080 } else if (current_function == NULL) {
4081 if (old_storage_class != STORAGE_CLASS_STATIC &&
4082 new_storage_class == STORAGE_CLASS_STATIC) {
4083 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4084 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4085 prev_decl->storage_class = STORAGE_CLASS_NONE;
4086 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4088 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4090 goto error_redeclaration;
4091 goto warn_redundant_declaration;
4093 } else if (is_type_valid(prev_type)) {
4094 if (old_storage_class == new_storage_class) {
4095 error_redeclaration:
4096 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4098 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4103 prev_decl->modifiers |= decl->modifiers;
4104 if (entity->kind == ENTITY_FUNCTION) {
4105 previous_entity->function.is_inline |= entity->function.is_inline;
4107 return previous_entity;
4111 if (is_warn_on(why = WARN_SHADOW) ||
4112 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4113 char const *const what = get_entity_kind_name(previous_entity->kind);
4114 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4118 if (entity->kind == ENTITY_FUNCTION) {
4119 if (is_definition &&
4120 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4122 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4123 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4125 goto warn_missing_declaration;
4128 } else if (entity->kind == ENTITY_VARIABLE) {
4129 if (current_scope == file_scope &&
4130 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4131 !entity->declaration.implicit) {
4132 warn_missing_declaration:
4133 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4138 environment_push(entity);
4139 append_entity(current_scope, entity);
4144 static void parser_error_multiple_definition(entity_t *entity,
4145 const source_position_t *source_position)
4147 errorf(source_position, "redefinition of '%N' (declared %P)", entity, &entity->base.source_position);
4150 static bool is_declaration_specifier(const token_t *token)
4152 switch (token->kind) {
4156 return is_typedef_symbol(token->base.symbol);
4163 static void parse_init_declarator_rest(entity_t *entity)
4165 type_t *orig_type = type_error_type;
4167 if (entity->base.kind == ENTITY_TYPEDEF) {
4168 source_position_t const *const pos = &entity->base.source_position;
4169 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4171 assert(is_declaration(entity));
4172 orig_type = entity->declaration.type;
4175 type_t *type = skip_typeref(orig_type);
4177 if (entity->kind == ENTITY_VARIABLE
4178 && entity->variable.initializer != NULL) {
4179 parser_error_multiple_definition(entity, HERE);
4183 declaration_t *const declaration = &entity->declaration;
4184 bool must_be_constant = false;
4185 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4186 entity->base.parent_scope == file_scope) {
4187 must_be_constant = true;
4190 if (is_type_function(type)) {
4191 source_position_t const *const pos = &entity->base.source_position;
4192 errorf(pos, "'%N' is initialized like a variable", entity);
4193 orig_type = type_error_type;
4196 parse_initializer_env_t env;
4197 env.type = orig_type;
4198 env.must_be_constant = must_be_constant;
4199 env.entity = entity;
4201 initializer_t *initializer = parse_initializer(&env);
4203 if (entity->kind == ENTITY_VARIABLE) {
4204 /* §6.7.5:22 array initializers for arrays with unknown size
4205 * determine the array type size */
4206 declaration->type = env.type;
4207 entity->variable.initializer = initializer;
4211 /* parse rest of a declaration without any declarator */
4212 static void parse_anonymous_declaration_rest(
4213 const declaration_specifiers_t *specifiers)
4216 anonymous_entity = NULL;
4218 source_position_t const *const pos = &specifiers->source_position;
4219 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4220 specifiers->thread_local) {
4221 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4224 type_t *type = specifiers->type;
4225 switch (type->kind) {
4226 case TYPE_COMPOUND_STRUCT:
4227 case TYPE_COMPOUND_UNION: {
4228 if (type->compound.compound->base.symbol == NULL) {
4229 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4238 warningf(WARN_OTHER, pos, "empty declaration");
4243 static void check_variable_type_complete(entity_t *ent)
4245 if (ent->kind != ENTITY_VARIABLE)
4248 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4249 * type for the object shall be complete [...] */
4250 declaration_t *decl = &ent->declaration;
4251 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4252 decl->storage_class == STORAGE_CLASS_STATIC)
4255 type_t *const type = skip_typeref(decl->type);
4256 if (!is_type_incomplete(type))
4259 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4260 * are given length one. */
4261 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4262 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4266 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4270 static void parse_declaration_rest(entity_t *ndeclaration,
4271 const declaration_specifiers_t *specifiers,
4272 parsed_declaration_func finished_declaration,
4273 declarator_flags_t flags)
4275 add_anchor_token(';');
4276 add_anchor_token(',');
4278 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4280 if (token.kind == '=') {
4281 parse_init_declarator_rest(entity);
4282 } else if (entity->kind == ENTITY_VARIABLE) {
4283 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4284 * [...] where the extern specifier is explicitly used. */
4285 declaration_t *decl = &entity->declaration;
4286 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4287 is_type_reference(skip_typeref(decl->type))) {
4288 source_position_t const *const pos = &entity->base.source_position;
4289 errorf(pos, "reference '%#N' must be initialized", entity);
4293 check_variable_type_complete(entity);
4298 add_anchor_token('=');
4299 ndeclaration = parse_declarator(specifiers, flags);
4300 rem_anchor_token('=');
4302 rem_anchor_token(',');
4303 rem_anchor_token(';');
4306 anonymous_entity = NULL;
4309 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4311 symbol_t *symbol = entity->base.symbol;
4315 assert(entity->base.namespc == NAMESPACE_NORMAL);
4316 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4317 if (previous_entity == NULL
4318 || previous_entity->base.parent_scope != current_scope) {
4319 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4324 if (is_definition) {
4325 errorf(HERE, "'%N' is initialised", entity);
4328 return record_entity(entity, false);
4331 static void parse_declaration(parsed_declaration_func finished_declaration,
4332 declarator_flags_t flags)
4334 add_anchor_token(';');
4335 declaration_specifiers_t specifiers;
4336 parse_declaration_specifiers(&specifiers);
4337 rem_anchor_token(';');
4339 if (token.kind == ';') {
4340 parse_anonymous_declaration_rest(&specifiers);
4342 entity_t *entity = parse_declarator(&specifiers, flags);
4343 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4348 static type_t *get_default_promoted_type(type_t *orig_type)
4350 type_t *result = orig_type;
4352 type_t *type = skip_typeref(orig_type);
4353 if (is_type_integer(type)) {
4354 result = promote_integer(type);
4355 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4356 result = type_double;
4362 static void parse_kr_declaration_list(entity_t *entity)
4364 if (entity->kind != ENTITY_FUNCTION)
4367 type_t *type = skip_typeref(entity->declaration.type);
4368 assert(is_type_function(type));
4369 if (!type->function.kr_style_parameters)
4372 add_anchor_token('{');
4374 PUSH_SCOPE(&entity->function.parameters);
4376 entity_t *parameter = entity->function.parameters.entities;
4377 for ( ; parameter != NULL; parameter = parameter->base.next) {
4378 assert(parameter->base.parent_scope == NULL);
4379 parameter->base.parent_scope = current_scope;
4380 environment_push(parameter);
4383 /* parse declaration list */
4385 switch (token.kind) {
4387 /* This covers symbols, which are no type, too, and results in
4388 * better error messages. The typical cases are misspelled type
4389 * names and missing includes. */
4391 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4401 /* update function type */
4402 type_t *new_type = duplicate_type(type);
4404 function_parameter_t *parameters = NULL;
4405 function_parameter_t **anchor = ¶meters;
4407 /* did we have an earlier prototype? */
4408 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4409 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4412 function_parameter_t *proto_parameter = NULL;
4413 if (proto_type != NULL) {
4414 type_t *proto_type_type = proto_type->declaration.type;
4415 proto_parameter = proto_type_type->function.parameters;
4416 /* If a K&R function definition has a variadic prototype earlier, then
4417 * make the function definition variadic, too. This should conform to
4418 * §6.7.5.3:15 and §6.9.1:8. */
4419 new_type->function.variadic = proto_type_type->function.variadic;
4421 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4423 new_type->function.unspecified_parameters = true;
4426 bool need_incompatible_warning = false;
4427 parameter = entity->function.parameters.entities;
4428 for (; parameter != NULL; parameter = parameter->base.next,
4430 proto_parameter == NULL ? NULL : proto_parameter->next) {
4431 if (parameter->kind != ENTITY_PARAMETER)
4434 type_t *parameter_type = parameter->declaration.type;
4435 if (parameter_type == NULL) {
4436 source_position_t const* const pos = ¶meter->base.source_position;
4438 errorf(pos, "no type specified for function '%N'", parameter);
4439 parameter_type = type_error_type;
4441 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4442 parameter_type = type_int;
4444 parameter->declaration.type = parameter_type;
4447 semantic_parameter_incomplete(parameter);
4449 /* we need the default promoted types for the function type */
4450 type_t *not_promoted = parameter_type;
4451 parameter_type = get_default_promoted_type(parameter_type);
4453 /* gcc special: if the type of the prototype matches the unpromoted
4454 * type don't promote */
4455 if (!strict_mode && proto_parameter != NULL) {
4456 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4457 type_t *promo_skip = skip_typeref(parameter_type);
4458 type_t *param_skip = skip_typeref(not_promoted);
4459 if (!types_compatible(proto_p_type, promo_skip)
4460 && types_compatible(proto_p_type, param_skip)) {
4462 need_incompatible_warning = true;
4463 parameter_type = not_promoted;
4466 function_parameter_t *const function_parameter
4467 = allocate_parameter(parameter_type);
4469 *anchor = function_parameter;
4470 anchor = &function_parameter->next;
4473 new_type->function.parameters = parameters;
4474 new_type = identify_new_type(new_type);
4476 if (need_incompatible_warning) {
4477 symbol_t const *const sym = entity->base.symbol;
4478 source_position_t const *const pos = &entity->base.source_position;
4479 source_position_t const *const ppos = &proto_type->base.source_position;
4480 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4482 entity->declaration.type = new_type;
4484 rem_anchor_token('{');
4487 static bool first_err = true;
4490 * When called with first_err set, prints the name of the current function,
4493 static void print_in_function(void)
4497 char const *const file = current_function->base.base.source_position.input_name;
4498 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4503 * Check if all labels are defined in the current function.
4504 * Check if all labels are used in the current function.
4506 static void check_labels(void)
4508 for (const goto_statement_t *goto_statement = goto_first;
4509 goto_statement != NULL;
4510 goto_statement = goto_statement->next) {
4511 label_t *label = goto_statement->label;
4512 if (label->base.source_position.input_name == NULL) {
4513 print_in_function();
4514 source_position_t const *const pos = &goto_statement->base.source_position;
4515 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4519 if (is_warn_on(WARN_UNUSED_LABEL)) {
4520 for (const label_statement_t *label_statement = label_first;
4521 label_statement != NULL;
4522 label_statement = label_statement->next) {
4523 label_t *label = label_statement->label;
4525 if (! label->used) {
4526 print_in_function();
4527 source_position_t const *const pos = &label_statement->base.source_position;
4528 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4534 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4536 entity_t const *const end = last != NULL ? last->base.next : NULL;
4537 for (; entity != end; entity = entity->base.next) {
4538 if (!is_declaration(entity))
4541 declaration_t *declaration = &entity->declaration;
4542 if (declaration->implicit)
4545 if (!declaration->used) {
4546 print_in_function();
4547 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4548 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4549 print_in_function();
4550 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4555 static void check_unused_variables(statement_t *const stmt, void *const env)
4559 switch (stmt->kind) {
4560 case STATEMENT_DECLARATION: {
4561 declaration_statement_t const *const decls = &stmt->declaration;
4562 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4567 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4576 * Check declarations of current_function for unused entities.
4578 static void check_declarations(void)
4580 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4581 const scope_t *scope = ¤t_function->parameters;
4582 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4584 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4585 walk_statements(current_function->body, check_unused_variables, NULL);
4589 static int determine_truth(expression_t const* const cond)
4592 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4593 fold_constant_to_bool(cond) ? 1 :
4597 static void check_reachable(statement_t *);
4598 static bool reaches_end;
4600 static bool expression_returns(expression_t const *const expr)
4602 switch (expr->kind) {
4604 expression_t const *const func = expr->call.function;
4605 type_t const *const type = skip_typeref(func->base.type);
4606 if (type->kind == TYPE_POINTER) {
4607 type_t const *const points_to
4608 = skip_typeref(type->pointer.points_to);
4609 if (points_to->kind == TYPE_FUNCTION
4610 && points_to->function.modifiers & DM_NORETURN)
4614 if (!expression_returns(func))
4617 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4618 if (!expression_returns(arg->expression))
4625 case EXPR_REFERENCE:
4626 case EXPR_ENUM_CONSTANT:
4627 case EXPR_LITERAL_CASES:
4628 case EXPR_LITERAL_CHARACTER:
4629 case EXPR_STRING_LITERAL:
4630 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4631 case EXPR_LABEL_ADDRESS:
4632 case EXPR_CLASSIFY_TYPE:
4633 case EXPR_SIZEOF: // TODO handle obscure VLA case
4636 case EXPR_BUILTIN_CONSTANT_P:
4637 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4642 case EXPR_STATEMENT: {
4643 bool old_reaches_end = reaches_end;
4644 reaches_end = false;
4645 check_reachable(expr->statement.statement);
4646 bool returns = reaches_end;
4647 reaches_end = old_reaches_end;
4651 case EXPR_CONDITIONAL:
4652 // TODO handle constant expression
4654 if (!expression_returns(expr->conditional.condition))
4657 if (expr->conditional.true_expression != NULL
4658 && expression_returns(expr->conditional.true_expression))
4661 return expression_returns(expr->conditional.false_expression);
4664 return expression_returns(expr->select.compound);
4666 case EXPR_ARRAY_ACCESS:
4668 expression_returns(expr->array_access.array_ref) &&
4669 expression_returns(expr->array_access.index);
4672 return expression_returns(expr->va_starte.ap);
4675 return expression_returns(expr->va_arge.ap);
4678 return expression_returns(expr->va_copye.src);
4680 case EXPR_UNARY_CASES_MANDATORY:
4681 return expression_returns(expr->unary.value);
4683 case EXPR_UNARY_THROW:
4686 case EXPR_BINARY_CASES:
4687 // TODO handle constant lhs of && and ||
4689 expression_returns(expr->binary.left) &&
4690 expression_returns(expr->binary.right);
4693 panic("unhandled expression");
4696 static bool initializer_returns(initializer_t const *const init)
4698 switch (init->kind) {
4699 case INITIALIZER_VALUE:
4700 return expression_returns(init->value.value);
4702 case INITIALIZER_LIST: {
4703 initializer_t * const* i = init->list.initializers;
4704 initializer_t * const* const end = i + init->list.len;
4705 bool returns = true;
4706 for (; i != end; ++i) {
4707 if (!initializer_returns(*i))
4713 case INITIALIZER_STRING:
4714 case INITIALIZER_DESIGNATOR: // designators have no payload
4717 panic("unhandled initializer");
4720 static bool noreturn_candidate;
4722 static void check_reachable(statement_t *const stmt)
4724 if (stmt->base.reachable)
4726 if (stmt->kind != STATEMENT_DO_WHILE)
4727 stmt->base.reachable = true;
4729 statement_t *last = stmt;
4731 switch (stmt->kind) {
4732 case STATEMENT_ERROR:
4733 case STATEMENT_EMPTY:
4735 next = stmt->base.next;
4738 case STATEMENT_DECLARATION: {
4739 declaration_statement_t const *const decl = &stmt->declaration;
4740 entity_t const * ent = decl->declarations_begin;
4741 entity_t const *const last_decl = decl->declarations_end;
4743 for (;; ent = ent->base.next) {
4744 if (ent->kind == ENTITY_VARIABLE &&
4745 ent->variable.initializer != NULL &&
4746 !initializer_returns(ent->variable.initializer)) {
4749 if (ent == last_decl)
4753 next = stmt->base.next;
4757 case STATEMENT_COMPOUND:
4758 next = stmt->compound.statements;
4760 next = stmt->base.next;
4763 case STATEMENT_RETURN: {
4764 expression_t const *const val = stmt->returns.value;
4765 if (val == NULL || expression_returns(val))
4766 noreturn_candidate = false;
4770 case STATEMENT_IF: {
4771 if_statement_t const *const ifs = &stmt->ifs;
4772 expression_t const *const cond = ifs->condition;
4774 if (!expression_returns(cond))
4777 int const val = determine_truth(cond);
4780 check_reachable(ifs->true_statement);
4785 if (ifs->false_statement != NULL) {
4786 check_reachable(ifs->false_statement);
4790 next = stmt->base.next;
4794 case STATEMENT_SWITCH: {
4795 switch_statement_t const *const switchs = &stmt->switchs;
4796 expression_t const *const expr = switchs->expression;
4798 if (!expression_returns(expr))
4801 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4802 ir_tarval *const val = fold_constant_to_tarval(expr);
4803 case_label_statement_t * defaults = NULL;
4804 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4805 if (i->expression == NULL) {
4810 if (i->first_case == val || i->last_case == val ||
4811 ((tarval_cmp(i->first_case, val) & ir_relation_less_equal)
4812 && (tarval_cmp(val, i->last_case) & ir_relation_less_equal))) {
4813 check_reachable((statement_t*)i);
4818 if (defaults != NULL) {
4819 check_reachable((statement_t*)defaults);
4823 bool has_default = false;
4824 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4825 if (i->expression == NULL)
4828 check_reachable((statement_t*)i);
4835 next = stmt->base.next;
4839 case STATEMENT_EXPRESSION: {
4840 /* Check for noreturn function call */
4841 expression_t const *const expr = stmt->expression.expression;
4842 if (!expression_returns(expr))
4845 next = stmt->base.next;
4849 case STATEMENT_CONTINUE:
4850 for (statement_t *parent = stmt;;) {
4851 parent = parent->base.parent;
4852 if (parent == NULL) /* continue not within loop */
4856 switch (parent->kind) {
4857 case STATEMENT_DO_WHILE: goto continue_do_while;
4858 case STATEMENT_FOR: goto continue_for;
4864 case STATEMENT_BREAK:
4865 for (statement_t *parent = stmt;;) {
4866 parent = parent->base.parent;
4867 if (parent == NULL) /* break not within loop/switch */
4870 switch (parent->kind) {
4871 case STATEMENT_SWITCH:
4872 case STATEMENT_DO_WHILE:
4875 next = parent->base.next;
4876 goto found_break_parent;
4884 case STATEMENT_COMPUTED_GOTO: {
4885 if (!expression_returns(stmt->computed_goto.expression))
4888 statement_t *parent = stmt->base.parent;
4889 if (parent == NULL) /* top level goto */
4895 case STATEMENT_GOTO:
4896 next = stmt->gotos.label->statement;
4897 if (next == NULL) /* missing label */
4901 case STATEMENT_LABEL:
4902 next = stmt->label.statement;
4905 case STATEMENT_CASE_LABEL:
4906 next = stmt->case_label.statement;
4909 case STATEMENT_DO_WHILE:
4910 next = stmt->do_while.body;
4913 case STATEMENT_FOR: {
4914 for_statement_t *const fors = &stmt->fors;
4916 if (fors->condition_reachable)
4918 fors->condition_reachable = true;
4920 expression_t const *const cond = fors->condition;
4925 } else if (expression_returns(cond)) {
4926 val = determine_truth(cond);
4932 check_reachable(fors->body);
4937 next = stmt->base.next;
4941 case STATEMENT_MS_TRY: {
4942 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4943 check_reachable(ms_try->try_statement);
4944 next = ms_try->final_statement;
4948 case STATEMENT_LEAVE: {
4949 statement_t *parent = stmt;
4951 parent = parent->base.parent;
4952 if (parent == NULL) /* __leave not within __try */
4955 if (parent->kind == STATEMENT_MS_TRY) {
4957 next = parent->ms_try.final_statement;
4965 panic("invalid statement kind");
4968 while (next == NULL) {
4969 next = last->base.parent;
4971 noreturn_candidate = false;
4973 type_t *const type = skip_typeref(current_function->base.type);
4974 assert(is_type_function(type));
4975 type_t *const ret = skip_typeref(type->function.return_type);
4976 if (!is_type_void(ret) &&
4977 is_type_valid(ret) &&
4978 !is_main(current_entity)) {
4979 source_position_t const *const pos = &stmt->base.source_position;
4980 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4985 switch (next->kind) {
4986 case STATEMENT_ERROR:
4987 case STATEMENT_EMPTY:
4988 case STATEMENT_DECLARATION:
4989 case STATEMENT_EXPRESSION:
4991 case STATEMENT_RETURN:
4992 case STATEMENT_CONTINUE:
4993 case STATEMENT_BREAK:
4994 case STATEMENT_COMPUTED_GOTO:
4995 case STATEMENT_GOTO:
4996 case STATEMENT_LEAVE:
4997 panic("invalid control flow in function");
4999 case STATEMENT_COMPOUND:
5000 if (next->compound.stmt_expr) {
5006 case STATEMENT_SWITCH:
5007 case STATEMENT_LABEL:
5008 case STATEMENT_CASE_LABEL:
5010 next = next->base.next;
5013 case STATEMENT_DO_WHILE: {
5015 if (next->base.reachable)
5017 next->base.reachable = true;
5019 do_while_statement_t const *const dw = &next->do_while;
5020 expression_t const *const cond = dw->condition;
5022 if (!expression_returns(cond))
5025 int const val = determine_truth(cond);
5028 check_reachable(dw->body);
5034 next = next->base.next;
5038 case STATEMENT_FOR: {
5040 for_statement_t *const fors = &next->fors;
5042 fors->step_reachable = true;
5044 if (fors->condition_reachable)
5046 fors->condition_reachable = true;
5048 expression_t const *const cond = fors->condition;
5053 } else if (expression_returns(cond)) {
5054 val = determine_truth(cond);
5060 check_reachable(fors->body);
5066 next = next->base.next;
5070 case STATEMENT_MS_TRY:
5072 next = next->ms_try.final_statement;
5077 check_reachable(next);
5080 static void check_unreachable(statement_t* const stmt, void *const env)
5084 switch (stmt->kind) {
5085 case STATEMENT_DO_WHILE:
5086 if (!stmt->base.reachable) {
5087 expression_t const *const cond = stmt->do_while.condition;
5088 if (determine_truth(cond) >= 0) {
5089 source_position_t const *const pos = &cond->base.source_position;
5090 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5095 case STATEMENT_FOR: {
5096 for_statement_t const* const fors = &stmt->fors;
5098 // if init and step are unreachable, cond is unreachable, too
5099 if (!stmt->base.reachable && !fors->step_reachable) {
5100 goto warn_unreachable;
5102 if (!stmt->base.reachable && fors->initialisation != NULL) {
5103 source_position_t const *const pos = &fors->initialisation->base.source_position;
5104 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5107 if (!fors->condition_reachable && fors->condition != NULL) {
5108 source_position_t const *const pos = &fors->condition->base.source_position;
5109 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5112 if (!fors->step_reachable && fors->step != NULL) {
5113 source_position_t const *const pos = &fors->step->base.source_position;
5114 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5120 case STATEMENT_COMPOUND:
5121 if (stmt->compound.statements != NULL)
5123 goto warn_unreachable;
5125 case STATEMENT_DECLARATION: {
5126 /* Only warn if there is at least one declarator with an initializer.
5127 * This typically occurs in switch statements. */
5128 declaration_statement_t const *const decl = &stmt->declaration;
5129 entity_t const * ent = decl->declarations_begin;
5130 entity_t const *const last = decl->declarations_end;
5132 for (;; ent = ent->base.next) {
5133 if (ent->kind == ENTITY_VARIABLE &&
5134 ent->variable.initializer != NULL) {
5135 goto warn_unreachable;
5145 if (!stmt->base.reachable) {
5146 source_position_t const *const pos = &stmt->base.source_position;
5147 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5153 static bool is_main(entity_t *entity)
5155 static symbol_t *sym_main = NULL;
5156 if (sym_main == NULL) {
5157 sym_main = symbol_table_insert("main");
5160 if (entity->base.symbol != sym_main)
5162 /* must be in outermost scope */
5163 if (entity->base.parent_scope != file_scope)
5169 static void prepare_main_collect2(entity_t*);
5171 static void parse_external_declaration(void)
5173 /* function-definitions and declarations both start with declaration
5175 add_anchor_token(';');
5176 declaration_specifiers_t specifiers;
5177 parse_declaration_specifiers(&specifiers);
5178 rem_anchor_token(';');
5180 /* must be a declaration */
5181 if (token.kind == ';') {
5182 parse_anonymous_declaration_rest(&specifiers);
5186 add_anchor_token(',');
5187 add_anchor_token('=');
5188 add_anchor_token(';');
5189 add_anchor_token('{');
5191 /* declarator is common to both function-definitions and declarations */
5192 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5194 rem_anchor_token('{');
5195 rem_anchor_token(';');
5196 rem_anchor_token('=');
5197 rem_anchor_token(',');
5199 /* must be a declaration */
5200 switch (token.kind) {
5204 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5209 /* must be a function definition */
5210 parse_kr_declaration_list(ndeclaration);
5212 if (token.kind != '{') {
5213 parse_error_expected("while parsing function definition", '{', NULL);
5214 eat_until_matching_token(';');
5218 assert(is_declaration(ndeclaration));
5219 type_t *const orig_type = ndeclaration->declaration.type;
5220 type_t * type = skip_typeref(orig_type);
5222 if (!is_type_function(type)) {
5223 if (is_type_valid(type)) {
5224 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5230 source_position_t const *const pos = &ndeclaration->base.source_position;
5231 if (is_typeref(orig_type)) {
5233 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5236 if (is_type_compound(skip_typeref(type->function.return_type))) {
5237 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5239 if (type->function.unspecified_parameters) {
5240 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5242 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5245 /* §6.7.5.3:14 a function definition with () means no
5246 * parameters (and not unspecified parameters) */
5247 if (type->function.unspecified_parameters &&
5248 type->function.parameters == NULL) {
5249 type_t *copy = duplicate_type(type);
5250 copy->function.unspecified_parameters = false;
5251 type = identify_new_type(copy);
5253 ndeclaration->declaration.type = type;
5256 entity_t *const entity = record_entity(ndeclaration, true);
5257 assert(entity->kind == ENTITY_FUNCTION);
5258 assert(ndeclaration->kind == ENTITY_FUNCTION);
5260 function_t *const function = &entity->function;
5261 if (ndeclaration != entity) {
5262 function->parameters = ndeclaration->function.parameters;
5265 PUSH_SCOPE(&function->parameters);
5267 entity_t *parameter = function->parameters.entities;
5268 for (; parameter != NULL; parameter = parameter->base.next) {
5269 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5270 parameter->base.parent_scope = current_scope;
5272 assert(parameter->base.parent_scope == NULL
5273 || parameter->base.parent_scope == current_scope);
5274 parameter->base.parent_scope = current_scope;
5275 if (parameter->base.symbol == NULL) {
5276 errorf(¶meter->base.source_position, "parameter name omitted");
5279 environment_push(parameter);
5282 if (function->body != NULL) {
5283 parser_error_multiple_definition(entity, HERE);
5286 /* parse function body */
5287 int label_stack_top = label_top();
5288 function_t *old_current_function = current_function;
5289 current_function = function;
5290 PUSH_CURRENT_ENTITY(entity);
5294 goto_anchor = &goto_first;
5296 label_anchor = &label_first;
5298 statement_t *const body = parse_compound_statement(false);
5299 function->body = body;
5302 check_declarations();
5303 if (is_warn_on(WARN_RETURN_TYPE) ||
5304 is_warn_on(WARN_UNREACHABLE_CODE) ||
5305 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5306 noreturn_candidate = true;
5307 check_reachable(body);
5308 if (is_warn_on(WARN_UNREACHABLE_CODE))
5309 walk_statements(body, check_unreachable, NULL);
5310 if (noreturn_candidate &&
5311 !(function->base.modifiers & DM_NORETURN)) {
5312 source_position_t const *const pos = &body->base.source_position;
5313 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5317 if (is_main(entity)) {
5318 /* Force main to C linkage. */
5319 type_t *const type = entity->declaration.type;
5320 assert(is_type_function(type));
5321 if (type->function.linkage != LINKAGE_C) {
5322 type_t *new_type = duplicate_type(type);
5323 new_type->function.linkage = LINKAGE_C;
5324 entity->declaration.type = identify_new_type(new_type);
5327 if (enable_main_collect2_hack)
5328 prepare_main_collect2(entity);
5331 POP_CURRENT_ENTITY();
5333 assert(current_function == function);
5334 current_function = old_current_function;
5335 label_pop_to(label_stack_top);
5341 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5343 entity_t *iter = compound->members.entities;
5344 for (; iter != NULL; iter = iter->base.next) {
5345 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5348 if (iter->base.symbol == symbol) {
5350 } else if (iter->base.symbol == NULL) {
5351 /* search in anonymous structs and unions */
5352 type_t *type = skip_typeref(iter->declaration.type);
5353 if (is_type_compound(type)) {
5354 if (find_compound_entry(type->compound.compound, symbol)
5365 static void check_deprecated(const source_position_t *source_position,
5366 const entity_t *entity)
5368 if (!is_declaration(entity))
5370 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5373 source_position_t const *const epos = &entity->base.source_position;
5374 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5376 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5378 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5383 static expression_t *create_select(const source_position_t *pos,
5385 type_qualifiers_t qualifiers,
5388 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5390 check_deprecated(pos, entry);
5392 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5393 select->select.compound = addr;
5394 select->select.compound_entry = entry;
5396 type_t *entry_type = entry->declaration.type;
5397 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5399 /* bitfields need special treatment */
5400 if (entry->compound_member.bitfield) {
5401 unsigned bit_size = entry->compound_member.bit_size;
5402 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5403 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5404 res_type = type_int;
5408 /* we always do the auto-type conversions; the & and sizeof parser contains
5409 * code to revert this! */
5410 select->base.type = automatic_type_conversion(res_type);
5417 * Find entry with symbol in compound. Search anonymous structs and unions and
5418 * creates implicit select expressions for them.
5419 * Returns the adress for the innermost compound.
5421 static expression_t *find_create_select(const source_position_t *pos,
5423 type_qualifiers_t qualifiers,
5424 compound_t *compound, symbol_t *symbol)
5426 entity_t *iter = compound->members.entities;
5427 for (; iter != NULL; iter = iter->base.next) {
5428 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5431 symbol_t *iter_symbol = iter->base.symbol;
5432 if (iter_symbol == NULL) {
5433 type_t *type = iter->declaration.type;
5434 if (!is_type_compound(type))
5437 compound_t *sub_compound = type->compound.compound;
5439 if (find_compound_entry(sub_compound, symbol) == NULL)
5442 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5443 sub_addr->base.source_position = *pos;
5444 sub_addr->base.implicit = true;
5445 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5449 if (iter_symbol == symbol) {
5450 return create_select(pos, addr, qualifiers, iter);
5457 static void parse_bitfield_member(entity_t *entity)
5461 expression_t *size = parse_constant_expression();
5464 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5465 type_t *type = entity->declaration.type;
5466 if (!is_type_integer(skip_typeref(type))) {
5467 errorf(HERE, "bitfield base type '%T' is not an integer type",
5471 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5472 /* error already reported by parse_constant_expression */
5473 size_long = get_type_size(type) * 8;
5475 size_long = fold_constant_to_int(size);
5477 const symbol_t *symbol = entity->base.symbol;
5478 const symbol_t *user_symbol
5479 = symbol == NULL ? sym_anonymous : symbol;
5480 unsigned bit_size = get_type_size(type) * 8;
5481 if (size_long < 0) {
5482 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5483 } else if (size_long == 0 && symbol != NULL) {
5484 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5485 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5486 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5489 /* hope that people don't invent crazy types with more bits
5490 * than our struct can hold */
5492 (1 << sizeof(entity->compound_member.bit_size)*8));
5496 entity->compound_member.bitfield = true;
5497 entity->compound_member.bit_size = (unsigned char)size_long;
5500 static void parse_compound_declarators(compound_t *compound,
5501 const declaration_specifiers_t *specifiers)
5503 add_anchor_token(';');
5504 add_anchor_token(',');
5508 if (token.kind == ':') {
5509 /* anonymous bitfield */
5510 type_t *type = specifiers->type;
5511 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5512 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5513 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5514 entity->declaration.type = type;
5516 parse_bitfield_member(entity);
5518 attribute_t *attributes = parse_attributes(NULL);
5519 attribute_t **anchor = &attributes;
5520 while (*anchor != NULL)
5521 anchor = &(*anchor)->next;
5522 *anchor = specifiers->attributes;
5523 if (attributes != NULL) {
5524 handle_entity_attributes(attributes, entity);
5526 entity->declaration.attributes = attributes;
5528 append_entity(&compound->members, entity);
5530 entity = parse_declarator(specifiers,
5531 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5532 source_position_t const *const pos = &entity->base.source_position;
5533 if (entity->kind == ENTITY_TYPEDEF) {
5534 errorf(pos, "typedef not allowed as compound member");
5536 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5538 /* make sure we don't define a symbol multiple times */
5539 symbol_t *symbol = entity->base.symbol;
5540 if (symbol != NULL) {
5541 entity_t *prev = find_compound_entry(compound, symbol);
5543 source_position_t const *const ppos = &prev->base.source_position;
5544 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5548 if (token.kind == ':') {
5549 parse_bitfield_member(entity);
5551 attribute_t *attributes = parse_attributes(NULL);
5552 handle_entity_attributes(attributes, entity);
5554 type_t *orig_type = entity->declaration.type;
5555 type_t *type = skip_typeref(orig_type);
5556 if (is_type_function(type)) {
5557 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5558 } else if (is_type_incomplete(type)) {
5559 /* §6.7.2.1:16 flexible array member */
5560 if (!is_type_array(type) ||
5561 token.kind != ';' ||
5562 look_ahead(1)->kind != '}') {
5563 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5564 } else if (compound->members.entities == NULL) {
5565 errorf(pos, "flexible array member in otherwise empty struct");
5570 append_entity(&compound->members, entity);
5573 } while (next_if(','));
5574 rem_anchor_token(',');
5575 rem_anchor_token(';');
5578 anonymous_entity = NULL;
5581 static void parse_compound_type_entries(compound_t *compound)
5584 add_anchor_token('}');
5587 switch (token.kind) {
5589 case T___extension__:
5590 case T_IDENTIFIER: {
5592 declaration_specifiers_t specifiers;
5593 parse_declaration_specifiers(&specifiers);
5594 parse_compound_declarators(compound, &specifiers);
5600 rem_anchor_token('}');
5603 compound->complete = true;
5609 static type_t *parse_typename(void)
5611 declaration_specifiers_t specifiers;
5612 parse_declaration_specifiers(&specifiers);
5613 if (specifiers.storage_class != STORAGE_CLASS_NONE
5614 || specifiers.thread_local) {
5615 /* TODO: improve error message, user does probably not know what a
5616 * storage class is...
5618 errorf(&specifiers.source_position, "typename must not have a storage class");
5621 type_t *result = parse_abstract_declarator(specifiers.type);
5629 typedef expression_t* (*parse_expression_function)(void);
5630 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5632 typedef struct expression_parser_function_t expression_parser_function_t;
5633 struct expression_parser_function_t {
5634 parse_expression_function parser;
5635 precedence_t infix_precedence;
5636 parse_expression_infix_function infix_parser;
5639 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5641 static type_t *get_string_type(string_encoding_t const enc)
5643 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5645 case STRING_ENCODING_CHAR:
5646 case STRING_ENCODING_UTF8: return warn ? type_const_char_ptr : type_char_ptr;
5647 case STRING_ENCODING_CHAR16: return warn ? type_char16_t_const_ptr : type_char16_t_ptr;
5648 case STRING_ENCODING_CHAR32: return warn ? type_char32_t_const_ptr : type_char32_t_ptr;
5649 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5651 panic("invalid string encoding");
5655 * Parse a string constant.
5657 static expression_t *parse_string_literal(void)
5659 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5660 expr->string_literal.value = concat_string_literals();
5661 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5666 * Parse a boolean constant.
5668 static expression_t *parse_boolean_literal(bool value)
5670 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5671 literal->base.type = type_bool;
5672 literal->literal.value.begin = value ? "true" : "false";
5673 literal->literal.value.size = value ? 4 : 5;
5675 eat(value ? T_true : T_false);
5679 static void warn_traditional_suffix(char const *const suffix)
5681 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5684 static void check_integer_suffix(expression_t *const expr, char const *const suffix)
5686 unsigned spec = SPECIFIER_NONE;
5687 char const *c = suffix;
5690 if (*c == 'L' || *c == 'l') {
5691 add = SPECIFIER_LONG;
5693 add |= SPECIFIER_LONG_LONG;
5696 } else if (*c == 'U' || *c == 'u') {
5697 add = SPECIFIER_UNSIGNED;
5710 case SPECIFIER_NONE: type = type_int; break;
5711 case SPECIFIER_LONG: type = type_long; break;
5712 case SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long; break;
5713 case SPECIFIER_UNSIGNED: type = type_unsigned_int; break;
5714 case SPECIFIER_UNSIGNED | SPECIFIER_LONG: type = type_unsigned_long; break;
5715 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5716 default: panic("inconsistent suffix");
5718 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG) {
5719 warn_traditional_suffix(suffix);
5721 expr->base.type = type;
5722 /* Integer type depends on the size of the number and the size
5723 * representable by the types. The backend/codegeneration has to
5724 * determine that. */
5725 determine_literal_type(&expr->literal);
5728 errorf(HERE, "invalid suffix '%s' on integer constant", suffix);
5732 static void check_floatingpoint_suffix(expression_t *const expr, char const *const suffix)
5735 char const *c = suffix;
5738 case 'f': type = type_float; ++c; break;
5740 case 'l': type = type_long_double; ++c; break;
5741 default: type = type_double; break;
5745 expr->base.type = type;
5746 if (suffix[0] != '\0') {
5747 warn_traditional_suffix(suffix);
5750 errorf(HERE, "invalid suffix '%s' on floatingpoint constant", suffix);
5754 static expression_t *parse_number_literal(void)
5756 string_t const *const str = &token.literal.string;
5757 char const * i = str->begin;
5758 unsigned digits = 0;
5759 bool is_float = false;
5761 /* Parse base prefix. */
5765 case 'B': case 'b': base = 2; ++i; break;
5766 case 'X': case 'x': base = 16; ++i; break;
5767 default: base = 8; digits |= 1U << 0; break;
5773 /* Parse mantissa. */
5779 errorf(HERE, "multiple decimal points in %K", &token);
5788 case '0': digit = 0; break;
5789 case '1': digit = 1; break;
5790 case '2': digit = 2; break;
5791 case '3': digit = 3; break;
5792 case '4': digit = 4; break;
5793 case '5': digit = 5; break;
5794 case '6': digit = 6; break;
5795 case '7': digit = 7; break;
5796 case '8': digit = 8; break;
5797 case '9': digit = 9; break;
5798 case 'A': case 'a': digit = 10; break;
5799 case 'B': case 'b': digit = 11; break;
5800 case 'C': case 'c': digit = 12; break;
5801 case 'D': case 'd': digit = 13; break;
5802 case 'E': case 'e': digit = 14; break;
5803 case 'F': case 'f': digit = 15; break;
5805 default: goto done_mantissa;
5808 if (digit >= 10 && base != 16)
5811 digits |= 1U << digit;
5815 /* Parse exponent. */
5819 errorf(HERE, "binary floating %K not allowed", &token);
5824 if (*i == 'E' || *i == 'e') {
5826 goto parse_exponent;
5831 if (*i == 'P' || *i == 'p') {
5836 if (*i == '-' || *i == '+')
5842 } while (isdigit(*i));
5844 errorf(HERE, "exponent of %K has no digits", &token);
5846 } else if (is_float) {
5847 errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5853 panic("invalid base");
5857 expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5858 expr->literal.value = *str;
5862 errorf(HERE, "%K has no digits", &token);
5863 } else if (digits & ~((1U << base) - 1)) {
5864 errorf(HERE, "invalid digit in %K", &token);
5866 expr->literal.suffix = i;
5868 check_floatingpoint_suffix(expr, i);
5870 check_integer_suffix(expr, i);
5880 * Parse a character constant.
5882 static expression_t *parse_character_constant(void)
5884 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5885 literal->string_literal.value = token.literal.string;
5887 size_t const size = get_string_len(&token.literal.string);
5888 switch (token.literal.string.encoding) {
5889 case STRING_ENCODING_CHAR:
5890 case STRING_ENCODING_UTF8:
5891 literal->base.type = c_mode & _CXX ? type_char : type_int;
5893 if (!GNU_MODE && !(c_mode & _C99)) {
5894 errorf(HERE, "more than 1 character in character constant");
5896 literal->base.type = type_int;
5897 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5902 case STRING_ENCODING_CHAR16: literal->base.type = type_char16_t; goto warn_multi;
5903 case STRING_ENCODING_CHAR32: literal->base.type = type_char32_t; goto warn_multi;
5904 case STRING_ENCODING_WIDE: literal->base.type = type_wchar_t; goto warn_multi;
5907 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5912 eat(T_CHARACTER_CONSTANT);
5916 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5918 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5919 ntype->function.return_type = type_int;
5920 ntype->function.unspecified_parameters = true;
5921 ntype->function.linkage = LINKAGE_C;
5922 type_t *type = identify_new_type(ntype);
5924 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5925 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5926 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5927 entity->declaration.type = type;
5928 entity->declaration.implicit = true;
5930 if (current_scope != NULL)
5931 record_entity(entity, false);
5937 * Performs automatic type cast as described in §6.3.2.1.
5939 * @param orig_type the original type
5941 static type_t *automatic_type_conversion(type_t *orig_type)
5943 type_t *type = skip_typeref(orig_type);
5944 if (is_type_array(type)) {
5945 array_type_t *array_type = &type->array;
5946 type_t *element_type = array_type->element_type;
5947 unsigned qualifiers = array_type->base.qualifiers;
5949 return make_pointer_type(element_type, qualifiers);
5952 if (is_type_function(type)) {
5953 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5960 * reverts the automatic casts of array to pointer types and function
5961 * to function-pointer types as defined §6.3.2.1
5963 type_t *revert_automatic_type_conversion(const expression_t *expression)
5965 switch (expression->kind) {
5966 case EXPR_REFERENCE: {
5967 entity_t *entity = expression->reference.entity;
5968 if (is_declaration(entity)) {
5969 return entity->declaration.type;
5970 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5971 return entity->enum_value.enum_type;
5973 panic("no declaration or enum in reference");
5978 entity_t *entity = expression->select.compound_entry;
5979 assert(is_declaration(entity));
5980 type_t *type = entity->declaration.type;
5981 return get_qualified_type(type, expression->base.type->base.qualifiers);
5984 case EXPR_UNARY_DEREFERENCE: {
5985 const expression_t *const value = expression->unary.value;
5986 type_t *const type = skip_typeref(value->base.type);
5987 if (!is_type_pointer(type))
5988 return type_error_type;
5989 return type->pointer.points_to;
5992 case EXPR_ARRAY_ACCESS: {
5993 const expression_t *array_ref = expression->array_access.array_ref;
5994 type_t *type_left = skip_typeref(array_ref->base.type);
5995 if (!is_type_pointer(type_left))
5996 return type_error_type;
5997 return type_left->pointer.points_to;
6000 case EXPR_STRING_LITERAL: {
6001 size_t const size = get_string_len(&expression->string_literal.value) + 1;
6002 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
6003 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
6006 case EXPR_COMPOUND_LITERAL:
6007 return expression->compound_literal.type;
6012 return expression->base.type;
6016 * Find an entity matching a symbol in a scope.
6017 * Uses current scope if scope is NULL
6019 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6020 namespace_tag_t namespc)
6022 if (scope == NULL) {
6023 return get_entity(symbol, namespc);
6026 /* we should optimize here, if scope grows above a certain size we should
6027 construct a hashmap here... */
6028 entity_t *entity = scope->entities;
6029 for ( ; entity != NULL; entity = entity->base.next) {
6030 if (entity->base.symbol == symbol
6031 && (namespace_tag_t)entity->base.namespc == namespc)
6038 static entity_t *parse_qualified_identifier(void)
6040 /* namespace containing the symbol */
6042 source_position_t pos;
6043 const scope_t *lookup_scope = NULL;
6045 if (next_if(T_COLONCOLON))
6046 lookup_scope = &unit->scope;
6050 symbol = expect_identifier("while parsing identifier", &pos);
6052 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6055 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6057 if (!next_if(T_COLONCOLON))
6060 switch (entity->kind) {
6061 case ENTITY_NAMESPACE:
6062 lookup_scope = &entity->namespacee.members;
6067 lookup_scope = &entity->compound.members;
6070 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6071 symbol, get_entity_kind_name(entity->kind));
6073 /* skip further qualifications */
6074 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6076 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6080 if (entity == NULL) {
6081 if (!strict_mode && token.kind == '(') {
6082 /* an implicitly declared function */
6083 entity = create_implicit_function(symbol, &pos);
6084 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6086 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6087 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6094 static expression_t *parse_reference(void)
6096 source_position_t const pos = *HERE;
6097 entity_t *const entity = parse_qualified_identifier();
6100 if (is_declaration(entity)) {
6101 orig_type = entity->declaration.type;
6102 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6103 orig_type = entity->enum_value.enum_type;
6105 panic("expected declaration or enum value in reference");
6108 /* we always do the auto-type conversions; the & and sizeof parser contains
6109 * code to revert this! */
6110 type_t *type = automatic_type_conversion(orig_type);
6112 expression_kind_t kind = EXPR_REFERENCE;
6113 if (entity->kind == ENTITY_ENUM_VALUE)
6114 kind = EXPR_ENUM_CONSTANT;
6116 expression_t *expression = allocate_expression_zero(kind);
6117 expression->base.source_position = pos;
6118 expression->base.type = type;
6119 expression->reference.entity = entity;
6121 /* this declaration is used */
6122 if (is_declaration(entity)) {
6123 entity->declaration.used = true;
6126 if (entity->base.parent_scope != file_scope
6127 && (current_function != NULL
6128 && entity->base.parent_scope->depth < current_function->parameters.depth)
6129 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6130 /* access of a variable from an outer function */
6131 entity->variable.address_taken = true;
6132 current_function->need_closure = true;
6135 check_deprecated(&pos, entity);
6140 static bool semantic_cast(expression_t *cast)
6142 expression_t *expression = cast->unary.value;
6143 type_t *orig_dest_type = cast->base.type;
6144 type_t *orig_type_right = expression->base.type;
6145 type_t const *dst_type = skip_typeref(orig_dest_type);
6146 type_t const *src_type = skip_typeref(orig_type_right);
6147 source_position_t const *pos = &cast->base.source_position;
6149 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6150 if (is_type_void(dst_type))
6153 /* only integer and pointer can be casted to pointer */
6154 if (is_type_pointer(dst_type) &&
6155 !is_type_pointer(src_type) &&
6156 !is_type_integer(src_type) &&
6157 is_type_valid(src_type)) {
6158 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6162 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6163 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6167 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6168 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6172 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6173 type_t *src = skip_typeref(src_type->pointer.points_to);
6174 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6175 unsigned missing_qualifiers =
6176 src->base.qualifiers & ~dst->base.qualifiers;
6177 if (missing_qualifiers != 0) {
6178 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6184 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6186 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6187 expression->base.source_position = *pos;
6189 parse_initializer_env_t env;
6192 env.must_be_constant = false;
6193 initializer_t *initializer = parse_initializer(&env);
6196 expression->compound_literal.initializer = initializer;
6197 expression->compound_literal.type = type;
6198 expression->base.type = automatic_type_conversion(type);
6204 * Parse a cast expression.
6206 static expression_t *parse_cast(void)
6208 source_position_t const pos = *HERE;
6211 add_anchor_token(')');
6213 type_t *type = parse_typename();
6215 rem_anchor_token(')');
6218 if (token.kind == '{') {
6219 return parse_compound_literal(&pos, type);
6222 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6223 cast->base.source_position = pos;
6225 expression_t *value = parse_subexpression(PREC_CAST);
6226 cast->base.type = type;
6227 cast->unary.value = value;
6229 if (! semantic_cast(cast)) {
6230 /* TODO: record the error in the AST. else it is impossible to detect it */
6237 * Parse a statement expression.
6239 static expression_t *parse_statement_expression(void)
6241 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6244 add_anchor_token(')');
6246 statement_t *statement = parse_compound_statement(true);
6247 statement->compound.stmt_expr = true;
6248 expression->statement.statement = statement;
6250 /* find last statement and use its type */
6251 type_t *type = type_void;
6252 const statement_t *stmt = statement->compound.statements;
6254 while (stmt->base.next != NULL)
6255 stmt = stmt->base.next;
6257 if (stmt->kind == STATEMENT_EXPRESSION) {
6258 type = stmt->expression.expression->base.type;
6261 source_position_t const *const pos = &expression->base.source_position;
6262 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6264 expression->base.type = type;
6266 rem_anchor_token(')');
6272 * Parse a parenthesized expression.
6274 static expression_t *parse_parenthesized_expression(void)
6276 token_t const* const la1 = look_ahead(1);
6277 switch (la1->kind) {
6279 /* gcc extension: a statement expression */
6280 return parse_statement_expression();
6283 if (is_typedef_symbol(la1->base.symbol)) {
6285 return parse_cast();
6290 add_anchor_token(')');
6291 expression_t *result = parse_expression();
6292 result->base.parenthesized = true;
6293 rem_anchor_token(')');
6299 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6301 if (current_function == NULL) {
6302 errorf(HERE, "'%K' used outside of a function", &token);
6305 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6306 expression->base.type = type_char_ptr;
6307 expression->funcname.kind = kind;
6314 static designator_t *parse_designator(void)
6316 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6317 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6318 if (!result->symbol)
6321 designator_t *last_designator = result;
6324 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6325 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6326 if (!designator->symbol)
6329 last_designator->next = designator;
6330 last_designator = designator;
6334 add_anchor_token(']');
6335 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6336 designator->source_position = *HERE;
6337 designator->array_index = parse_expression();
6338 rem_anchor_token(']');
6340 if (designator->array_index == NULL) {
6344 last_designator->next = designator;
6345 last_designator = designator;
6355 * Parse the __builtin_offsetof() expression.
6357 static expression_t *parse_offsetof(void)
6359 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6360 expression->base.type = type_size_t;
6362 eat(T___builtin_offsetof);
6364 add_anchor_token(')');
6365 add_anchor_token(',');
6367 type_t *type = parse_typename();
6368 rem_anchor_token(',');
6370 designator_t *designator = parse_designator();
6371 rem_anchor_token(')');
6374 expression->offsetofe.type = type;
6375 expression->offsetofe.designator = designator;
6378 memset(&path, 0, sizeof(path));
6379 path.top_type = type;
6380 path.path = NEW_ARR_F(type_path_entry_t, 0);
6382 descend_into_subtype(&path);
6384 if (!walk_designator(&path, designator, true)) {
6385 return create_error_expression();
6388 DEL_ARR_F(path.path);
6393 static bool is_last_parameter(expression_t *const param)
6395 if (param->kind == EXPR_REFERENCE) {
6396 entity_t *const entity = param->reference.entity;
6397 if (entity->kind == ENTITY_PARAMETER &&
6398 !entity->base.next &&
6399 entity->base.parent_scope == ¤t_function->parameters) {
6404 if (!is_type_valid(skip_typeref(param->base.type)))
6411 * Parses a __builtin_va_start() expression.
6413 static expression_t *parse_va_start(void)
6415 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6417 eat(T___builtin_va_start);
6419 add_anchor_token(')');
6420 add_anchor_token(',');
6422 expression->va_starte.ap = parse_assignment_expression();
6423 rem_anchor_token(',');
6425 expression_t *const param = parse_assignment_expression();
6426 expression->va_starte.parameter = param;
6427 rem_anchor_token(')');
6430 if (!current_function) {
6431 errorf(&expression->base.source_position, "'va_start' used outside of function");
6432 } else if (!current_function->base.type->function.variadic) {
6433 errorf(&expression->base.source_position, "'va_start' used in non-variadic function");
6434 } else if (!is_last_parameter(param)) {
6435 errorf(¶m->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
6442 * Parses a __builtin_va_arg() expression.
6444 static expression_t *parse_va_arg(void)
6446 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6448 eat(T___builtin_va_arg);
6450 add_anchor_token(')');
6451 add_anchor_token(',');
6454 ap.expression = parse_assignment_expression();
6455 expression->va_arge.ap = ap.expression;
6456 check_call_argument(type_valist, &ap, 1);
6458 rem_anchor_token(',');
6460 expression->base.type = parse_typename();
6461 rem_anchor_token(')');
6468 * Parses a __builtin_va_copy() expression.
6470 static expression_t *parse_va_copy(void)
6472 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6474 eat(T___builtin_va_copy);
6476 add_anchor_token(')');
6477 add_anchor_token(',');
6479 expression_t *dst = parse_assignment_expression();
6480 assign_error_t error = semantic_assign(type_valist, dst);
6481 report_assign_error(error, type_valist, dst, "call argument 1",
6482 &dst->base.source_position);
6483 expression->va_copye.dst = dst;
6485 rem_anchor_token(',');
6488 call_argument_t src;
6489 src.expression = parse_assignment_expression();
6490 check_call_argument(type_valist, &src, 2);
6491 expression->va_copye.src = src.expression;
6492 rem_anchor_token(')');
6499 * Parses a __builtin_constant_p() expression.
6501 static expression_t *parse_builtin_constant(void)
6503 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6505 eat(T___builtin_constant_p);
6507 add_anchor_token(')');
6509 expression->builtin_constant.value = parse_assignment_expression();
6510 rem_anchor_token(')');
6512 expression->base.type = type_int;
6518 * Parses a __builtin_types_compatible_p() expression.
6520 static expression_t *parse_builtin_types_compatible(void)
6522 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6524 eat(T___builtin_types_compatible_p);
6526 add_anchor_token(')');
6527 add_anchor_token(',');
6529 expression->builtin_types_compatible.left = parse_typename();
6530 rem_anchor_token(',');
6532 expression->builtin_types_compatible.right = parse_typename();
6533 rem_anchor_token(')');
6535 expression->base.type = type_int;
6541 * Parses a __builtin_is_*() compare expression.
6543 static expression_t *parse_compare_builtin(void)
6545 expression_kind_t kind;
6546 switch (token.kind) {
6547 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6548 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6549 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6550 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6551 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6552 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6553 default: internal_errorf(HERE, "invalid compare builtin found");
6555 expression_t *const expression = allocate_expression_zero(kind);
6558 add_anchor_token(')');
6559 add_anchor_token(',');
6561 expression->binary.left = parse_assignment_expression();
6562 rem_anchor_token(',');
6564 expression->binary.right = parse_assignment_expression();
6565 rem_anchor_token(')');
6568 type_t *const orig_type_left = expression->binary.left->base.type;
6569 type_t *const orig_type_right = expression->binary.right->base.type;
6571 type_t *const type_left = skip_typeref(orig_type_left);
6572 type_t *const type_right = skip_typeref(orig_type_right);
6573 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6574 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6575 type_error_incompatible("invalid operands in comparison",
6576 &expression->base.source_position, orig_type_left, orig_type_right);
6579 semantic_comparison(&expression->binary);
6586 * Parses a MS assume() expression.
6588 static expression_t *parse_assume(void)
6590 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6594 add_anchor_token(')');
6596 expression->unary.value = parse_assignment_expression();
6597 rem_anchor_token(')');
6600 expression->base.type = type_void;
6605 * Return the label for the current symbol or create a new one.
6607 static label_t *get_label(char const *const context)
6609 assert(current_function != NULL);
6611 symbol_t *const sym = expect_identifier(context, NULL);
6615 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6616 /* If we find a local label, we already created the declaration. */
6617 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6618 if (label->base.parent_scope != current_scope) {
6619 assert(label->base.parent_scope->depth < current_scope->depth);
6620 current_function->goto_to_outer = true;
6622 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6623 /* There is no matching label in the same function, so create a new one. */
6624 source_position_t const nowhere = { NULL, 0, 0, false };
6625 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6629 return &label->label;
6633 * Parses a GNU && label address expression.
6635 static expression_t *parse_label_address(void)
6637 source_position_t const source_position = *HERE;
6640 label_t *const label = get_label("while parsing label address");
6642 return create_error_expression();
6645 label->address_taken = true;
6647 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6648 expression->base.source_position = source_position;
6650 /* label address is treated as a void pointer */
6651 expression->base.type = type_void_ptr;
6652 expression->label_address.label = label;
6657 * Parse a microsoft __noop expression.
6659 static expression_t *parse_noop_expression(void)
6661 /* the result is a (int)0 */
6662 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6663 literal->base.type = type_int;
6664 literal->literal.value.begin = "__noop";
6665 literal->literal.value.size = 6;
6669 if (token.kind == '(') {
6670 /* parse arguments */
6672 add_anchor_token(')');
6673 add_anchor_token(',');
6675 if (token.kind != ')') do {
6676 (void)parse_assignment_expression();
6677 } while (next_if(','));
6679 rem_anchor_token(',');
6680 rem_anchor_token(')');
6688 * Parses a primary expression.
6690 static expression_t *parse_primary_expression(void)
6692 switch (token.kind) {
6693 case T_false: return parse_boolean_literal(false);
6694 case T_true: return parse_boolean_literal(true);
6695 case T_NUMBER: return parse_number_literal();
6696 case T_CHARACTER_CONSTANT: return parse_character_constant();
6697 case T_STRING_LITERAL: return parse_string_literal();
6698 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6699 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6700 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6701 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6702 case T___builtin_offsetof: return parse_offsetof();
6703 case T___builtin_va_start: return parse_va_start();
6704 case T___builtin_va_arg: return parse_va_arg();
6705 case T___builtin_va_copy: return parse_va_copy();
6706 case T___builtin_isgreater:
6707 case T___builtin_isgreaterequal:
6708 case T___builtin_isless:
6709 case T___builtin_islessequal:
6710 case T___builtin_islessgreater:
6711 case T___builtin_isunordered: return parse_compare_builtin();
6712 case T___builtin_constant_p: return parse_builtin_constant();
6713 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6714 case T__assume: return parse_assume();
6717 return parse_label_address();
6720 case '(': return parse_parenthesized_expression();
6721 case T___noop: return parse_noop_expression();
6723 /* Gracefully handle type names while parsing expressions. */
6725 return parse_reference();
6727 if (!is_typedef_symbol(token.base.symbol)) {
6728 return parse_reference();
6732 source_position_t const pos = *HERE;
6733 declaration_specifiers_t specifiers;
6734 parse_declaration_specifiers(&specifiers);
6735 type_t const *const type = parse_abstract_declarator(specifiers.type);
6736 errorf(&pos, "encountered type '%T' while parsing expression", type);
6737 return create_error_expression();
6741 errorf(HERE, "unexpected token %K, expected an expression", &token);
6743 return create_error_expression();
6746 static expression_t *parse_array_expression(expression_t *left)
6748 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6749 array_access_expression_t *const arr = &expr->array_access;
6752 add_anchor_token(']');
6754 expression_t *const inside = parse_expression();
6756 type_t *const orig_type_left = left->base.type;
6757 type_t *const orig_type_inside = inside->base.type;
6759 type_t *const type_left = skip_typeref(orig_type_left);
6760 type_t *const type_inside = skip_typeref(orig_type_inside);
6766 if (is_type_pointer(type_left)) {
6769 idx_type = type_inside;
6770 res_type = type_left->pointer.points_to;
6772 } else if (is_type_pointer(type_inside)) {
6773 arr->flipped = true;
6776 idx_type = type_left;
6777 res_type = type_inside->pointer.points_to;
6779 res_type = automatic_type_conversion(res_type);
6780 if (!is_type_integer(idx_type)) {
6781 if (is_type_valid(idx_type))
6782 errorf(&idx->base.source_position, "array subscript must have integer type");
6783 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6784 source_position_t const *const pos = &idx->base.source_position;
6785 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6788 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6789 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6791 res_type = type_error_type;
6796 arr->array_ref = ref;
6798 arr->base.type = res_type;
6800 rem_anchor_token(']');
6805 static bool is_bitfield(const expression_t *expression)
6807 return expression->kind == EXPR_SELECT
6808 && expression->select.compound_entry->compound_member.bitfield;
6811 static expression_t *parse_typeprop(expression_kind_t const kind)
6813 expression_t *tp_expression = allocate_expression_zero(kind);
6814 tp_expression->base.type = type_size_t;
6816 eat(kind == EXPR_SIZEOF ? T_sizeof : T__Alignof);
6819 expression_t *expression;
6820 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6821 source_position_t const pos = *HERE;
6823 add_anchor_token(')');
6824 orig_type = parse_typename();
6825 rem_anchor_token(')');
6828 if (token.kind == '{') {
6829 /* It was not sizeof(type) after all. It is sizeof of an expression
6830 * starting with a compound literal */
6831 expression = parse_compound_literal(&pos, orig_type);
6832 goto typeprop_expression;
6835 expression = parse_subexpression(PREC_UNARY);
6837 typeprop_expression:
6838 if (is_bitfield(expression)) {
6839 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6840 errorf(&tp_expression->base.source_position,
6841 "operand of %s expression must not be a bitfield", what);
6844 tp_expression->typeprop.tp_expression = expression;
6846 orig_type = revert_automatic_type_conversion(expression);
6847 expression->base.type = orig_type;
6850 tp_expression->typeprop.type = orig_type;
6851 type_t const* const type = skip_typeref(orig_type);
6852 char const* wrong_type = NULL;
6853 if (is_type_incomplete(type)) {
6854 if (!is_type_void(type) || !GNU_MODE)
6855 wrong_type = "incomplete";
6856 } else if (type->kind == TYPE_FUNCTION) {
6858 /* function types are allowed (and return 1) */
6859 source_position_t const *const pos = &tp_expression->base.source_position;
6860 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6861 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6863 wrong_type = "function";
6867 if (wrong_type != NULL) {
6868 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6869 errorf(&tp_expression->base.source_position,
6870 "operand of %s expression must not be of %s type '%T'",
6871 what, wrong_type, orig_type);
6874 return tp_expression;
6877 static expression_t *parse_sizeof(void)
6879 return parse_typeprop(EXPR_SIZEOF);
6882 static expression_t *parse_alignof(void)
6884 return parse_typeprop(EXPR_ALIGNOF);
6887 static expression_t *parse_select_expression(expression_t *addr)
6889 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6890 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6891 source_position_t const pos = *HERE;
6894 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6896 return create_error_expression();
6898 type_t *const orig_type = addr->base.type;
6899 type_t *const type = skip_typeref(orig_type);
6902 bool saw_error = false;
6903 if (is_type_pointer(type)) {
6904 if (!select_left_arrow) {
6906 "request for member '%Y' in something not a struct or union, but '%T'",
6910 type_left = skip_typeref(type->pointer.points_to);
6912 if (select_left_arrow && is_type_valid(type)) {
6913 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6919 if (!is_type_compound(type_left)) {
6920 if (is_type_valid(type_left) && !saw_error) {
6922 "request for member '%Y' in something not a struct or union, but '%T'",
6925 return create_error_expression();
6928 compound_t *compound = type_left->compound.compound;
6929 if (!compound->complete) {
6930 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6932 return create_error_expression();
6935 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6936 expression_t *result =
6937 find_create_select(&pos, addr, qualifiers, compound, symbol);
6939 if (result == NULL) {
6940 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6941 return create_error_expression();
6947 static void check_call_argument(type_t *expected_type,
6948 call_argument_t *argument, unsigned pos)
6950 type_t *expected_type_skip = skip_typeref(expected_type);
6951 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6952 expression_t *arg_expr = argument->expression;
6953 type_t *arg_type = skip_typeref(arg_expr->base.type);
6955 /* handle transparent union gnu extension */
6956 if (is_type_union(expected_type_skip)
6957 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6958 compound_t *union_decl = expected_type_skip->compound.compound;
6959 type_t *best_type = NULL;
6960 entity_t *entry = union_decl->members.entities;
6961 for ( ; entry != NULL; entry = entry->base.next) {
6962 assert(is_declaration(entry));
6963 type_t *decl_type = entry->declaration.type;
6964 error = semantic_assign(decl_type, arg_expr);
6965 if (error == ASSIGN_ERROR_INCOMPATIBLE
6966 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6969 if (error == ASSIGN_SUCCESS) {
6970 best_type = decl_type;
6971 } else if (best_type == NULL) {
6972 best_type = decl_type;
6976 if (best_type != NULL) {
6977 expected_type = best_type;
6981 error = semantic_assign(expected_type, arg_expr);
6982 argument->expression = create_implicit_cast(arg_expr, expected_type);
6984 if (error != ASSIGN_SUCCESS) {
6985 /* report exact scope in error messages (like "in argument 3") */
6987 snprintf(buf, sizeof(buf), "call argument %u", pos);
6988 report_assign_error(error, expected_type, arg_expr, buf,
6989 &arg_expr->base.source_position);
6991 type_t *const promoted_type = get_default_promoted_type(arg_type);
6992 if (!types_compatible(expected_type_skip, promoted_type) &&
6993 !types_compatible(expected_type_skip, type_void_ptr) &&
6994 !types_compatible(type_void_ptr, promoted_type)) {
6995 /* Deliberately show the skipped types in this warning */
6996 source_position_t const *const apos = &arg_expr->base.source_position;
6997 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7003 * Handle the semantic restrictions of builtin calls
7005 static void handle_builtin_argument_restrictions(call_expression_t *call)
7007 entity_t *entity = call->function->reference.entity;
7008 switch (entity->function.btk) {
7010 switch (entity->function.b.firm_builtin_kind) {
7011 case ir_bk_return_address:
7012 case ir_bk_frame_address: {
7013 /* argument must be constant */
7014 call_argument_t *argument = call->arguments;
7016 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7017 errorf(&call->base.source_position,
7018 "argument of '%Y' must be a constant expression",
7019 call->function->reference.entity->base.symbol);
7023 case ir_bk_prefetch:
7024 /* second and third argument must be constant if existent */
7025 if (call->arguments == NULL)
7027 call_argument_t *rw = call->arguments->next;
7028 call_argument_t *locality = NULL;
7031 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7032 errorf(&call->base.source_position,
7033 "second argument of '%Y' must be a constant expression",
7034 call->function->reference.entity->base.symbol);
7036 locality = rw->next;
7038 if (locality != NULL) {
7039 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7040 errorf(&call->base.source_position,
7041 "third argument of '%Y' must be a constant expression",
7042 call->function->reference.entity->base.symbol);
7050 case BUILTIN_OBJECT_SIZE:
7051 if (call->arguments == NULL)
7054 call_argument_t *arg = call->arguments->next;
7055 if (arg != NULL && is_constant_expression(arg->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);
7067 * Parse a call expression, ie. expression '( ... )'.
7069 * @param expression the function address
7071 static expression_t *parse_call_expression(expression_t *expression)
7073 expression_t *result = allocate_expression_zero(EXPR_CALL);
7074 call_expression_t *call = &result->call;
7075 call->function = expression;
7077 type_t *const orig_type = expression->base.type;
7078 type_t *const type = skip_typeref(orig_type);
7080 function_type_t *function_type = NULL;
7081 if (is_type_pointer(type)) {
7082 type_t *const to_type = skip_typeref(type->pointer.points_to);
7084 if (is_type_function(to_type)) {
7085 function_type = &to_type->function;
7086 call->base.type = function_type->return_type;
7090 if (function_type == NULL && is_type_valid(type)) {
7092 "called object '%E' (type '%T') is not a pointer to a function",
7093 expression, orig_type);
7096 /* parse arguments */
7098 add_anchor_token(')');
7099 add_anchor_token(',');
7101 if (token.kind != ')') {
7102 call_argument_t **anchor = &call->arguments;
7104 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7105 argument->expression = parse_assignment_expression();
7108 anchor = &argument->next;
7109 } while (next_if(','));
7111 rem_anchor_token(',');
7112 rem_anchor_token(')');
7115 if (function_type == NULL)
7118 /* check type and count of call arguments */
7119 function_parameter_t *parameter = function_type->parameters;
7120 call_argument_t *argument = call->arguments;
7121 if (!function_type->unspecified_parameters) {
7122 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7123 parameter = parameter->next, argument = argument->next) {
7124 check_call_argument(parameter->type, argument, ++pos);
7127 if (parameter != NULL) {
7128 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7129 } else if (argument != NULL && !function_type->variadic) {
7130 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7134 /* do default promotion for other arguments */
7135 for (; argument != NULL; argument = argument->next) {
7136 type_t *argument_type = argument->expression->base.type;
7137 if (!is_type_object(skip_typeref(argument_type))) {
7138 errorf(&argument->expression->base.source_position,
7139 "call argument '%E' must not be void", argument->expression);
7142 argument_type = get_default_promoted_type(argument_type);
7144 argument->expression
7145 = create_implicit_cast(argument->expression, argument_type);
7150 if (is_type_compound(skip_typeref(function_type->return_type))) {
7151 source_position_t const *const pos = &expression->base.source_position;
7152 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7155 if (expression->kind == EXPR_REFERENCE) {
7156 reference_expression_t *reference = &expression->reference;
7157 if (reference->entity->kind == ENTITY_FUNCTION &&
7158 reference->entity->function.btk != BUILTIN_NONE)
7159 handle_builtin_argument_restrictions(call);
7165 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7167 static bool same_compound_type(const type_t *type1, const type_t *type2)
7170 is_type_compound(type1) &&
7171 type1->kind == type2->kind &&
7172 type1->compound.compound == type2->compound.compound;
7175 static expression_t const *get_reference_address(expression_t const *expr)
7177 bool regular_take_address = true;
7179 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7180 expr = expr->unary.value;
7182 regular_take_address = false;
7185 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7188 expr = expr->unary.value;
7191 if (expr->kind != EXPR_REFERENCE)
7194 /* special case for functions which are automatically converted to a
7195 * pointer to function without an extra TAKE_ADDRESS operation */
7196 if (!regular_take_address &&
7197 expr->reference.entity->kind != ENTITY_FUNCTION) {
7204 static void warn_reference_address_as_bool(expression_t const* expr)
7206 expr = get_reference_address(expr);
7208 source_position_t const *const pos = &expr->base.source_position;
7209 entity_t const *const ent = expr->reference.entity;
7210 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7214 static void warn_assignment_in_condition(const expression_t *const expr)
7216 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7218 if (expr->base.parenthesized)
7220 source_position_t const *const pos = &expr->base.source_position;
7221 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7224 static void semantic_condition(expression_t const *const expr,
7225 char const *const context)
7227 type_t *const type = skip_typeref(expr->base.type);
7228 if (is_type_scalar(type)) {
7229 warn_reference_address_as_bool(expr);
7230 warn_assignment_in_condition(expr);
7231 } else if (is_type_valid(type)) {
7232 errorf(&expr->base.source_position,
7233 "%s must have scalar type", context);
7238 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7240 * @param expression the conditional expression
7242 static expression_t *parse_conditional_expression(expression_t *expression)
7244 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7246 conditional_expression_t *conditional = &result->conditional;
7247 conditional->condition = expression;
7250 add_anchor_token(':');
7252 /* §6.5.15:2 The first operand shall have scalar type. */
7253 semantic_condition(expression, "condition of conditional operator");
7255 expression_t *true_expression = expression;
7256 bool gnu_cond = false;
7257 if (GNU_MODE && token.kind == ':') {
7260 true_expression = parse_expression();
7262 rem_anchor_token(':');
7264 expression_t *false_expression =
7265 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7267 type_t *const orig_true_type = true_expression->base.type;
7268 type_t *const orig_false_type = false_expression->base.type;
7269 type_t *const true_type = skip_typeref(orig_true_type);
7270 type_t *const false_type = skip_typeref(orig_false_type);
7273 source_position_t const *const pos = &conditional->base.source_position;
7274 type_t *result_type;
7275 if (is_type_void(true_type) || is_type_void(false_type)) {
7276 /* ISO/IEC 14882:1998(E) §5.16:2 */
7277 if (true_expression->kind == EXPR_UNARY_THROW) {
7278 result_type = false_type;
7279 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7280 result_type = true_type;
7282 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7283 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7285 result_type = type_void;
7287 } else if (is_type_arithmetic(true_type)
7288 && is_type_arithmetic(false_type)) {
7289 result_type = semantic_arithmetic(true_type, false_type);
7290 } else if (same_compound_type(true_type, false_type)) {
7291 /* just take 1 of the 2 types */
7292 result_type = true_type;
7293 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7294 type_t *pointer_type;
7296 expression_t *other_expression;
7297 if (is_type_pointer(true_type) &&
7298 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7299 pointer_type = true_type;
7300 other_type = false_type;
7301 other_expression = false_expression;
7303 pointer_type = false_type;
7304 other_type = true_type;
7305 other_expression = true_expression;
7308 if (is_null_pointer_constant(other_expression)) {
7309 result_type = pointer_type;
7310 } else if (is_type_pointer(other_type)) {
7311 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7312 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7315 if (is_type_void(to1) || is_type_void(to2)) {
7317 } else if (types_compatible(get_unqualified_type(to1),
7318 get_unqualified_type(to2))) {
7321 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7325 type_t *const type =
7326 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7327 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7328 } else if (is_type_integer(other_type)) {
7329 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7330 result_type = pointer_type;
7332 goto types_incompatible;
7336 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7337 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7339 result_type = type_error_type;
7342 conditional->true_expression
7343 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7344 conditional->false_expression
7345 = create_implicit_cast(false_expression, result_type);
7346 conditional->base.type = result_type;
7351 * Parse an extension expression.
7353 static expression_t *parse_extension(void)
7356 expression_t *expression = parse_subexpression(PREC_UNARY);
7362 * Parse a __builtin_classify_type() expression.
7364 static expression_t *parse_builtin_classify_type(void)
7366 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7367 result->base.type = type_int;
7369 eat(T___builtin_classify_type);
7371 add_anchor_token(')');
7373 expression_t *expression = parse_expression();
7374 rem_anchor_token(')');
7376 result->classify_type.type_expression = expression;
7382 * Parse a delete expression
7383 * ISO/IEC 14882:1998(E) §5.3.5
7385 static expression_t *parse_delete(void)
7387 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7388 result->base.type = type_void;
7393 result->kind = EXPR_UNARY_DELETE_ARRAY;
7397 expression_t *const value = parse_subexpression(PREC_CAST);
7398 result->unary.value = value;
7400 type_t *const type = skip_typeref(value->base.type);
7401 if (!is_type_pointer(type)) {
7402 if (is_type_valid(type)) {
7403 errorf(&value->base.source_position,
7404 "operand of delete must have pointer type");
7406 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7407 source_position_t const *const pos = &value->base.source_position;
7408 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7415 * Parse a throw expression
7416 * ISO/IEC 14882:1998(E) §15:1
7418 static expression_t *parse_throw(void)
7420 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7421 result->base.type = type_void;
7425 expression_t *value = NULL;
7426 switch (token.kind) {
7428 value = parse_assignment_expression();
7429 /* ISO/IEC 14882:1998(E) §15.1:3 */
7430 type_t *const orig_type = value->base.type;
7431 type_t *const type = skip_typeref(orig_type);
7432 if (is_type_incomplete(type)) {
7433 errorf(&value->base.source_position,
7434 "cannot throw object of incomplete type '%T'", orig_type);
7435 } else if (is_type_pointer(type)) {
7436 type_t *const points_to = skip_typeref(type->pointer.points_to);
7437 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7438 errorf(&value->base.source_position,
7439 "cannot throw pointer to incomplete type '%T'", orig_type);
7447 result->unary.value = value;
7452 static bool check_pointer_arithmetic(const source_position_t *source_position,
7453 type_t *pointer_type,
7454 type_t *orig_pointer_type)
7456 type_t *points_to = pointer_type->pointer.points_to;
7457 points_to = skip_typeref(points_to);
7459 if (is_type_incomplete(points_to)) {
7460 if (!GNU_MODE || !is_type_void(points_to)) {
7461 errorf(source_position,
7462 "arithmetic with pointer to incomplete type '%T' not allowed",
7466 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7468 } else if (is_type_function(points_to)) {
7470 errorf(source_position,
7471 "arithmetic with pointer to function type '%T' not allowed",
7475 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7481 static bool is_lvalue(const expression_t *expression)
7483 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7484 switch (expression->kind) {
7485 case EXPR_ARRAY_ACCESS:
7486 case EXPR_COMPOUND_LITERAL:
7487 case EXPR_REFERENCE:
7489 case EXPR_UNARY_DEREFERENCE:
7493 type_t *type = skip_typeref(expression->base.type);
7495 /* ISO/IEC 14882:1998(E) §3.10:3 */
7496 is_type_reference(type) ||
7497 /* Claim it is an lvalue, if the type is invalid. There was a parse
7498 * error before, which maybe prevented properly recognizing it as
7500 !is_type_valid(type);
7505 static void semantic_incdec(unary_expression_t *expression)
7507 type_t *const orig_type = expression->value->base.type;
7508 type_t *const type = skip_typeref(orig_type);
7509 if (is_type_pointer(type)) {
7510 if (!check_pointer_arithmetic(&expression->base.source_position,
7514 } else if (!is_type_real(type) && is_type_valid(type)) {
7515 /* TODO: improve error message */
7516 errorf(&expression->base.source_position,
7517 "operation needs an arithmetic or pointer type");
7520 if (!is_lvalue(expression->value)) {
7521 /* TODO: improve error message */
7522 errorf(&expression->base.source_position, "lvalue required as operand");
7524 expression->base.type = orig_type;
7527 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7529 type_t *const res_type = promote_integer(type);
7530 expr->base.type = res_type;
7531 expr->value = create_implicit_cast(expr->value, res_type);
7534 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7536 type_t *const orig_type = expression->value->base.type;
7537 type_t *const type = skip_typeref(orig_type);
7538 if (!is_type_arithmetic(type)) {
7539 if (is_type_valid(type)) {
7540 /* TODO: improve error message */
7541 errorf(&expression->base.source_position,
7542 "operation needs an arithmetic type");
7545 } else if (is_type_integer(type)) {
7546 promote_unary_int_expr(expression, type);
7548 expression->base.type = orig_type;
7552 static void semantic_unexpr_plus(unary_expression_t *expression)
7554 semantic_unexpr_arithmetic(expression);
7555 source_position_t const *const pos = &expression->base.source_position;
7556 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7559 static void semantic_not(unary_expression_t *expression)
7561 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7562 semantic_condition(expression->value, "operand of !");
7563 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7566 static void semantic_unexpr_integer(unary_expression_t *expression)
7568 type_t *const orig_type = expression->value->base.type;
7569 type_t *const type = skip_typeref(orig_type);
7570 if (!is_type_integer(type)) {
7571 if (is_type_valid(type)) {
7572 errorf(&expression->base.source_position,
7573 "operand of ~ must be of integer type");
7578 promote_unary_int_expr(expression, type);
7581 static void semantic_dereference(unary_expression_t *expression)
7583 type_t *const orig_type = expression->value->base.type;
7584 type_t *const type = skip_typeref(orig_type);
7585 if (!is_type_pointer(type)) {
7586 if (is_type_valid(type)) {
7587 errorf(&expression->base.source_position,
7588 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7593 type_t *result_type = type->pointer.points_to;
7594 result_type = automatic_type_conversion(result_type);
7595 expression->base.type = result_type;
7599 * Record that an address is taken (expression represents an lvalue).
7601 * @param expression the expression
7602 * @param may_be_register if true, the expression might be an register
7604 static void set_address_taken(expression_t *expression, bool may_be_register)
7606 if (expression->kind != EXPR_REFERENCE)
7609 entity_t *const entity = expression->reference.entity;
7611 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7614 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7615 && !may_be_register) {
7616 source_position_t const *const pos = &expression->base.source_position;
7617 errorf(pos, "address of register '%N' requested", entity);
7620 entity->variable.address_taken = true;
7624 * Check the semantic of the address taken expression.
7626 static void semantic_take_addr(unary_expression_t *expression)
7628 expression_t *value = expression->value;
7629 value->base.type = revert_automatic_type_conversion(value);
7631 type_t *orig_type = value->base.type;
7632 type_t *type = skip_typeref(orig_type);
7633 if (!is_type_valid(type))
7637 if (!is_lvalue(value)) {
7638 errorf(&expression->base.source_position, "'&' requires an lvalue");
7640 if (is_bitfield(value)) {
7641 errorf(&expression->base.source_position,
7642 "'&' not allowed on bitfield");
7645 set_address_taken(value, false);
7647 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7650 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7651 static expression_t *parse_##unexpression_type(void) \
7653 expression_t *unary_expression \
7654 = allocate_expression_zero(unexpression_type); \
7656 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7658 sfunc(&unary_expression->unary); \
7660 return unary_expression; \
7663 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7664 semantic_unexpr_arithmetic)
7665 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7666 semantic_unexpr_plus)
7667 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7669 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7670 semantic_dereference)
7671 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7673 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7674 semantic_unexpr_integer)
7675 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7677 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7680 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7682 static expression_t *parse_##unexpression_type(expression_t *left) \
7684 expression_t *unary_expression \
7685 = allocate_expression_zero(unexpression_type); \
7687 unary_expression->unary.value = left; \
7689 sfunc(&unary_expression->unary); \
7691 return unary_expression; \
7694 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7695 EXPR_UNARY_POSTFIX_INCREMENT,
7697 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7698 EXPR_UNARY_POSTFIX_DECREMENT,
7701 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7703 /* TODO: handle complex + imaginary types */
7705 type_left = get_unqualified_type(type_left);
7706 type_right = get_unqualified_type(type_right);
7708 /* §6.3.1.8 Usual arithmetic conversions */
7709 if (type_left == type_long_double || type_right == type_long_double) {
7710 return type_long_double;
7711 } else if (type_left == type_double || type_right == type_double) {
7713 } else if (type_left == type_float || type_right == type_float) {
7717 type_left = promote_integer(type_left);
7718 type_right = promote_integer(type_right);
7720 if (type_left == type_right)
7723 bool const signed_left = is_type_signed(type_left);
7724 bool const signed_right = is_type_signed(type_right);
7725 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7726 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7728 if (signed_left == signed_right)
7729 return rank_left >= rank_right ? type_left : type_right;
7733 atomic_type_kind_t s_akind;
7734 atomic_type_kind_t u_akind;
7739 u_type = type_right;
7741 s_type = type_right;
7744 s_akind = get_akind(s_type);
7745 u_akind = get_akind(u_type);
7746 s_rank = get_akind_rank(s_akind);
7747 u_rank = get_akind_rank(u_akind);
7749 if (u_rank >= s_rank)
7752 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7756 case ATOMIC_TYPE_INT: return type_unsigned_int;
7757 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7758 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7760 default: panic("invalid atomic type");
7765 * Check the semantic restrictions for a binary expression.
7767 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7769 expression_t *const left = expression->left;
7770 expression_t *const right = expression->right;
7771 type_t *const orig_type_left = left->base.type;
7772 type_t *const orig_type_right = right->base.type;
7773 type_t *const type_left = skip_typeref(orig_type_left);
7774 type_t *const type_right = skip_typeref(orig_type_right);
7776 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7777 /* TODO: improve error message */
7778 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7779 errorf(&expression->base.source_position,
7780 "operation needs arithmetic types");
7785 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7786 expression->left = create_implicit_cast(left, arithmetic_type);
7787 expression->right = create_implicit_cast(right, arithmetic_type);
7788 expression->base.type = arithmetic_type;
7791 static void semantic_binexpr_integer(binary_expression_t *const expression)
7793 expression_t *const left = expression->left;
7794 expression_t *const right = expression->right;
7795 type_t *const orig_type_left = left->base.type;
7796 type_t *const orig_type_right = right->base.type;
7797 type_t *const type_left = skip_typeref(orig_type_left);
7798 type_t *const type_right = skip_typeref(orig_type_right);
7800 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7801 /* TODO: improve error message */
7802 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7803 errorf(&expression->base.source_position,
7804 "operation needs integer types");
7809 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7810 expression->left = create_implicit_cast(left, result_type);
7811 expression->right = create_implicit_cast(right, result_type);
7812 expression->base.type = result_type;
7815 static void warn_div_by_zero(binary_expression_t const *const expression)
7817 if (!is_type_integer(expression->base.type))
7820 expression_t const *const right = expression->right;
7821 /* The type of the right operand can be different for /= */
7822 if (is_type_integer(right->base.type) &&
7823 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7824 !fold_constant_to_bool(right)) {
7825 source_position_t const *const pos = &expression->base.source_position;
7826 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7831 * Check the semantic restrictions for a div/mod expression.
7833 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7835 semantic_binexpr_arithmetic(expression);
7836 warn_div_by_zero(expression);
7839 static void warn_addsub_in_shift(const expression_t *const expr)
7841 if (expr->base.parenthesized)
7845 switch (expr->kind) {
7846 case EXPR_BINARY_ADD: op = '+'; break;
7847 case EXPR_BINARY_SUB: op = '-'; break;
7851 source_position_t const *const pos = &expr->base.source_position;
7852 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7855 static bool semantic_shift(binary_expression_t *expression)
7857 expression_t *const left = expression->left;
7858 expression_t *const right = expression->right;
7859 type_t *const orig_type_left = left->base.type;
7860 type_t *const orig_type_right = right->base.type;
7861 type_t * type_left = skip_typeref(orig_type_left);
7862 type_t * type_right = skip_typeref(orig_type_right);
7864 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7865 /* TODO: improve error message */
7866 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7867 errorf(&expression->base.source_position,
7868 "operands of shift operation must have integer types");
7873 type_left = promote_integer(type_left);
7875 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7876 source_position_t const *const pos = &right->base.source_position;
7877 long const count = fold_constant_to_int(right);
7879 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7880 } else if ((unsigned long)count >=
7881 get_atomic_type_size(type_left->atomic.akind) * 8) {
7882 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7886 type_right = promote_integer(type_right);
7887 expression->right = create_implicit_cast(right, type_right);
7892 static void semantic_shift_op(binary_expression_t *expression)
7894 expression_t *const left = expression->left;
7895 expression_t *const right = expression->right;
7897 if (!semantic_shift(expression))
7900 warn_addsub_in_shift(left);
7901 warn_addsub_in_shift(right);
7903 type_t *const orig_type_left = left->base.type;
7904 type_t * type_left = skip_typeref(orig_type_left);
7906 type_left = promote_integer(type_left);
7907 expression->left = create_implicit_cast(left, type_left);
7908 expression->base.type = type_left;
7911 static void semantic_add(binary_expression_t *expression)
7913 expression_t *const left = expression->left;
7914 expression_t *const right = expression->right;
7915 type_t *const orig_type_left = left->base.type;
7916 type_t *const orig_type_right = right->base.type;
7917 type_t *const type_left = skip_typeref(orig_type_left);
7918 type_t *const type_right = skip_typeref(orig_type_right);
7921 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7922 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7923 expression->left = create_implicit_cast(left, arithmetic_type);
7924 expression->right = create_implicit_cast(right, arithmetic_type);
7925 expression->base.type = arithmetic_type;
7926 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7927 check_pointer_arithmetic(&expression->base.source_position,
7928 type_left, orig_type_left);
7929 expression->base.type = type_left;
7930 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7931 check_pointer_arithmetic(&expression->base.source_position,
7932 type_right, orig_type_right);
7933 expression->base.type = type_right;
7934 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7935 errorf(&expression->base.source_position,
7936 "invalid operands to binary + ('%T', '%T')",
7937 orig_type_left, orig_type_right);
7941 static void semantic_sub(binary_expression_t *expression)
7943 expression_t *const left = expression->left;
7944 expression_t *const right = expression->right;
7945 type_t *const orig_type_left = left->base.type;
7946 type_t *const orig_type_right = right->base.type;
7947 type_t *const type_left = skip_typeref(orig_type_left);
7948 type_t *const type_right = skip_typeref(orig_type_right);
7949 source_position_t const *const pos = &expression->base.source_position;
7952 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7953 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7954 expression->left = create_implicit_cast(left, arithmetic_type);
7955 expression->right = create_implicit_cast(right, arithmetic_type);
7956 expression->base.type = arithmetic_type;
7957 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7958 check_pointer_arithmetic(&expression->base.source_position,
7959 type_left, orig_type_left);
7960 expression->base.type = type_left;
7961 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7962 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7963 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7964 if (!types_compatible(unqual_left, unqual_right)) {
7966 "subtracting pointers to incompatible types '%T' and '%T'",
7967 orig_type_left, orig_type_right);
7968 } else if (!is_type_object(unqual_left)) {
7969 if (!is_type_void(unqual_left)) {
7970 errorf(pos, "subtracting pointers to non-object types '%T'",
7973 warningf(WARN_OTHER, pos, "subtracting pointers to void");
7976 expression->base.type = type_ptrdiff_t;
7977 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7978 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7979 orig_type_left, orig_type_right);
7983 static void warn_string_literal_address(expression_t const* expr)
7985 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7986 expr = expr->unary.value;
7987 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7989 expr = expr->unary.value;
7992 if (expr->kind == EXPR_STRING_LITERAL) {
7993 source_position_t const *const pos = &expr->base.source_position;
7994 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
7998 static bool maybe_negative(expression_t const *const expr)
8000 switch (is_constant_expression(expr)) {
8001 case EXPR_CLASS_ERROR: return false;
8002 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8003 default: return true;
8007 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8009 warn_string_literal_address(expr);
8011 expression_t const* const ref = get_reference_address(expr);
8012 if (ref != NULL && is_null_pointer_constant(other)) {
8013 entity_t const *const ent = ref->reference.entity;
8014 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8017 if (!expr->base.parenthesized) {
8018 switch (expr->base.kind) {
8019 case EXPR_BINARY_LESS:
8020 case EXPR_BINARY_GREATER:
8021 case EXPR_BINARY_LESSEQUAL:
8022 case EXPR_BINARY_GREATEREQUAL:
8023 case EXPR_BINARY_NOTEQUAL:
8024 case EXPR_BINARY_EQUAL:
8025 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8034 * Check the semantics of comparison expressions.
8036 * @param expression The expression to check.
8038 static void semantic_comparison(binary_expression_t *expression)
8040 source_position_t const *const pos = &expression->base.source_position;
8041 expression_t *const left = expression->left;
8042 expression_t *const right = expression->right;
8044 warn_comparison(pos, left, right);
8045 warn_comparison(pos, right, left);
8047 type_t *orig_type_left = left->base.type;
8048 type_t *orig_type_right = right->base.type;
8049 type_t *type_left = skip_typeref(orig_type_left);
8050 type_t *type_right = skip_typeref(orig_type_right);
8052 /* TODO non-arithmetic types */
8053 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8054 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8056 /* test for signed vs unsigned compares */
8057 if (is_type_integer(arithmetic_type)) {
8058 bool const signed_left = is_type_signed(type_left);
8059 bool const signed_right = is_type_signed(type_right);
8060 if (signed_left != signed_right) {
8061 /* FIXME long long needs better const folding magic */
8062 /* TODO check whether constant value can be represented by other type */
8063 if ((signed_left && maybe_negative(left)) ||
8064 (signed_right && maybe_negative(right))) {
8065 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8070 expression->left = create_implicit_cast(left, arithmetic_type);
8071 expression->right = create_implicit_cast(right, arithmetic_type);
8072 expression->base.type = arithmetic_type;
8073 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8074 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8075 is_type_float(arithmetic_type)) {
8076 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8078 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8079 /* TODO check compatibility */
8080 } else if (is_type_pointer(type_left)) {
8081 expression->right = create_implicit_cast(right, type_left);
8082 } else if (is_type_pointer(type_right)) {
8083 expression->left = create_implicit_cast(left, type_right);
8084 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8085 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8087 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8091 * Checks if a compound type has constant fields.
8093 static bool has_const_fields(const compound_type_t *type)
8095 compound_t *compound = type->compound;
8096 entity_t *entry = compound->members.entities;
8098 for (; entry != NULL; entry = entry->base.next) {
8099 if (!is_declaration(entry))
8102 const type_t *decl_type = skip_typeref(entry->declaration.type);
8103 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8110 static bool is_valid_assignment_lhs(expression_t const* const left)
8112 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8113 type_t *const type_left = skip_typeref(orig_type_left);
8115 if (!is_lvalue(left)) {
8116 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8121 if (left->kind == EXPR_REFERENCE
8122 && left->reference.entity->kind == ENTITY_FUNCTION) {
8123 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8127 if (is_type_array(type_left)) {
8128 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8131 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8132 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8136 if (is_type_incomplete(type_left)) {
8137 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8138 left, orig_type_left);
8141 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8142 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8143 left, orig_type_left);
8150 static void semantic_arithmetic_assign(binary_expression_t *expression)
8152 expression_t *left = expression->left;
8153 expression_t *right = expression->right;
8154 type_t *orig_type_left = left->base.type;
8155 type_t *orig_type_right = right->base.type;
8157 if (!is_valid_assignment_lhs(left))
8160 type_t *type_left = skip_typeref(orig_type_left);
8161 type_t *type_right = skip_typeref(orig_type_right);
8163 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8164 /* TODO: improve error message */
8165 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8166 errorf(&expression->base.source_position,
8167 "operation needs arithmetic types");
8172 /* combined instructions are tricky. We can't create an implicit cast on
8173 * the left side, because we need the uncasted form for the store.
8174 * The ast2firm pass has to know that left_type must be right_type
8175 * for the arithmetic operation and create a cast by itself */
8176 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8177 expression->right = create_implicit_cast(right, arithmetic_type);
8178 expression->base.type = type_left;
8181 static void semantic_divmod_assign(binary_expression_t *expression)
8183 semantic_arithmetic_assign(expression);
8184 warn_div_by_zero(expression);
8187 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8189 expression_t *const left = expression->left;
8190 expression_t *const right = expression->right;
8191 type_t *const orig_type_left = left->base.type;
8192 type_t *const orig_type_right = right->base.type;
8193 type_t *const type_left = skip_typeref(orig_type_left);
8194 type_t *const type_right = skip_typeref(orig_type_right);
8196 if (!is_valid_assignment_lhs(left))
8199 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8200 /* combined instructions are tricky. We can't create an implicit cast on
8201 * the left side, because we need the uncasted form for the store.
8202 * The ast2firm pass has to know that left_type must be right_type
8203 * for the arithmetic operation and create a cast by itself */
8204 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8205 expression->right = create_implicit_cast(right, arithmetic_type);
8206 expression->base.type = type_left;
8207 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8208 check_pointer_arithmetic(&expression->base.source_position,
8209 type_left, orig_type_left);
8210 expression->base.type = type_left;
8211 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8212 errorf(&expression->base.source_position,
8213 "incompatible types '%T' and '%T' in assignment",
8214 orig_type_left, orig_type_right);
8218 static void semantic_integer_assign(binary_expression_t *expression)
8220 expression_t *left = expression->left;
8221 expression_t *right = expression->right;
8222 type_t *orig_type_left = left->base.type;
8223 type_t *orig_type_right = right->base.type;
8225 if (!is_valid_assignment_lhs(left))
8228 type_t *type_left = skip_typeref(orig_type_left);
8229 type_t *type_right = skip_typeref(orig_type_right);
8231 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8232 /* TODO: improve error message */
8233 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8234 errorf(&expression->base.source_position,
8235 "operation needs integer types");
8240 /* combined instructions are tricky. We can't create an implicit cast on
8241 * the left side, because we need the uncasted form for the store.
8242 * The ast2firm pass has to know that left_type must be right_type
8243 * for the arithmetic operation and create a cast by itself */
8244 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8245 expression->right = create_implicit_cast(right, arithmetic_type);
8246 expression->base.type = type_left;
8249 static void semantic_shift_assign(binary_expression_t *expression)
8251 expression_t *left = expression->left;
8253 if (!is_valid_assignment_lhs(left))
8256 if (!semantic_shift(expression))
8259 expression->base.type = skip_typeref(left->base.type);
8262 static void warn_logical_and_within_or(const expression_t *const expr)
8264 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8266 if (expr->base.parenthesized)
8268 source_position_t const *const pos = &expr->base.source_position;
8269 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8273 * Check the semantic restrictions of a logical expression.
8275 static void semantic_logical_op(binary_expression_t *expression)
8277 /* §6.5.13:2 Each of the operands shall have scalar type.
8278 * §6.5.14:2 Each of the operands shall have scalar type. */
8279 semantic_condition(expression->left, "left operand of logical operator");
8280 semantic_condition(expression->right, "right operand of logical operator");
8281 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8282 warn_logical_and_within_or(expression->left);
8283 warn_logical_and_within_or(expression->right);
8285 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8289 * Check the semantic restrictions of a binary assign expression.
8291 static void semantic_binexpr_assign(binary_expression_t *expression)
8293 expression_t *left = expression->left;
8294 type_t *orig_type_left = left->base.type;
8296 if (!is_valid_assignment_lhs(left))
8299 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8300 report_assign_error(error, orig_type_left, expression->right,
8301 "assignment", &left->base.source_position);
8302 expression->right = create_implicit_cast(expression->right, orig_type_left);
8303 expression->base.type = orig_type_left;
8307 * Determine if the outermost operation (or parts thereof) of the given
8308 * expression has no effect in order to generate a warning about this fact.
8309 * Therefore in some cases this only examines some of the operands of the
8310 * expression (see comments in the function and examples below).
8312 * f() + 23; // warning, because + has no effect
8313 * x || f(); // no warning, because x controls execution of f()
8314 * x ? y : f(); // warning, because y has no effect
8315 * (void)x; // no warning to be able to suppress the warning
8316 * This function can NOT be used for an "expression has definitely no effect"-
8318 static bool expression_has_effect(const expression_t *const expr)
8320 switch (expr->kind) {
8321 case EXPR_ERROR: return true; /* do NOT warn */
8322 case EXPR_REFERENCE: return false;
8323 case EXPR_ENUM_CONSTANT: return false;
8324 case EXPR_LABEL_ADDRESS: return false;
8326 /* suppress the warning for microsoft __noop operations */
8327 case EXPR_LITERAL_MS_NOOP: return true;
8328 case EXPR_LITERAL_BOOLEAN:
8329 case EXPR_LITERAL_CHARACTER:
8330 case EXPR_LITERAL_INTEGER:
8331 case EXPR_LITERAL_FLOATINGPOINT:
8332 case EXPR_STRING_LITERAL: return false;
8335 const call_expression_t *const call = &expr->call;
8336 if (call->function->kind != EXPR_REFERENCE)
8339 switch (call->function->reference.entity->function.btk) {
8340 /* FIXME: which builtins have no effect? */
8341 default: return true;
8345 /* Generate the warning if either the left or right hand side of a
8346 * conditional expression has no effect */
8347 case EXPR_CONDITIONAL: {
8348 conditional_expression_t const *const cond = &expr->conditional;
8349 expression_t const *const t = cond->true_expression;
8351 (t == NULL || expression_has_effect(t)) &&
8352 expression_has_effect(cond->false_expression);
8355 case EXPR_SELECT: return false;
8356 case EXPR_ARRAY_ACCESS: return false;
8357 case EXPR_SIZEOF: return false;
8358 case EXPR_CLASSIFY_TYPE: return false;
8359 case EXPR_ALIGNOF: return false;
8361 case EXPR_FUNCNAME: return false;
8362 case EXPR_BUILTIN_CONSTANT_P: return false;
8363 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8364 case EXPR_OFFSETOF: return false;
8365 case EXPR_VA_START: return true;
8366 case EXPR_VA_ARG: return true;
8367 case EXPR_VA_COPY: return true;
8368 case EXPR_STATEMENT: return true; // TODO
8369 case EXPR_COMPOUND_LITERAL: return false;
8371 case EXPR_UNARY_NEGATE: return false;
8372 case EXPR_UNARY_PLUS: return false;
8373 case EXPR_UNARY_BITWISE_NEGATE: return false;
8374 case EXPR_UNARY_NOT: return false;
8375 case EXPR_UNARY_DEREFERENCE: return false;
8376 case EXPR_UNARY_TAKE_ADDRESS: return false;
8377 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8378 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8379 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8380 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8382 /* Treat void casts as if they have an effect in order to being able to
8383 * suppress the warning */
8384 case EXPR_UNARY_CAST: {
8385 type_t *const type = skip_typeref(expr->base.type);
8386 return is_type_void(type);
8389 case EXPR_UNARY_ASSUME: return true;
8390 case EXPR_UNARY_DELETE: return true;
8391 case EXPR_UNARY_DELETE_ARRAY: return true;
8392 case EXPR_UNARY_THROW: return true;
8394 case EXPR_BINARY_ADD: return false;
8395 case EXPR_BINARY_SUB: return false;
8396 case EXPR_BINARY_MUL: return false;
8397 case EXPR_BINARY_DIV: return false;
8398 case EXPR_BINARY_MOD: return false;
8399 case EXPR_BINARY_EQUAL: return false;
8400 case EXPR_BINARY_NOTEQUAL: return false;
8401 case EXPR_BINARY_LESS: return false;
8402 case EXPR_BINARY_LESSEQUAL: return false;
8403 case EXPR_BINARY_GREATER: return false;
8404 case EXPR_BINARY_GREATEREQUAL: return false;
8405 case EXPR_BINARY_BITWISE_AND: return false;
8406 case EXPR_BINARY_BITWISE_OR: return false;
8407 case EXPR_BINARY_BITWISE_XOR: return false;
8408 case EXPR_BINARY_SHIFTLEFT: return false;
8409 case EXPR_BINARY_SHIFTRIGHT: return false;
8410 case EXPR_BINARY_ASSIGN: return true;
8411 case EXPR_BINARY_MUL_ASSIGN: return true;
8412 case EXPR_BINARY_DIV_ASSIGN: return true;
8413 case EXPR_BINARY_MOD_ASSIGN: return true;
8414 case EXPR_BINARY_ADD_ASSIGN: return true;
8415 case EXPR_BINARY_SUB_ASSIGN: return true;
8416 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8417 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8418 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8419 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8420 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8422 /* Only examine the right hand side of && and ||, because the left hand
8423 * side already has the effect of controlling the execution of the right
8425 case EXPR_BINARY_LOGICAL_AND:
8426 case EXPR_BINARY_LOGICAL_OR:
8427 /* Only examine the right hand side of a comma expression, because the left
8428 * hand side has a separate warning */
8429 case EXPR_BINARY_COMMA:
8430 return expression_has_effect(expr->binary.right);
8432 case EXPR_BINARY_ISGREATER: return false;
8433 case EXPR_BINARY_ISGREATEREQUAL: return false;
8434 case EXPR_BINARY_ISLESS: return false;
8435 case EXPR_BINARY_ISLESSEQUAL: return false;
8436 case EXPR_BINARY_ISLESSGREATER: return false;
8437 case EXPR_BINARY_ISUNORDERED: return false;
8440 internal_errorf(HERE, "unexpected expression");
8443 static void semantic_comma(binary_expression_t *expression)
8445 const expression_t *const left = expression->left;
8446 if (!expression_has_effect(left)) {
8447 source_position_t const *const pos = &left->base.source_position;
8448 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8450 expression->base.type = expression->right->base.type;
8454 * @param prec_r precedence of the right operand
8456 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8457 static expression_t *parse_##binexpression_type(expression_t *left) \
8459 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8460 binexpr->binary.left = left; \
8463 expression_t *right = parse_subexpression(prec_r); \
8465 binexpr->binary.right = right; \
8466 sfunc(&binexpr->binary); \
8471 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8472 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8473 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8474 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8475 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8476 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8477 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8478 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8479 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8480 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8481 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8482 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8483 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8484 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8485 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8486 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8487 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8488 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8489 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8490 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8491 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8492 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8493 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8494 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8495 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8496 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8497 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8498 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8499 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8500 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8503 static expression_t *parse_subexpression(precedence_t precedence)
8505 expression_parser_function_t *parser
8506 = &expression_parsers[token.kind];
8509 if (parser->parser != NULL) {
8510 left = parser->parser();
8512 left = parse_primary_expression();
8514 assert(left != NULL);
8517 parser = &expression_parsers[token.kind];
8518 if (parser->infix_parser == NULL)
8520 if (parser->infix_precedence < precedence)
8523 left = parser->infix_parser(left);
8525 assert(left != NULL);
8532 * Parse an expression.
8534 static expression_t *parse_expression(void)
8536 return parse_subexpression(PREC_EXPRESSION);
8540 * Register a parser for a prefix-like operator.
8542 * @param parser the parser function
8543 * @param token_kind the token type of the prefix token
8545 static void register_expression_parser(parse_expression_function parser,
8548 expression_parser_function_t *entry = &expression_parsers[token_kind];
8550 assert(!entry->parser);
8551 entry->parser = parser;
8555 * Register a parser for an infix operator with given precedence.
8557 * @param parser the parser function
8558 * @param token_kind the token type of the infix operator
8559 * @param precedence the precedence of the operator
8561 static void register_infix_parser(parse_expression_infix_function parser,
8562 int token_kind, precedence_t precedence)
8564 expression_parser_function_t *entry = &expression_parsers[token_kind];
8566 assert(!entry->infix_parser);
8567 entry->infix_parser = parser;
8568 entry->infix_precedence = precedence;
8572 * Initialize the expression parsers.
8574 static void init_expression_parsers(void)
8576 memset(&expression_parsers, 0, sizeof(expression_parsers));
8578 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8579 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8580 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8581 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8582 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8583 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8584 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8585 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8586 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8587 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8588 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8589 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8590 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8591 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8592 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8593 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8594 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8595 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8596 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8597 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8598 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8599 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8600 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8601 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8602 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8603 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8604 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8605 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8606 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8607 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8608 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8609 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8610 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8611 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8612 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8613 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8614 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8616 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8617 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8618 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8619 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8620 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8621 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8622 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8623 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8624 register_expression_parser(parse_sizeof, T_sizeof);
8625 register_expression_parser(parse_alignof, T__Alignof);
8626 register_expression_parser(parse_extension, T___extension__);
8627 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8628 register_expression_parser(parse_delete, T_delete);
8629 register_expression_parser(parse_throw, T_throw);
8633 * Parse a asm statement arguments specification.
8635 static asm_argument_t *parse_asm_arguments(bool is_out)
8637 asm_argument_t *result = NULL;
8638 asm_argument_t **anchor = &result;
8640 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8641 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8644 add_anchor_token(']');
8645 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8646 rem_anchor_token(']');
8648 if (!argument->symbol)
8652 argument->constraints = parse_string_literals("asm argument");
8653 add_anchor_token(')');
8655 expression_t *expression = parse_expression();
8656 rem_anchor_token(')');
8658 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8659 * change size or type representation (e.g. int -> long is ok, but
8660 * int -> float is not) */
8661 if (expression->kind == EXPR_UNARY_CAST) {
8662 type_t *const type = expression->base.type;
8663 type_kind_t const kind = type->kind;
8664 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8667 if (kind == TYPE_ATOMIC) {
8668 atomic_type_kind_t const akind = type->atomic.akind;
8669 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8670 size = get_atomic_type_size(akind);
8672 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8673 size = get_type_size(type_void_ptr);
8677 expression_t *const value = expression->unary.value;
8678 type_t *const value_type = value->base.type;
8679 type_kind_t const value_kind = value_type->kind;
8681 unsigned value_flags;
8682 unsigned value_size;
8683 if (value_kind == TYPE_ATOMIC) {
8684 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8685 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8686 value_size = get_atomic_type_size(value_akind);
8687 } else if (value_kind == TYPE_POINTER) {
8688 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8689 value_size = get_type_size(type_void_ptr);
8694 if (value_flags != flags || value_size != size)
8698 } while (expression->kind == EXPR_UNARY_CAST);
8702 if (!is_lvalue(expression)) {
8703 errorf(&expression->base.source_position,
8704 "asm output argument is not an lvalue");
8707 if (argument->constraints.begin[0] == '=')
8708 determine_lhs_ent(expression, NULL);
8710 mark_vars_read(expression, NULL);
8712 mark_vars_read(expression, NULL);
8714 argument->expression = expression;
8717 set_address_taken(expression, true);
8720 anchor = &argument->next;
8730 * Parse a asm statement clobber specification.
8732 static asm_clobber_t *parse_asm_clobbers(void)
8734 asm_clobber_t *result = NULL;
8735 asm_clobber_t **anchor = &result;
8737 while (token.kind == T_STRING_LITERAL) {
8738 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8739 clobber->clobber = parse_string_literals(NULL);
8742 anchor = &clobber->next;
8752 * Parse an asm statement.
8754 static statement_t *parse_asm_statement(void)
8756 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8757 asm_statement_t *asm_statement = &statement->asms;
8760 add_anchor_token(')');
8761 add_anchor_token(':');
8762 add_anchor_token(T_STRING_LITERAL);
8764 if (next_if(T_volatile))
8765 asm_statement->is_volatile = true;
8768 rem_anchor_token(T_STRING_LITERAL);
8769 asm_statement->asm_text = parse_string_literals("asm statement");
8772 asm_statement->outputs = parse_asm_arguments(true);
8775 asm_statement->inputs = parse_asm_arguments(false);
8777 rem_anchor_token(':');
8779 asm_statement->clobbers = parse_asm_clobbers();
8781 rem_anchor_token(')');
8785 if (asm_statement->outputs == NULL) {
8786 /* GCC: An 'asm' instruction without any output operands will be treated
8787 * identically to a volatile 'asm' instruction. */
8788 asm_statement->is_volatile = true;
8794 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8796 statement_t *inner_stmt;
8797 switch (token.kind) {
8799 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8800 inner_stmt = create_error_statement();
8804 if (label->kind == STATEMENT_LABEL) {
8805 /* Eat an empty statement here, to avoid the warning about an empty
8806 * statement after a label. label:; is commonly used to have a label
8807 * before a closing brace. */
8808 inner_stmt = create_empty_statement();
8815 inner_stmt = parse_statement();
8816 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8817 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8818 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8819 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8827 * Parse a case statement.
8829 static statement_t *parse_case_statement(void)
8831 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8832 source_position_t *const pos = &statement->base.source_position;
8835 add_anchor_token(':');
8837 expression_t *expression = parse_expression();
8838 type_t *expression_type = expression->base.type;
8839 type_t *skipped = skip_typeref(expression_type);
8840 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8841 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8842 expression, expression_type);
8845 type_t *type = expression_type;
8846 if (current_switch != NULL) {
8847 type_t *switch_type = current_switch->expression->base.type;
8848 if (is_type_valid(switch_type)) {
8849 expression = create_implicit_cast(expression, switch_type);
8853 statement->case_label.expression = expression;
8854 expression_classification_t const expr_class = is_constant_expression(expression);
8855 if (expr_class != EXPR_CLASS_CONSTANT) {
8856 if (expr_class != EXPR_CLASS_ERROR) {
8857 errorf(pos, "case label does not reduce to an integer constant");
8859 statement->case_label.is_bad = true;
8861 ir_tarval *val = fold_constant_to_tarval(expression);
8862 statement->case_label.first_case = val;
8863 statement->case_label.last_case = val;
8867 if (next_if(T_DOTDOTDOT)) {
8868 expression_t *end_range = parse_expression();
8869 expression_type = expression->base.type;
8870 skipped = skip_typeref(expression_type);
8871 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8872 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8873 expression, expression_type);
8876 end_range = create_implicit_cast(end_range, type);
8877 statement->case_label.end_range = end_range;
8878 expression_classification_t const end_class = is_constant_expression(end_range);
8879 if (end_class != EXPR_CLASS_CONSTANT) {
8880 if (end_class != EXPR_CLASS_ERROR) {
8881 errorf(pos, "case range does not reduce to an integer constant");
8883 statement->case_label.is_bad = true;
8885 ir_tarval *val = fold_constant_to_tarval(end_range);
8886 statement->case_label.last_case = val;
8888 if (tarval_cmp(val, statement->case_label.first_case)
8889 == ir_relation_less) {
8890 statement->case_label.is_empty_range = true;
8891 warningf(WARN_OTHER, pos, "empty range specified");
8897 PUSH_PARENT(statement);
8899 rem_anchor_token(':');
8902 if (current_switch != NULL) {
8903 if (! statement->case_label.is_bad) {
8904 /* Check for duplicate case values */
8905 case_label_statement_t *c = &statement->case_label;
8906 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8907 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8910 if (c->last_case < l->first_case || c->first_case > l->last_case)
8913 errorf(pos, "duplicate case value (previously used %P)",
8914 &l->base.source_position);
8918 /* link all cases into the switch statement */
8919 if (current_switch->last_case == NULL) {
8920 current_switch->first_case = &statement->case_label;
8922 current_switch->last_case->next = &statement->case_label;
8924 current_switch->last_case = &statement->case_label;
8926 errorf(pos, "case label not within a switch statement");
8929 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
8936 * Parse a default statement.
8938 static statement_t *parse_default_statement(void)
8940 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8944 PUSH_PARENT(statement);
8948 if (current_switch != NULL) {
8949 const case_label_statement_t *def_label = current_switch->default_label;
8950 if (def_label != NULL) {
8951 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
8953 current_switch->default_label = &statement->case_label;
8955 /* link all cases into the switch statement */
8956 if (current_switch->last_case == NULL) {
8957 current_switch->first_case = &statement->case_label;
8959 current_switch->last_case->next = &statement->case_label;
8961 current_switch->last_case = &statement->case_label;
8964 errorf(&statement->base.source_position,
8965 "'default' label not within a switch statement");
8968 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
8975 * Parse a label statement.
8977 static statement_t *parse_label_statement(void)
8979 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8980 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
8981 statement->label.label = label;
8983 PUSH_PARENT(statement);
8985 /* if statement is already set then the label is defined twice,
8986 * otherwise it was just mentioned in a goto/local label declaration so far
8988 source_position_t const* const pos = &statement->base.source_position;
8989 if (label->statement != NULL) {
8990 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
8992 label->base.source_position = *pos;
8993 label->statement = statement;
8994 label->n_users += 1;
8999 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9000 parse_attributes(NULL); // TODO process attributes
9003 statement->label.statement = parse_label_inner_statement(statement, "label");
9005 /* remember the labels in a list for later checking */
9006 *label_anchor = &statement->label;
9007 label_anchor = &statement->label.next;
9013 static statement_t *parse_inner_statement(void)
9015 statement_t *const stmt = parse_statement();
9016 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9017 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9018 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9019 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9025 * Parse an expression in parentheses and mark its variables as read.
9027 static expression_t *parse_condition(void)
9029 add_anchor_token(')');
9031 expression_t *const expr = parse_expression();
9032 mark_vars_read(expr, NULL);
9033 rem_anchor_token(')');
9039 * Parse an if statement.
9041 static statement_t *parse_if(void)
9043 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9047 PUSH_PARENT(statement);
9048 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9050 add_anchor_token(T_else);
9052 expression_t *const expr = parse_condition();
9053 statement->ifs.condition = expr;
9054 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9056 semantic_condition(expr, "condition of 'if'-statment");
9058 statement_t *const true_stmt = parse_inner_statement();
9059 statement->ifs.true_statement = true_stmt;
9060 rem_anchor_token(T_else);
9062 if (true_stmt->kind == STATEMENT_EMPTY) {
9063 warningf(WARN_EMPTY_BODY, HERE,
9064 "suggest braces around empty body in an ‘if’ statement");
9067 if (next_if(T_else)) {
9068 statement->ifs.false_statement = parse_inner_statement();
9070 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9071 warningf(WARN_EMPTY_BODY, HERE,
9072 "suggest braces around empty body in an ‘if’ statement");
9074 } else if (true_stmt->kind == STATEMENT_IF &&
9075 true_stmt->ifs.false_statement != NULL) {
9076 source_position_t const *const pos = &true_stmt->base.source_position;
9077 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9086 * Check that all enums are handled in a switch.
9088 * @param statement the switch statement to check
9090 static void check_enum_cases(const switch_statement_t *statement)
9092 if (!is_warn_on(WARN_SWITCH_ENUM))
9094 type_t *type = skip_typeref(statement->expression->base.type);
9095 if (! is_type_enum(type))
9097 enum_type_t *enumt = &type->enumt;
9099 /* if we have a default, no warnings */
9100 if (statement->default_label != NULL)
9103 determine_enum_values(enumt);
9105 /* FIXME: calculation of value should be done while parsing */
9106 /* TODO: quadratic algorithm here. Change to an n log n one */
9107 const entity_t *entry = enumt->enume->base.next;
9108 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9109 entry = entry->base.next) {
9110 ir_tarval *value = entry->enum_value.tv;
9112 for (const case_label_statement_t *l = statement->first_case; l != NULL;
9114 if (l->expression == NULL)
9116 if (l->first_case == l->last_case && l->first_case != value)
9118 if ((tarval_cmp(l->first_case, value) & ir_relation_less_equal)
9119 && (tarval_cmp(value, l->last_case) & ir_relation_less_equal)) {
9125 source_position_t const *const pos = &statement->base.source_position;
9126 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9132 * Parse a switch statement.
9134 static statement_t *parse_switch(void)
9136 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9140 PUSH_PARENT(statement);
9141 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9143 expression_t *const expr = parse_condition();
9144 type_t * type = skip_typeref(expr->base.type);
9145 if (is_type_integer(type)) {
9146 type = promote_integer(type);
9147 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9148 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9150 } else if (is_type_valid(type)) {
9151 errorf(&expr->base.source_position,
9152 "switch quantity is not an integer, but '%T'", type);
9153 type = type_error_type;
9155 statement->switchs.expression = create_implicit_cast(expr, type);
9157 switch_statement_t *rem = current_switch;
9158 current_switch = &statement->switchs;
9159 statement->switchs.body = parse_inner_statement();
9160 current_switch = rem;
9162 if (statement->switchs.default_label == NULL) {
9163 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9165 check_enum_cases(&statement->switchs);
9172 static statement_t *parse_loop_body(statement_t *const loop)
9174 statement_t *const rem = current_loop;
9175 current_loop = loop;
9177 statement_t *const body = parse_inner_statement();
9184 * Parse a while statement.
9186 static statement_t *parse_while(void)
9188 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9192 PUSH_PARENT(statement);
9193 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9195 expression_t *const cond = parse_condition();
9196 statement->fors.condition = cond;
9197 /* §6.8.5:2 The controlling expression of an iteration statement shall
9198 * have scalar type. */
9199 semantic_condition(cond, "condition of 'while'-statement");
9201 statement->fors.body = parse_loop_body(statement);
9209 * Parse a do statement.
9211 static statement_t *parse_do(void)
9213 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9217 PUSH_PARENT(statement);
9218 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9220 add_anchor_token(T_while);
9221 statement->do_while.body = parse_loop_body(statement);
9222 rem_anchor_token(T_while);
9225 expression_t *const cond = parse_condition();
9226 statement->do_while.condition = cond;
9227 /* §6.8.5:2 The controlling expression of an iteration statement shall
9228 * have scalar type. */
9229 semantic_condition(cond, "condition of 'do-while'-statement");
9238 * Parse a for statement.
9240 static statement_t *parse_for(void)
9242 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9246 PUSH_PARENT(statement);
9247 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9249 add_anchor_token(')');
9255 } else if (is_declaration_specifier(&token)) {
9256 parse_declaration(record_entity, DECL_FLAGS_NONE);
9258 add_anchor_token(';');
9259 expression_t *const init = parse_expression();
9260 statement->fors.initialisation = init;
9261 mark_vars_read(init, ENT_ANY);
9262 if (!expression_has_effect(init)) {
9263 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9265 rem_anchor_token(';');
9271 if (token.kind != ';') {
9272 add_anchor_token(';');
9273 expression_t *const cond = parse_expression();
9274 statement->fors.condition = cond;
9275 /* §6.8.5:2 The controlling expression of an iteration statement
9276 * shall have scalar type. */
9277 semantic_condition(cond, "condition of 'for'-statement");
9278 mark_vars_read(cond, NULL);
9279 rem_anchor_token(';');
9282 if (token.kind != ')') {
9283 expression_t *const step = parse_expression();
9284 statement->fors.step = step;
9285 mark_vars_read(step, ENT_ANY);
9286 if (!expression_has_effect(step)) {
9287 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9290 rem_anchor_token(')');
9292 statement->fors.body = parse_loop_body(statement);
9300 * Parse a goto statement.
9302 static statement_t *parse_goto(void)
9304 statement_t *statement;
9305 if (GNU_MODE && look_ahead(1)->kind == '*') {
9306 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9310 expression_t *expression = parse_expression();
9311 mark_vars_read(expression, NULL);
9313 /* Argh: although documentation says the expression must be of type void*,
9314 * gcc accepts anything that can be casted into void* without error */
9315 type_t *type = expression->base.type;
9317 if (type != type_error_type) {
9318 if (!is_type_pointer(type) && !is_type_integer(type)) {
9319 errorf(&expression->base.source_position,
9320 "cannot convert to a pointer type");
9321 } else if (type != type_void_ptr) {
9322 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9324 expression = create_implicit_cast(expression, type_void_ptr);
9327 statement->computed_goto.expression = expression;
9329 statement = allocate_statement_zero(STATEMENT_GOTO);
9332 label_t *const label = get_label("while parsing goto");
9334 label->n_users += 1;
9336 statement->gotos.label = label;
9338 /* remember the goto's in a list for later checking */
9339 *goto_anchor = &statement->gotos;
9340 goto_anchor = &statement->gotos.next;
9342 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9351 * Parse a continue statement.
9353 static statement_t *parse_continue(void)
9355 if (current_loop == NULL) {
9356 errorf(HERE, "continue statement not within loop");
9359 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9367 * Parse a break statement.
9369 static statement_t *parse_break(void)
9371 if (current_switch == NULL && current_loop == NULL) {
9372 errorf(HERE, "break statement not within loop or switch");
9375 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9383 * Parse a __leave statement.
9385 static statement_t *parse_leave_statement(void)
9387 if (current_try == NULL) {
9388 errorf(HERE, "__leave statement not within __try");
9391 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9399 * Check if a given entity represents a local variable.
9401 static bool is_local_variable(const entity_t *entity)
9403 if (entity->kind != ENTITY_VARIABLE)
9406 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9407 case STORAGE_CLASS_AUTO:
9408 case STORAGE_CLASS_REGISTER: {
9409 const type_t *type = skip_typeref(entity->declaration.type);
9410 if (is_type_function(type)) {
9422 * Check if a given expression represents a local variable.
9424 static bool expression_is_local_variable(const expression_t *expression)
9426 if (expression->base.kind != EXPR_REFERENCE) {
9429 const entity_t *entity = expression->reference.entity;
9430 return is_local_variable(entity);
9433 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9435 if (c_mode & _CXX || strict_mode) {
9438 warningf(WARN_OTHER, pos, msg);
9443 * Parse a return statement.
9445 static statement_t *parse_return(void)
9447 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9450 expression_t *return_value = NULL;
9451 if (token.kind != ';') {
9452 return_value = parse_expression();
9453 mark_vars_read(return_value, NULL);
9456 const type_t *const func_type = skip_typeref(current_function->base.type);
9457 assert(is_type_function(func_type));
9458 type_t *const return_type = skip_typeref(func_type->function.return_type);
9460 source_position_t const *const pos = &statement->base.source_position;
9461 if (return_value != NULL) {
9462 type_t *return_value_type = skip_typeref(return_value->base.type);
9464 if (is_type_void(return_type)) {
9465 if (!is_type_void(return_value_type)) {
9466 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9467 /* Only warn in C mode, because GCC does the same */
9468 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9469 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9470 /* Only warn in C mode, because GCC does the same */
9471 err_or_warn(pos, "'return' with expression in function returning 'void'");
9474 assign_error_t error = semantic_assign(return_type, return_value);
9475 report_assign_error(error, return_type, return_value, "'return'",
9478 return_value = create_implicit_cast(return_value, return_type);
9479 /* check for returning address of a local var */
9480 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9481 const expression_t *expression = return_value->unary.value;
9482 if (expression_is_local_variable(expression)) {
9483 warningf(WARN_OTHER, pos, "function returns address of local variable");
9486 } else if (!is_type_void(return_type)) {
9487 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9488 err_or_warn(pos, "'return' without value, in function returning non-void");
9490 statement->returns.value = return_value;
9497 * Parse a declaration statement.
9499 static statement_t *parse_declaration_statement(void)
9501 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9503 entity_t *before = current_scope->last_entity;
9505 parse_external_declaration();
9507 parse_declaration(record_entity, DECL_FLAGS_NONE);
9510 declaration_statement_t *const decl = &statement->declaration;
9511 entity_t *const begin =
9512 before != NULL ? before->base.next : current_scope->entities;
9513 decl->declarations_begin = begin;
9514 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9520 * Parse an expression statement, ie. expr ';'.
9522 static statement_t *parse_expression_statement(void)
9524 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9526 expression_t *const expr = parse_expression();
9527 statement->expression.expression = expr;
9528 mark_vars_read(expr, ENT_ANY);
9535 * Parse a microsoft __try { } __finally { } or
9536 * __try{ } __except() { }
9538 static statement_t *parse_ms_try_statment(void)
9540 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9543 PUSH_PARENT(statement);
9545 ms_try_statement_t *rem = current_try;
9546 current_try = &statement->ms_try;
9547 statement->ms_try.try_statement = parse_compound_statement(false);
9552 if (next_if(T___except)) {
9553 expression_t *const expr = parse_condition();
9554 type_t * type = skip_typeref(expr->base.type);
9555 if (is_type_integer(type)) {
9556 type = promote_integer(type);
9557 } else if (is_type_valid(type)) {
9558 errorf(&expr->base.source_position,
9559 "__expect expression is not an integer, but '%T'", type);
9560 type = type_error_type;
9562 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9563 } else if (!next_if(T__finally)) {
9564 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9566 statement->ms_try.final_statement = parse_compound_statement(false);
9570 static statement_t *parse_empty_statement(void)
9572 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9573 statement_t *const statement = create_empty_statement();
9578 static statement_t *parse_local_label_declaration(void)
9580 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9584 entity_t *begin = NULL;
9585 entity_t *end = NULL;
9586 entity_t **anchor = &begin;
9587 add_anchor_token(';');
9588 add_anchor_token(',');
9590 source_position_t pos;
9591 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9593 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9594 if (entity != NULL && entity->base.parent_scope == current_scope) {
9595 source_position_t const *const ppos = &entity->base.source_position;
9596 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9598 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9599 entity->base.parent_scope = current_scope;
9602 anchor = &entity->base.next;
9605 environment_push(entity);
9608 } while (next_if(','));
9609 rem_anchor_token(',');
9610 rem_anchor_token(';');
9612 statement->declaration.declarations_begin = begin;
9613 statement->declaration.declarations_end = end;
9617 static void parse_namespace_definition(void)
9621 entity_t *entity = NULL;
9622 symbol_t *symbol = NULL;
9624 if (token.kind == T_IDENTIFIER) {
9625 symbol = token.base.symbol;
9626 entity = get_entity(symbol, NAMESPACE_NORMAL);
9627 if (entity && entity->kind != ENTITY_NAMESPACE) {
9629 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9630 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9636 if (entity == NULL) {
9637 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9638 entity->base.parent_scope = current_scope;
9641 if (token.kind == '=') {
9642 /* TODO: parse namespace alias */
9643 panic("namespace alias definition not supported yet");
9646 environment_push(entity);
9647 append_entity(current_scope, entity);
9649 PUSH_SCOPE(&entity->namespacee.members);
9650 PUSH_CURRENT_ENTITY(entity);
9652 add_anchor_token('}');
9655 rem_anchor_token('}');
9658 POP_CURRENT_ENTITY();
9663 * Parse a statement.
9664 * There's also parse_statement() which additionally checks for
9665 * "statement has no effect" warnings
9667 static statement_t *intern_parse_statement(void)
9669 /* declaration or statement */
9670 statement_t *statement;
9671 switch (token.kind) {
9672 case T_IDENTIFIER: {
9673 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9674 if (la1_type == ':') {
9675 statement = parse_label_statement();
9676 } else if (is_typedef_symbol(token.base.symbol)) {
9677 statement = parse_declaration_statement();
9679 /* it's an identifier, the grammar says this must be an
9680 * expression statement. However it is common that users mistype
9681 * declaration types, so we guess a bit here to improve robustness
9682 * for incorrect programs */
9686 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9688 statement = parse_expression_statement();
9692 statement = parse_declaration_statement();
9700 case T___extension__: {
9701 /* This can be a prefix to a declaration or an expression statement.
9702 * We simply eat it now and parse the rest with tail recursion. */
9704 statement = intern_parse_statement();
9710 statement = parse_declaration_statement();
9714 statement = parse_local_label_declaration();
9717 case ';': statement = parse_empty_statement(); break;
9718 case '{': statement = parse_compound_statement(false); break;
9719 case T___leave: statement = parse_leave_statement(); break;
9720 case T___try: statement = parse_ms_try_statment(); break;
9721 case T_asm: statement = parse_asm_statement(); break;
9722 case T_break: statement = parse_break(); break;
9723 case T_case: statement = parse_case_statement(); break;
9724 case T_continue: statement = parse_continue(); break;
9725 case T_default: statement = parse_default_statement(); break;
9726 case T_do: statement = parse_do(); break;
9727 case T_for: statement = parse_for(); break;
9728 case T_goto: statement = parse_goto(); break;
9729 case T_if: statement = parse_if(); break;
9730 case T_return: statement = parse_return(); break;
9731 case T_switch: statement = parse_switch(); break;
9732 case T_while: statement = parse_while(); break;
9735 statement = parse_expression_statement();
9739 errorf(HERE, "unexpected token %K while parsing statement", &token);
9740 statement = create_error_statement();
9749 * parse a statement and emits "statement has no effect" warning if needed
9750 * (This is really a wrapper around intern_parse_statement with check for 1
9751 * single warning. It is needed, because for statement expressions we have
9752 * to avoid the warning on the last statement)
9754 static statement_t *parse_statement(void)
9756 statement_t *statement = intern_parse_statement();
9758 if (statement->kind == STATEMENT_EXPRESSION) {
9759 expression_t *expression = statement->expression.expression;
9760 if (!expression_has_effect(expression)) {
9761 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9769 * Parse a compound statement.
9771 static statement_t *parse_compound_statement(bool inside_expression_statement)
9773 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9775 PUSH_PARENT(statement);
9776 PUSH_SCOPE(&statement->compound.scope);
9779 add_anchor_token('}');
9780 /* tokens, which can start a statement */
9781 /* TODO MS, __builtin_FOO */
9782 add_anchor_token('!');
9783 add_anchor_token('&');
9784 add_anchor_token('(');
9785 add_anchor_token('*');
9786 add_anchor_token('+');
9787 add_anchor_token('-');
9788 add_anchor_token(';');
9789 add_anchor_token('{');
9790 add_anchor_token('~');
9791 add_anchor_token(T_CHARACTER_CONSTANT);
9792 add_anchor_token(T_COLONCOLON);
9793 add_anchor_token(T_IDENTIFIER);
9794 add_anchor_token(T_MINUSMINUS);
9795 add_anchor_token(T_NUMBER);
9796 add_anchor_token(T_PLUSPLUS);
9797 add_anchor_token(T_STRING_LITERAL);
9798 add_anchor_token(T__Alignof);
9799 add_anchor_token(T__Bool);
9800 add_anchor_token(T__Complex);
9801 add_anchor_token(T__Imaginary);
9802 add_anchor_token(T__Thread_local);
9803 add_anchor_token(T___PRETTY_FUNCTION__);
9804 add_anchor_token(T___attribute__);
9805 add_anchor_token(T___builtin_va_start);
9806 add_anchor_token(T___extension__);
9807 add_anchor_token(T___func__);
9808 add_anchor_token(T___imag__);
9809 add_anchor_token(T___label__);
9810 add_anchor_token(T___real__);
9811 add_anchor_token(T_asm);
9812 add_anchor_token(T_auto);
9813 add_anchor_token(T_bool);
9814 add_anchor_token(T_break);
9815 add_anchor_token(T_case);
9816 add_anchor_token(T_char);
9817 add_anchor_token(T_class);
9818 add_anchor_token(T_const);
9819 add_anchor_token(T_const_cast);
9820 add_anchor_token(T_continue);
9821 add_anchor_token(T_default);
9822 add_anchor_token(T_delete);
9823 add_anchor_token(T_double);
9824 add_anchor_token(T_do);
9825 add_anchor_token(T_dynamic_cast);
9826 add_anchor_token(T_enum);
9827 add_anchor_token(T_extern);
9828 add_anchor_token(T_false);
9829 add_anchor_token(T_float);
9830 add_anchor_token(T_for);
9831 add_anchor_token(T_goto);
9832 add_anchor_token(T_if);
9833 add_anchor_token(T_inline);
9834 add_anchor_token(T_int);
9835 add_anchor_token(T_long);
9836 add_anchor_token(T_new);
9837 add_anchor_token(T_operator);
9838 add_anchor_token(T_register);
9839 add_anchor_token(T_reinterpret_cast);
9840 add_anchor_token(T_restrict);
9841 add_anchor_token(T_return);
9842 add_anchor_token(T_short);
9843 add_anchor_token(T_signed);
9844 add_anchor_token(T_sizeof);
9845 add_anchor_token(T_static);
9846 add_anchor_token(T_static_cast);
9847 add_anchor_token(T_struct);
9848 add_anchor_token(T_switch);
9849 add_anchor_token(T_template);
9850 add_anchor_token(T_this);
9851 add_anchor_token(T_throw);
9852 add_anchor_token(T_true);
9853 add_anchor_token(T_try);
9854 add_anchor_token(T_typedef);
9855 add_anchor_token(T_typeid);
9856 add_anchor_token(T_typename);
9857 add_anchor_token(T_typeof);
9858 add_anchor_token(T_union);
9859 add_anchor_token(T_unsigned);
9860 add_anchor_token(T_using);
9861 add_anchor_token(T_void);
9862 add_anchor_token(T_volatile);
9863 add_anchor_token(T_wchar_t);
9864 add_anchor_token(T_while);
9866 statement_t **anchor = &statement->compound.statements;
9867 bool only_decls_so_far = true;
9868 while (token.kind != '}' && token.kind != T_EOF) {
9869 statement_t *sub_statement = intern_parse_statement();
9870 if (sub_statement->kind == STATEMENT_ERROR) {
9874 if (sub_statement->kind != STATEMENT_DECLARATION) {
9875 only_decls_so_far = false;
9876 } else if (!only_decls_so_far) {
9877 source_position_t const *const pos = &sub_statement->base.source_position;
9878 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9881 *anchor = sub_statement;
9882 anchor = &sub_statement->base.next;
9886 /* look over all statements again to produce no effect warnings */
9887 if (is_warn_on(WARN_UNUSED_VALUE)) {
9888 statement_t *sub_statement = statement->compound.statements;
9889 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9890 if (sub_statement->kind != STATEMENT_EXPRESSION)
9892 /* don't emit a warning for the last expression in an expression
9893 * statement as it has always an effect */
9894 if (inside_expression_statement && sub_statement->base.next == NULL)
9897 expression_t *expression = sub_statement->expression.expression;
9898 if (!expression_has_effect(expression)) {
9899 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9904 rem_anchor_token(T_while);
9905 rem_anchor_token(T_wchar_t);
9906 rem_anchor_token(T_volatile);
9907 rem_anchor_token(T_void);
9908 rem_anchor_token(T_using);
9909 rem_anchor_token(T_unsigned);
9910 rem_anchor_token(T_union);
9911 rem_anchor_token(T_typeof);
9912 rem_anchor_token(T_typename);
9913 rem_anchor_token(T_typeid);
9914 rem_anchor_token(T_typedef);
9915 rem_anchor_token(T_try);
9916 rem_anchor_token(T_true);
9917 rem_anchor_token(T_throw);
9918 rem_anchor_token(T_this);
9919 rem_anchor_token(T_template);
9920 rem_anchor_token(T_switch);
9921 rem_anchor_token(T_struct);
9922 rem_anchor_token(T_static_cast);
9923 rem_anchor_token(T_static);
9924 rem_anchor_token(T_sizeof);
9925 rem_anchor_token(T_signed);
9926 rem_anchor_token(T_short);
9927 rem_anchor_token(T_return);
9928 rem_anchor_token(T_restrict);
9929 rem_anchor_token(T_reinterpret_cast);
9930 rem_anchor_token(T_register);
9931 rem_anchor_token(T_operator);
9932 rem_anchor_token(T_new);
9933 rem_anchor_token(T_long);
9934 rem_anchor_token(T_int);
9935 rem_anchor_token(T_inline);
9936 rem_anchor_token(T_if);
9937 rem_anchor_token(T_goto);
9938 rem_anchor_token(T_for);
9939 rem_anchor_token(T_float);
9940 rem_anchor_token(T_false);
9941 rem_anchor_token(T_extern);
9942 rem_anchor_token(T_enum);
9943 rem_anchor_token(T_dynamic_cast);
9944 rem_anchor_token(T_do);
9945 rem_anchor_token(T_double);
9946 rem_anchor_token(T_delete);
9947 rem_anchor_token(T_default);
9948 rem_anchor_token(T_continue);
9949 rem_anchor_token(T_const_cast);
9950 rem_anchor_token(T_const);
9951 rem_anchor_token(T_class);
9952 rem_anchor_token(T_char);
9953 rem_anchor_token(T_case);
9954 rem_anchor_token(T_break);
9955 rem_anchor_token(T_bool);
9956 rem_anchor_token(T_auto);
9957 rem_anchor_token(T_asm);
9958 rem_anchor_token(T___real__);
9959 rem_anchor_token(T___label__);
9960 rem_anchor_token(T___imag__);
9961 rem_anchor_token(T___func__);
9962 rem_anchor_token(T___extension__);
9963 rem_anchor_token(T___builtin_va_start);
9964 rem_anchor_token(T___attribute__);
9965 rem_anchor_token(T___PRETTY_FUNCTION__);
9966 rem_anchor_token(T__Thread_local);
9967 rem_anchor_token(T__Imaginary);
9968 rem_anchor_token(T__Complex);
9969 rem_anchor_token(T__Bool);
9970 rem_anchor_token(T__Alignof);
9971 rem_anchor_token(T_STRING_LITERAL);
9972 rem_anchor_token(T_PLUSPLUS);
9973 rem_anchor_token(T_NUMBER);
9974 rem_anchor_token(T_MINUSMINUS);
9975 rem_anchor_token(T_IDENTIFIER);
9976 rem_anchor_token(T_COLONCOLON);
9977 rem_anchor_token(T_CHARACTER_CONSTANT);
9978 rem_anchor_token('~');
9979 rem_anchor_token('{');
9980 rem_anchor_token(';');
9981 rem_anchor_token('-');
9982 rem_anchor_token('+');
9983 rem_anchor_token('*');
9984 rem_anchor_token('(');
9985 rem_anchor_token('&');
9986 rem_anchor_token('!');
9987 rem_anchor_token('}');
9995 * Check for unused global static functions and variables
9997 static void check_unused_globals(void)
9999 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10002 for (const entity_t *entity = file_scope->entities; entity != NULL;
10003 entity = entity->base.next) {
10004 if (!is_declaration(entity))
10007 const declaration_t *declaration = &entity->declaration;
10008 if (declaration->used ||
10009 declaration->modifiers & DM_UNUSED ||
10010 declaration->modifiers & DM_USED ||
10011 declaration->storage_class != STORAGE_CLASS_STATIC)
10016 if (entity->kind == ENTITY_FUNCTION) {
10017 /* inhibit warning for static inline functions */
10018 if (entity->function.is_inline)
10021 why = WARN_UNUSED_FUNCTION;
10022 s = entity->function.body != NULL ? "defined" : "declared";
10024 why = WARN_UNUSED_VARIABLE;
10028 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10032 static void parse_global_asm(void)
10034 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10037 add_anchor_token(';');
10038 add_anchor_token(')');
10039 add_anchor_token(T_STRING_LITERAL);
10042 rem_anchor_token(T_STRING_LITERAL);
10043 statement->asms.asm_text = parse_string_literals("global asm");
10044 statement->base.next = unit->global_asm;
10045 unit->global_asm = statement;
10047 rem_anchor_token(')');
10049 rem_anchor_token(';');
10053 static void parse_linkage_specification(void)
10057 source_position_t const pos = *HERE;
10058 char const *const linkage = parse_string_literals(NULL).begin;
10060 linkage_kind_t old_linkage = current_linkage;
10061 linkage_kind_t new_linkage;
10062 if (streq(linkage, "C")) {
10063 new_linkage = LINKAGE_C;
10064 } else if (streq(linkage, "C++")) {
10065 new_linkage = LINKAGE_CXX;
10067 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10068 new_linkage = LINKAGE_C;
10070 current_linkage = new_linkage;
10072 if (next_if('{')) {
10079 assert(current_linkage == new_linkage);
10080 current_linkage = old_linkage;
10083 static void parse_external(void)
10085 switch (token.kind) {
10087 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10088 parse_linkage_specification();
10090 DECLARATION_START_NO_EXTERN
10092 case T___extension__:
10093 /* tokens below are for implicit int */
10094 case '&': /* & x; -> int& x; (and error later, because C++ has no
10096 case '*': /* * x; -> int* x; */
10097 case '(': /* (x); -> int (x); */
10099 parse_external_declaration();
10105 parse_global_asm();
10109 parse_namespace_definition();
10113 if (!strict_mode) {
10114 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10121 errorf(HERE, "stray %K outside of function", &token);
10122 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10123 eat_until_matching_token(token.kind);
10129 static void parse_externals(void)
10131 add_anchor_token('}');
10132 add_anchor_token(T_EOF);
10135 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10136 unsigned short token_anchor_copy[T_LAST_TOKEN];
10137 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10140 while (token.kind != T_EOF && token.kind != '}') {
10142 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10143 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10145 /* the anchor set and its copy differs */
10146 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10149 if (in_gcc_extension) {
10150 /* an gcc extension scope was not closed */
10151 internal_errorf(HERE, "Leaked __extension__");
10158 rem_anchor_token(T_EOF);
10159 rem_anchor_token('}');
10163 * Parse a translation unit.
10165 static void parse_translation_unit(void)
10167 add_anchor_token(T_EOF);
10172 if (token.kind == T_EOF)
10175 errorf(HERE, "stray %K outside of function", &token);
10176 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10177 eat_until_matching_token(token.kind);
10182 void set_default_visibility(elf_visibility_tag_t visibility)
10184 default_visibility = visibility;
10190 * @return the translation unit or NULL if errors occurred.
10192 void start_parsing(void)
10194 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10195 label_stack = NEW_ARR_F(stack_entry_t, 0);
10197 print_to_file(stderr);
10199 assert(unit == NULL);
10200 unit = allocate_ast_zero(sizeof(unit[0]));
10202 assert(file_scope == NULL);
10203 file_scope = &unit->scope;
10205 assert(current_scope == NULL);
10206 scope_push(&unit->scope);
10208 create_gnu_builtins();
10210 create_microsoft_intrinsics();
10213 translation_unit_t *finish_parsing(void)
10215 assert(current_scope == &unit->scope);
10218 assert(file_scope == &unit->scope);
10219 check_unused_globals();
10222 DEL_ARR_F(environment_stack);
10223 DEL_ARR_F(label_stack);
10225 translation_unit_t *result = unit;
10230 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10231 * are given length one. */
10232 static void complete_incomplete_arrays(void)
10234 size_t n = ARR_LEN(incomplete_arrays);
10235 for (size_t i = 0; i != n; ++i) {
10236 declaration_t *const decl = incomplete_arrays[i];
10237 type_t *const type = skip_typeref(decl->type);
10239 if (!is_type_incomplete(type))
10242 source_position_t const *const pos = &decl->base.source_position;
10243 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10245 type_t *const new_type = duplicate_type(type);
10246 new_type->array.size_constant = true;
10247 new_type->array.has_implicit_size = true;
10248 new_type->array.size = 1;
10250 type_t *const result = identify_new_type(new_type);
10252 decl->type = result;
10256 static void prepare_main_collect2(entity_t *const entity)
10258 PUSH_SCOPE(&entity->function.body->compound.scope);
10260 // create call to __main
10261 symbol_t *symbol = symbol_table_insert("__main");
10262 entity_t *subsubmain_ent
10263 = create_implicit_function(symbol, &builtin_source_position);
10265 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10266 type_t *ftype = subsubmain_ent->declaration.type;
10267 ref->base.source_position = builtin_source_position;
10268 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10269 ref->reference.entity = subsubmain_ent;
10271 expression_t *call = allocate_expression_zero(EXPR_CALL);
10272 call->base.source_position = builtin_source_position;
10273 call->base.type = type_void;
10274 call->call.function = ref;
10276 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10277 expr_statement->base.source_position = builtin_source_position;
10278 expr_statement->expression.expression = call;
10280 statement_t *const body = entity->function.body;
10281 assert(body->kind == STATEMENT_COMPOUND);
10282 compound_statement_t *compounds = &body->compound;
10284 expr_statement->base.next = compounds->statements;
10285 compounds->statements = expr_statement;
10292 lookahead_bufpos = 0;
10293 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10296 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10297 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10298 parse_translation_unit();
10299 complete_incomplete_arrays();
10300 DEL_ARR_F(incomplete_arrays);
10301 incomplete_arrays = NULL;
10305 * Initialize the parser.
10307 void init_parser(void)
10309 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10311 init_expression_parsers();
10312 obstack_init(&temp_obst);
10316 * Terminate the parser.
10318 void exit_parser(void)
10320 obstack_free(&temp_obst, NULL);