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
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_CURRENT_ENTITY(entity) \
113 entity_t *const new_current_entity = (entity); \
114 entity_t *const old_current_entity = current_entity; \
115 ((void)(current_entity = new_current_entity))
116 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
118 #define PUSH_PARENT(stmt) \
119 statement_t *const new_parent = (stmt); \
120 statement_t *const old_parent = current_parent; \
121 ((void)(current_parent = new_parent))
122 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
124 #define PUSH_SCOPE(scope) \
125 size_t const top = environment_top(); \
126 scope_t *const new_scope = (scope); \
127 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
128 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
129 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
131 #define PUSH_EXTENSION() \
133 bool const old_gcc_extension = in_gcc_extension; \
134 while (next_if(T___extension__)) { \
135 in_gcc_extension = true; \
138 #define POP_EXTENSION() \
139 ((void)(in_gcc_extension = old_gcc_extension))
141 /** special symbol used for anonymous entities. */
142 static symbol_t *sym_anonymous = NULL;
144 /** The token anchor set */
145 static unsigned short token_anchor_set[T_LAST_TOKEN];
147 /** The current source position. */
148 #define HERE (&token.base.source_position)
150 /** true if we are in GCC mode. */
151 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
153 static statement_t *parse_compound_statement(bool inside_expression_statement);
154 static statement_t *parse_statement(void);
156 static expression_t *parse_subexpression(precedence_t);
157 static expression_t *parse_expression(void);
158 static type_t *parse_typename(void);
159 static void parse_externals(void);
160 static void parse_external(void);
162 static void parse_compound_type_entries(compound_t *compound_declaration);
164 static void check_call_argument(type_t *expected_type,
165 call_argument_t *argument, unsigned pos);
167 typedef enum declarator_flags_t {
169 DECL_MAY_BE_ABSTRACT = 1U << 0,
170 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
171 DECL_IS_PARAMETER = 1U << 2
172 } declarator_flags_t;
174 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
175 declarator_flags_t flags);
177 static void semantic_comparison(binary_expression_t *expression);
179 #define STORAGE_CLASSES \
180 STORAGE_CLASSES_NO_EXTERN \
183 #define STORAGE_CLASSES_NO_EXTERN \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #define COMPLEX_SPECIFIERS \
200 #define IMAGINARY_SPECIFIERS \
203 #define TYPE_SPECIFIERS \
205 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define DECLARATION_START_NO_EXTERN \
236 STORAGE_CLASSES_NO_EXTERN \
240 #define EXPRESSION_START \
249 case T_CHARACTER_CONSTANT: \
250 case T_FLOATINGPOINT: \
251 case T_FLOATINGPOINT_HEXADECIMAL: \
253 case T_INTEGER_HEXADECIMAL: \
254 case T_INTEGER_OCTAL: \
257 case T_STRING_LITERAL: \
258 case T_WIDE_CHARACTER_CONSTANT: \
259 case T_WIDE_STRING_LITERAL: \
260 case T___FUNCDNAME__: \
261 case T___FUNCSIG__: \
262 case T___FUNCTION__: \
263 case T___PRETTY_FUNCTION__: \
264 case T___alignof__: \
265 case T___builtin_classify_type: \
266 case T___builtin_constant_p: \
267 case T___builtin_isgreater: \
268 case T___builtin_isgreaterequal: \
269 case T___builtin_isless: \
270 case T___builtin_islessequal: \
271 case T___builtin_islessgreater: \
272 case T___builtin_isunordered: \
273 case T___builtin_offsetof: \
274 case T___builtin_va_arg: \
275 case T___builtin_va_copy: \
276 case T___builtin_va_start: \
287 * Returns the size of a statement node.
289 * @param kind the statement kind
291 static size_t get_statement_struct_size(statement_kind_t kind)
293 static const size_t sizes[] = {
294 [STATEMENT_ERROR] = sizeof(statement_base_t),
295 [STATEMENT_EMPTY] = sizeof(statement_base_t),
296 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
297 [STATEMENT_RETURN] = sizeof(return_statement_t),
298 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
299 [STATEMENT_IF] = sizeof(if_statement_t),
300 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
301 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
302 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
303 [STATEMENT_BREAK] = sizeof(statement_base_t),
304 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
305 [STATEMENT_GOTO] = sizeof(goto_statement_t),
306 [STATEMENT_LABEL] = sizeof(label_statement_t),
307 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
308 [STATEMENT_WHILE] = sizeof(while_statement_t),
309 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
310 [STATEMENT_FOR] = sizeof(for_statement_t),
311 [STATEMENT_ASM] = sizeof(asm_statement_t),
312 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
313 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
315 assert((size_t)kind < lengthof(sizes));
316 assert(sizes[kind] != 0);
321 * Returns the size of an expression node.
323 * @param kind the expression kind
325 static size_t get_expression_struct_size(expression_kind_t kind)
327 static const size_t sizes[] = {
328 [EXPR_ERROR] = sizeof(expression_base_t),
329 [EXPR_REFERENCE] = sizeof(reference_expression_t),
330 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
331 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
332 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
333 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
334 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
335 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
336 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
337 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
338 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
339 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
340 [EXPR_CALL] = sizeof(call_expression_t),
341 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
342 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
343 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
344 [EXPR_SELECT] = sizeof(select_expression_t),
345 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
346 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
347 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
348 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
349 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
350 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
351 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
352 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
353 [EXPR_VA_START] = sizeof(va_start_expression_t),
354 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
355 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
356 [EXPR_STATEMENT] = sizeof(statement_expression_t),
357 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
359 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
360 return sizes[EXPR_UNARY_FIRST];
362 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
363 return sizes[EXPR_BINARY_FIRST];
365 assert((size_t)kind < lengthof(sizes));
366 assert(sizes[kind] != 0);
371 * Allocate a statement node of given kind and initialize all
372 * fields with zero. Sets its source position to the position
373 * of the current token.
375 static statement_t *allocate_statement_zero(statement_kind_t kind)
377 size_t size = get_statement_struct_size(kind);
378 statement_t *res = allocate_ast_zero(size);
380 res->base.kind = kind;
381 res->base.parent = current_parent;
382 res->base.source_position = token.base.source_position;
387 * Allocate an expression node of given kind and initialize all
390 * @param kind the kind of the expression to allocate
392 static expression_t *allocate_expression_zero(expression_kind_t kind)
394 size_t size = get_expression_struct_size(kind);
395 expression_t *res = allocate_ast_zero(size);
397 res->base.kind = kind;
398 res->base.type = type_error_type;
399 res->base.source_position = token.base.source_position;
404 * Creates a new invalid expression at the source position
405 * of the current token.
407 static expression_t *create_error_expression(void)
409 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
410 expression->base.type = type_error_type;
415 * Creates a new invalid statement.
417 static statement_t *create_error_statement(void)
419 return allocate_statement_zero(STATEMENT_ERROR);
423 * Allocate a new empty statement.
425 static statement_t *create_empty_statement(void)
427 return allocate_statement_zero(STATEMENT_EMPTY);
431 * Returns the size of an initializer node.
433 * @param kind the initializer kind
435 static size_t get_initializer_size(initializer_kind_t kind)
437 static const size_t sizes[] = {
438 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
439 [INITIALIZER_STRING] = sizeof(initializer_string_t),
440 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
441 [INITIALIZER_LIST] = sizeof(initializer_list_t),
442 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
444 assert((size_t)kind < lengthof(sizes));
445 assert(sizes[kind] != 0);
450 * Allocate an initializer node of given kind and initialize all
453 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
455 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
462 * Returns the index of the top element of the environment stack.
464 static size_t environment_top(void)
466 return ARR_LEN(environment_stack);
470 * Returns the index of the top element of the global label stack.
472 static size_t label_top(void)
474 return ARR_LEN(label_stack);
478 * Return the next token.
480 static inline void next_token(void)
482 token = lookahead_buffer[lookahead_bufpos];
483 lookahead_buffer[lookahead_bufpos] = lexer_token;
486 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
489 print_token(stderr, &token);
490 fprintf(stderr, "\n");
494 static inline bool next_if(token_kind_t const type)
496 if (token.kind == type) {
505 * Return the next token with a given lookahead.
507 static inline const token_t *look_ahead(size_t num)
509 assert(0 < num && num <= MAX_LOOKAHEAD);
510 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
511 return &lookahead_buffer[pos];
515 * Adds a token type to the token type anchor set (a multi-set).
517 static void add_anchor_token(token_kind_t const token_kind)
519 assert(token_kind < T_LAST_TOKEN);
520 ++token_anchor_set[token_kind];
524 * Remove a token type from the token type anchor set (a multi-set).
526 static void rem_anchor_token(token_kind_t const token_kind)
528 assert(token_kind < T_LAST_TOKEN);
529 assert(token_anchor_set[token_kind] != 0);
530 --token_anchor_set[token_kind];
534 * Eat tokens until a matching token type is found.
536 static void eat_until_matching_token(token_kind_t const type)
538 token_kind_t end_token;
540 case '(': end_token = ')'; break;
541 case '{': end_token = '}'; break;
542 case '[': end_token = ']'; break;
543 default: end_token = type; break;
546 unsigned parenthesis_count = 0;
547 unsigned brace_count = 0;
548 unsigned bracket_count = 0;
549 while (token.kind != end_token ||
550 parenthesis_count != 0 ||
552 bracket_count != 0) {
553 switch (token.kind) {
555 case '(': ++parenthesis_count; break;
556 case '{': ++brace_count; break;
557 case '[': ++bracket_count; break;
560 if (parenthesis_count > 0)
570 if (bracket_count > 0)
573 if (token.kind == end_token &&
574 parenthesis_count == 0 &&
588 * Eat input tokens until an anchor is found.
590 static void eat_until_anchor(void)
592 while (token_anchor_set[token.kind] == 0) {
593 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
594 eat_until_matching_token(token.kind);
600 * Eat a whole block from input tokens.
602 static void eat_block(void)
604 eat_until_matching_token('{');
608 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
611 * Report a parse error because an expected token was not found.
614 #if defined __GNUC__ && __GNUC__ >= 4
615 __attribute__((sentinel))
617 void parse_error_expected(const char *message, ...)
619 if (message != NULL) {
620 errorf(HERE, "%s", message);
623 va_start(ap, message);
624 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
629 * Report an incompatible type.
631 static void type_error_incompatible(const char *msg,
632 const source_position_t *source_position, type_t *type1, type_t *type2)
634 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
639 * Expect the current token is the expected token.
640 * If not, generate an error and skip until the next anchor.
642 static void expect(token_kind_t const expected)
644 if (UNLIKELY(token.kind != expected)) {
645 parse_error_expected(NULL, expected, NULL);
646 add_anchor_token(expected);
648 rem_anchor_token(expected);
649 if (token.kind != expected)
655 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
657 if (token.kind != T_IDENTIFIER) {
658 parse_error_expected(context, T_IDENTIFIER, NULL);
659 add_anchor_token(T_IDENTIFIER);
661 rem_anchor_token(T_IDENTIFIER);
662 if (token.kind != T_IDENTIFIER)
665 symbol_t *const sym = token.identifier.symbol;
673 * Push a given scope on the scope stack and make it the
676 static scope_t *scope_push(scope_t *new_scope)
678 if (current_scope != NULL) {
679 new_scope->depth = current_scope->depth + 1;
682 scope_t *old_scope = current_scope;
683 current_scope = new_scope;
688 * Pop the current scope from the scope stack.
690 static void scope_pop(scope_t *old_scope)
692 current_scope = old_scope;
696 * Search an entity by its symbol in a given namespace.
698 static entity_t *get_entity(const symbol_t *const symbol,
699 namespace_tag_t namespc)
701 entity_t *entity = symbol->entity;
702 for (; entity != NULL; entity = entity->base.symbol_next) {
703 if ((namespace_tag_t)entity->base.namespc == namespc)
710 /* §6.2.3:1 24) There is only one name space for tags even though three are
712 static entity_t *get_tag(symbol_t const *const symbol,
713 entity_kind_tag_t const kind)
715 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
716 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
718 "'%Y' defined as wrong kind of tag (previous definition %P)",
719 symbol, &entity->base.source_position);
726 * pushs an entity on the environment stack and links the corresponding symbol
729 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
731 symbol_t *symbol = entity->base.symbol;
732 entity_namespace_t namespc = entity->base.namespc;
733 assert(namespc != 0);
735 /* replace/add entity into entity list of the symbol */
738 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
743 /* replace an entry? */
744 if (iter->base.namespc == namespc) {
745 entity->base.symbol_next = iter->base.symbol_next;
751 /* remember old declaration */
753 entry.symbol = symbol;
754 entry.old_entity = iter;
755 entry.namespc = namespc;
756 ARR_APP1(stack_entry_t, *stack_ptr, entry);
760 * Push an entity on the environment stack.
762 static void environment_push(entity_t *entity)
764 assert(entity->base.source_position.input_name != NULL);
765 assert(entity->base.parent_scope != NULL);
766 stack_push(&environment_stack, entity);
770 * Push a declaration on the global label stack.
772 * @param declaration the declaration
774 static void label_push(entity_t *label)
776 /* we abuse the parameters scope as parent for the labels */
777 label->base.parent_scope = ¤t_function->parameters;
778 stack_push(&label_stack, label);
782 * pops symbols from the environment stack until @p new_top is the top element
784 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
786 stack_entry_t *stack = *stack_ptr;
787 size_t top = ARR_LEN(stack);
790 assert(new_top <= top);
794 for (i = top; i > new_top; --i) {
795 stack_entry_t *entry = &stack[i - 1];
797 entity_t *old_entity = entry->old_entity;
798 symbol_t *symbol = entry->symbol;
799 entity_namespace_t namespc = entry->namespc;
801 /* replace with old_entity/remove */
804 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
806 assert(iter != NULL);
807 /* replace an entry? */
808 if (iter->base.namespc == namespc)
812 /* restore definition from outer scopes (if there was one) */
813 if (old_entity != NULL) {
814 old_entity->base.symbol_next = iter->base.symbol_next;
815 *anchor = old_entity;
817 /* remove entry from list */
818 *anchor = iter->base.symbol_next;
822 ARR_SHRINKLEN(*stack_ptr, new_top);
826 * Pop all entries from the environment stack until the new_top
829 * @param new_top the new stack top
831 static void environment_pop_to(size_t new_top)
833 stack_pop_to(&environment_stack, new_top);
837 * Pop all entries from the global label stack until the new_top
840 * @param new_top the new stack top
842 static void label_pop_to(size_t new_top)
844 stack_pop_to(&label_stack, new_top);
847 static atomic_type_kind_t get_akind(const type_t *type)
849 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
850 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
851 return type->atomic.akind;
855 * §6.3.1.1:2 Do integer promotion for a given type.
857 * @param type the type to promote
858 * @return the promoted type
860 static type_t *promote_integer(type_t *type)
862 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
869 * Check if a given expression represents a null pointer constant.
871 * @param expression the expression to check
873 static bool is_null_pointer_constant(const expression_t *expression)
875 /* skip void* cast */
876 if (expression->kind == EXPR_UNARY_CAST) {
877 type_t *const type = skip_typeref(expression->base.type);
878 if (types_compatible(type, type_void_ptr))
879 expression = expression->unary.value;
882 type_t *const type = skip_typeref(expression->base.type);
883 if (!is_type_integer(type))
885 switch (is_constant_expression(expression)) {
886 case EXPR_CLASS_ERROR: return true;
887 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
888 default: return false;
893 * Create an implicit cast expression.
895 * @param expression the expression to cast
896 * @param dest_type the destination type
898 static expression_t *create_implicit_cast(expression_t *expression,
901 type_t *const source_type = expression->base.type;
903 if (source_type == dest_type)
906 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
907 cast->unary.value = expression;
908 cast->base.type = dest_type;
909 cast->base.implicit = true;
914 typedef enum assign_error_t {
916 ASSIGN_ERROR_INCOMPATIBLE,
917 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
918 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
919 ASSIGN_WARNING_POINTER_FROM_INT,
920 ASSIGN_WARNING_INT_FROM_POINTER
923 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)
925 type_t *const orig_type_right = right->base.type;
926 type_t *const type_left = skip_typeref(orig_type_left);
927 type_t *const type_right = skip_typeref(orig_type_right);
932 case ASSIGN_ERROR_INCOMPATIBLE:
933 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
936 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
937 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
938 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
940 /* the left type has all qualifiers from the right type */
941 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
942 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);
946 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
947 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
950 case ASSIGN_WARNING_POINTER_FROM_INT:
951 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
954 case ASSIGN_WARNING_INT_FROM_POINTER:
955 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
959 panic("invalid error value");
963 /** Implements the rules from §6.5.16.1 */
964 static assign_error_t semantic_assign(type_t *orig_type_left,
965 const expression_t *const right)
967 type_t *const orig_type_right = right->base.type;
968 type_t *const type_left = skip_typeref(orig_type_left);
969 type_t *const type_right = skip_typeref(orig_type_right);
971 if (is_type_pointer(type_left)) {
972 if (is_null_pointer_constant(right)) {
973 return ASSIGN_SUCCESS;
974 } else if (is_type_pointer(type_right)) {
975 type_t *points_to_left
976 = skip_typeref(type_left->pointer.points_to);
977 type_t *points_to_right
978 = skip_typeref(type_right->pointer.points_to);
979 assign_error_t res = ASSIGN_SUCCESS;
981 /* the left type has all qualifiers from the right type */
982 unsigned missing_qualifiers
983 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
984 if (missing_qualifiers != 0) {
985 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
988 points_to_left = get_unqualified_type(points_to_left);
989 points_to_right = get_unqualified_type(points_to_right);
991 if (is_type_void(points_to_left))
994 if (is_type_void(points_to_right)) {
995 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
996 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
999 if (!types_compatible(points_to_left, points_to_right)) {
1000 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1004 } else if (is_type_integer(type_right)) {
1005 return ASSIGN_WARNING_POINTER_FROM_INT;
1007 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1008 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1009 && is_type_pointer(type_right))) {
1010 return ASSIGN_SUCCESS;
1011 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1012 type_t *const unqual_type_left = get_unqualified_type(type_left);
1013 type_t *const unqual_type_right = get_unqualified_type(type_right);
1014 if (types_compatible(unqual_type_left, unqual_type_right)) {
1015 return ASSIGN_SUCCESS;
1017 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1018 return ASSIGN_WARNING_INT_FROM_POINTER;
1021 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1022 return ASSIGN_SUCCESS;
1024 return ASSIGN_ERROR_INCOMPATIBLE;
1027 static expression_t *parse_constant_expression(void)
1029 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1031 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1032 errorf(&result->base.source_position,
1033 "expression '%E' is not constant", result);
1039 static expression_t *parse_assignment_expression(void)
1041 return parse_subexpression(PREC_ASSIGNMENT);
1044 static void warn_string_concat(const source_position_t *pos)
1046 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1049 static string_t parse_string_literals(void)
1051 assert(token.kind == T_STRING_LITERAL);
1052 string_t result = token.string.string;
1056 while (token.kind == T_STRING_LITERAL) {
1057 warn_string_concat(&token.base.source_position);
1058 result = concat_strings(&result, &token.string.string);
1065 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1067 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1068 attribute->kind = kind;
1069 attribute->source_position = *HERE;
1074 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1077 * __attribute__ ( ( attribute-list ) )
1081 * attribute_list , attrib
1086 * any-word ( identifier )
1087 * any-word ( identifier , nonempty-expr-list )
1088 * any-word ( expr-list )
1090 * where the "identifier" must not be declared as a type, and
1091 * "any-word" may be any identifier (including one declared as a
1092 * type), a reserved word storage class specifier, type specifier or
1093 * type qualifier. ??? This still leaves out most reserved keywords
1094 * (following the old parser), shouldn't we include them, and why not
1095 * allow identifiers declared as types to start the arguments?
1097 * Matze: this all looks confusing and little systematic, so we're even less
1098 * strict and parse any list of things which are identifiers or
1099 * (assignment-)expressions.
1101 static attribute_argument_t *parse_attribute_arguments(void)
1103 attribute_argument_t *first = NULL;
1104 attribute_argument_t **anchor = &first;
1105 if (token.kind != ')') do {
1106 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1108 /* is it an identifier */
1109 if (token.kind == T_IDENTIFIER
1110 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1111 symbol_t *symbol = token.identifier.symbol;
1112 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1113 argument->v.symbol = symbol;
1116 /* must be an expression */
1117 expression_t *expression = parse_assignment_expression();
1119 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1120 argument->v.expression = expression;
1123 /* append argument */
1125 anchor = &argument->next;
1126 } while (next_if(','));
1131 static attribute_t *parse_attribute_asm(void)
1133 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1136 attribute->a.arguments = parse_attribute_arguments();
1140 static symbol_t *get_symbol_from_token(void)
1142 switch(token.kind) {
1143 case T_CHARACTER_CONSTANT:
1145 case T_FLOATINGPOINT:
1146 case T_FLOATINGPOINT_HEXADECIMAL:
1148 case T_INTEGER_HEXADECIMAL:
1149 case T_INTEGER_OCTAL:
1150 case T_STRING_LITERAL:
1151 case T_WIDE_CHARACTER_CONSTANT:
1152 case T_WIDE_STRING_LITERAL:
1156 return token.identifier.symbol;
1160 static attribute_t *parse_attribute_gnu_single(void)
1162 /* parse "any-word" */
1163 symbol_t *symbol = get_symbol_from_token();
1164 if (symbol == NULL) {
1165 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1169 attribute_kind_t kind;
1170 char const *const name = symbol->string;
1171 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1172 if (kind > ATTRIBUTE_GNU_LAST) {
1173 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1174 /* TODO: we should still save the attribute in the list... */
1175 kind = ATTRIBUTE_UNKNOWN;
1179 const char *attribute_name = get_attribute_name(kind);
1180 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1184 attribute_t *attribute = allocate_attribute_zero(kind);
1187 /* parse arguments */
1189 attribute->a.arguments = parse_attribute_arguments();
1194 static attribute_t *parse_attribute_gnu(void)
1196 attribute_t *first = NULL;
1197 attribute_t **anchor = &first;
1199 eat(T___attribute__);
1203 add_anchor_token(')');
1204 add_anchor_token(',');
1205 if (token.kind != ')') do {
1206 attribute_t *attribute = parse_attribute_gnu_single();
1208 *anchor = attribute;
1209 anchor = &attribute->next;
1211 } while (next_if(','));
1212 rem_anchor_token(',');
1213 rem_anchor_token(')');
1220 /** Parse attributes. */
1221 static attribute_t *parse_attributes(attribute_t *first)
1223 attribute_t **anchor = &first;
1225 while (*anchor != NULL)
1226 anchor = &(*anchor)->next;
1228 attribute_t *attribute;
1229 switch (token.kind) {
1230 case T___attribute__:
1231 attribute = parse_attribute_gnu();
1232 if (attribute == NULL)
1237 attribute = parse_attribute_asm();
1241 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1246 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1250 case T__forceinline:
1251 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1252 eat(T__forceinline);
1256 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1261 /* TODO record modifier */
1262 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1263 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1271 *anchor = attribute;
1272 anchor = &attribute->next;
1276 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1278 static entity_t *determine_lhs_ent(expression_t *const expr,
1281 switch (expr->kind) {
1282 case EXPR_REFERENCE: {
1283 entity_t *const entity = expr->reference.entity;
1284 /* we should only find variables as lvalues... */
1285 if (entity->base.kind != ENTITY_VARIABLE
1286 && entity->base.kind != ENTITY_PARAMETER)
1292 case EXPR_ARRAY_ACCESS: {
1293 expression_t *const ref = expr->array_access.array_ref;
1294 entity_t * ent = NULL;
1295 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1296 ent = determine_lhs_ent(ref, lhs_ent);
1299 mark_vars_read(ref, lhs_ent);
1301 mark_vars_read(expr->array_access.index, lhs_ent);
1306 mark_vars_read(expr->select.compound, lhs_ent);
1307 if (is_type_compound(skip_typeref(expr->base.type)))
1308 return determine_lhs_ent(expr->select.compound, lhs_ent);
1312 case EXPR_UNARY_DEREFERENCE: {
1313 expression_t *const val = expr->unary.value;
1314 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1316 return determine_lhs_ent(val->unary.value, lhs_ent);
1318 mark_vars_read(val, NULL);
1324 mark_vars_read(expr, NULL);
1329 #define ENT_ANY ((entity_t*)-1)
1332 * Mark declarations, which are read. This is used to detect variables, which
1336 * x is not marked as "read", because it is only read to calculate its own new
1340 * x and y are not detected as "not read", because multiple variables are
1343 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1345 switch (expr->kind) {
1346 case EXPR_REFERENCE: {
1347 entity_t *const entity = expr->reference.entity;
1348 if (entity->kind != ENTITY_VARIABLE
1349 && entity->kind != ENTITY_PARAMETER)
1352 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1353 if (entity->kind == ENTITY_VARIABLE) {
1354 entity->variable.read = true;
1356 entity->parameter.read = true;
1363 // TODO respect pure/const
1364 mark_vars_read(expr->call.function, NULL);
1365 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1366 mark_vars_read(arg->expression, NULL);
1370 case EXPR_CONDITIONAL:
1371 // TODO lhs_decl should depend on whether true/false have an effect
1372 mark_vars_read(expr->conditional.condition, NULL);
1373 if (expr->conditional.true_expression != NULL)
1374 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1375 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1379 if (lhs_ent == ENT_ANY
1380 && !is_type_compound(skip_typeref(expr->base.type)))
1382 mark_vars_read(expr->select.compound, lhs_ent);
1385 case EXPR_ARRAY_ACCESS: {
1386 mark_vars_read(expr->array_access.index, lhs_ent);
1387 expression_t *const ref = expr->array_access.array_ref;
1388 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1389 if (lhs_ent == ENT_ANY)
1392 mark_vars_read(ref, lhs_ent);
1397 mark_vars_read(expr->va_arge.ap, lhs_ent);
1401 mark_vars_read(expr->va_copye.src, lhs_ent);
1404 case EXPR_UNARY_CAST:
1405 /* Special case: Use void cast to mark a variable as "read" */
1406 if (is_type_void(skip_typeref(expr->base.type)))
1411 case EXPR_UNARY_THROW:
1412 if (expr->unary.value == NULL)
1415 case EXPR_UNARY_DEREFERENCE:
1416 case EXPR_UNARY_DELETE:
1417 case EXPR_UNARY_DELETE_ARRAY:
1418 if (lhs_ent == ENT_ANY)
1422 case EXPR_UNARY_NEGATE:
1423 case EXPR_UNARY_PLUS:
1424 case EXPR_UNARY_BITWISE_NEGATE:
1425 case EXPR_UNARY_NOT:
1426 case EXPR_UNARY_TAKE_ADDRESS:
1427 case EXPR_UNARY_POSTFIX_INCREMENT:
1428 case EXPR_UNARY_POSTFIX_DECREMENT:
1429 case EXPR_UNARY_PREFIX_INCREMENT:
1430 case EXPR_UNARY_PREFIX_DECREMENT:
1431 case EXPR_UNARY_ASSUME:
1433 mark_vars_read(expr->unary.value, lhs_ent);
1436 case EXPR_BINARY_ADD:
1437 case EXPR_BINARY_SUB:
1438 case EXPR_BINARY_MUL:
1439 case EXPR_BINARY_DIV:
1440 case EXPR_BINARY_MOD:
1441 case EXPR_BINARY_EQUAL:
1442 case EXPR_BINARY_NOTEQUAL:
1443 case EXPR_BINARY_LESS:
1444 case EXPR_BINARY_LESSEQUAL:
1445 case EXPR_BINARY_GREATER:
1446 case EXPR_BINARY_GREATEREQUAL:
1447 case EXPR_BINARY_BITWISE_AND:
1448 case EXPR_BINARY_BITWISE_OR:
1449 case EXPR_BINARY_BITWISE_XOR:
1450 case EXPR_BINARY_LOGICAL_AND:
1451 case EXPR_BINARY_LOGICAL_OR:
1452 case EXPR_BINARY_SHIFTLEFT:
1453 case EXPR_BINARY_SHIFTRIGHT:
1454 case EXPR_BINARY_COMMA:
1455 case EXPR_BINARY_ISGREATER:
1456 case EXPR_BINARY_ISGREATEREQUAL:
1457 case EXPR_BINARY_ISLESS:
1458 case EXPR_BINARY_ISLESSEQUAL:
1459 case EXPR_BINARY_ISLESSGREATER:
1460 case EXPR_BINARY_ISUNORDERED:
1461 mark_vars_read(expr->binary.left, lhs_ent);
1462 mark_vars_read(expr->binary.right, lhs_ent);
1465 case EXPR_BINARY_ASSIGN:
1466 case EXPR_BINARY_MUL_ASSIGN:
1467 case EXPR_BINARY_DIV_ASSIGN:
1468 case EXPR_BINARY_MOD_ASSIGN:
1469 case EXPR_BINARY_ADD_ASSIGN:
1470 case EXPR_BINARY_SUB_ASSIGN:
1471 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1472 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1473 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1474 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1475 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1476 if (lhs_ent == ENT_ANY)
1478 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1479 mark_vars_read(expr->binary.right, lhs_ent);
1484 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1487 case EXPR_LITERAL_CASES:
1489 case EXPR_STRING_LITERAL:
1490 case EXPR_WIDE_STRING_LITERAL:
1491 case EXPR_COMPOUND_LITERAL: // TODO init?
1493 case EXPR_CLASSIFY_TYPE:
1496 case EXPR_BUILTIN_CONSTANT_P:
1497 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1499 case EXPR_STATEMENT: // TODO
1500 case EXPR_LABEL_ADDRESS:
1501 case EXPR_ENUM_CONSTANT:
1505 panic("unhandled expression");
1508 static designator_t *parse_designation(void)
1510 designator_t *result = NULL;
1511 designator_t **anchor = &result;
1514 designator_t *designator;
1515 switch (token.kind) {
1517 designator = allocate_ast_zero(sizeof(designator[0]));
1518 designator->source_position = token.base.source_position;
1520 add_anchor_token(']');
1521 designator->array_index = parse_constant_expression();
1522 rem_anchor_token(']');
1526 designator = allocate_ast_zero(sizeof(designator[0]));
1527 designator->source_position = token.base.source_position;
1529 designator->symbol = expect_identifier("while parsing designator", NULL);
1530 if (!designator->symbol)
1538 assert(designator != NULL);
1539 *anchor = designator;
1540 anchor = &designator->next;
1544 static initializer_t *initializer_from_string(array_type_t *const type,
1545 const string_t *const string)
1547 /* TODO: check len vs. size of array type */
1550 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1551 initializer->string.string = *string;
1556 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1557 const string_t *const string)
1559 /* TODO: check len vs. size of array type */
1562 initializer_t *const initializer =
1563 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1564 initializer->wide_string.string = *string;
1570 * Build an initializer from a given expression.
1572 static initializer_t *initializer_from_expression(type_t *orig_type,
1573 expression_t *expression)
1575 /* TODO check that expression is a constant expression */
1577 /* §6.7.8.14/15 char array may be initialized by string literals */
1578 type_t *type = skip_typeref(orig_type);
1579 type_t *expr_type_orig = expression->base.type;
1580 type_t *expr_type = skip_typeref(expr_type_orig);
1582 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1583 array_type_t *const array_type = &type->array;
1584 type_t *const element_type = skip_typeref(array_type->element_type);
1586 if (element_type->kind == TYPE_ATOMIC) {
1587 atomic_type_kind_t akind = element_type->atomic.akind;
1588 switch (expression->kind) {
1589 case EXPR_STRING_LITERAL:
1590 if (akind == ATOMIC_TYPE_CHAR
1591 || akind == ATOMIC_TYPE_SCHAR
1592 || akind == ATOMIC_TYPE_UCHAR) {
1593 return initializer_from_string(array_type,
1594 &expression->string_literal.value);
1598 case EXPR_WIDE_STRING_LITERAL: {
1599 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1600 if (get_unqualified_type(element_type) == bare_wchar_type) {
1601 return initializer_from_wide_string(array_type,
1602 &expression->string_literal.value);
1613 assign_error_t error = semantic_assign(type, expression);
1614 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1616 report_assign_error(error, type, expression, "initializer",
1617 &expression->base.source_position);
1619 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1620 result->value.value = create_implicit_cast(expression, type);
1626 * Parses an scalar initializer.
1628 * §6.7.8.11; eat {} without warning
1630 static initializer_t *parse_scalar_initializer(type_t *type,
1631 bool must_be_constant)
1633 /* there might be extra {} hierarchies */
1635 if (token.kind == '{') {
1636 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1640 } while (token.kind == '{');
1643 expression_t *expression = parse_assignment_expression();
1644 mark_vars_read(expression, NULL);
1645 if (must_be_constant && !is_linker_constant(expression)) {
1646 errorf(&expression->base.source_position,
1647 "initialisation expression '%E' is not constant",
1651 initializer_t *initializer = initializer_from_expression(type, expression);
1653 if (initializer == NULL) {
1654 errorf(&expression->base.source_position,
1655 "expression '%E' (type '%T') doesn't match expected type '%T'",
1656 expression, expression->base.type, type);
1661 bool additional_warning_displayed = false;
1662 while (braces > 0) {
1664 if (token.kind != '}') {
1665 if (!additional_warning_displayed) {
1666 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1667 additional_warning_displayed = true;
1678 * An entry in the type path.
1680 typedef struct type_path_entry_t type_path_entry_t;
1681 struct type_path_entry_t {
1682 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1684 size_t index; /**< For array types: the current index. */
1685 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1690 * A type path expression a position inside compound or array types.
1692 typedef struct type_path_t type_path_t;
1693 struct type_path_t {
1694 type_path_entry_t *path; /**< An flexible array containing the current path. */
1695 type_t *top_type; /**< type of the element the path points */
1696 size_t max_index; /**< largest index in outermost array */
1700 * Prints a type path for debugging.
1702 static __attribute__((unused)) void debug_print_type_path(
1703 const type_path_t *path)
1705 size_t len = ARR_LEN(path->path);
1707 for (size_t i = 0; i < len; ++i) {
1708 const type_path_entry_t *entry = & path->path[i];
1710 type_t *type = skip_typeref(entry->type);
1711 if (is_type_compound(type)) {
1712 /* in gcc mode structs can have no members */
1713 if (entry->v.compound_entry == NULL) {
1717 fprintf(stderr, ".%s",
1718 entry->v.compound_entry->base.symbol->string);
1719 } else if (is_type_array(type)) {
1720 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1722 fprintf(stderr, "-INVALID-");
1725 if (path->top_type != NULL) {
1726 fprintf(stderr, " (");
1727 print_type(path->top_type);
1728 fprintf(stderr, ")");
1733 * Return the top type path entry, ie. in a path
1734 * (type).a.b returns the b.
1736 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1738 size_t len = ARR_LEN(path->path);
1740 return &path->path[len-1];
1744 * Enlarge the type path by an (empty) element.
1746 static type_path_entry_t *append_to_type_path(type_path_t *path)
1748 size_t len = ARR_LEN(path->path);
1749 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1751 type_path_entry_t *result = & path->path[len];
1752 memset(result, 0, sizeof(result[0]));
1757 * Descending into a sub-type. Enter the scope of the current top_type.
1759 static void descend_into_subtype(type_path_t *path)
1761 type_t *orig_top_type = path->top_type;
1762 type_t *top_type = skip_typeref(orig_top_type);
1764 type_path_entry_t *top = append_to_type_path(path);
1765 top->type = top_type;
1767 if (is_type_compound(top_type)) {
1768 compound_t *const compound = top_type->compound.compound;
1769 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1771 if (entry != NULL) {
1772 top->v.compound_entry = &entry->declaration;
1773 path->top_type = entry->declaration.type;
1775 path->top_type = NULL;
1777 } else if (is_type_array(top_type)) {
1779 path->top_type = top_type->array.element_type;
1781 assert(!is_type_valid(top_type));
1786 * Pop an entry from the given type path, ie. returning from
1787 * (type).a.b to (type).a
1789 static void ascend_from_subtype(type_path_t *path)
1791 type_path_entry_t *top = get_type_path_top(path);
1793 path->top_type = top->type;
1795 size_t len = ARR_LEN(path->path);
1796 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1800 * Pop entries from the given type path until the given
1801 * path level is reached.
1803 static void ascend_to(type_path_t *path, size_t top_path_level)
1805 size_t len = ARR_LEN(path->path);
1807 while (len > top_path_level) {
1808 ascend_from_subtype(path);
1809 len = ARR_LEN(path->path);
1813 static bool walk_designator(type_path_t *path, const designator_t *designator,
1814 bool used_in_offsetof)
1816 for (; designator != NULL; designator = designator->next) {
1817 type_path_entry_t *top = get_type_path_top(path);
1818 type_t *orig_type = top->type;
1820 type_t *type = skip_typeref(orig_type);
1822 if (designator->symbol != NULL) {
1823 symbol_t *symbol = designator->symbol;
1824 if (!is_type_compound(type)) {
1825 if (is_type_valid(type)) {
1826 errorf(&designator->source_position,
1827 "'.%Y' designator used for non-compound type '%T'",
1831 top->type = type_error_type;
1832 top->v.compound_entry = NULL;
1833 orig_type = type_error_type;
1835 compound_t *compound = type->compound.compound;
1836 entity_t *iter = compound->members.entities;
1837 for (; iter != NULL; iter = iter->base.next) {
1838 if (iter->base.symbol == symbol) {
1843 errorf(&designator->source_position,
1844 "'%T' has no member named '%Y'", orig_type, symbol);
1847 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1848 if (used_in_offsetof && iter->compound_member.bitfield) {
1849 errorf(&designator->source_position,
1850 "offsetof designator '%Y' must not specify bitfield",
1855 top->type = orig_type;
1856 top->v.compound_entry = &iter->declaration;
1857 orig_type = iter->declaration.type;
1860 expression_t *array_index = designator->array_index;
1861 assert(designator->array_index != NULL);
1863 if (!is_type_array(type)) {
1864 if (is_type_valid(type)) {
1865 errorf(&designator->source_position,
1866 "[%E] designator used for non-array type '%T'",
1867 array_index, orig_type);
1872 long index = fold_constant_to_int(array_index);
1873 if (!used_in_offsetof) {
1875 errorf(&designator->source_position,
1876 "array index [%E] must be positive", array_index);
1877 } else if (type->array.size_constant) {
1878 long array_size = type->array.size;
1879 if (index >= array_size) {
1880 errorf(&designator->source_position,
1881 "designator [%E] (%d) exceeds array size %d",
1882 array_index, index, array_size);
1887 top->type = orig_type;
1888 top->v.index = (size_t) index;
1889 orig_type = type->array.element_type;
1891 path->top_type = orig_type;
1893 if (designator->next != NULL) {
1894 descend_into_subtype(path);
1900 static void advance_current_object(type_path_t *path, size_t top_path_level)
1902 type_path_entry_t *top = get_type_path_top(path);
1904 type_t *type = skip_typeref(top->type);
1905 if (is_type_union(type)) {
1906 /* in unions only the first element is initialized */
1907 top->v.compound_entry = NULL;
1908 } else if (is_type_struct(type)) {
1909 declaration_t *entry = top->v.compound_entry;
1911 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1912 if (next_entity != NULL) {
1913 assert(is_declaration(next_entity));
1914 entry = &next_entity->declaration;
1919 top->v.compound_entry = entry;
1920 if (entry != NULL) {
1921 path->top_type = entry->type;
1924 } else if (is_type_array(type)) {
1925 assert(is_type_array(type));
1929 if (!type->array.size_constant || top->v.index < type->array.size) {
1933 assert(!is_type_valid(type));
1937 /* we're past the last member of the current sub-aggregate, try if we
1938 * can ascend in the type hierarchy and continue with another subobject */
1939 size_t len = ARR_LEN(path->path);
1941 if (len > top_path_level) {
1942 ascend_from_subtype(path);
1943 advance_current_object(path, top_path_level);
1945 path->top_type = NULL;
1950 * skip any {...} blocks until a closing bracket is reached.
1952 static void skip_initializers(void)
1956 while (token.kind != '}') {
1957 if (token.kind == T_EOF)
1959 if (token.kind == '{') {
1967 static initializer_t *create_empty_initializer(void)
1969 static initializer_t empty_initializer
1970 = { .list = { { INITIALIZER_LIST }, 0 } };
1971 return &empty_initializer;
1975 * Parse a part of an initialiser for a struct or union,
1977 static initializer_t *parse_sub_initializer(type_path_t *path,
1978 type_t *outer_type, size_t top_path_level,
1979 parse_initializer_env_t *env)
1981 if (token.kind == '}') {
1982 /* empty initializer */
1983 return create_empty_initializer();
1986 type_t *orig_type = path->top_type;
1987 type_t *type = NULL;
1989 if (orig_type == NULL) {
1990 /* We are initializing an empty compound. */
1992 type = skip_typeref(orig_type);
1995 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1998 designator_t *designator = NULL;
1999 if (token.kind == '.' || token.kind == '[') {
2000 designator = parse_designation();
2001 goto finish_designator;
2002 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2003 /* GNU-style designator ("identifier: value") */
2004 designator = allocate_ast_zero(sizeof(designator[0]));
2005 designator->source_position = token.base.source_position;
2006 designator->symbol = token.identifier.symbol;
2011 /* reset path to toplevel, evaluate designator from there */
2012 ascend_to(path, top_path_level);
2013 if (!walk_designator(path, designator, false)) {
2014 /* can't continue after designation error */
2018 initializer_t *designator_initializer
2019 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2020 designator_initializer->designator.designator = designator;
2021 ARR_APP1(initializer_t*, initializers, designator_initializer);
2023 orig_type = path->top_type;
2024 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2029 if (token.kind == '{') {
2030 if (type != NULL && is_type_scalar(type)) {
2031 sub = parse_scalar_initializer(type, env->must_be_constant);
2034 if (env->entity != NULL) {
2036 "extra brace group at end of initializer for '%Y'",
2037 env->entity->base.symbol);
2039 errorf(HERE, "extra brace group at end of initializer");
2044 descend_into_subtype(path);
2047 add_anchor_token('}');
2048 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2050 rem_anchor_token('}');
2055 goto error_parse_next;
2057 ascend_from_subtype(path);
2060 /* must be an expression */
2061 expression_t *expression = parse_assignment_expression();
2062 mark_vars_read(expression, NULL);
2064 if (env->must_be_constant && !is_linker_constant(expression)) {
2065 errorf(&expression->base.source_position,
2066 "Initialisation expression '%E' is not constant",
2071 /* we are already outside, ... */
2072 if (outer_type == NULL)
2073 goto error_parse_next;
2074 type_t *const outer_type_skip = skip_typeref(outer_type);
2075 if (is_type_compound(outer_type_skip) &&
2076 !outer_type_skip->compound.compound->complete) {
2077 goto error_parse_next;
2080 source_position_t const* const pos = &expression->base.source_position;
2081 if (env->entity != NULL) {
2082 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2084 warningf(WARN_OTHER, pos, "excess elements in initializer");
2086 goto error_parse_next;
2089 /* handle { "string" } special case */
2090 if ((expression->kind == EXPR_STRING_LITERAL
2091 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2092 && outer_type != NULL) {
2093 sub = initializer_from_expression(outer_type, expression);
2096 if (token.kind != '}') {
2097 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2099 /* TODO: eat , ... */
2104 /* descend into subtypes until expression matches type */
2106 orig_type = path->top_type;
2107 type = skip_typeref(orig_type);
2109 sub = initializer_from_expression(orig_type, expression);
2113 if (!is_type_valid(type)) {
2116 if (is_type_scalar(type)) {
2117 errorf(&expression->base.source_position,
2118 "expression '%E' doesn't match expected type '%T'",
2119 expression, orig_type);
2123 descend_into_subtype(path);
2127 /* update largest index of top array */
2128 const type_path_entry_t *first = &path->path[0];
2129 type_t *first_type = first->type;
2130 first_type = skip_typeref(first_type);
2131 if (is_type_array(first_type)) {
2132 size_t index = first->v.index;
2133 if (index > path->max_index)
2134 path->max_index = index;
2137 /* append to initializers list */
2138 ARR_APP1(initializer_t*, initializers, sub);
2141 if (token.kind == '}') {
2144 add_anchor_token('}');
2146 rem_anchor_token('}');
2147 if (token.kind == '}') {
2152 /* advance to the next declaration if we are not at the end */
2153 advance_current_object(path, top_path_level);
2154 orig_type = path->top_type;
2155 if (orig_type != NULL)
2156 type = skip_typeref(orig_type);
2162 size_t len = ARR_LEN(initializers);
2163 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2164 initializer_t *result = allocate_ast_zero(size);
2165 result->kind = INITIALIZER_LIST;
2166 result->list.len = len;
2167 memcpy(&result->list.initializers, initializers,
2168 len * sizeof(initializers[0]));
2170 DEL_ARR_F(initializers);
2171 ascend_to(path, top_path_level+1);
2176 skip_initializers();
2177 DEL_ARR_F(initializers);
2178 ascend_to(path, top_path_level+1);
2182 static expression_t *make_size_literal(size_t value)
2184 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2185 literal->base.type = type_size_t;
2188 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2189 literal->literal.value = make_string(buf);
2195 * Parses an initializer. Parsers either a compound literal
2196 * (env->declaration == NULL) or an initializer of a declaration.
2198 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2200 type_t *type = skip_typeref(env->type);
2201 size_t max_index = 0;
2202 initializer_t *result;
2204 if (is_type_scalar(type)) {
2205 result = parse_scalar_initializer(type, env->must_be_constant);
2206 } else if (token.kind == '{') {
2210 memset(&path, 0, sizeof(path));
2211 path.top_type = env->type;
2212 path.path = NEW_ARR_F(type_path_entry_t, 0);
2214 descend_into_subtype(&path);
2216 add_anchor_token('}');
2217 result = parse_sub_initializer(&path, env->type, 1, env);
2218 rem_anchor_token('}');
2220 max_index = path.max_index;
2221 DEL_ARR_F(path.path);
2225 /* parse_scalar_initializer() also works in this case: we simply
2226 * have an expression without {} around it */
2227 result = parse_scalar_initializer(type, env->must_be_constant);
2230 /* §6.7.8:22 array initializers for arrays with unknown size determine
2231 * the array type size */
2232 if (is_type_array(type) && type->array.size_expression == NULL
2233 && result != NULL) {
2235 switch (result->kind) {
2236 case INITIALIZER_LIST:
2237 assert(max_index != 0xdeadbeaf);
2238 size = max_index + 1;
2241 case INITIALIZER_STRING:
2242 size = result->string.string.size;
2245 case INITIALIZER_WIDE_STRING:
2246 size = result->wide_string.string.size;
2249 case INITIALIZER_DESIGNATOR:
2250 case INITIALIZER_VALUE:
2251 /* can happen for parse errors */
2256 internal_errorf(HERE, "invalid initializer type");
2259 type_t *new_type = duplicate_type(type);
2261 new_type->array.size_expression = make_size_literal(size);
2262 new_type->array.size_constant = true;
2263 new_type->array.has_implicit_size = true;
2264 new_type->array.size = size;
2265 env->type = new_type;
2271 static void append_entity(scope_t *scope, entity_t *entity)
2273 if (scope->last_entity != NULL) {
2274 scope->last_entity->base.next = entity;
2276 scope->entities = entity;
2278 entity->base.parent_entity = current_entity;
2279 scope->last_entity = entity;
2283 static compound_t *parse_compound_type_specifier(bool is_struct)
2285 source_position_t const pos = *HERE;
2286 eat(is_struct ? T_struct : T_union);
2288 symbol_t *symbol = NULL;
2289 entity_t *entity = NULL;
2290 attribute_t *attributes = NULL;
2292 if (token.kind == T___attribute__) {
2293 attributes = parse_attributes(NULL);
2296 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2297 if (token.kind == T_IDENTIFIER) {
2298 /* the compound has a name, check if we have seen it already */
2299 symbol = token.identifier.symbol;
2300 entity = get_tag(symbol, kind);
2303 if (entity != NULL) {
2304 if (entity->base.parent_scope != current_scope &&
2305 (token.kind == '{' || token.kind == ';')) {
2306 /* we're in an inner scope and have a definition. Shadow
2307 * existing definition in outer scope */
2309 } else if (entity->compound.complete && token.kind == '{') {
2310 source_position_t const *const ppos = &entity->base.source_position;
2311 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2312 /* clear members in the hope to avoid further errors */
2313 entity->compound.members.entities = NULL;
2316 } else if (token.kind != '{') {
2317 char const *const msg =
2318 is_struct ? "while parsing struct type specifier" :
2319 "while parsing union type specifier";
2320 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2325 if (entity == NULL) {
2326 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2327 entity->compound.alignment = 1;
2328 entity->base.parent_scope = current_scope;
2329 if (symbol != NULL) {
2330 environment_push(entity);
2332 append_entity(current_scope, entity);
2335 if (token.kind == '{') {
2336 parse_compound_type_entries(&entity->compound);
2338 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2339 if (symbol == NULL) {
2340 assert(anonymous_entity == NULL);
2341 anonymous_entity = entity;
2345 if (attributes != NULL) {
2346 handle_entity_attributes(attributes, entity);
2349 return &entity->compound;
2352 static void parse_enum_entries(type_t *const enum_type)
2356 if (token.kind == '}') {
2357 errorf(HERE, "empty enum not allowed");
2362 add_anchor_token('}');
2363 add_anchor_token(',');
2365 add_anchor_token('=');
2366 source_position_t pos;
2367 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2368 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2369 entity->enum_value.enum_type = enum_type;
2370 rem_anchor_token('=');
2373 expression_t *value = parse_constant_expression();
2375 value = create_implicit_cast(value, enum_type);
2376 entity->enum_value.value = value;
2381 record_entity(entity, false);
2382 } while (next_if(',') && token.kind != '}');
2383 rem_anchor_token(',');
2384 rem_anchor_token('}');
2389 static type_t *parse_enum_specifier(void)
2391 source_position_t const pos = *HERE;
2396 switch (token.kind) {
2398 symbol = token.identifier.symbol;
2399 entity = get_tag(symbol, ENTITY_ENUM);
2402 if (entity != NULL) {
2403 if (entity->base.parent_scope != current_scope &&
2404 (token.kind == '{' || token.kind == ';')) {
2405 /* we're in an inner scope and have a definition. Shadow
2406 * existing definition in outer scope */
2408 } else if (entity->enume.complete && token.kind == '{') {
2409 source_position_t const *const ppos = &entity->base.source_position;
2410 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2421 parse_error_expected("while parsing enum type specifier",
2422 T_IDENTIFIER, '{', NULL);
2426 if (entity == NULL) {
2427 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2428 entity->base.parent_scope = current_scope;
2431 type_t *const type = allocate_type_zero(TYPE_ENUM);
2432 type->enumt.enume = &entity->enume;
2433 type->enumt.base.akind = ATOMIC_TYPE_INT;
2435 if (token.kind == '{') {
2436 if (symbol != NULL) {
2437 environment_push(entity);
2439 append_entity(current_scope, entity);
2440 entity->enume.complete = true;
2442 parse_enum_entries(type);
2443 parse_attributes(NULL);
2445 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2446 if (symbol == NULL) {
2447 assert(anonymous_entity == NULL);
2448 anonymous_entity = entity;
2450 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2451 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2458 * if a symbol is a typedef to another type, return true
2460 static bool is_typedef_symbol(symbol_t *symbol)
2462 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2463 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2466 static type_t *parse_typeof(void)
2473 add_anchor_token(')');
2475 expression_t *expression = NULL;
2477 switch (token.kind) {
2479 if (is_typedef_symbol(token.identifier.symbol)) {
2481 type = parse_typename();
2484 expression = parse_expression();
2485 type = revert_automatic_type_conversion(expression);
2490 rem_anchor_token(')');
2493 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2494 typeof_type->typeoft.expression = expression;
2495 typeof_type->typeoft.typeof_type = type;
2500 typedef enum specifiers_t {
2501 SPECIFIER_SIGNED = 1 << 0,
2502 SPECIFIER_UNSIGNED = 1 << 1,
2503 SPECIFIER_LONG = 1 << 2,
2504 SPECIFIER_INT = 1 << 3,
2505 SPECIFIER_DOUBLE = 1 << 4,
2506 SPECIFIER_CHAR = 1 << 5,
2507 SPECIFIER_WCHAR_T = 1 << 6,
2508 SPECIFIER_SHORT = 1 << 7,
2509 SPECIFIER_LONG_LONG = 1 << 8,
2510 SPECIFIER_FLOAT = 1 << 9,
2511 SPECIFIER_BOOL = 1 << 10,
2512 SPECIFIER_VOID = 1 << 11,
2513 SPECIFIER_INT8 = 1 << 12,
2514 SPECIFIER_INT16 = 1 << 13,
2515 SPECIFIER_INT32 = 1 << 14,
2516 SPECIFIER_INT64 = 1 << 15,
2517 SPECIFIER_INT128 = 1 << 16,
2518 SPECIFIER_COMPLEX = 1 << 17,
2519 SPECIFIER_IMAGINARY = 1 << 18,
2522 static type_t *get_typedef_type(symbol_t *symbol)
2524 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2525 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2528 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2529 type->typedeft.typedefe = &entity->typedefe;
2534 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2536 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2540 add_anchor_token(')');
2541 add_anchor_token(',');
2543 add_anchor_token('=');
2544 source_position_t pos;
2545 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2546 rem_anchor_token('=');
2548 symbol_t **prop = NULL;
2550 if (streq(prop_sym->string, "put")) {
2551 prop = &property->put_symbol;
2552 } else if (streq(prop_sym->string, "get")) {
2553 prop = &property->get_symbol;
2555 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2559 add_anchor_token(T_IDENTIFIER);
2561 rem_anchor_token(T_IDENTIFIER);
2563 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2565 *prop = sym ? sym : sym_anonymous;
2566 } while (next_if(','));
2567 rem_anchor_token(',');
2568 rem_anchor_token(')');
2570 attribute->a.property = property;
2576 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2578 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2579 if (next_if(T_restrict)) {
2580 kind = ATTRIBUTE_MS_RESTRICT;
2581 } else if (token.kind == T_IDENTIFIER) {
2582 const char *name = token.identifier.symbol->string;
2583 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2585 const char *attribute_name = get_attribute_name(k);
2586 if (attribute_name != NULL && streq(attribute_name, name)) {
2592 if (kind == ATTRIBUTE_UNKNOWN) {
2593 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2596 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2600 attribute_t *attribute = allocate_attribute_zero(kind);
2603 if (kind == ATTRIBUTE_MS_PROPERTY) {
2604 return parse_attribute_ms_property(attribute);
2607 /* parse arguments */
2609 attribute->a.arguments = parse_attribute_arguments();
2614 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2619 if (token.kind != ')') {
2620 add_anchor_token(')');
2622 attribute_t **anchor = &first;
2624 while (*anchor != NULL)
2625 anchor = &(*anchor)->next;
2627 attribute_t *attribute
2628 = parse_microsoft_extended_decl_modifier_single();
2629 if (attribute == NULL)
2632 *anchor = attribute;
2633 anchor = &attribute->next;
2634 } while (next_if(','));
2636 rem_anchor_token(')');
2642 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2644 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2645 if (is_declaration(entity)) {
2646 entity->declaration.type = type_error_type;
2647 entity->declaration.implicit = true;
2648 } else if (kind == ENTITY_TYPEDEF) {
2649 entity->typedefe.type = type_error_type;
2650 entity->typedefe.builtin = true;
2652 if (kind != ENTITY_COMPOUND_MEMBER)
2653 record_entity(entity, false);
2657 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2659 type_t *type = NULL;
2660 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2661 unsigned type_specifiers = 0;
2662 bool newtype = false;
2663 bool saw_error = false;
2665 memset(specifiers, 0, sizeof(*specifiers));
2666 specifiers->source_position = token.base.source_position;
2669 specifiers->attributes = parse_attributes(specifiers->attributes);
2671 switch (token.kind) {
2673 #define MATCH_STORAGE_CLASS(token, class) \
2675 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2676 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2678 specifiers->storage_class = class; \
2679 if (specifiers->thread_local) \
2680 goto check_thread_storage_class; \
2684 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2685 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2686 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2687 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2688 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2691 specifiers->attributes
2692 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2696 if (specifiers->thread_local) {
2697 errorf(HERE, "duplicate '__thread'");
2699 specifiers->thread_local = true;
2700 check_thread_storage_class:
2701 switch (specifiers->storage_class) {
2702 case STORAGE_CLASS_EXTERN:
2703 case STORAGE_CLASS_NONE:
2704 case STORAGE_CLASS_STATIC:
2708 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2709 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2710 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2711 wrong_thread_storage_class:
2712 errorf(HERE, "'__thread' used with '%s'", wrong);
2719 /* type qualifiers */
2720 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2722 qualifiers |= qualifier; \
2726 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2727 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2728 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2729 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2730 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2731 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2732 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2733 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2735 /* type specifiers */
2736 #define MATCH_SPECIFIER(token, specifier, name) \
2738 if (type_specifiers & specifier) { \
2739 errorf(HERE, "multiple " name " type specifiers given"); \
2741 type_specifiers |= specifier; \
2746 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2747 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2748 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2749 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2750 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2751 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2752 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2753 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2754 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2755 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2756 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2757 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2758 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2759 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2760 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2761 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2762 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2763 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2767 specifiers->is_inline = true;
2771 case T__forceinline:
2773 specifiers->modifiers |= DM_FORCEINLINE;
2778 if (type_specifiers & SPECIFIER_LONG_LONG) {
2779 errorf(HERE, "too many long type specifiers given");
2780 } else if (type_specifiers & SPECIFIER_LONG) {
2781 type_specifiers |= SPECIFIER_LONG_LONG;
2783 type_specifiers |= SPECIFIER_LONG;
2788 #define CHECK_DOUBLE_TYPE() \
2789 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2792 CHECK_DOUBLE_TYPE();
2793 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2795 type->compound.compound = parse_compound_type_specifier(true);
2798 CHECK_DOUBLE_TYPE();
2799 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2800 type->compound.compound = parse_compound_type_specifier(false);
2803 CHECK_DOUBLE_TYPE();
2804 type = parse_enum_specifier();
2807 CHECK_DOUBLE_TYPE();
2808 type = parse_typeof();
2810 case T___builtin_va_list:
2811 CHECK_DOUBLE_TYPE();
2812 type = duplicate_type(type_valist);
2816 case T_IDENTIFIER: {
2817 /* only parse identifier if we haven't found a type yet */
2818 if (type != NULL || type_specifiers != 0) {
2819 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2820 * declaration, so it doesn't generate errors about expecting '(' or
2822 switch (look_ahead(1)->kind) {
2829 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2833 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2838 goto finish_specifiers;
2842 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2843 if (typedef_type == NULL) {
2844 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2845 * declaration, so it doesn't generate 'implicit int' followed by more
2846 * errors later on. */
2847 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2853 errorf(HERE, "%K does not name a type", &token);
2855 symbol_t *symbol = token.identifier.symbol;
2857 = create_error_entity(symbol, ENTITY_TYPEDEF);
2859 type = allocate_type_zero(TYPE_TYPEDEF);
2860 type->typedeft.typedefe = &entity->typedefe;
2868 goto finish_specifiers;
2873 type = typedef_type;
2877 /* function specifier */
2879 goto finish_specifiers;
2884 specifiers->attributes = parse_attributes(specifiers->attributes);
2886 if (type == NULL || (saw_error && type_specifiers != 0)) {
2887 atomic_type_kind_t atomic_type;
2889 /* match valid basic types */
2890 switch (type_specifiers) {
2891 case SPECIFIER_VOID:
2892 atomic_type = ATOMIC_TYPE_VOID;
2894 case SPECIFIER_WCHAR_T:
2895 atomic_type = ATOMIC_TYPE_WCHAR_T;
2897 case SPECIFIER_CHAR:
2898 atomic_type = ATOMIC_TYPE_CHAR;
2900 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2901 atomic_type = ATOMIC_TYPE_SCHAR;
2903 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2904 atomic_type = ATOMIC_TYPE_UCHAR;
2906 case SPECIFIER_SHORT:
2907 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2908 case SPECIFIER_SHORT | SPECIFIER_INT:
2909 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2910 atomic_type = ATOMIC_TYPE_SHORT;
2912 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2913 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2914 atomic_type = ATOMIC_TYPE_USHORT;
2917 case SPECIFIER_SIGNED:
2918 case SPECIFIER_SIGNED | SPECIFIER_INT:
2919 atomic_type = ATOMIC_TYPE_INT;
2921 case SPECIFIER_UNSIGNED:
2922 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2923 atomic_type = ATOMIC_TYPE_UINT;
2925 case SPECIFIER_LONG:
2926 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2927 case SPECIFIER_LONG | SPECIFIER_INT:
2928 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2929 atomic_type = ATOMIC_TYPE_LONG;
2931 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2932 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2933 atomic_type = ATOMIC_TYPE_ULONG;
2936 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2937 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2938 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2939 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2941 atomic_type = ATOMIC_TYPE_LONGLONG;
2942 goto warn_about_long_long;
2944 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2945 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2947 atomic_type = ATOMIC_TYPE_ULONGLONG;
2948 warn_about_long_long:
2949 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2952 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2953 atomic_type = unsigned_int8_type_kind;
2956 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2957 atomic_type = unsigned_int16_type_kind;
2960 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2961 atomic_type = unsigned_int32_type_kind;
2964 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2965 atomic_type = unsigned_int64_type_kind;
2968 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2969 atomic_type = unsigned_int128_type_kind;
2972 case SPECIFIER_INT8:
2973 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2974 atomic_type = int8_type_kind;
2977 case SPECIFIER_INT16:
2978 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2979 atomic_type = int16_type_kind;
2982 case SPECIFIER_INT32:
2983 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2984 atomic_type = int32_type_kind;
2987 case SPECIFIER_INT64:
2988 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2989 atomic_type = int64_type_kind;
2992 case SPECIFIER_INT128:
2993 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2994 atomic_type = int128_type_kind;
2997 case SPECIFIER_FLOAT:
2998 atomic_type = ATOMIC_TYPE_FLOAT;
3000 case SPECIFIER_DOUBLE:
3001 atomic_type = ATOMIC_TYPE_DOUBLE;
3003 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3004 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3006 case SPECIFIER_BOOL:
3007 atomic_type = ATOMIC_TYPE_BOOL;
3009 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3010 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3011 atomic_type = ATOMIC_TYPE_FLOAT;
3013 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3014 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3015 atomic_type = ATOMIC_TYPE_DOUBLE;
3017 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3018 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3019 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3022 /* invalid specifier combination, give an error message */
3023 source_position_t const* const pos = &specifiers->source_position;
3024 if (type_specifiers == 0) {
3026 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3027 if (!(c_mode & _CXX) && !strict_mode) {
3028 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3029 atomic_type = ATOMIC_TYPE_INT;
3032 errorf(pos, "no type specifiers given in declaration");
3035 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3036 (type_specifiers & SPECIFIER_UNSIGNED)) {
3037 errorf(pos, "signed and unsigned specifiers given");
3038 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3039 errorf(pos, "only integer types can be signed or unsigned");
3041 errorf(pos, "multiple datatypes in declaration");
3047 if (type_specifiers & SPECIFIER_COMPLEX) {
3048 type = allocate_type_zero(TYPE_COMPLEX);
3049 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3050 type = allocate_type_zero(TYPE_IMAGINARY);
3052 type = allocate_type_zero(TYPE_ATOMIC);
3054 type->atomic.akind = atomic_type;
3056 } else if (type_specifiers != 0) {
3057 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3060 /* FIXME: check type qualifiers here */
3061 type->base.qualifiers = qualifiers;
3064 type = identify_new_type(type);
3066 type = typehash_insert(type);
3069 if (specifiers->attributes != NULL)
3070 type = handle_type_attributes(specifiers->attributes, type);
3071 specifiers->type = type;
3075 specifiers->type = type_error_type;
3078 static type_qualifiers_t parse_type_qualifiers(void)
3080 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3083 switch (token.kind) {
3084 /* type qualifiers */
3085 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3086 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3087 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3088 /* microsoft extended type modifiers */
3089 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3090 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3091 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3092 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3093 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3102 * Parses an K&R identifier list
3104 static void parse_identifier_list(scope_t *scope)
3106 assert(token.kind == T_IDENTIFIER);
3108 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3109 /* a K&R parameter has no type, yet */
3113 append_entity(scope, entity);
3114 } while (next_if(',') && token.kind == T_IDENTIFIER);
3117 static entity_t *parse_parameter(void)
3119 declaration_specifiers_t specifiers;
3120 parse_declaration_specifiers(&specifiers);
3122 entity_t *entity = parse_declarator(&specifiers,
3123 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3124 anonymous_entity = NULL;
3128 static void semantic_parameter_incomplete(const entity_t *entity)
3130 assert(entity->kind == ENTITY_PARAMETER);
3132 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3133 * list in a function declarator that is part of a
3134 * definition of that function shall not have
3135 * incomplete type. */
3136 type_t *type = skip_typeref(entity->declaration.type);
3137 if (is_type_incomplete(type)) {
3138 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3142 static bool has_parameters(void)
3144 /* func(void) is not a parameter */
3145 if (look_ahead(1)->kind != ')')
3147 if (token.kind == T_IDENTIFIER) {
3148 entity_t const *const entity
3149 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3152 if (entity->kind != ENTITY_TYPEDEF)
3154 type_t const *const type = skip_typeref(entity->typedefe.type);
3155 if (!is_type_void(type))
3157 if (c_mode & _CXX) {
3158 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3159 * is not allowed. */
3160 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3161 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3162 /* §6.7.5.3:10 Qualification is not allowed here. */
3163 errorf(HERE, "'void' as parameter must not have type qualifiers");
3165 } else if (token.kind != T_void) {
3173 * Parses function type parameters (and optionally creates variable_t entities
3174 * for them in a scope)
3176 static void parse_parameters(function_type_t *type, scope_t *scope)
3179 add_anchor_token(')');
3181 if (token.kind == T_IDENTIFIER &&
3182 !is_typedef_symbol(token.identifier.symbol) &&
3183 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3184 type->kr_style_parameters = true;
3185 parse_identifier_list(scope);
3186 } else if (token.kind == ')') {
3187 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3188 if (!(c_mode & _CXX))
3189 type->unspecified_parameters = true;
3190 } else if (has_parameters()) {
3191 function_parameter_t **anchor = &type->parameters;
3192 add_anchor_token(',');
3194 switch (token.kind) {
3197 type->variadic = true;
3198 goto parameters_finished;
3203 entity_t *entity = parse_parameter();
3204 if (entity->kind == ENTITY_TYPEDEF) {
3205 errorf(&entity->base.source_position,
3206 "typedef not allowed as function parameter");
3209 assert(is_declaration(entity));
3211 semantic_parameter_incomplete(entity);
3213 function_parameter_t *const parameter =
3214 allocate_parameter(entity->declaration.type);
3216 if (scope != NULL) {
3217 append_entity(scope, entity);
3220 *anchor = parameter;
3221 anchor = ¶meter->next;
3226 goto parameters_finished;
3228 } while (next_if(','));
3229 parameters_finished:
3230 rem_anchor_token(',');
3233 rem_anchor_token(')');
3237 typedef enum construct_type_kind_t {
3238 CONSTRUCT_POINTER = 1,
3239 CONSTRUCT_REFERENCE,
3242 } construct_type_kind_t;
3244 typedef union construct_type_t construct_type_t;
3246 typedef struct construct_type_base_t {
3247 construct_type_kind_t kind;
3248 source_position_t pos;
3249 construct_type_t *next;
3250 } construct_type_base_t;
3252 typedef struct parsed_pointer_t {
3253 construct_type_base_t base;
3254 type_qualifiers_t type_qualifiers;
3255 variable_t *base_variable; /**< MS __based extension. */
3258 typedef struct parsed_reference_t {
3259 construct_type_base_t base;
3260 } parsed_reference_t;
3262 typedef struct construct_function_type_t {
3263 construct_type_base_t base;
3264 type_t *function_type;
3265 } construct_function_type_t;
3267 typedef struct parsed_array_t {
3268 construct_type_base_t base;
3269 type_qualifiers_t type_qualifiers;
3275 union construct_type_t {
3276 construct_type_kind_t kind;
3277 construct_type_base_t base;
3278 parsed_pointer_t pointer;
3279 parsed_reference_t reference;
3280 construct_function_type_t function;
3281 parsed_array_t array;
3284 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3286 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3287 memset(cons, 0, size);
3289 cons->base.pos = *HERE;
3294 static construct_type_t *parse_pointer_declarator(void)
3296 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3298 cons->pointer.type_qualifiers = parse_type_qualifiers();
3299 //cons->pointer.base_variable = base_variable;
3304 /* ISO/IEC 14882:1998(E) §8.3.2 */
3305 static construct_type_t *parse_reference_declarator(void)
3307 if (!(c_mode & _CXX))
3308 errorf(HERE, "references are only available for C++");
3310 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3317 static construct_type_t *parse_array_declarator(void)
3319 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3320 parsed_array_t *const array = &cons->array;
3323 add_anchor_token(']');
3325 bool is_static = next_if(T_static);
3327 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3330 is_static = next_if(T_static);
3332 array->type_qualifiers = type_qualifiers;
3333 array->is_static = is_static;
3335 expression_t *size = NULL;
3336 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3337 array->is_variable = true;
3339 } else if (token.kind != ']') {
3340 size = parse_assignment_expression();
3342 /* §6.7.5.2:1 Array size must have integer type */
3343 type_t *const orig_type = size->base.type;
3344 type_t *const type = skip_typeref(orig_type);
3345 if (!is_type_integer(type) && is_type_valid(type)) {
3346 errorf(&size->base.source_position,
3347 "array size '%E' must have integer type but has type '%T'",
3352 mark_vars_read(size, NULL);
3355 if (is_static && size == NULL)
3356 errorf(&array->base.pos, "static array parameters require a size");
3358 rem_anchor_token(']');
3364 static construct_type_t *parse_function_declarator(scope_t *scope)
3366 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3368 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3369 function_type_t *ftype = &type->function;
3371 ftype->linkage = current_linkage;
3372 ftype->calling_convention = CC_DEFAULT;
3374 parse_parameters(ftype, scope);
3376 cons->function.function_type = type;
3381 typedef struct parse_declarator_env_t {
3382 bool may_be_abstract : 1;
3383 bool must_be_abstract : 1;
3384 decl_modifiers_t modifiers;
3386 source_position_t source_position;
3388 attribute_t *attributes;
3389 } parse_declarator_env_t;
3392 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3394 /* construct a single linked list of construct_type_t's which describe
3395 * how to construct the final declarator type */
3396 construct_type_t *first = NULL;
3397 construct_type_t **anchor = &first;
3399 env->attributes = parse_attributes(env->attributes);
3402 construct_type_t *type;
3403 //variable_t *based = NULL; /* MS __based extension */
3404 switch (token.kind) {
3406 type = parse_reference_declarator();
3410 panic("based not supported anymore");
3415 type = parse_pointer_declarator();
3419 goto ptr_operator_end;
3423 anchor = &type->base.next;
3425 /* TODO: find out if this is correct */
3426 env->attributes = parse_attributes(env->attributes);
3430 construct_type_t *inner_types = NULL;
3432 switch (token.kind) {
3434 if (env->must_be_abstract) {
3435 errorf(HERE, "no identifier expected in typename");
3437 env->symbol = token.identifier.symbol;
3438 env->source_position = token.base.source_position;
3444 /* Parenthesized declarator or function declarator? */
3445 token_t const *const la1 = look_ahead(1);
3446 switch (la1->kind) {
3448 if (is_typedef_symbol(la1->identifier.symbol)) {
3450 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3451 * interpreted as ``function with no parameter specification'', rather
3452 * than redundant parentheses around the omitted identifier. */
3454 /* Function declarator. */
3455 if (!env->may_be_abstract) {
3456 errorf(HERE, "function declarator must have a name");
3463 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3464 /* Paranthesized declarator. */
3466 add_anchor_token(')');
3467 inner_types = parse_inner_declarator(env);
3468 if (inner_types != NULL) {
3469 /* All later declarators only modify the return type */
3470 env->must_be_abstract = true;
3472 rem_anchor_token(')');
3481 if (env->may_be_abstract)
3483 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3488 construct_type_t **const p = anchor;
3491 construct_type_t *type;
3492 switch (token.kind) {
3494 scope_t *scope = NULL;
3495 if (!env->must_be_abstract) {
3496 scope = &env->parameters;
3499 type = parse_function_declarator(scope);
3503 type = parse_array_declarator();
3506 goto declarator_finished;
3509 /* insert in the middle of the list (at p) */
3510 type->base.next = *p;
3513 anchor = &type->base.next;
3516 declarator_finished:
3517 /* append inner_types at the end of the list, we don't to set anchor anymore
3518 * as it's not needed anymore */
3519 *anchor = inner_types;
3524 static type_t *construct_declarator_type(construct_type_t *construct_list,
3527 construct_type_t *iter = construct_list;
3528 for (; iter != NULL; iter = iter->base.next) {
3529 source_position_t const* const pos = &iter->base.pos;
3530 switch (iter->kind) {
3531 case CONSTRUCT_FUNCTION: {
3532 construct_function_type_t *function = &iter->function;
3533 type_t *function_type = function->function_type;
3535 function_type->function.return_type = type;
3537 type_t *skipped_return_type = skip_typeref(type);
3539 if (is_type_function(skipped_return_type)) {
3540 errorf(pos, "function returning function is not allowed");
3541 } else if (is_type_array(skipped_return_type)) {
3542 errorf(pos, "function returning array is not allowed");
3544 if (skipped_return_type->base.qualifiers != 0) {
3545 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3549 /* The function type was constructed earlier. Freeing it here will
3550 * destroy other types. */
3551 type = typehash_insert(function_type);
3555 case CONSTRUCT_POINTER: {
3556 if (is_type_reference(skip_typeref(type)))
3557 errorf(pos, "cannot declare a pointer to reference");
3559 parsed_pointer_t *pointer = &iter->pointer;
3560 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3564 case CONSTRUCT_REFERENCE:
3565 if (is_type_reference(skip_typeref(type)))
3566 errorf(pos, "cannot declare a reference to reference");
3568 type = make_reference_type(type);
3571 case CONSTRUCT_ARRAY: {
3572 if (is_type_reference(skip_typeref(type)))
3573 errorf(pos, "cannot declare an array of references");
3575 parsed_array_t *array = &iter->array;
3576 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3578 expression_t *size_expression = array->size;
3579 if (size_expression != NULL) {
3581 = create_implicit_cast(size_expression, type_size_t);
3584 array_type->base.qualifiers = array->type_qualifiers;
3585 array_type->array.element_type = type;
3586 array_type->array.is_static = array->is_static;
3587 array_type->array.is_variable = array->is_variable;
3588 array_type->array.size_expression = size_expression;
3590 if (size_expression != NULL) {
3591 switch (is_constant_expression(size_expression)) {
3592 case EXPR_CLASS_CONSTANT: {
3593 long const size = fold_constant_to_int(size_expression);
3594 array_type->array.size = size;
3595 array_type->array.size_constant = true;
3596 /* §6.7.5.2:1 If the expression is a constant expression,
3597 * it shall have a value greater than zero. */
3599 errorf(&size_expression->base.source_position,
3600 "size of array must be greater than zero");
3601 } else if (size == 0 && !GNU_MODE) {
3602 errorf(&size_expression->base.source_position,
3603 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3608 case EXPR_CLASS_VARIABLE:
3609 array_type->array.is_vla = true;
3612 case EXPR_CLASS_ERROR:
3617 type_t *skipped_type = skip_typeref(type);
3619 if (is_type_incomplete(skipped_type)) {
3620 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3621 } else if (is_type_function(skipped_type)) {
3622 errorf(pos, "array of functions is not allowed");
3624 type = identify_new_type(array_type);
3628 internal_errorf(pos, "invalid type construction found");
3634 static type_t *automatic_type_conversion(type_t *orig_type);
3636 static type_t *semantic_parameter(const source_position_t *pos,
3638 const declaration_specifiers_t *specifiers,
3639 entity_t const *const param)
3641 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3642 * shall be adjusted to ``qualified pointer to type'',
3644 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3645 * type'' shall be adjusted to ``pointer to function
3646 * returning type'', as in 6.3.2.1. */
3647 type = automatic_type_conversion(type);
3649 if (specifiers->is_inline && is_type_valid(type)) {
3650 errorf(pos, "'%N' declared 'inline'", param);
3653 /* §6.9.1:6 The declarations in the declaration list shall contain
3654 * no storage-class specifier other than register and no
3655 * initializations. */
3656 if (specifiers->thread_local || (
3657 specifiers->storage_class != STORAGE_CLASS_NONE &&
3658 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3660 errorf(pos, "invalid storage class for '%N'", param);
3663 /* delay test for incomplete type, because we might have (void)
3664 * which is legal but incomplete... */
3669 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3670 declarator_flags_t flags)
3672 parse_declarator_env_t env;
3673 memset(&env, 0, sizeof(env));
3674 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3676 construct_type_t *construct_type = parse_inner_declarator(&env);
3678 construct_declarator_type(construct_type, specifiers->type);
3679 type_t *type = skip_typeref(orig_type);
3681 if (construct_type != NULL) {
3682 obstack_free(&temp_obst, construct_type);
3685 attribute_t *attributes = parse_attributes(env.attributes);
3686 /* append (shared) specifier attribute behind attributes of this
3688 attribute_t **anchor = &attributes;
3689 while (*anchor != NULL)
3690 anchor = &(*anchor)->next;
3691 *anchor = specifiers->attributes;
3694 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3695 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3696 entity->typedefe.type = orig_type;
3698 if (anonymous_entity != NULL) {
3699 if (is_type_compound(type)) {
3700 assert(anonymous_entity->compound.alias == NULL);
3701 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3702 anonymous_entity->kind == ENTITY_UNION);
3703 anonymous_entity->compound.alias = entity;
3704 anonymous_entity = NULL;
3705 } else if (is_type_enum(type)) {
3706 assert(anonymous_entity->enume.alias == NULL);
3707 assert(anonymous_entity->kind == ENTITY_ENUM);
3708 anonymous_entity->enume.alias = entity;
3709 anonymous_entity = NULL;
3713 /* create a declaration type entity */
3714 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3715 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3716 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3718 if (env.symbol != NULL) {
3719 if (specifiers->is_inline && is_type_valid(type)) {
3720 errorf(&env.source_position,
3721 "compound member '%Y' declared 'inline'", env.symbol);
3724 if (specifiers->thread_local ||
3725 specifiers->storage_class != STORAGE_CLASS_NONE) {
3726 errorf(&env.source_position,
3727 "compound member '%Y' must have no storage class",
3731 } else if (flags & DECL_IS_PARAMETER) {
3732 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3733 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3734 } else if (is_type_function(type)) {
3735 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3736 entity->function.is_inline = specifiers->is_inline;
3737 entity->function.elf_visibility = default_visibility;
3738 entity->function.parameters = env.parameters;
3740 if (env.symbol != NULL) {
3741 /* this needs fixes for C++ */
3742 bool in_function_scope = current_function != NULL;
3744 if (specifiers->thread_local || (
3745 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3746 specifiers->storage_class != STORAGE_CLASS_NONE &&
3747 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3749 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3753 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3754 entity->variable.elf_visibility = default_visibility;
3755 entity->variable.thread_local = specifiers->thread_local;
3757 if (env.symbol != NULL) {
3758 if (specifiers->is_inline && is_type_valid(type)) {
3759 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3762 bool invalid_storage_class = false;
3763 if (current_scope == file_scope) {
3764 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3765 specifiers->storage_class != STORAGE_CLASS_NONE &&
3766 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3767 invalid_storage_class = true;
3770 if (specifiers->thread_local &&
3771 specifiers->storage_class == STORAGE_CLASS_NONE) {
3772 invalid_storage_class = true;
3775 if (invalid_storage_class) {
3776 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3781 entity->declaration.type = orig_type;
3782 entity->declaration.alignment = get_type_alignment(orig_type);
3783 entity->declaration.modifiers = env.modifiers;
3784 entity->declaration.attributes = attributes;
3786 storage_class_t storage_class = specifiers->storage_class;
3787 entity->declaration.declared_storage_class = storage_class;
3789 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3790 storage_class = STORAGE_CLASS_AUTO;
3791 entity->declaration.storage_class = storage_class;
3794 if (attributes != NULL) {
3795 handle_entity_attributes(attributes, entity);
3798 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3799 adapt_special_functions(&entity->function);
3805 static type_t *parse_abstract_declarator(type_t *base_type)
3807 parse_declarator_env_t env;
3808 memset(&env, 0, sizeof(env));
3809 env.may_be_abstract = true;
3810 env.must_be_abstract = true;
3812 construct_type_t *construct_type = parse_inner_declarator(&env);
3814 type_t *result = construct_declarator_type(construct_type, base_type);
3815 if (construct_type != NULL) {
3816 obstack_free(&temp_obst, construct_type);
3818 result = handle_type_attributes(env.attributes, result);
3824 * Check if the declaration of main is suspicious. main should be a
3825 * function with external linkage, returning int, taking either zero
3826 * arguments, two, or three arguments of appropriate types, ie.
3828 * int main([ int argc, char **argv [, char **env ] ]).
3830 * @param decl the declaration to check
3831 * @param type the function type of the declaration
3833 static void check_main(const entity_t *entity)
3835 const source_position_t *pos = &entity->base.source_position;
3836 if (entity->kind != ENTITY_FUNCTION) {
3837 warningf(WARN_MAIN, pos, "'main' is not a function");
3841 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3842 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3845 type_t *type = skip_typeref(entity->declaration.type);
3846 assert(is_type_function(type));
3848 function_type_t const *const func_type = &type->function;
3849 type_t *const ret_type = func_type->return_type;
3850 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3851 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3853 const function_parameter_t *parm = func_type->parameters;
3855 type_t *const first_type = skip_typeref(parm->type);
3856 type_t *const first_type_unqual = get_unqualified_type(first_type);
3857 if (!types_compatible(first_type_unqual, type_int)) {
3858 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3862 type_t *const second_type = skip_typeref(parm->type);
3863 type_t *const second_type_unqual
3864 = get_unqualified_type(second_type);
3865 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3866 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3870 type_t *const third_type = skip_typeref(parm->type);
3871 type_t *const third_type_unqual
3872 = get_unqualified_type(third_type);
3873 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3874 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3878 goto warn_arg_count;
3882 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3887 static void error_redefined_as_different_kind(const source_position_t *pos,
3888 const entity_t *old, entity_kind_t new_kind)
3890 char const *const what = get_entity_kind_name(new_kind);
3891 source_position_t const *const ppos = &old->base.source_position;
3892 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3895 static bool is_entity_valid(entity_t *const ent)
3897 if (is_declaration(ent)) {
3898 return is_type_valid(skip_typeref(ent->declaration.type));
3899 } else if (ent->kind == ENTITY_TYPEDEF) {
3900 return is_type_valid(skip_typeref(ent->typedefe.type));
3905 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3907 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3908 if (attributes_equal(tattr, attr))
3915 * test wether new_list contains any attributes not included in old_list
3917 static bool has_new_attributes(const attribute_t *old_list,
3918 const attribute_t *new_list)
3920 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3921 if (!contains_attribute(old_list, attr))
3928 * Merge in attributes from an attribute list (probably from a previous
3929 * declaration with the same name). Warning: destroys the old structure
3930 * of the attribute list - don't reuse attributes after this call.
3932 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3935 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3937 if (contains_attribute(decl->attributes, attr))
3940 /* move attribute to new declarations attributes list */
3941 attr->next = decl->attributes;
3942 decl->attributes = attr;
3946 static bool is_main(entity_t*);
3949 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3950 * for various problems that occur for multiple definitions
3952 entity_t *record_entity(entity_t *entity, const bool is_definition)
3954 const symbol_t *const symbol = entity->base.symbol;
3955 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3956 const source_position_t *pos = &entity->base.source_position;
3958 /* can happen in error cases */
3962 assert(!entity->base.parent_scope);
3963 assert(current_scope);
3964 entity->base.parent_scope = current_scope;
3966 entity_t *const previous_entity = get_entity(symbol, namespc);
3967 /* pushing the same entity twice will break the stack structure */
3968 assert(previous_entity != entity);
3970 if (entity->kind == ENTITY_FUNCTION) {
3971 type_t *const orig_type = entity->declaration.type;
3972 type_t *const type = skip_typeref(orig_type);
3974 assert(is_type_function(type));
3975 if (type->function.unspecified_parameters &&
3976 previous_entity == NULL &&
3977 !entity->declaration.implicit) {
3978 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3981 if (is_main(entity)) {
3986 if (is_declaration(entity) &&
3987 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3988 current_scope != file_scope &&
3989 !entity->declaration.implicit) {
3990 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3993 if (previous_entity != NULL) {
3994 source_position_t const *const ppos = &previous_entity->base.source_position;
3996 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3997 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3998 assert(previous_entity->kind == ENTITY_PARAMETER);
3999 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4003 if (previous_entity->base.parent_scope == current_scope) {
4004 if (previous_entity->kind != entity->kind) {
4005 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4006 error_redefined_as_different_kind(pos, previous_entity,
4011 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4012 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4015 if (previous_entity->kind == ENTITY_TYPEDEF) {
4016 type_t *const type = skip_typeref(entity->typedefe.type);
4017 type_t *const prev_type
4018 = skip_typeref(previous_entity->typedefe.type);
4019 if (c_mode & _CXX) {
4020 /* C++ allows double typedef if they are identical
4021 * (after skipping typedefs) */
4022 if (type == prev_type)
4025 /* GCC extension: redef in system headers is allowed */
4026 if ((pos->is_system_header || ppos->is_system_header) &&
4027 types_compatible(type, prev_type))
4030 errorf(pos, "redefinition of '%N' (declared %P)",
4035 /* at this point we should have only VARIABLES or FUNCTIONS */
4036 assert(is_declaration(previous_entity) && is_declaration(entity));
4038 declaration_t *const prev_decl = &previous_entity->declaration;
4039 declaration_t *const decl = &entity->declaration;
4041 /* can happen for K&R style declarations */
4042 if (prev_decl->type == NULL &&
4043 previous_entity->kind == ENTITY_PARAMETER &&
4044 entity->kind == ENTITY_PARAMETER) {
4045 prev_decl->type = decl->type;
4046 prev_decl->storage_class = decl->storage_class;
4047 prev_decl->declared_storage_class = decl->declared_storage_class;
4048 prev_decl->modifiers = decl->modifiers;
4049 return previous_entity;
4052 type_t *const type = skip_typeref(decl->type);
4053 type_t *const prev_type = skip_typeref(prev_decl->type);
4055 if (!types_compatible(type, prev_type)) {
4056 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4058 unsigned old_storage_class = prev_decl->storage_class;
4060 if (is_definition &&
4062 !(prev_decl->modifiers & DM_USED) &&
4063 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4064 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4067 storage_class_t new_storage_class = decl->storage_class;
4069 /* pretend no storage class means extern for function
4070 * declarations (except if the previous declaration is neither
4071 * none nor extern) */
4072 if (entity->kind == ENTITY_FUNCTION) {
4073 /* the previous declaration could have unspecified parameters or
4074 * be a typedef, so use the new type */
4075 if (prev_type->function.unspecified_parameters || is_definition)
4076 prev_decl->type = type;
4078 switch (old_storage_class) {
4079 case STORAGE_CLASS_NONE:
4080 old_storage_class = STORAGE_CLASS_EXTERN;
4083 case STORAGE_CLASS_EXTERN:
4084 if (is_definition) {
4085 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4086 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4088 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4089 new_storage_class = STORAGE_CLASS_EXTERN;
4096 } else if (is_type_incomplete(prev_type)) {
4097 prev_decl->type = type;
4100 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4101 new_storage_class == STORAGE_CLASS_EXTERN) {
4103 warn_redundant_declaration: ;
4105 = has_new_attributes(prev_decl->attributes,
4107 if (has_new_attrs) {
4108 merge_in_attributes(decl, prev_decl->attributes);
4109 } else if (!is_definition &&
4110 is_type_valid(prev_type) &&
4111 !pos->is_system_header) {
4112 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4114 } else if (current_function == NULL) {
4115 if (old_storage_class != STORAGE_CLASS_STATIC &&
4116 new_storage_class == STORAGE_CLASS_STATIC) {
4117 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4118 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4119 prev_decl->storage_class = STORAGE_CLASS_NONE;
4120 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4122 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4124 goto error_redeclaration;
4125 goto warn_redundant_declaration;
4127 } else if (is_type_valid(prev_type)) {
4128 if (old_storage_class == new_storage_class) {
4129 error_redeclaration:
4130 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4132 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4137 prev_decl->modifiers |= decl->modifiers;
4138 if (entity->kind == ENTITY_FUNCTION) {
4139 previous_entity->function.is_inline |= entity->function.is_inline;
4141 return previous_entity;
4145 if (is_warn_on(why = WARN_SHADOW) ||
4146 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4147 char const *const what = get_entity_kind_name(previous_entity->kind);
4148 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4152 if (entity->kind == ENTITY_FUNCTION) {
4153 if (is_definition &&
4154 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4156 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4157 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4159 goto warn_missing_declaration;
4162 } else if (entity->kind == ENTITY_VARIABLE) {
4163 if (current_scope == file_scope &&
4164 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4165 !entity->declaration.implicit) {
4166 warn_missing_declaration:
4167 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4172 environment_push(entity);
4173 append_entity(current_scope, entity);
4178 static void parser_error_multiple_definition(entity_t *entity,
4179 const source_position_t *source_position)
4181 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4182 entity->base.symbol, &entity->base.source_position);
4185 static bool is_declaration_specifier(const token_t *token)
4187 switch (token->kind) {
4191 return is_typedef_symbol(token->identifier.symbol);
4198 static void parse_init_declarator_rest(entity_t *entity)
4200 type_t *orig_type = type_error_type;
4202 if (entity->base.kind == ENTITY_TYPEDEF) {
4203 source_position_t const *const pos = &entity->base.source_position;
4204 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4206 assert(is_declaration(entity));
4207 orig_type = entity->declaration.type;
4210 type_t *type = skip_typeref(orig_type);
4212 if (entity->kind == ENTITY_VARIABLE
4213 && entity->variable.initializer != NULL) {
4214 parser_error_multiple_definition(entity, HERE);
4218 declaration_t *const declaration = &entity->declaration;
4219 bool must_be_constant = false;
4220 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4221 entity->base.parent_scope == file_scope) {
4222 must_be_constant = true;
4225 if (is_type_function(type)) {
4226 source_position_t const *const pos = &entity->base.source_position;
4227 errorf(pos, "'%N' is initialized like a variable", entity);
4228 orig_type = type_error_type;
4231 parse_initializer_env_t env;
4232 env.type = orig_type;
4233 env.must_be_constant = must_be_constant;
4234 env.entity = entity;
4236 initializer_t *initializer = parse_initializer(&env);
4238 if (entity->kind == ENTITY_VARIABLE) {
4239 /* §6.7.5:22 array initializers for arrays with unknown size
4240 * determine the array type size */
4241 declaration->type = env.type;
4242 entity->variable.initializer = initializer;
4246 /* parse rest of a declaration without any declarator */
4247 static void parse_anonymous_declaration_rest(
4248 const declaration_specifiers_t *specifiers)
4251 anonymous_entity = NULL;
4253 source_position_t const *const pos = &specifiers->source_position;
4254 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4255 specifiers->thread_local) {
4256 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4259 type_t *type = specifiers->type;
4260 switch (type->kind) {
4261 case TYPE_COMPOUND_STRUCT:
4262 case TYPE_COMPOUND_UNION: {
4263 if (type->compound.compound->base.symbol == NULL) {
4264 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4273 warningf(WARN_OTHER, pos, "empty declaration");
4278 static void check_variable_type_complete(entity_t *ent)
4280 if (ent->kind != ENTITY_VARIABLE)
4283 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4284 * type for the object shall be complete [...] */
4285 declaration_t *decl = &ent->declaration;
4286 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4287 decl->storage_class == STORAGE_CLASS_STATIC)
4290 type_t *const type = skip_typeref(decl->type);
4291 if (!is_type_incomplete(type))
4294 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4295 * are given length one. */
4296 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4297 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4301 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4305 static void parse_declaration_rest(entity_t *ndeclaration,
4306 const declaration_specifiers_t *specifiers,
4307 parsed_declaration_func finished_declaration,
4308 declarator_flags_t flags)
4310 add_anchor_token(';');
4311 add_anchor_token(',');
4313 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4315 if (token.kind == '=') {
4316 parse_init_declarator_rest(entity);
4317 } else if (entity->kind == ENTITY_VARIABLE) {
4318 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4319 * [...] where the extern specifier is explicitly used. */
4320 declaration_t *decl = &entity->declaration;
4321 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4322 is_type_reference(skip_typeref(decl->type))) {
4323 source_position_t const *const pos = &entity->base.source_position;
4324 errorf(pos, "reference '%#N' must be initialized", entity);
4328 check_variable_type_complete(entity);
4333 add_anchor_token('=');
4334 ndeclaration = parse_declarator(specifiers, flags);
4335 rem_anchor_token('=');
4337 rem_anchor_token(',');
4338 rem_anchor_token(';');
4341 anonymous_entity = NULL;
4344 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4346 symbol_t *symbol = entity->base.symbol;
4350 assert(entity->base.namespc == NAMESPACE_NORMAL);
4351 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4352 if (previous_entity == NULL
4353 || previous_entity->base.parent_scope != current_scope) {
4354 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4359 if (is_definition) {
4360 errorf(HERE, "'%N' is initialised", entity);
4363 return record_entity(entity, false);
4366 static void parse_declaration(parsed_declaration_func finished_declaration,
4367 declarator_flags_t flags)
4369 add_anchor_token(';');
4370 declaration_specifiers_t specifiers;
4371 parse_declaration_specifiers(&specifiers);
4372 rem_anchor_token(';');
4374 if (token.kind == ';') {
4375 parse_anonymous_declaration_rest(&specifiers);
4377 entity_t *entity = parse_declarator(&specifiers, flags);
4378 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4383 static type_t *get_default_promoted_type(type_t *orig_type)
4385 type_t *result = orig_type;
4387 type_t *type = skip_typeref(orig_type);
4388 if (is_type_integer(type)) {
4389 result = promote_integer(type);
4390 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4391 result = type_double;
4397 static void parse_kr_declaration_list(entity_t *entity)
4399 if (entity->kind != ENTITY_FUNCTION)
4402 type_t *type = skip_typeref(entity->declaration.type);
4403 assert(is_type_function(type));
4404 if (!type->function.kr_style_parameters)
4407 add_anchor_token('{');
4409 PUSH_SCOPE(&entity->function.parameters);
4411 entity_t *parameter = entity->function.parameters.entities;
4412 for ( ; parameter != NULL; parameter = parameter->base.next) {
4413 assert(parameter->base.parent_scope == NULL);
4414 parameter->base.parent_scope = current_scope;
4415 environment_push(parameter);
4418 /* parse declaration list */
4420 switch (token.kind) {
4422 /* This covers symbols, which are no type, too, and results in
4423 * better error messages. The typical cases are misspelled type
4424 * names and missing includes. */
4426 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4436 /* update function type */
4437 type_t *new_type = duplicate_type(type);
4439 function_parameter_t *parameters = NULL;
4440 function_parameter_t **anchor = ¶meters;
4442 /* did we have an earlier prototype? */
4443 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4444 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4447 function_parameter_t *proto_parameter = NULL;
4448 if (proto_type != NULL) {
4449 type_t *proto_type_type = proto_type->declaration.type;
4450 proto_parameter = proto_type_type->function.parameters;
4451 /* If a K&R function definition has a variadic prototype earlier, then
4452 * make the function definition variadic, too. This should conform to
4453 * §6.7.5.3:15 and §6.9.1:8. */
4454 new_type->function.variadic = proto_type_type->function.variadic;
4456 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4458 new_type->function.unspecified_parameters = true;
4461 bool need_incompatible_warning = false;
4462 parameter = entity->function.parameters.entities;
4463 for (; parameter != NULL; parameter = parameter->base.next,
4465 proto_parameter == NULL ? NULL : proto_parameter->next) {
4466 if (parameter->kind != ENTITY_PARAMETER)
4469 type_t *parameter_type = parameter->declaration.type;
4470 if (parameter_type == NULL) {
4471 source_position_t const* const pos = ¶meter->base.source_position;
4473 errorf(pos, "no type specified for function '%N'", parameter);
4474 parameter_type = type_error_type;
4476 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4477 parameter_type = type_int;
4479 parameter->declaration.type = parameter_type;
4482 semantic_parameter_incomplete(parameter);
4484 /* we need the default promoted types for the function type */
4485 type_t *not_promoted = parameter_type;
4486 parameter_type = get_default_promoted_type(parameter_type);
4488 /* gcc special: if the type of the prototype matches the unpromoted
4489 * type don't promote */
4490 if (!strict_mode && proto_parameter != NULL) {
4491 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4492 type_t *promo_skip = skip_typeref(parameter_type);
4493 type_t *param_skip = skip_typeref(not_promoted);
4494 if (!types_compatible(proto_p_type, promo_skip)
4495 && types_compatible(proto_p_type, param_skip)) {
4497 need_incompatible_warning = true;
4498 parameter_type = not_promoted;
4501 function_parameter_t *const function_parameter
4502 = allocate_parameter(parameter_type);
4504 *anchor = function_parameter;
4505 anchor = &function_parameter->next;
4508 new_type->function.parameters = parameters;
4509 new_type = identify_new_type(new_type);
4511 if (need_incompatible_warning) {
4512 symbol_t const *const sym = entity->base.symbol;
4513 source_position_t const *const pos = &entity->base.source_position;
4514 source_position_t const *const ppos = &proto_type->base.source_position;
4515 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4517 entity->declaration.type = new_type;
4519 rem_anchor_token('{');
4522 static bool first_err = true;
4525 * When called with first_err set, prints the name of the current function,
4528 static void print_in_function(void)
4532 char const *const file = current_function->base.base.source_position.input_name;
4533 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4538 * Check if all labels are defined in the current function.
4539 * Check if all labels are used in the current function.
4541 static void check_labels(void)
4543 for (const goto_statement_t *goto_statement = goto_first;
4544 goto_statement != NULL;
4545 goto_statement = goto_statement->next) {
4546 label_t *label = goto_statement->label;
4547 if (label->base.source_position.input_name == NULL) {
4548 print_in_function();
4549 source_position_t const *const pos = &goto_statement->base.source_position;
4550 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4554 if (is_warn_on(WARN_UNUSED_LABEL)) {
4555 for (const label_statement_t *label_statement = label_first;
4556 label_statement != NULL;
4557 label_statement = label_statement->next) {
4558 label_t *label = label_statement->label;
4560 if (! label->used) {
4561 print_in_function();
4562 source_position_t const *const pos = &label_statement->base.source_position;
4563 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4569 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4571 entity_t const *const end = last != NULL ? last->base.next : NULL;
4572 for (; entity != end; entity = entity->base.next) {
4573 if (!is_declaration(entity))
4576 declaration_t *declaration = &entity->declaration;
4577 if (declaration->implicit)
4580 if (!declaration->used) {
4581 print_in_function();
4582 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4583 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4584 print_in_function();
4585 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4590 static void check_unused_variables(statement_t *const stmt, void *const env)
4594 switch (stmt->kind) {
4595 case STATEMENT_DECLARATION: {
4596 declaration_statement_t const *const decls = &stmt->declaration;
4597 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4602 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4611 * Check declarations of current_function for unused entities.
4613 static void check_declarations(void)
4615 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4616 const scope_t *scope = ¤t_function->parameters;
4617 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4619 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4620 walk_statements(current_function->statement, check_unused_variables,
4625 static int determine_truth(expression_t const* const cond)
4628 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4629 fold_constant_to_bool(cond) ? 1 :
4633 static void check_reachable(statement_t *);
4634 static bool reaches_end;
4636 static bool expression_returns(expression_t const *const expr)
4638 switch (expr->kind) {
4640 expression_t const *const func = expr->call.function;
4641 type_t const *const type = skip_typeref(func->base.type);
4642 if (type->kind == TYPE_POINTER) {
4643 type_t const *const points_to
4644 = skip_typeref(type->pointer.points_to);
4645 if (points_to->kind == TYPE_FUNCTION
4646 && points_to->function.modifiers & DM_NORETURN)
4650 if (!expression_returns(func))
4653 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4654 if (!expression_returns(arg->expression))
4661 case EXPR_REFERENCE:
4662 case EXPR_ENUM_CONSTANT:
4663 case EXPR_LITERAL_CASES:
4664 case EXPR_STRING_LITERAL:
4665 case EXPR_WIDE_STRING_LITERAL:
4666 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4667 case EXPR_LABEL_ADDRESS:
4668 case EXPR_CLASSIFY_TYPE:
4669 case EXPR_SIZEOF: // TODO handle obscure VLA case
4672 case EXPR_BUILTIN_CONSTANT_P:
4673 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4678 case EXPR_STATEMENT: {
4679 bool old_reaches_end = reaches_end;
4680 reaches_end = false;
4681 check_reachable(expr->statement.statement);
4682 bool returns = reaches_end;
4683 reaches_end = old_reaches_end;
4687 case EXPR_CONDITIONAL:
4688 // TODO handle constant expression
4690 if (!expression_returns(expr->conditional.condition))
4693 if (expr->conditional.true_expression != NULL
4694 && expression_returns(expr->conditional.true_expression))
4697 return expression_returns(expr->conditional.false_expression);
4700 return expression_returns(expr->select.compound);
4702 case EXPR_ARRAY_ACCESS:
4704 expression_returns(expr->array_access.array_ref) &&
4705 expression_returns(expr->array_access.index);
4708 return expression_returns(expr->va_starte.ap);
4711 return expression_returns(expr->va_arge.ap);
4714 return expression_returns(expr->va_copye.src);
4716 case EXPR_UNARY_CASES_MANDATORY:
4717 return expression_returns(expr->unary.value);
4719 case EXPR_UNARY_THROW:
4722 case EXPR_BINARY_CASES:
4723 // TODO handle constant lhs of && and ||
4725 expression_returns(expr->binary.left) &&
4726 expression_returns(expr->binary.right);
4729 panic("unhandled expression");
4732 static bool initializer_returns(initializer_t const *const init)
4734 switch (init->kind) {
4735 case INITIALIZER_VALUE:
4736 return expression_returns(init->value.value);
4738 case INITIALIZER_LIST: {
4739 initializer_t * const* i = init->list.initializers;
4740 initializer_t * const* const end = i + init->list.len;
4741 bool returns = true;
4742 for (; i != end; ++i) {
4743 if (!initializer_returns(*i))
4749 case INITIALIZER_STRING:
4750 case INITIALIZER_WIDE_STRING:
4751 case INITIALIZER_DESIGNATOR: // designators have no payload
4754 panic("unhandled initializer");
4757 static bool noreturn_candidate;
4759 static void check_reachable(statement_t *const stmt)
4761 if (stmt->base.reachable)
4763 if (stmt->kind != STATEMENT_DO_WHILE)
4764 stmt->base.reachable = true;
4766 statement_t *last = stmt;
4768 switch (stmt->kind) {
4769 case STATEMENT_ERROR:
4770 case STATEMENT_EMPTY:
4772 next = stmt->base.next;
4775 case STATEMENT_DECLARATION: {
4776 declaration_statement_t const *const decl = &stmt->declaration;
4777 entity_t const * ent = decl->declarations_begin;
4778 entity_t const *const last_decl = decl->declarations_end;
4780 for (;; ent = ent->base.next) {
4781 if (ent->kind == ENTITY_VARIABLE &&
4782 ent->variable.initializer != NULL &&
4783 !initializer_returns(ent->variable.initializer)) {
4786 if (ent == last_decl)
4790 next = stmt->base.next;
4794 case STATEMENT_COMPOUND:
4795 next = stmt->compound.statements;
4797 next = stmt->base.next;
4800 case STATEMENT_RETURN: {
4801 expression_t const *const val = stmt->returns.value;
4802 if (val == NULL || expression_returns(val))
4803 noreturn_candidate = false;
4807 case STATEMENT_IF: {
4808 if_statement_t const *const ifs = &stmt->ifs;
4809 expression_t const *const cond = ifs->condition;
4811 if (!expression_returns(cond))
4814 int const val = determine_truth(cond);
4817 check_reachable(ifs->true_statement);
4822 if (ifs->false_statement != NULL) {
4823 check_reachable(ifs->false_statement);
4827 next = stmt->base.next;
4831 case STATEMENT_SWITCH: {
4832 switch_statement_t const *const switchs = &stmt->switchs;
4833 expression_t const *const expr = switchs->expression;
4835 if (!expression_returns(expr))
4838 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4839 long const val = fold_constant_to_int(expr);
4840 case_label_statement_t * defaults = NULL;
4841 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4842 if (i->expression == NULL) {
4847 if (i->first_case <= val && val <= i->last_case) {
4848 check_reachable((statement_t*)i);
4853 if (defaults != NULL) {
4854 check_reachable((statement_t*)defaults);
4858 bool has_default = false;
4859 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4860 if (i->expression == NULL)
4863 check_reachable((statement_t*)i);
4870 next = stmt->base.next;
4874 case STATEMENT_EXPRESSION: {
4875 /* Check for noreturn function call */
4876 expression_t const *const expr = stmt->expression.expression;
4877 if (!expression_returns(expr))
4880 next = stmt->base.next;
4884 case STATEMENT_CONTINUE:
4885 for (statement_t *parent = stmt;;) {
4886 parent = parent->base.parent;
4887 if (parent == NULL) /* continue not within loop */
4891 switch (parent->kind) {
4892 case STATEMENT_WHILE: goto continue_while;
4893 case STATEMENT_DO_WHILE: goto continue_do_while;
4894 case STATEMENT_FOR: goto continue_for;
4900 case STATEMENT_BREAK:
4901 for (statement_t *parent = stmt;;) {
4902 parent = parent->base.parent;
4903 if (parent == NULL) /* break not within loop/switch */
4906 switch (parent->kind) {
4907 case STATEMENT_SWITCH:
4908 case STATEMENT_WHILE:
4909 case STATEMENT_DO_WHILE:
4912 next = parent->base.next;
4913 goto found_break_parent;
4921 case STATEMENT_COMPUTED_GOTO: {
4922 if (!expression_returns(stmt->computed_goto.expression))
4925 statement_t *parent = stmt->base.parent;
4926 if (parent == NULL) /* top level goto */
4932 case STATEMENT_GOTO:
4933 next = stmt->gotos.label->statement;
4934 if (next == NULL) /* missing label */
4938 case STATEMENT_LABEL:
4939 next = stmt->label.statement;
4942 case STATEMENT_CASE_LABEL:
4943 next = stmt->case_label.statement;
4946 case STATEMENT_WHILE: {
4947 while_statement_t const *const whiles = &stmt->whiles;
4948 expression_t const *const cond = whiles->condition;
4950 if (!expression_returns(cond))
4953 int const val = determine_truth(cond);
4956 check_reachable(whiles->body);
4961 next = stmt->base.next;
4965 case STATEMENT_DO_WHILE:
4966 next = stmt->do_while.body;
4969 case STATEMENT_FOR: {
4970 for_statement_t *const fors = &stmt->fors;
4972 if (fors->condition_reachable)
4974 fors->condition_reachable = true;
4976 expression_t const *const cond = fors->condition;
4981 } else if (expression_returns(cond)) {
4982 val = determine_truth(cond);
4988 check_reachable(fors->body);
4993 next = stmt->base.next;
4997 case STATEMENT_MS_TRY: {
4998 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4999 check_reachable(ms_try->try_statement);
5000 next = ms_try->final_statement;
5004 case STATEMENT_LEAVE: {
5005 statement_t *parent = stmt;
5007 parent = parent->base.parent;
5008 if (parent == NULL) /* __leave not within __try */
5011 if (parent->kind == STATEMENT_MS_TRY) {
5013 next = parent->ms_try.final_statement;
5021 panic("invalid statement kind");
5024 while (next == NULL) {
5025 next = last->base.parent;
5027 noreturn_candidate = false;
5029 type_t *const type = skip_typeref(current_function->base.type);
5030 assert(is_type_function(type));
5031 type_t *const ret = skip_typeref(type->function.return_type);
5032 if (!is_type_void(ret) &&
5033 is_type_valid(ret) &&
5034 !is_main(current_entity)) {
5035 source_position_t const *const pos = &stmt->base.source_position;
5036 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5041 switch (next->kind) {
5042 case STATEMENT_ERROR:
5043 case STATEMENT_EMPTY:
5044 case STATEMENT_DECLARATION:
5045 case STATEMENT_EXPRESSION:
5047 case STATEMENT_RETURN:
5048 case STATEMENT_CONTINUE:
5049 case STATEMENT_BREAK:
5050 case STATEMENT_COMPUTED_GOTO:
5051 case STATEMENT_GOTO:
5052 case STATEMENT_LEAVE:
5053 panic("invalid control flow in function");
5055 case STATEMENT_COMPOUND:
5056 if (next->compound.stmt_expr) {
5062 case STATEMENT_SWITCH:
5063 case STATEMENT_LABEL:
5064 case STATEMENT_CASE_LABEL:
5066 next = next->base.next;
5069 case STATEMENT_WHILE: {
5071 if (next->base.reachable)
5073 next->base.reachable = true;
5075 while_statement_t const *const whiles = &next->whiles;
5076 expression_t const *const cond = whiles->condition;
5078 if (!expression_returns(cond))
5081 int const val = determine_truth(cond);
5084 check_reachable(whiles->body);
5090 next = next->base.next;
5094 case STATEMENT_DO_WHILE: {
5096 if (next->base.reachable)
5098 next->base.reachable = true;
5100 do_while_statement_t const *const dw = &next->do_while;
5101 expression_t const *const cond = dw->condition;
5103 if (!expression_returns(cond))
5106 int const val = determine_truth(cond);
5109 check_reachable(dw->body);
5115 next = next->base.next;
5119 case STATEMENT_FOR: {
5121 for_statement_t *const fors = &next->fors;
5123 fors->step_reachable = true;
5125 if (fors->condition_reachable)
5127 fors->condition_reachable = true;
5129 expression_t const *const cond = fors->condition;
5134 } else if (expression_returns(cond)) {
5135 val = determine_truth(cond);
5141 check_reachable(fors->body);
5147 next = next->base.next;
5151 case STATEMENT_MS_TRY:
5153 next = next->ms_try.final_statement;
5158 check_reachable(next);
5161 static void check_unreachable(statement_t* const stmt, void *const env)
5165 switch (stmt->kind) {
5166 case STATEMENT_DO_WHILE:
5167 if (!stmt->base.reachable) {
5168 expression_t const *const cond = stmt->do_while.condition;
5169 if (determine_truth(cond) >= 0) {
5170 source_position_t const *const pos = &cond->base.source_position;
5171 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5176 case STATEMENT_FOR: {
5177 for_statement_t const* const fors = &stmt->fors;
5179 // if init and step are unreachable, cond is unreachable, too
5180 if (!stmt->base.reachable && !fors->step_reachable) {
5181 goto warn_unreachable;
5183 if (!stmt->base.reachable && fors->initialisation != NULL) {
5184 source_position_t const *const pos = &fors->initialisation->base.source_position;
5185 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5188 if (!fors->condition_reachable && fors->condition != NULL) {
5189 source_position_t const *const pos = &fors->condition->base.source_position;
5190 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5193 if (!fors->step_reachable && fors->step != NULL) {
5194 source_position_t const *const pos = &fors->step->base.source_position;
5195 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5201 case STATEMENT_COMPOUND:
5202 if (stmt->compound.statements != NULL)
5204 goto warn_unreachable;
5206 case STATEMENT_DECLARATION: {
5207 /* Only warn if there is at least one declarator with an initializer.
5208 * This typically occurs in switch statements. */
5209 declaration_statement_t const *const decl = &stmt->declaration;
5210 entity_t const * ent = decl->declarations_begin;
5211 entity_t const *const last = decl->declarations_end;
5213 for (;; ent = ent->base.next) {
5214 if (ent->kind == ENTITY_VARIABLE &&
5215 ent->variable.initializer != NULL) {
5216 goto warn_unreachable;
5226 if (!stmt->base.reachable) {
5227 source_position_t const *const pos = &stmt->base.source_position;
5228 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5234 static bool is_main(entity_t *entity)
5236 static symbol_t *sym_main = NULL;
5237 if (sym_main == NULL) {
5238 sym_main = symbol_table_insert("main");
5241 if (entity->base.symbol != sym_main)
5243 /* must be in outermost scope */
5244 if (entity->base.parent_scope != file_scope)
5250 static void prepare_main_collect2(entity_t*);
5252 static void parse_external_declaration(void)
5254 /* function-definitions and declarations both start with declaration
5256 add_anchor_token(';');
5257 declaration_specifiers_t specifiers;
5258 parse_declaration_specifiers(&specifiers);
5259 rem_anchor_token(';');
5261 /* must be a declaration */
5262 if (token.kind == ';') {
5263 parse_anonymous_declaration_rest(&specifiers);
5267 add_anchor_token(',');
5268 add_anchor_token('=');
5269 add_anchor_token(';');
5270 add_anchor_token('{');
5272 /* declarator is common to both function-definitions and declarations */
5273 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5275 rem_anchor_token('{');
5276 rem_anchor_token(';');
5277 rem_anchor_token('=');
5278 rem_anchor_token(',');
5280 /* must be a declaration */
5281 switch (token.kind) {
5285 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5290 /* must be a function definition */
5291 parse_kr_declaration_list(ndeclaration);
5293 if (token.kind != '{') {
5294 parse_error_expected("while parsing function definition", '{', NULL);
5295 eat_until_matching_token(';');
5299 assert(is_declaration(ndeclaration));
5300 type_t *const orig_type = ndeclaration->declaration.type;
5301 type_t * type = skip_typeref(orig_type);
5303 if (!is_type_function(type)) {
5304 if (is_type_valid(type)) {
5305 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5311 source_position_t const *const pos = &ndeclaration->base.source_position;
5312 if (is_typeref(orig_type)) {
5314 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5317 if (is_type_compound(skip_typeref(type->function.return_type))) {
5318 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5320 if (type->function.unspecified_parameters) {
5321 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5323 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5326 /* §6.7.5.3:14 a function definition with () means no
5327 * parameters (and not unspecified parameters) */
5328 if (type->function.unspecified_parameters &&
5329 type->function.parameters == NULL) {
5330 type_t *copy = duplicate_type(type);
5331 copy->function.unspecified_parameters = false;
5332 type = identify_new_type(copy);
5334 ndeclaration->declaration.type = type;
5337 entity_t *const entity = record_entity(ndeclaration, true);
5338 assert(entity->kind == ENTITY_FUNCTION);
5339 assert(ndeclaration->kind == ENTITY_FUNCTION);
5341 function_t *const function = &entity->function;
5342 if (ndeclaration != entity) {
5343 function->parameters = ndeclaration->function.parameters;
5346 PUSH_SCOPE(&function->parameters);
5348 entity_t *parameter = function->parameters.entities;
5349 for (; parameter != NULL; parameter = parameter->base.next) {
5350 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5351 parameter->base.parent_scope = current_scope;
5353 assert(parameter->base.parent_scope == NULL
5354 || parameter->base.parent_scope == current_scope);
5355 parameter->base.parent_scope = current_scope;
5356 if (parameter->base.symbol == NULL) {
5357 errorf(¶meter->base.source_position, "parameter name omitted");
5360 environment_push(parameter);
5363 if (function->statement != NULL) {
5364 parser_error_multiple_definition(entity, HERE);
5367 /* parse function body */
5368 int label_stack_top = label_top();
5369 function_t *old_current_function = current_function;
5370 current_function = function;
5371 PUSH_CURRENT_ENTITY(entity);
5375 goto_anchor = &goto_first;
5377 label_anchor = &label_first;
5379 statement_t *const body = parse_compound_statement(false);
5380 function->statement = body;
5383 check_declarations();
5384 if (is_warn_on(WARN_RETURN_TYPE) ||
5385 is_warn_on(WARN_UNREACHABLE_CODE) ||
5386 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5387 noreturn_candidate = true;
5388 check_reachable(body);
5389 if (is_warn_on(WARN_UNREACHABLE_CODE))
5390 walk_statements(body, check_unreachable, NULL);
5391 if (noreturn_candidate &&
5392 !(function->base.modifiers & DM_NORETURN)) {
5393 source_position_t const *const pos = &body->base.source_position;
5394 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5398 if (is_main(entity)) {
5399 /* Force main to C linkage. */
5400 type_t *const type = entity->declaration.type;
5401 assert(is_type_function(type));
5402 if (type->function.linkage != LINKAGE_C) {
5403 type_t *new_type = duplicate_type(type);
5404 new_type->function.linkage = LINKAGE_C;
5405 entity->declaration.type = identify_new_type(new_type);
5408 if (enable_main_collect2_hack)
5409 prepare_main_collect2(entity);
5412 POP_CURRENT_ENTITY();
5414 assert(current_function == function);
5415 current_function = old_current_function;
5416 label_pop_to(label_stack_top);
5422 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5424 entity_t *iter = compound->members.entities;
5425 for (; iter != NULL; iter = iter->base.next) {
5426 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5429 if (iter->base.symbol == symbol) {
5431 } else if (iter->base.symbol == NULL) {
5432 /* search in anonymous structs and unions */
5433 type_t *type = skip_typeref(iter->declaration.type);
5434 if (is_type_compound(type)) {
5435 if (find_compound_entry(type->compound.compound, symbol)
5446 static void check_deprecated(const source_position_t *source_position,
5447 const entity_t *entity)
5449 if (!is_declaration(entity))
5451 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5454 source_position_t const *const epos = &entity->base.source_position;
5455 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5457 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5459 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5464 static expression_t *create_select(const source_position_t *pos,
5466 type_qualifiers_t qualifiers,
5469 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5471 check_deprecated(pos, entry);
5473 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5474 select->select.compound = addr;
5475 select->select.compound_entry = entry;
5477 type_t *entry_type = entry->declaration.type;
5478 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5480 /* bitfields need special treatment */
5481 if (entry->compound_member.bitfield) {
5482 unsigned bit_size = entry->compound_member.bit_size;
5483 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5484 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5485 res_type = type_int;
5489 /* we always do the auto-type conversions; the & and sizeof parser contains
5490 * code to revert this! */
5491 select->base.type = automatic_type_conversion(res_type);
5498 * Find entry with symbol in compound. Search anonymous structs and unions and
5499 * creates implicit select expressions for them.
5500 * Returns the adress for the innermost compound.
5502 static expression_t *find_create_select(const source_position_t *pos,
5504 type_qualifiers_t qualifiers,
5505 compound_t *compound, symbol_t *symbol)
5507 entity_t *iter = compound->members.entities;
5508 for (; iter != NULL; iter = iter->base.next) {
5509 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5512 symbol_t *iter_symbol = iter->base.symbol;
5513 if (iter_symbol == NULL) {
5514 type_t *type = iter->declaration.type;
5515 if (type->kind != TYPE_COMPOUND_STRUCT
5516 && type->kind != TYPE_COMPOUND_UNION)
5519 compound_t *sub_compound = type->compound.compound;
5521 if (find_compound_entry(sub_compound, symbol) == NULL)
5524 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5525 sub_addr->base.source_position = *pos;
5526 sub_addr->base.implicit = true;
5527 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5531 if (iter_symbol == symbol) {
5532 return create_select(pos, addr, qualifiers, iter);
5539 static void parse_bitfield_member(entity_t *entity)
5543 expression_t *size = parse_constant_expression();
5546 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5547 type_t *type = entity->declaration.type;
5548 if (!is_type_integer(skip_typeref(type))) {
5549 errorf(HERE, "bitfield base type '%T' is not an integer type",
5553 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5554 /* error already reported by parse_constant_expression */
5555 size_long = get_type_size(type) * 8;
5557 size_long = fold_constant_to_int(size);
5559 const symbol_t *symbol = entity->base.symbol;
5560 const symbol_t *user_symbol
5561 = symbol == NULL ? sym_anonymous : symbol;
5562 unsigned bit_size = get_type_size(type) * 8;
5563 if (size_long < 0) {
5564 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5565 } else if (size_long == 0 && symbol != NULL) {
5566 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5567 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5568 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5571 /* hope that people don't invent crazy types with more bits
5572 * than our struct can hold */
5574 (1 << sizeof(entity->compound_member.bit_size)*8));
5578 entity->compound_member.bitfield = true;
5579 entity->compound_member.bit_size = (unsigned char)size_long;
5582 static void parse_compound_declarators(compound_t *compound,
5583 const declaration_specifiers_t *specifiers)
5585 add_anchor_token(';');
5586 add_anchor_token(',');
5590 if (token.kind == ':') {
5591 /* anonymous bitfield */
5592 type_t *type = specifiers->type;
5593 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5594 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5595 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5596 entity->declaration.type = type;
5598 parse_bitfield_member(entity);
5600 attribute_t *attributes = parse_attributes(NULL);
5601 attribute_t **anchor = &attributes;
5602 while (*anchor != NULL)
5603 anchor = &(*anchor)->next;
5604 *anchor = specifiers->attributes;
5605 if (attributes != NULL) {
5606 handle_entity_attributes(attributes, entity);
5608 entity->declaration.attributes = attributes;
5610 append_entity(&compound->members, entity);
5612 entity = parse_declarator(specifiers,
5613 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5614 source_position_t const *const pos = &entity->base.source_position;
5615 if (entity->kind == ENTITY_TYPEDEF) {
5616 errorf(pos, "typedef not allowed as compound member");
5618 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5620 /* make sure we don't define a symbol multiple times */
5621 symbol_t *symbol = entity->base.symbol;
5622 if (symbol != NULL) {
5623 entity_t *prev = find_compound_entry(compound, symbol);
5625 source_position_t const *const ppos = &prev->base.source_position;
5626 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5630 if (token.kind == ':') {
5631 parse_bitfield_member(entity);
5633 attribute_t *attributes = parse_attributes(NULL);
5634 handle_entity_attributes(attributes, entity);
5636 type_t *orig_type = entity->declaration.type;
5637 type_t *type = skip_typeref(orig_type);
5638 if (is_type_function(type)) {
5639 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5640 } else if (is_type_incomplete(type)) {
5641 /* §6.7.2.1:16 flexible array member */
5642 if (!is_type_array(type) ||
5643 token.kind != ';' ||
5644 look_ahead(1)->kind != '}') {
5645 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5646 } else if (compound->members.entities == NULL) {
5647 errorf(pos, "flexible array member in otherwise empty struct");
5652 append_entity(&compound->members, entity);
5655 } while (next_if(','));
5656 rem_anchor_token(',');
5657 rem_anchor_token(';');
5660 anonymous_entity = NULL;
5663 static void parse_compound_type_entries(compound_t *compound)
5666 add_anchor_token('}');
5669 switch (token.kind) {
5671 case T___extension__:
5672 case T_IDENTIFIER: {
5674 declaration_specifiers_t specifiers;
5675 parse_declaration_specifiers(&specifiers);
5676 parse_compound_declarators(compound, &specifiers);
5682 rem_anchor_token('}');
5685 compound->complete = true;
5691 static type_t *parse_typename(void)
5693 declaration_specifiers_t specifiers;
5694 parse_declaration_specifiers(&specifiers);
5695 if (specifiers.storage_class != STORAGE_CLASS_NONE
5696 || specifiers.thread_local) {
5697 /* TODO: improve error message, user does probably not know what a
5698 * storage class is...
5700 errorf(&specifiers.source_position, "typename must not have a storage class");
5703 type_t *result = parse_abstract_declarator(specifiers.type);
5711 typedef expression_t* (*parse_expression_function)(void);
5712 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5714 typedef struct expression_parser_function_t expression_parser_function_t;
5715 struct expression_parser_function_t {
5716 parse_expression_function parser;
5717 precedence_t infix_precedence;
5718 parse_expression_infix_function infix_parser;
5721 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5723 static type_t *get_string_type(void)
5725 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5728 static type_t *get_wide_string_type(void)
5730 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5734 * Parse a string constant.
5736 static expression_t *parse_string_literal(void)
5738 source_position_t begin = token.base.source_position;
5739 string_t res = token.string.string;
5740 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5743 while (token.kind == T_STRING_LITERAL
5744 || token.kind == T_WIDE_STRING_LITERAL) {
5745 warn_string_concat(&token.base.source_position);
5746 res = concat_strings(&res, &token.string.string);
5748 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5751 expression_t *literal;
5753 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5754 literal->base.type = get_wide_string_type();
5756 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5757 literal->base.type = get_string_type();
5759 literal->base.source_position = begin;
5760 literal->literal.value = res;
5766 * Parse a boolean constant.
5768 static expression_t *parse_boolean_literal(bool value)
5770 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5771 literal->base.type = type_bool;
5772 literal->literal.value.begin = value ? "true" : "false";
5773 literal->literal.value.size = value ? 4 : 5;
5779 static void warn_traditional_suffix(void)
5781 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5782 &token.number.suffix);
5785 static void check_integer_suffix(void)
5787 const string_t *suffix = &token.number.suffix;
5788 if (suffix->size == 0)
5791 bool not_traditional = false;
5792 const char *c = suffix->begin;
5793 if (*c == 'l' || *c == 'L') {
5796 not_traditional = true;
5798 if (*c == 'u' || *c == 'U') {
5801 } else if (*c == 'u' || *c == 'U') {
5802 not_traditional = true;
5805 } else if (*c == 'u' || *c == 'U') {
5806 not_traditional = true;
5808 if (*c == 'l' || *c == 'L') {
5816 errorf(&token.base.source_position,
5817 "invalid suffix '%S' on integer constant", suffix);
5818 } else if (not_traditional) {
5819 warn_traditional_suffix();
5823 static type_t *check_floatingpoint_suffix(void)
5825 const string_t *suffix = &token.number.suffix;
5826 type_t *type = type_double;
5827 if (suffix->size == 0)
5830 bool not_traditional = false;
5831 const char *c = suffix->begin;
5832 if (*c == 'f' || *c == 'F') {
5835 } else if (*c == 'l' || *c == 'L') {
5837 type = type_long_double;
5840 errorf(&token.base.source_position,
5841 "invalid suffix '%S' on floatingpoint constant", suffix);
5842 } else if (not_traditional) {
5843 warn_traditional_suffix();
5850 * Parse an integer constant.
5852 static expression_t *parse_number_literal(void)
5854 expression_kind_t kind;
5857 switch (token.kind) {
5859 case T_INTEGER_OCTAL:
5860 case T_INTEGER_HEXADECIMAL:
5861 kind = EXPR_LITERAL_INTEGER;
5862 check_integer_suffix();
5866 case T_FLOATINGPOINT:
5867 kind = EXPR_LITERAL_FLOATINGPOINT;
5868 type = check_floatingpoint_suffix();
5870 case T_FLOATINGPOINT_HEXADECIMAL:
5871 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5872 type = check_floatingpoint_suffix();
5875 panic("unexpected token type in parse_number_literal");
5878 expression_t *literal = allocate_expression_zero(kind);
5879 literal->base.type = type;
5880 literal->literal.value = token.number.number;
5881 literal->literal.suffix = token.number.suffix;
5884 /* integer type depends on the size of the number and the size
5885 * representable by the types. The backend/codegeneration has to determine
5888 determine_literal_type(&literal->literal);
5893 * Parse a character constant.
5895 static expression_t *parse_character_constant(void)
5897 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5898 literal->base.type = c_mode & _CXX ? type_char : type_int;
5899 literal->literal.value = token.string.string;
5901 size_t len = literal->literal.value.size;
5903 if (!GNU_MODE && !(c_mode & _C99)) {
5904 errorf(HERE, "more than 1 character in character constant");
5906 literal->base.type = type_int;
5907 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5916 * Parse a wide character constant.
5918 static expression_t *parse_wide_character_constant(void)
5920 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5921 literal->base.type = type_int;
5922 literal->literal.value = token.string.string;
5924 size_t len = wstrlen(&literal->literal.value);
5926 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5933 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5935 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5936 ntype->function.return_type = type_int;
5937 ntype->function.unspecified_parameters = true;
5938 ntype->function.linkage = LINKAGE_C;
5939 type_t *type = identify_new_type(ntype);
5941 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5942 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5943 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5944 entity->declaration.type = type;
5945 entity->declaration.implicit = true;
5947 if (current_scope != NULL)
5948 record_entity(entity, false);
5954 * Performs automatic type cast as described in §6.3.2.1.
5956 * @param orig_type the original type
5958 static type_t *automatic_type_conversion(type_t *orig_type)
5960 type_t *type = skip_typeref(orig_type);
5961 if (is_type_array(type)) {
5962 array_type_t *array_type = &type->array;
5963 type_t *element_type = array_type->element_type;
5964 unsigned qualifiers = array_type->base.qualifiers;
5966 return make_pointer_type(element_type, qualifiers);
5969 if (is_type_function(type)) {
5970 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5977 * reverts the automatic casts of array to pointer types and function
5978 * to function-pointer types as defined §6.3.2.1
5980 type_t *revert_automatic_type_conversion(const expression_t *expression)
5982 switch (expression->kind) {
5983 case EXPR_REFERENCE: {
5984 entity_t *entity = expression->reference.entity;
5985 if (is_declaration(entity)) {
5986 return entity->declaration.type;
5987 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5988 return entity->enum_value.enum_type;
5990 panic("no declaration or enum in reference");
5995 entity_t *entity = expression->select.compound_entry;
5996 assert(is_declaration(entity));
5997 type_t *type = entity->declaration.type;
5998 return get_qualified_type(type, expression->base.type->base.qualifiers);
6001 case EXPR_UNARY_DEREFERENCE: {
6002 const expression_t *const value = expression->unary.value;
6003 type_t *const type = skip_typeref(value->base.type);
6004 if (!is_type_pointer(type))
6005 return type_error_type;
6006 return type->pointer.points_to;
6009 case EXPR_ARRAY_ACCESS: {
6010 const expression_t *array_ref = expression->array_access.array_ref;
6011 type_t *type_left = skip_typeref(array_ref->base.type);
6012 if (!is_type_pointer(type_left))
6013 return type_error_type;
6014 return type_left->pointer.points_to;
6017 case EXPR_STRING_LITERAL: {
6018 size_t size = expression->string_literal.value.size;
6019 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6022 case EXPR_WIDE_STRING_LITERAL: {
6023 size_t size = wstrlen(&expression->string_literal.value);
6024 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6027 case EXPR_COMPOUND_LITERAL:
6028 return expression->compound_literal.type;
6033 return expression->base.type;
6037 * Find an entity matching a symbol in a scope.
6038 * Uses current scope if scope is NULL
6040 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6041 namespace_tag_t namespc)
6043 if (scope == NULL) {
6044 return get_entity(symbol, namespc);
6047 /* we should optimize here, if scope grows above a certain size we should
6048 construct a hashmap here... */
6049 entity_t *entity = scope->entities;
6050 for ( ; entity != NULL; entity = entity->base.next) {
6051 if (entity->base.symbol == symbol
6052 && (namespace_tag_t)entity->base.namespc == namespc)
6059 static entity_t *parse_qualified_identifier(void)
6061 /* namespace containing the symbol */
6063 source_position_t pos;
6064 const scope_t *lookup_scope = NULL;
6066 if (next_if(T_COLONCOLON))
6067 lookup_scope = &unit->scope;
6071 symbol = expect_identifier("while parsing identifier", &pos);
6073 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6076 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6078 if (!next_if(T_COLONCOLON))
6081 switch (entity->kind) {
6082 case ENTITY_NAMESPACE:
6083 lookup_scope = &entity->namespacee.members;
6088 lookup_scope = &entity->compound.members;
6091 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6092 symbol, get_entity_kind_name(entity->kind));
6094 /* skip further qualifications */
6095 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6097 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6101 if (entity == NULL) {
6102 if (!strict_mode && token.kind == '(') {
6103 /* an implicitly declared function */
6104 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6105 "implicit declaration of function '%Y'", symbol);
6106 entity = create_implicit_function(symbol, &pos);
6108 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6109 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6116 static expression_t *parse_reference(void)
6118 source_position_t const pos = token.base.source_position;
6119 entity_t *const entity = parse_qualified_identifier();
6122 if (is_declaration(entity)) {
6123 orig_type = entity->declaration.type;
6124 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6125 orig_type = entity->enum_value.enum_type;
6127 panic("expected declaration or enum value in reference");
6130 /* we always do the auto-type conversions; the & and sizeof parser contains
6131 * code to revert this! */
6132 type_t *type = automatic_type_conversion(orig_type);
6134 expression_kind_t kind = EXPR_REFERENCE;
6135 if (entity->kind == ENTITY_ENUM_VALUE)
6136 kind = EXPR_ENUM_CONSTANT;
6138 expression_t *expression = allocate_expression_zero(kind);
6139 expression->base.source_position = pos;
6140 expression->base.type = type;
6141 expression->reference.entity = entity;
6143 /* this declaration is used */
6144 if (is_declaration(entity)) {
6145 entity->declaration.used = true;
6148 if (entity->base.parent_scope != file_scope
6149 && (current_function != NULL
6150 && entity->base.parent_scope->depth < current_function->parameters.depth)
6151 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6152 if (entity->kind == ENTITY_VARIABLE) {
6153 /* access of a variable from an outer function */
6154 entity->variable.address_taken = true;
6155 } else if (entity->kind == ENTITY_PARAMETER) {
6156 entity->parameter.address_taken = true;
6158 current_function->need_closure = true;
6161 check_deprecated(&pos, entity);
6166 static bool semantic_cast(expression_t *cast)
6168 expression_t *expression = cast->unary.value;
6169 type_t *orig_dest_type = cast->base.type;
6170 type_t *orig_type_right = expression->base.type;
6171 type_t const *dst_type = skip_typeref(orig_dest_type);
6172 type_t const *src_type = skip_typeref(orig_type_right);
6173 source_position_t const *pos = &cast->base.source_position;
6175 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6176 if (is_type_void(dst_type))
6179 /* only integer and pointer can be casted to pointer */
6180 if (is_type_pointer(dst_type) &&
6181 !is_type_pointer(src_type) &&
6182 !is_type_integer(src_type) &&
6183 is_type_valid(src_type)) {
6184 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6188 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6189 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6193 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6194 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6198 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6199 type_t *src = skip_typeref(src_type->pointer.points_to);
6200 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6201 unsigned missing_qualifiers =
6202 src->base.qualifiers & ~dst->base.qualifiers;
6203 if (missing_qualifiers != 0) {
6204 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6210 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6212 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6213 expression->base.source_position = *pos;
6215 parse_initializer_env_t env;
6218 env.must_be_constant = false;
6219 initializer_t *initializer = parse_initializer(&env);
6222 expression->compound_literal.initializer = initializer;
6223 expression->compound_literal.type = type;
6224 expression->base.type = automatic_type_conversion(type);
6230 * Parse a cast expression.
6232 static expression_t *parse_cast(void)
6234 source_position_t const pos = *HERE;
6237 add_anchor_token(')');
6239 type_t *type = parse_typename();
6241 rem_anchor_token(')');
6244 if (token.kind == '{') {
6245 return parse_compound_literal(&pos, type);
6248 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6249 cast->base.source_position = pos;
6251 expression_t *value = parse_subexpression(PREC_CAST);
6252 cast->base.type = type;
6253 cast->unary.value = value;
6255 if (! semantic_cast(cast)) {
6256 /* TODO: record the error in the AST. else it is impossible to detect it */
6263 * Parse a statement expression.
6265 static expression_t *parse_statement_expression(void)
6267 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6270 add_anchor_token(')');
6272 statement_t *statement = parse_compound_statement(true);
6273 statement->compound.stmt_expr = true;
6274 expression->statement.statement = statement;
6276 /* find last statement and use its type */
6277 type_t *type = type_void;
6278 const statement_t *stmt = statement->compound.statements;
6280 while (stmt->base.next != NULL)
6281 stmt = stmt->base.next;
6283 if (stmt->kind == STATEMENT_EXPRESSION) {
6284 type = stmt->expression.expression->base.type;
6287 source_position_t const *const pos = &expression->base.source_position;
6288 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6290 expression->base.type = type;
6292 rem_anchor_token(')');
6298 * Parse a parenthesized expression.
6300 static expression_t *parse_parenthesized_expression(void)
6302 token_t const* const la1 = look_ahead(1);
6303 switch (la1->kind) {
6305 /* gcc extension: a statement expression */
6306 return parse_statement_expression();
6309 if (is_typedef_symbol(la1->identifier.symbol)) {
6311 return parse_cast();
6316 add_anchor_token(')');
6317 expression_t *result = parse_expression();
6318 result->base.parenthesized = true;
6319 rem_anchor_token(')');
6325 static expression_t *parse_function_keyword(void)
6329 if (current_function == NULL) {
6330 errorf(HERE, "'__func__' used outside of a function");
6333 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6334 expression->base.type = type_char_ptr;
6335 expression->funcname.kind = FUNCNAME_FUNCTION;
6342 static expression_t *parse_pretty_function_keyword(void)
6344 if (current_function == NULL) {
6345 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6348 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6349 expression->base.type = type_char_ptr;
6350 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6352 eat(T___PRETTY_FUNCTION__);
6357 static expression_t *parse_funcsig_keyword(void)
6359 if (current_function == NULL) {
6360 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6363 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6364 expression->base.type = type_char_ptr;
6365 expression->funcname.kind = FUNCNAME_FUNCSIG;
6372 static expression_t *parse_funcdname_keyword(void)
6374 if (current_function == NULL) {
6375 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6378 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6379 expression->base.type = type_char_ptr;
6380 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6382 eat(T___FUNCDNAME__);
6387 static designator_t *parse_designator(void)
6389 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6390 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6391 if (!result->symbol)
6394 designator_t *last_designator = result;
6397 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6398 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6399 if (!designator->symbol)
6402 last_designator->next = designator;
6403 last_designator = designator;
6407 add_anchor_token(']');
6408 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6409 designator->source_position = *HERE;
6410 designator->array_index = parse_expression();
6411 rem_anchor_token(']');
6413 if (designator->array_index == NULL) {
6417 last_designator->next = designator;
6418 last_designator = designator;
6428 * Parse the __builtin_offsetof() expression.
6430 static expression_t *parse_offsetof(void)
6432 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6433 expression->base.type = type_size_t;
6435 eat(T___builtin_offsetof);
6438 add_anchor_token(')');
6439 add_anchor_token(',');
6440 type_t *type = parse_typename();
6441 rem_anchor_token(',');
6443 designator_t *designator = parse_designator();
6444 rem_anchor_token(')');
6447 expression->offsetofe.type = type;
6448 expression->offsetofe.designator = designator;
6451 memset(&path, 0, sizeof(path));
6452 path.top_type = type;
6453 path.path = NEW_ARR_F(type_path_entry_t, 0);
6455 descend_into_subtype(&path);
6457 if (!walk_designator(&path, designator, true)) {
6458 return create_error_expression();
6461 DEL_ARR_F(path.path);
6467 * Parses a _builtin_va_start() expression.
6469 static expression_t *parse_va_start(void)
6471 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6473 eat(T___builtin_va_start);
6476 add_anchor_token(')');
6477 add_anchor_token(',');
6478 expression->va_starte.ap = parse_assignment_expression();
6479 rem_anchor_token(',');
6481 expression_t *const expr = parse_assignment_expression();
6482 if (expr->kind == EXPR_REFERENCE) {
6483 entity_t *const entity = expr->reference.entity;
6484 if (!current_function->base.type->function.variadic) {
6485 errorf(&expr->base.source_position,
6486 "'va_start' used in non-variadic function");
6487 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6488 entity->base.next != NULL ||
6489 entity->kind != ENTITY_PARAMETER) {
6490 errorf(&expr->base.source_position,
6491 "second argument of 'va_start' must be last parameter of the current function");
6493 expression->va_starte.parameter = &entity->variable;
6496 expression = create_error_expression();
6498 rem_anchor_token(')');
6504 * Parses a __builtin_va_arg() expression.
6506 static expression_t *parse_va_arg(void)
6508 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6510 eat(T___builtin_va_arg);
6513 add_anchor_token(')');
6514 add_anchor_token(',');
6516 ap.expression = parse_assignment_expression();
6517 expression->va_arge.ap = ap.expression;
6518 check_call_argument(type_valist, &ap, 1);
6520 rem_anchor_token(',');
6522 expression->base.type = parse_typename();
6523 rem_anchor_token(')');
6530 * Parses a __builtin_va_copy() expression.
6532 static expression_t *parse_va_copy(void)
6534 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6536 eat(T___builtin_va_copy);
6539 add_anchor_token(')');
6540 add_anchor_token(',');
6541 expression_t *dst = parse_assignment_expression();
6542 assign_error_t error = semantic_assign(type_valist, dst);
6543 report_assign_error(error, type_valist, dst, "call argument 1",
6544 &dst->base.source_position);
6545 expression->va_copye.dst = dst;
6547 rem_anchor_token(',');
6550 call_argument_t src;
6551 src.expression = parse_assignment_expression();
6552 check_call_argument(type_valist, &src, 2);
6553 expression->va_copye.src = src.expression;
6554 rem_anchor_token(')');
6561 * Parses a __builtin_constant_p() expression.
6563 static expression_t *parse_builtin_constant(void)
6565 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6567 eat(T___builtin_constant_p);
6570 add_anchor_token(')');
6571 expression->builtin_constant.value = parse_assignment_expression();
6572 rem_anchor_token(')');
6574 expression->base.type = type_int;
6580 * Parses a __builtin_types_compatible_p() expression.
6582 static expression_t *parse_builtin_types_compatible(void)
6584 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6586 eat(T___builtin_types_compatible_p);
6589 add_anchor_token(')');
6590 add_anchor_token(',');
6591 expression->builtin_types_compatible.left = parse_typename();
6592 rem_anchor_token(',');
6594 expression->builtin_types_compatible.right = parse_typename();
6595 rem_anchor_token(')');
6597 expression->base.type = type_int;
6603 * Parses a __builtin_is_*() compare expression.
6605 static expression_t *parse_compare_builtin(void)
6607 expression_t *expression;
6609 switch (token.kind) {
6610 case T___builtin_isgreater:
6611 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6613 case T___builtin_isgreaterequal:
6614 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6616 case T___builtin_isless:
6617 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6619 case T___builtin_islessequal:
6620 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6622 case T___builtin_islessgreater:
6623 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6625 case T___builtin_isunordered:
6626 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6629 internal_errorf(HERE, "invalid compare builtin found");
6631 expression->base.source_position = *HERE;
6635 add_anchor_token(')');
6636 add_anchor_token(',');
6637 expression->binary.left = parse_assignment_expression();
6638 rem_anchor_token(',');
6640 expression->binary.right = parse_assignment_expression();
6641 rem_anchor_token(')');
6644 type_t *const orig_type_left = expression->binary.left->base.type;
6645 type_t *const orig_type_right = expression->binary.right->base.type;
6647 type_t *const type_left = skip_typeref(orig_type_left);
6648 type_t *const type_right = skip_typeref(orig_type_right);
6649 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6650 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6651 type_error_incompatible("invalid operands in comparison",
6652 &expression->base.source_position, orig_type_left, orig_type_right);
6655 semantic_comparison(&expression->binary);
6662 * Parses a MS assume() expression.
6664 static expression_t *parse_assume(void)
6666 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6671 add_anchor_token(')');
6672 expression->unary.value = parse_assignment_expression();
6673 rem_anchor_token(')');
6676 expression->base.type = type_void;
6681 * Return the label for the current symbol or create a new one.
6683 static label_t *get_label(void)
6685 assert(token.kind == T_IDENTIFIER);
6686 assert(current_function != NULL);
6688 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6689 /* If we find a local label, we already created the declaration. */
6690 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6691 if (label->base.parent_scope != current_scope) {
6692 assert(label->base.parent_scope->depth < current_scope->depth);
6693 current_function->goto_to_outer = true;
6695 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6696 /* There is no matching label in the same function, so create a new one. */
6697 source_position_t const nowhere = { NULL, 0, 0, false };
6698 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6703 return &label->label;
6707 * Parses a GNU && label address expression.
6709 static expression_t *parse_label_address(void)
6711 source_position_t source_position = token.base.source_position;
6713 if (token.kind != T_IDENTIFIER) {
6714 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6715 return create_error_expression();
6718 label_t *const label = get_label();
6720 label->address_taken = true;
6722 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6723 expression->base.source_position = source_position;
6725 /* label address is treated as a void pointer */
6726 expression->base.type = type_void_ptr;
6727 expression->label_address.label = label;
6732 * Parse a microsoft __noop expression.
6734 static expression_t *parse_noop_expression(void)
6736 /* the result is a (int)0 */
6737 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6738 literal->base.type = type_int;
6739 literal->literal.value.begin = "__noop";
6740 literal->literal.value.size = 6;
6744 if (token.kind == '(') {
6745 /* parse arguments */
6747 add_anchor_token(')');
6748 add_anchor_token(',');
6750 if (token.kind != ')') do {
6751 (void)parse_assignment_expression();
6752 } while (next_if(','));
6754 rem_anchor_token(',');
6755 rem_anchor_token(')');
6763 * Parses a primary expression.
6765 static expression_t *parse_primary_expression(void)
6767 switch (token.kind) {
6768 case T_false: return parse_boolean_literal(false);
6769 case T_true: return parse_boolean_literal(true);
6771 case T_INTEGER_OCTAL:
6772 case T_INTEGER_HEXADECIMAL:
6773 case T_FLOATINGPOINT:
6774 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6775 case T_CHARACTER_CONSTANT: return parse_character_constant();
6776 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6777 case T_STRING_LITERAL:
6778 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6779 case T___FUNCTION__:
6780 case T___func__: return parse_function_keyword();
6781 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6782 case T___FUNCSIG__: return parse_funcsig_keyword();
6783 case T___FUNCDNAME__: return parse_funcdname_keyword();
6784 case T___builtin_offsetof: return parse_offsetof();
6785 case T___builtin_va_start: return parse_va_start();
6786 case T___builtin_va_arg: return parse_va_arg();
6787 case T___builtin_va_copy: return parse_va_copy();
6788 case T___builtin_isgreater:
6789 case T___builtin_isgreaterequal:
6790 case T___builtin_isless:
6791 case T___builtin_islessequal:
6792 case T___builtin_islessgreater:
6793 case T___builtin_isunordered: return parse_compare_builtin();
6794 case T___builtin_constant_p: return parse_builtin_constant();
6795 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6796 case T__assume: return parse_assume();
6799 return parse_label_address();
6802 case '(': return parse_parenthesized_expression();
6803 case T___noop: return parse_noop_expression();
6805 /* Gracefully handle type names while parsing expressions. */
6807 return parse_reference();
6809 if (!is_typedef_symbol(token.identifier.symbol)) {
6810 return parse_reference();
6814 source_position_t const pos = *HERE;
6815 declaration_specifiers_t specifiers;
6816 parse_declaration_specifiers(&specifiers);
6817 type_t const *const type = parse_abstract_declarator(specifiers.type);
6818 errorf(&pos, "encountered type '%T' while parsing expression", type);
6819 return create_error_expression();
6823 errorf(HERE, "unexpected token %K, expected an expression", &token);
6825 return create_error_expression();
6828 static expression_t *parse_array_expression(expression_t *left)
6830 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6831 array_access_expression_t *const arr = &expr->array_access;
6834 add_anchor_token(']');
6836 expression_t *const inside = parse_expression();
6838 type_t *const orig_type_left = left->base.type;
6839 type_t *const orig_type_inside = inside->base.type;
6841 type_t *const type_left = skip_typeref(orig_type_left);
6842 type_t *const type_inside = skip_typeref(orig_type_inside);
6848 if (is_type_pointer(type_left)) {
6851 idx_type = type_inside;
6852 res_type = type_left->pointer.points_to;
6854 } else if (is_type_pointer(type_inside)) {
6855 arr->flipped = true;
6858 idx_type = type_left;
6859 res_type = type_inside->pointer.points_to;
6861 res_type = automatic_type_conversion(res_type);
6862 if (!is_type_integer(idx_type)) {
6863 errorf(&idx->base.source_position, "array subscript must have integer type");
6864 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6865 source_position_t const *const pos = &idx->base.source_position;
6866 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6869 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6870 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6872 res_type = type_error_type;
6877 arr->array_ref = ref;
6879 arr->base.type = res_type;
6881 rem_anchor_token(']');
6886 static bool is_bitfield(const expression_t *expression)
6888 return expression->kind == EXPR_SELECT
6889 && expression->select.compound_entry->compound_member.bitfield;
6892 static expression_t *parse_typeprop(expression_kind_t const kind)
6894 expression_t *tp_expression = allocate_expression_zero(kind);
6895 tp_expression->base.type = type_size_t;
6897 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6900 expression_t *expression;
6901 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6902 source_position_t const pos = *HERE;
6904 add_anchor_token(')');
6905 orig_type = parse_typename();
6906 rem_anchor_token(')');
6909 if (token.kind == '{') {
6910 /* It was not sizeof(type) after all. It is sizeof of an expression
6911 * starting with a compound literal */
6912 expression = parse_compound_literal(&pos, orig_type);
6913 goto typeprop_expression;
6916 expression = parse_subexpression(PREC_UNARY);
6918 typeprop_expression:
6919 if (is_bitfield(expression)) {
6920 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6921 errorf(&tp_expression->base.source_position,
6922 "operand of %s expression must not be a bitfield", what);
6925 tp_expression->typeprop.tp_expression = expression;
6927 orig_type = revert_automatic_type_conversion(expression);
6928 expression->base.type = orig_type;
6931 tp_expression->typeprop.type = orig_type;
6932 type_t const* const type = skip_typeref(orig_type);
6933 char const* wrong_type = NULL;
6934 if (is_type_incomplete(type)) {
6935 if (!is_type_void(type) || !GNU_MODE)
6936 wrong_type = "incomplete";
6937 } else if (type->kind == TYPE_FUNCTION) {
6939 /* function types are allowed (and return 1) */
6940 source_position_t const *const pos = &tp_expression->base.source_position;
6941 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6942 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6944 wrong_type = "function";
6948 if (wrong_type != NULL) {
6949 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6950 errorf(&tp_expression->base.source_position,
6951 "operand of %s expression must not be of %s type '%T'",
6952 what, wrong_type, orig_type);
6955 return tp_expression;
6958 static expression_t *parse_sizeof(void)
6960 return parse_typeprop(EXPR_SIZEOF);
6963 static expression_t *parse_alignof(void)
6965 return parse_typeprop(EXPR_ALIGNOF);
6968 static expression_t *parse_select_expression(expression_t *addr)
6970 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6971 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6972 source_position_t const pos = *HERE;
6975 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6977 return create_error_expression();
6979 type_t *const orig_type = addr->base.type;
6980 type_t *const type = skip_typeref(orig_type);
6983 bool saw_error = false;
6984 if (is_type_pointer(type)) {
6985 if (!select_left_arrow) {
6987 "request for member '%Y' in something not a struct or union, but '%T'",
6991 type_left = skip_typeref(type->pointer.points_to);
6993 if (select_left_arrow && is_type_valid(type)) {
6994 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7000 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7001 type_left->kind != TYPE_COMPOUND_UNION) {
7003 if (is_type_valid(type_left) && !saw_error) {
7005 "request for member '%Y' in something not a struct or union, but '%T'",
7008 return create_error_expression();
7011 compound_t *compound = type_left->compound.compound;
7012 if (!compound->complete) {
7013 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7015 return create_error_expression();
7018 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7019 expression_t *result =
7020 find_create_select(&pos, addr, qualifiers, compound, symbol);
7022 if (result == NULL) {
7023 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7024 return create_error_expression();
7030 static void check_call_argument(type_t *expected_type,
7031 call_argument_t *argument, unsigned pos)
7033 type_t *expected_type_skip = skip_typeref(expected_type);
7034 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7035 expression_t *arg_expr = argument->expression;
7036 type_t *arg_type = skip_typeref(arg_expr->base.type);
7038 /* handle transparent union gnu extension */
7039 if (is_type_union(expected_type_skip)
7040 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7041 compound_t *union_decl = expected_type_skip->compound.compound;
7042 type_t *best_type = NULL;
7043 entity_t *entry = union_decl->members.entities;
7044 for ( ; entry != NULL; entry = entry->base.next) {
7045 assert(is_declaration(entry));
7046 type_t *decl_type = entry->declaration.type;
7047 error = semantic_assign(decl_type, arg_expr);
7048 if (error == ASSIGN_ERROR_INCOMPATIBLE
7049 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7052 if (error == ASSIGN_SUCCESS) {
7053 best_type = decl_type;
7054 } else if (best_type == NULL) {
7055 best_type = decl_type;
7059 if (best_type != NULL) {
7060 expected_type = best_type;
7064 error = semantic_assign(expected_type, arg_expr);
7065 argument->expression = create_implicit_cast(arg_expr, expected_type);
7067 if (error != ASSIGN_SUCCESS) {
7068 /* report exact scope in error messages (like "in argument 3") */
7070 snprintf(buf, sizeof(buf), "call argument %u", pos);
7071 report_assign_error(error, expected_type, arg_expr, buf,
7072 &arg_expr->base.source_position);
7074 type_t *const promoted_type = get_default_promoted_type(arg_type);
7075 if (!types_compatible(expected_type_skip, promoted_type) &&
7076 !types_compatible(expected_type_skip, type_void_ptr) &&
7077 !types_compatible(type_void_ptr, promoted_type)) {
7078 /* Deliberately show the skipped types in this warning */
7079 source_position_t const *const apos = &arg_expr->base.source_position;
7080 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7086 * Handle the semantic restrictions of builtin calls
7088 static void handle_builtin_argument_restrictions(call_expression_t *call)
7090 entity_t *entity = call->function->reference.entity;
7091 switch (entity->function.btk) {
7093 switch (entity->function.b.firm_builtin_kind) {
7094 case ir_bk_return_address:
7095 case ir_bk_frame_address: {
7096 /* argument must be constant */
7097 call_argument_t *argument = call->arguments;
7099 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7100 errorf(&call->base.source_position,
7101 "argument of '%Y' must be a constant expression",
7102 call->function->reference.entity->base.symbol);
7106 case ir_bk_prefetch:
7107 /* second and third argument must be constant if existent */
7108 if (call->arguments == NULL)
7110 call_argument_t *rw = call->arguments->next;
7111 call_argument_t *locality = NULL;
7114 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7115 errorf(&call->base.source_position,
7116 "second argument of '%Y' must be a constant expression",
7117 call->function->reference.entity->base.symbol);
7119 locality = rw->next;
7121 if (locality != NULL) {
7122 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7123 errorf(&call->base.source_position,
7124 "third argument of '%Y' must be a constant expression",
7125 call->function->reference.entity->base.symbol);
7127 locality = rw->next;
7134 case BUILTIN_OBJECT_SIZE:
7135 if (call->arguments == NULL)
7138 call_argument_t *arg = call->arguments->next;
7139 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7140 errorf(&call->base.source_position,
7141 "second argument of '%Y' must be a constant expression",
7142 call->function->reference.entity->base.symbol);
7151 * Parse a call expression, ie. expression '( ... )'.
7153 * @param expression the function address
7155 static expression_t *parse_call_expression(expression_t *expression)
7157 expression_t *result = allocate_expression_zero(EXPR_CALL);
7158 call_expression_t *call = &result->call;
7159 call->function = expression;
7161 type_t *const orig_type = expression->base.type;
7162 type_t *const type = skip_typeref(orig_type);
7164 function_type_t *function_type = NULL;
7165 if (is_type_pointer(type)) {
7166 type_t *const to_type = skip_typeref(type->pointer.points_to);
7168 if (is_type_function(to_type)) {
7169 function_type = &to_type->function;
7170 call->base.type = function_type->return_type;
7174 if (function_type == NULL && is_type_valid(type)) {
7176 "called object '%E' (type '%T') is not a pointer to a function",
7177 expression, orig_type);
7180 /* parse arguments */
7182 add_anchor_token(')');
7183 add_anchor_token(',');
7185 if (token.kind != ')') {
7186 call_argument_t **anchor = &call->arguments;
7188 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7189 argument->expression = parse_assignment_expression();
7192 anchor = &argument->next;
7193 } while (next_if(','));
7195 rem_anchor_token(',');
7196 rem_anchor_token(')');
7199 if (function_type == NULL)
7202 /* check type and count of call arguments */
7203 function_parameter_t *parameter = function_type->parameters;
7204 call_argument_t *argument = call->arguments;
7205 if (!function_type->unspecified_parameters) {
7206 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7207 parameter = parameter->next, argument = argument->next) {
7208 check_call_argument(parameter->type, argument, ++pos);
7211 if (parameter != NULL) {
7212 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7213 } else if (argument != NULL && !function_type->variadic) {
7214 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7218 /* do default promotion for other arguments */
7219 for (; argument != NULL; argument = argument->next) {
7220 type_t *argument_type = argument->expression->base.type;
7221 if (!is_type_object(skip_typeref(argument_type))) {
7222 errorf(&argument->expression->base.source_position,
7223 "call argument '%E' must not be void", argument->expression);
7226 argument_type = get_default_promoted_type(argument_type);
7228 argument->expression
7229 = create_implicit_cast(argument->expression, argument_type);
7234 if (is_type_compound(skip_typeref(function_type->return_type))) {
7235 source_position_t const *const pos = &expression->base.source_position;
7236 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7239 if (expression->kind == EXPR_REFERENCE) {
7240 reference_expression_t *reference = &expression->reference;
7241 if (reference->entity->kind == ENTITY_FUNCTION &&
7242 reference->entity->function.btk != BUILTIN_NONE)
7243 handle_builtin_argument_restrictions(call);
7249 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7251 static bool same_compound_type(const type_t *type1, const type_t *type2)
7254 is_type_compound(type1) &&
7255 type1->kind == type2->kind &&
7256 type1->compound.compound == type2->compound.compound;
7259 static expression_t const *get_reference_address(expression_t const *expr)
7261 bool regular_take_address = true;
7263 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7264 expr = expr->unary.value;
7266 regular_take_address = false;
7269 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7272 expr = expr->unary.value;
7275 if (expr->kind != EXPR_REFERENCE)
7278 /* special case for functions which are automatically converted to a
7279 * pointer to function without an extra TAKE_ADDRESS operation */
7280 if (!regular_take_address &&
7281 expr->reference.entity->kind != ENTITY_FUNCTION) {
7288 static void warn_reference_address_as_bool(expression_t const* expr)
7290 expr = get_reference_address(expr);
7292 source_position_t const *const pos = &expr->base.source_position;
7293 entity_t const *const ent = expr->reference.entity;
7294 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7298 static void warn_assignment_in_condition(const expression_t *const expr)
7300 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7302 if (expr->base.parenthesized)
7304 source_position_t const *const pos = &expr->base.source_position;
7305 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7308 static void semantic_condition(expression_t const *const expr,
7309 char const *const context)
7311 type_t *const type = skip_typeref(expr->base.type);
7312 if (is_type_scalar(type)) {
7313 warn_reference_address_as_bool(expr);
7314 warn_assignment_in_condition(expr);
7315 } else if (is_type_valid(type)) {
7316 errorf(&expr->base.source_position,
7317 "%s must have scalar type", context);
7322 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7324 * @param expression the conditional expression
7326 static expression_t *parse_conditional_expression(expression_t *expression)
7328 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7330 conditional_expression_t *conditional = &result->conditional;
7331 conditional->condition = expression;
7334 add_anchor_token(':');
7336 /* §6.5.15:2 The first operand shall have scalar type. */
7337 semantic_condition(expression, "condition of conditional operator");
7339 expression_t *true_expression = expression;
7340 bool gnu_cond = false;
7341 if (GNU_MODE && token.kind == ':') {
7344 true_expression = parse_expression();
7346 rem_anchor_token(':');
7348 expression_t *false_expression =
7349 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7351 type_t *const orig_true_type = true_expression->base.type;
7352 type_t *const orig_false_type = false_expression->base.type;
7353 type_t *const true_type = skip_typeref(orig_true_type);
7354 type_t *const false_type = skip_typeref(orig_false_type);
7357 source_position_t const *const pos = &conditional->base.source_position;
7358 type_t *result_type;
7359 if (is_type_void(true_type) || is_type_void(false_type)) {
7360 /* ISO/IEC 14882:1998(E) §5.16:2 */
7361 if (true_expression->kind == EXPR_UNARY_THROW) {
7362 result_type = false_type;
7363 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7364 result_type = true_type;
7366 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7367 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7369 result_type = type_void;
7371 } else if (is_type_arithmetic(true_type)
7372 && is_type_arithmetic(false_type)) {
7373 result_type = semantic_arithmetic(true_type, false_type);
7374 } else if (same_compound_type(true_type, false_type)) {
7375 /* just take 1 of the 2 types */
7376 result_type = true_type;
7377 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7378 type_t *pointer_type;
7380 expression_t *other_expression;
7381 if (is_type_pointer(true_type) &&
7382 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7383 pointer_type = true_type;
7384 other_type = false_type;
7385 other_expression = false_expression;
7387 pointer_type = false_type;
7388 other_type = true_type;
7389 other_expression = true_expression;
7392 if (is_null_pointer_constant(other_expression)) {
7393 result_type = pointer_type;
7394 } else if (is_type_pointer(other_type)) {
7395 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7396 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7399 if (is_type_void(to1) || is_type_void(to2)) {
7401 } else if (types_compatible(get_unqualified_type(to1),
7402 get_unqualified_type(to2))) {
7405 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7409 type_t *const type =
7410 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7411 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7412 } else if (is_type_integer(other_type)) {
7413 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7414 result_type = pointer_type;
7416 goto types_incompatible;
7420 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7421 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7423 result_type = type_error_type;
7426 conditional->true_expression
7427 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7428 conditional->false_expression
7429 = create_implicit_cast(false_expression, result_type);
7430 conditional->base.type = result_type;
7435 * Parse an extension expression.
7437 static expression_t *parse_extension(void)
7440 expression_t *expression = parse_subexpression(PREC_UNARY);
7446 * Parse a __builtin_classify_type() expression.
7448 static expression_t *parse_builtin_classify_type(void)
7450 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7451 result->base.type = type_int;
7453 eat(T___builtin_classify_type);
7456 add_anchor_token(')');
7457 expression_t *expression = parse_expression();
7458 rem_anchor_token(')');
7460 result->classify_type.type_expression = expression;
7466 * Parse a delete expression
7467 * ISO/IEC 14882:1998(E) §5.3.5
7469 static expression_t *parse_delete(void)
7471 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7472 result->base.type = type_void;
7477 result->kind = EXPR_UNARY_DELETE_ARRAY;
7481 expression_t *const value = parse_subexpression(PREC_CAST);
7482 result->unary.value = value;
7484 type_t *const type = skip_typeref(value->base.type);
7485 if (!is_type_pointer(type)) {
7486 if (is_type_valid(type)) {
7487 errorf(&value->base.source_position,
7488 "operand of delete must have pointer type");
7490 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7491 source_position_t const *const pos = &value->base.source_position;
7492 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7499 * Parse a throw expression
7500 * ISO/IEC 14882:1998(E) §15:1
7502 static expression_t *parse_throw(void)
7504 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7505 result->base.type = type_void;
7509 expression_t *value = NULL;
7510 switch (token.kind) {
7512 value = parse_assignment_expression();
7513 /* ISO/IEC 14882:1998(E) §15.1:3 */
7514 type_t *const orig_type = value->base.type;
7515 type_t *const type = skip_typeref(orig_type);
7516 if (is_type_incomplete(type)) {
7517 errorf(&value->base.source_position,
7518 "cannot throw object of incomplete type '%T'", orig_type);
7519 } else if (is_type_pointer(type)) {
7520 type_t *const points_to = skip_typeref(type->pointer.points_to);
7521 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7522 errorf(&value->base.source_position,
7523 "cannot throw pointer to incomplete type '%T'", orig_type);
7531 result->unary.value = value;
7536 static bool check_pointer_arithmetic(const source_position_t *source_position,
7537 type_t *pointer_type,
7538 type_t *orig_pointer_type)
7540 type_t *points_to = pointer_type->pointer.points_to;
7541 points_to = skip_typeref(points_to);
7543 if (is_type_incomplete(points_to)) {
7544 if (!GNU_MODE || !is_type_void(points_to)) {
7545 errorf(source_position,
7546 "arithmetic with pointer to incomplete type '%T' not allowed",
7550 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7552 } else if (is_type_function(points_to)) {
7554 errorf(source_position,
7555 "arithmetic with pointer to function type '%T' not allowed",
7559 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7565 static bool is_lvalue(const expression_t *expression)
7567 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7568 switch (expression->kind) {
7569 case EXPR_ARRAY_ACCESS:
7570 case EXPR_COMPOUND_LITERAL:
7571 case EXPR_REFERENCE:
7573 case EXPR_UNARY_DEREFERENCE:
7577 type_t *type = skip_typeref(expression->base.type);
7579 /* ISO/IEC 14882:1998(E) §3.10:3 */
7580 is_type_reference(type) ||
7581 /* Claim it is an lvalue, if the type is invalid. There was a parse
7582 * error before, which maybe prevented properly recognizing it as
7584 !is_type_valid(type);
7589 static void semantic_incdec(unary_expression_t *expression)
7591 type_t *const orig_type = expression->value->base.type;
7592 type_t *const type = skip_typeref(orig_type);
7593 if (is_type_pointer(type)) {
7594 if (!check_pointer_arithmetic(&expression->base.source_position,
7598 } else if (!is_type_real(type) && is_type_valid(type)) {
7599 /* TODO: improve error message */
7600 errorf(&expression->base.source_position,
7601 "operation needs an arithmetic or pointer type");
7604 if (!is_lvalue(expression->value)) {
7605 /* TODO: improve error message */
7606 errorf(&expression->base.source_position, "lvalue required as operand");
7608 expression->base.type = orig_type;
7611 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7613 type_t *const res_type = promote_integer(type);
7614 expr->base.type = res_type;
7615 expr->value = create_implicit_cast(expr->value, res_type);
7618 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7620 type_t *const orig_type = expression->value->base.type;
7621 type_t *const type = skip_typeref(orig_type);
7622 if (!is_type_arithmetic(type)) {
7623 if (is_type_valid(type)) {
7624 /* TODO: improve error message */
7625 errorf(&expression->base.source_position,
7626 "operation needs an arithmetic type");
7629 } else if (is_type_integer(type)) {
7630 promote_unary_int_expr(expression, type);
7632 expression->base.type = orig_type;
7636 static void semantic_unexpr_plus(unary_expression_t *expression)
7638 semantic_unexpr_arithmetic(expression);
7639 source_position_t const *const pos = &expression->base.source_position;
7640 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7643 static void semantic_not(unary_expression_t *expression)
7645 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7646 semantic_condition(expression->value, "operand of !");
7647 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7650 static void semantic_unexpr_integer(unary_expression_t *expression)
7652 type_t *const orig_type = expression->value->base.type;
7653 type_t *const type = skip_typeref(orig_type);
7654 if (!is_type_integer(type)) {
7655 if (is_type_valid(type)) {
7656 errorf(&expression->base.source_position,
7657 "operand of ~ must be of integer type");
7662 promote_unary_int_expr(expression, type);
7665 static void semantic_dereference(unary_expression_t *expression)
7667 type_t *const orig_type = expression->value->base.type;
7668 type_t *const type = skip_typeref(orig_type);
7669 if (!is_type_pointer(type)) {
7670 if (is_type_valid(type)) {
7671 errorf(&expression->base.source_position,
7672 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7677 type_t *result_type = type->pointer.points_to;
7678 result_type = automatic_type_conversion(result_type);
7679 expression->base.type = result_type;
7683 * Record that an address is taken (expression represents an lvalue).
7685 * @param expression the expression
7686 * @param may_be_register if true, the expression might be an register
7688 static void set_address_taken(expression_t *expression, bool may_be_register)
7690 if (expression->kind != EXPR_REFERENCE)
7693 entity_t *const entity = expression->reference.entity;
7695 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7698 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7699 && !may_be_register) {
7700 source_position_t const *const pos = &expression->base.source_position;
7701 errorf(pos, "address of register '%N' requested", entity);
7704 if (entity->kind == ENTITY_VARIABLE) {
7705 entity->variable.address_taken = true;
7707 assert(entity->kind == ENTITY_PARAMETER);
7708 entity->parameter.address_taken = true;
7713 * Check the semantic of the address taken expression.
7715 static void semantic_take_addr(unary_expression_t *expression)
7717 expression_t *value = expression->value;
7718 value->base.type = revert_automatic_type_conversion(value);
7720 type_t *orig_type = value->base.type;
7721 type_t *type = skip_typeref(orig_type);
7722 if (!is_type_valid(type))
7726 if (!is_lvalue(value)) {
7727 errorf(&expression->base.source_position, "'&' requires an lvalue");
7729 if (is_bitfield(value)) {
7730 errorf(&expression->base.source_position,
7731 "'&' not allowed on bitfield");
7734 set_address_taken(value, false);
7736 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7739 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7740 static expression_t *parse_##unexpression_type(void) \
7742 expression_t *unary_expression \
7743 = allocate_expression_zero(unexpression_type); \
7745 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7747 sfunc(&unary_expression->unary); \
7749 return unary_expression; \
7752 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7753 semantic_unexpr_arithmetic)
7754 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7755 semantic_unexpr_plus)
7756 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7758 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7759 semantic_dereference)
7760 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7762 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7763 semantic_unexpr_integer)
7764 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7766 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7769 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7771 static expression_t *parse_##unexpression_type(expression_t *left) \
7773 expression_t *unary_expression \
7774 = allocate_expression_zero(unexpression_type); \
7776 unary_expression->unary.value = left; \
7778 sfunc(&unary_expression->unary); \
7780 return unary_expression; \
7783 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7784 EXPR_UNARY_POSTFIX_INCREMENT,
7786 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7787 EXPR_UNARY_POSTFIX_DECREMENT,
7790 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7792 /* TODO: handle complex + imaginary types */
7794 type_left = get_unqualified_type(type_left);
7795 type_right = get_unqualified_type(type_right);
7797 /* §6.3.1.8 Usual arithmetic conversions */
7798 if (type_left == type_long_double || type_right == type_long_double) {
7799 return type_long_double;
7800 } else if (type_left == type_double || type_right == type_double) {
7802 } else if (type_left == type_float || type_right == type_float) {
7806 type_left = promote_integer(type_left);
7807 type_right = promote_integer(type_right);
7809 if (type_left == type_right)
7812 bool const signed_left = is_type_signed(type_left);
7813 bool const signed_right = is_type_signed(type_right);
7814 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7815 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7817 if (signed_left == signed_right)
7818 return rank_left >= rank_right ? type_left : type_right;
7822 atomic_type_kind_t s_akind;
7823 atomic_type_kind_t u_akind;
7828 u_type = type_right;
7830 s_type = type_right;
7833 s_akind = get_akind(s_type);
7834 u_akind = get_akind(u_type);
7835 s_rank = get_akind_rank(s_akind);
7836 u_rank = get_akind_rank(u_akind);
7838 if (u_rank >= s_rank)
7841 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7845 case ATOMIC_TYPE_INT: return type_unsigned_int;
7846 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7847 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7849 default: panic("invalid atomic type");
7854 * Check the semantic restrictions for a binary expression.
7856 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7858 expression_t *const left = expression->left;
7859 expression_t *const right = expression->right;
7860 type_t *const orig_type_left = left->base.type;
7861 type_t *const orig_type_right = right->base.type;
7862 type_t *const type_left = skip_typeref(orig_type_left);
7863 type_t *const type_right = skip_typeref(orig_type_right);
7865 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7866 /* TODO: improve error message */
7867 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7868 errorf(&expression->base.source_position,
7869 "operation needs arithmetic types");
7874 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7875 expression->left = create_implicit_cast(left, arithmetic_type);
7876 expression->right = create_implicit_cast(right, arithmetic_type);
7877 expression->base.type = arithmetic_type;
7880 static void semantic_binexpr_integer(binary_expression_t *const expression)
7882 expression_t *const left = expression->left;
7883 expression_t *const right = expression->right;
7884 type_t *const orig_type_left = left->base.type;
7885 type_t *const orig_type_right = right->base.type;
7886 type_t *const type_left = skip_typeref(orig_type_left);
7887 type_t *const type_right = skip_typeref(orig_type_right);
7889 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7890 /* TODO: improve error message */
7891 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7892 errorf(&expression->base.source_position,
7893 "operation needs integer types");
7898 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7899 expression->left = create_implicit_cast(left, result_type);
7900 expression->right = create_implicit_cast(right, result_type);
7901 expression->base.type = result_type;
7904 static void warn_div_by_zero(binary_expression_t const *const expression)
7906 if (!is_type_integer(expression->base.type))
7909 expression_t const *const right = expression->right;
7910 /* The type of the right operand can be different for /= */
7911 if (is_type_integer(right->base.type) &&
7912 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7913 !fold_constant_to_bool(right)) {
7914 source_position_t const *const pos = &expression->base.source_position;
7915 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7920 * Check the semantic restrictions for a div/mod expression.
7922 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7924 semantic_binexpr_arithmetic(expression);
7925 warn_div_by_zero(expression);
7928 static void warn_addsub_in_shift(const expression_t *const expr)
7930 if (expr->base.parenthesized)
7934 switch (expr->kind) {
7935 case EXPR_BINARY_ADD: op = '+'; break;
7936 case EXPR_BINARY_SUB: op = '-'; break;
7940 source_position_t const *const pos = &expr->base.source_position;
7941 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7944 static bool semantic_shift(binary_expression_t *expression)
7946 expression_t *const left = expression->left;
7947 expression_t *const right = expression->right;
7948 type_t *const orig_type_left = left->base.type;
7949 type_t *const orig_type_right = right->base.type;
7950 type_t * type_left = skip_typeref(orig_type_left);
7951 type_t * type_right = skip_typeref(orig_type_right);
7953 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7954 /* TODO: improve error message */
7955 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7956 errorf(&expression->base.source_position,
7957 "operands of shift operation must have integer types");
7962 type_left = promote_integer(type_left);
7964 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7965 source_position_t const *const pos = &right->base.source_position;
7966 long const count = fold_constant_to_int(right);
7968 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7969 } else if ((unsigned long)count >=
7970 get_atomic_type_size(type_left->atomic.akind) * 8) {
7971 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7975 type_right = promote_integer(type_right);
7976 expression->right = create_implicit_cast(right, type_right);
7981 static void semantic_shift_op(binary_expression_t *expression)
7983 expression_t *const left = expression->left;
7984 expression_t *const right = expression->right;
7986 if (!semantic_shift(expression))
7989 warn_addsub_in_shift(left);
7990 warn_addsub_in_shift(right);
7992 type_t *const orig_type_left = left->base.type;
7993 type_t * type_left = skip_typeref(orig_type_left);
7995 type_left = promote_integer(type_left);
7996 expression->left = create_implicit_cast(left, type_left);
7997 expression->base.type = type_left;
8000 static void semantic_add(binary_expression_t *expression)
8002 expression_t *const left = expression->left;
8003 expression_t *const right = expression->right;
8004 type_t *const orig_type_left = left->base.type;
8005 type_t *const orig_type_right = right->base.type;
8006 type_t *const type_left = skip_typeref(orig_type_left);
8007 type_t *const type_right = skip_typeref(orig_type_right);
8010 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8011 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8012 expression->left = create_implicit_cast(left, arithmetic_type);
8013 expression->right = create_implicit_cast(right, arithmetic_type);
8014 expression->base.type = arithmetic_type;
8015 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8016 check_pointer_arithmetic(&expression->base.source_position,
8017 type_left, orig_type_left);
8018 expression->base.type = type_left;
8019 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8020 check_pointer_arithmetic(&expression->base.source_position,
8021 type_right, orig_type_right);
8022 expression->base.type = type_right;
8023 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8024 errorf(&expression->base.source_position,
8025 "invalid operands to binary + ('%T', '%T')",
8026 orig_type_left, orig_type_right);
8030 static void semantic_sub(binary_expression_t *expression)
8032 expression_t *const left = expression->left;
8033 expression_t *const right = expression->right;
8034 type_t *const orig_type_left = left->base.type;
8035 type_t *const orig_type_right = right->base.type;
8036 type_t *const type_left = skip_typeref(orig_type_left);
8037 type_t *const type_right = skip_typeref(orig_type_right);
8038 source_position_t const *const pos = &expression->base.source_position;
8041 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8042 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8043 expression->left = create_implicit_cast(left, arithmetic_type);
8044 expression->right = create_implicit_cast(right, arithmetic_type);
8045 expression->base.type = arithmetic_type;
8046 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8047 check_pointer_arithmetic(&expression->base.source_position,
8048 type_left, orig_type_left);
8049 expression->base.type = type_left;
8050 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8051 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8052 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8053 if (!types_compatible(unqual_left, unqual_right)) {
8055 "subtracting pointers to incompatible types '%T' and '%T'",
8056 orig_type_left, orig_type_right);
8057 } else if (!is_type_object(unqual_left)) {
8058 if (!is_type_void(unqual_left)) {
8059 errorf(pos, "subtracting pointers to non-object types '%T'",
8062 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8065 expression->base.type = type_ptrdiff_t;
8066 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8067 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8068 orig_type_left, orig_type_right);
8072 static void warn_string_literal_address(expression_t const* expr)
8074 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8075 expr = expr->unary.value;
8076 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8078 expr = expr->unary.value;
8081 if (expr->kind == EXPR_STRING_LITERAL
8082 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8083 source_position_t const *const pos = &expr->base.source_position;
8084 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8088 static bool maybe_negative(expression_t const *const expr)
8090 switch (is_constant_expression(expr)) {
8091 case EXPR_CLASS_ERROR: return false;
8092 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8093 default: return true;
8097 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8099 warn_string_literal_address(expr);
8101 expression_t const* const ref = get_reference_address(expr);
8102 if (ref != NULL && is_null_pointer_constant(other)) {
8103 entity_t const *const ent = ref->reference.entity;
8104 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8107 if (!expr->base.parenthesized) {
8108 switch (expr->base.kind) {
8109 case EXPR_BINARY_LESS:
8110 case EXPR_BINARY_GREATER:
8111 case EXPR_BINARY_LESSEQUAL:
8112 case EXPR_BINARY_GREATEREQUAL:
8113 case EXPR_BINARY_NOTEQUAL:
8114 case EXPR_BINARY_EQUAL:
8115 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8124 * Check the semantics of comparison expressions.
8126 * @param expression The expression to check.
8128 static void semantic_comparison(binary_expression_t *expression)
8130 source_position_t const *const pos = &expression->base.source_position;
8131 expression_t *const left = expression->left;
8132 expression_t *const right = expression->right;
8134 warn_comparison(pos, left, right);
8135 warn_comparison(pos, right, left);
8137 type_t *orig_type_left = left->base.type;
8138 type_t *orig_type_right = right->base.type;
8139 type_t *type_left = skip_typeref(orig_type_left);
8140 type_t *type_right = skip_typeref(orig_type_right);
8142 /* TODO non-arithmetic types */
8143 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8144 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8146 /* test for signed vs unsigned compares */
8147 if (is_type_integer(arithmetic_type)) {
8148 bool const signed_left = is_type_signed(type_left);
8149 bool const signed_right = is_type_signed(type_right);
8150 if (signed_left != signed_right) {
8151 /* FIXME long long needs better const folding magic */
8152 /* TODO check whether constant value can be represented by other type */
8153 if ((signed_left && maybe_negative(left)) ||
8154 (signed_right && maybe_negative(right))) {
8155 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8160 expression->left = create_implicit_cast(left, arithmetic_type);
8161 expression->right = create_implicit_cast(right, arithmetic_type);
8162 expression->base.type = arithmetic_type;
8163 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8164 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8165 is_type_float(arithmetic_type)) {
8166 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8168 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8169 /* TODO check compatibility */
8170 } else if (is_type_pointer(type_left)) {
8171 expression->right = create_implicit_cast(right, type_left);
8172 } else if (is_type_pointer(type_right)) {
8173 expression->left = create_implicit_cast(left, type_right);
8174 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8175 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8177 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8181 * Checks if a compound type has constant fields.
8183 static bool has_const_fields(const compound_type_t *type)
8185 compound_t *compound = type->compound;
8186 entity_t *entry = compound->members.entities;
8188 for (; entry != NULL; entry = entry->base.next) {
8189 if (!is_declaration(entry))
8192 const type_t *decl_type = skip_typeref(entry->declaration.type);
8193 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8200 static bool is_valid_assignment_lhs(expression_t const* const left)
8202 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8203 type_t *const type_left = skip_typeref(orig_type_left);
8205 if (!is_lvalue(left)) {
8206 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8211 if (left->kind == EXPR_REFERENCE
8212 && left->reference.entity->kind == ENTITY_FUNCTION) {
8213 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8217 if (is_type_array(type_left)) {
8218 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8221 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8222 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8226 if (is_type_incomplete(type_left)) {
8227 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8228 left, orig_type_left);
8231 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8232 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8233 left, orig_type_left);
8240 static void semantic_arithmetic_assign(binary_expression_t *expression)
8242 expression_t *left = expression->left;
8243 expression_t *right = expression->right;
8244 type_t *orig_type_left = left->base.type;
8245 type_t *orig_type_right = right->base.type;
8247 if (!is_valid_assignment_lhs(left))
8250 type_t *type_left = skip_typeref(orig_type_left);
8251 type_t *type_right = skip_typeref(orig_type_right);
8253 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8254 /* TODO: improve error message */
8255 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8256 errorf(&expression->base.source_position,
8257 "operation needs arithmetic types");
8262 /* combined instructions are tricky. We can't create an implicit cast on
8263 * the left side, because we need the uncasted form for the store.
8264 * The ast2firm pass has to know that left_type must be right_type
8265 * for the arithmetic operation and create a cast by itself */
8266 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8267 expression->right = create_implicit_cast(right, arithmetic_type);
8268 expression->base.type = type_left;
8271 static void semantic_divmod_assign(binary_expression_t *expression)
8273 semantic_arithmetic_assign(expression);
8274 warn_div_by_zero(expression);
8277 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8279 expression_t *const left = expression->left;
8280 expression_t *const right = expression->right;
8281 type_t *const orig_type_left = left->base.type;
8282 type_t *const orig_type_right = right->base.type;
8283 type_t *const type_left = skip_typeref(orig_type_left);
8284 type_t *const type_right = skip_typeref(orig_type_right);
8286 if (!is_valid_assignment_lhs(left))
8289 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8290 /* combined instructions are tricky. We can't create an implicit cast on
8291 * the left side, because we need the uncasted form for the store.
8292 * The ast2firm pass has to know that left_type must be right_type
8293 * for the arithmetic operation and create a cast by itself */
8294 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8295 expression->right = create_implicit_cast(right, arithmetic_type);
8296 expression->base.type = type_left;
8297 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8298 check_pointer_arithmetic(&expression->base.source_position,
8299 type_left, orig_type_left);
8300 expression->base.type = type_left;
8301 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8302 errorf(&expression->base.source_position,
8303 "incompatible types '%T' and '%T' in assignment",
8304 orig_type_left, orig_type_right);
8308 static void semantic_integer_assign(binary_expression_t *expression)
8310 expression_t *left = expression->left;
8311 expression_t *right = expression->right;
8312 type_t *orig_type_left = left->base.type;
8313 type_t *orig_type_right = right->base.type;
8315 if (!is_valid_assignment_lhs(left))
8318 type_t *type_left = skip_typeref(orig_type_left);
8319 type_t *type_right = skip_typeref(orig_type_right);
8321 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8322 /* TODO: improve error message */
8323 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8324 errorf(&expression->base.source_position,
8325 "operation needs integer types");
8330 /* combined instructions are tricky. We can't create an implicit cast on
8331 * the left side, because we need the uncasted form for the store.
8332 * The ast2firm pass has to know that left_type must be right_type
8333 * for the arithmetic operation and create a cast by itself */
8334 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8335 expression->right = create_implicit_cast(right, arithmetic_type);
8336 expression->base.type = type_left;
8339 static void semantic_shift_assign(binary_expression_t *expression)
8341 expression_t *left = expression->left;
8343 if (!is_valid_assignment_lhs(left))
8346 if (!semantic_shift(expression))
8349 expression->base.type = skip_typeref(left->base.type);
8352 static void warn_logical_and_within_or(const expression_t *const expr)
8354 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8356 if (expr->base.parenthesized)
8358 source_position_t const *const pos = &expr->base.source_position;
8359 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8363 * Check the semantic restrictions of a logical expression.
8365 static void semantic_logical_op(binary_expression_t *expression)
8367 /* §6.5.13:2 Each of the operands shall have scalar type.
8368 * §6.5.14:2 Each of the operands shall have scalar type. */
8369 semantic_condition(expression->left, "left operand of logical operator");
8370 semantic_condition(expression->right, "right operand of logical operator");
8371 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8372 warn_logical_and_within_or(expression->left);
8373 warn_logical_and_within_or(expression->right);
8375 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8379 * Check the semantic restrictions of a binary assign expression.
8381 static void semantic_binexpr_assign(binary_expression_t *expression)
8383 expression_t *left = expression->left;
8384 type_t *orig_type_left = left->base.type;
8386 if (!is_valid_assignment_lhs(left))
8389 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8390 report_assign_error(error, orig_type_left, expression->right,
8391 "assignment", &left->base.source_position);
8392 expression->right = create_implicit_cast(expression->right, orig_type_left);
8393 expression->base.type = orig_type_left;
8397 * Determine if the outermost operation (or parts thereof) of the given
8398 * expression has no effect in order to generate a warning about this fact.
8399 * Therefore in some cases this only examines some of the operands of the
8400 * expression (see comments in the function and examples below).
8402 * f() + 23; // warning, because + has no effect
8403 * x || f(); // no warning, because x controls execution of f()
8404 * x ? y : f(); // warning, because y has no effect
8405 * (void)x; // no warning to be able to suppress the warning
8406 * This function can NOT be used for an "expression has definitely no effect"-
8408 static bool expression_has_effect(const expression_t *const expr)
8410 switch (expr->kind) {
8411 case EXPR_ERROR: return true; /* do NOT warn */
8412 case EXPR_REFERENCE: return false;
8413 case EXPR_ENUM_CONSTANT: return false;
8414 case EXPR_LABEL_ADDRESS: return false;
8416 /* suppress the warning for microsoft __noop operations */
8417 case EXPR_LITERAL_MS_NOOP: return true;
8418 case EXPR_LITERAL_BOOLEAN:
8419 case EXPR_LITERAL_CHARACTER:
8420 case EXPR_LITERAL_WIDE_CHARACTER:
8421 case EXPR_LITERAL_INTEGER:
8422 case EXPR_LITERAL_FLOATINGPOINT:
8423 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8424 case EXPR_STRING_LITERAL: return false;
8425 case EXPR_WIDE_STRING_LITERAL: return false;
8428 const call_expression_t *const call = &expr->call;
8429 if (call->function->kind != EXPR_REFERENCE)
8432 switch (call->function->reference.entity->function.btk) {
8433 /* FIXME: which builtins have no effect? */
8434 default: return true;
8438 /* Generate the warning if either the left or right hand side of a
8439 * conditional expression has no effect */
8440 case EXPR_CONDITIONAL: {
8441 conditional_expression_t const *const cond = &expr->conditional;
8442 expression_t const *const t = cond->true_expression;
8444 (t == NULL || expression_has_effect(t)) &&
8445 expression_has_effect(cond->false_expression);
8448 case EXPR_SELECT: return false;
8449 case EXPR_ARRAY_ACCESS: return false;
8450 case EXPR_SIZEOF: return false;
8451 case EXPR_CLASSIFY_TYPE: return false;
8452 case EXPR_ALIGNOF: return false;
8454 case EXPR_FUNCNAME: return false;
8455 case EXPR_BUILTIN_CONSTANT_P: return false;
8456 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8457 case EXPR_OFFSETOF: return false;
8458 case EXPR_VA_START: return true;
8459 case EXPR_VA_ARG: return true;
8460 case EXPR_VA_COPY: return true;
8461 case EXPR_STATEMENT: return true; // TODO
8462 case EXPR_COMPOUND_LITERAL: return false;
8464 case EXPR_UNARY_NEGATE: return false;
8465 case EXPR_UNARY_PLUS: return false;
8466 case EXPR_UNARY_BITWISE_NEGATE: return false;
8467 case EXPR_UNARY_NOT: return false;
8468 case EXPR_UNARY_DEREFERENCE: return false;
8469 case EXPR_UNARY_TAKE_ADDRESS: return false;
8470 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8471 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8472 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8473 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8475 /* Treat void casts as if they have an effect in order to being able to
8476 * suppress the warning */
8477 case EXPR_UNARY_CAST: {
8478 type_t *const type = skip_typeref(expr->base.type);
8479 return is_type_void(type);
8482 case EXPR_UNARY_ASSUME: return true;
8483 case EXPR_UNARY_DELETE: return true;
8484 case EXPR_UNARY_DELETE_ARRAY: return true;
8485 case EXPR_UNARY_THROW: return true;
8487 case EXPR_BINARY_ADD: return false;
8488 case EXPR_BINARY_SUB: return false;
8489 case EXPR_BINARY_MUL: return false;
8490 case EXPR_BINARY_DIV: return false;
8491 case EXPR_BINARY_MOD: return false;
8492 case EXPR_BINARY_EQUAL: return false;
8493 case EXPR_BINARY_NOTEQUAL: return false;
8494 case EXPR_BINARY_LESS: return false;
8495 case EXPR_BINARY_LESSEQUAL: return false;
8496 case EXPR_BINARY_GREATER: return false;
8497 case EXPR_BINARY_GREATEREQUAL: return false;
8498 case EXPR_BINARY_BITWISE_AND: return false;
8499 case EXPR_BINARY_BITWISE_OR: return false;
8500 case EXPR_BINARY_BITWISE_XOR: return false;
8501 case EXPR_BINARY_SHIFTLEFT: return false;
8502 case EXPR_BINARY_SHIFTRIGHT: return false;
8503 case EXPR_BINARY_ASSIGN: return true;
8504 case EXPR_BINARY_MUL_ASSIGN: return true;
8505 case EXPR_BINARY_DIV_ASSIGN: return true;
8506 case EXPR_BINARY_MOD_ASSIGN: return true;
8507 case EXPR_BINARY_ADD_ASSIGN: return true;
8508 case EXPR_BINARY_SUB_ASSIGN: return true;
8509 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8510 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8511 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8512 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8513 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8515 /* Only examine the right hand side of && and ||, because the left hand
8516 * side already has the effect of controlling the execution of the right
8518 case EXPR_BINARY_LOGICAL_AND:
8519 case EXPR_BINARY_LOGICAL_OR:
8520 /* Only examine the right hand side of a comma expression, because the left
8521 * hand side has a separate warning */
8522 case EXPR_BINARY_COMMA:
8523 return expression_has_effect(expr->binary.right);
8525 case EXPR_BINARY_ISGREATER: return false;
8526 case EXPR_BINARY_ISGREATEREQUAL: return false;
8527 case EXPR_BINARY_ISLESS: return false;
8528 case EXPR_BINARY_ISLESSEQUAL: return false;
8529 case EXPR_BINARY_ISLESSGREATER: return false;
8530 case EXPR_BINARY_ISUNORDERED: return false;
8533 internal_errorf(HERE, "unexpected expression");
8536 static void semantic_comma(binary_expression_t *expression)
8538 const expression_t *const left = expression->left;
8539 if (!expression_has_effect(left)) {
8540 source_position_t const *const pos = &left->base.source_position;
8541 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8543 expression->base.type = expression->right->base.type;
8547 * @param prec_r precedence of the right operand
8549 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8550 static expression_t *parse_##binexpression_type(expression_t *left) \
8552 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8553 binexpr->binary.left = left; \
8556 expression_t *right = parse_subexpression(prec_r); \
8558 binexpr->binary.right = right; \
8559 sfunc(&binexpr->binary); \
8564 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8565 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8566 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8567 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8568 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8569 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8570 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8571 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8572 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8573 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8574 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8575 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8576 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8577 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8578 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8579 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8580 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8581 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8582 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8583 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8584 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8585 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8586 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8587 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8588 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8589 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8590 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8591 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8592 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8593 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8596 static expression_t *parse_subexpression(precedence_t precedence)
8598 expression_parser_function_t *parser
8599 = &expression_parsers[token.kind];
8602 if (parser->parser != NULL) {
8603 left = parser->parser();
8605 left = parse_primary_expression();
8607 assert(left != NULL);
8610 parser = &expression_parsers[token.kind];
8611 if (parser->infix_parser == NULL)
8613 if (parser->infix_precedence < precedence)
8616 left = parser->infix_parser(left);
8618 assert(left != NULL);
8625 * Parse an expression.
8627 static expression_t *parse_expression(void)
8629 return parse_subexpression(PREC_EXPRESSION);
8633 * Register a parser for a prefix-like operator.
8635 * @param parser the parser function
8636 * @param token_kind the token type of the prefix token
8638 static void register_expression_parser(parse_expression_function parser,
8641 expression_parser_function_t *entry = &expression_parsers[token_kind];
8643 if (entry->parser != NULL) {
8644 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8645 panic("trying to register multiple expression parsers for a token");
8647 entry->parser = parser;
8651 * Register a parser for an infix operator with given precedence.
8653 * @param parser the parser function
8654 * @param token_kind the token type of the infix operator
8655 * @param precedence the precedence of the operator
8657 static void register_infix_parser(parse_expression_infix_function parser,
8658 int token_kind, precedence_t precedence)
8660 expression_parser_function_t *entry = &expression_parsers[token_kind];
8662 if (entry->infix_parser != NULL) {
8663 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8664 panic("trying to register multiple infix expression parsers for a "
8667 entry->infix_parser = parser;
8668 entry->infix_precedence = precedence;
8672 * Initialize the expression parsers.
8674 static void init_expression_parsers(void)
8676 memset(&expression_parsers, 0, sizeof(expression_parsers));
8678 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8679 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8680 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8681 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8682 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8683 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8684 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8685 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8686 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8687 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8688 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8689 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8690 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8691 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8692 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8693 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8694 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8695 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8696 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8697 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8698 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8699 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8700 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8701 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8702 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8703 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8704 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8705 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8706 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8707 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8708 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8709 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8710 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8711 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8712 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8713 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8714 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8716 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8717 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8718 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8719 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8720 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8721 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8722 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8723 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8724 register_expression_parser(parse_sizeof, T_sizeof);
8725 register_expression_parser(parse_alignof, T___alignof__);
8726 register_expression_parser(parse_extension, T___extension__);
8727 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8728 register_expression_parser(parse_delete, T_delete);
8729 register_expression_parser(parse_throw, T_throw);
8733 * Parse a asm statement arguments specification.
8735 static asm_argument_t *parse_asm_arguments(bool is_out)
8737 asm_argument_t *result = NULL;
8738 asm_argument_t **anchor = &result;
8740 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8741 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8744 add_anchor_token(']');
8745 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8746 rem_anchor_token(']');
8748 if (!argument->symbol)
8752 argument->constraints = parse_string_literals();
8754 add_anchor_token(')');
8755 expression_t *expression = parse_expression();
8756 rem_anchor_token(')');
8758 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8759 * change size or type representation (e.g. int -> long is ok, but
8760 * int -> float is not) */
8761 if (expression->kind == EXPR_UNARY_CAST) {
8762 type_t *const type = expression->base.type;
8763 type_kind_t const kind = type->kind;
8764 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8767 if (kind == TYPE_ATOMIC) {
8768 atomic_type_kind_t const akind = type->atomic.akind;
8769 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8770 size = get_atomic_type_size(akind);
8772 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8773 size = get_type_size(type_void_ptr);
8777 expression_t *const value = expression->unary.value;
8778 type_t *const value_type = value->base.type;
8779 type_kind_t const value_kind = value_type->kind;
8781 unsigned value_flags;
8782 unsigned value_size;
8783 if (value_kind == TYPE_ATOMIC) {
8784 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8785 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8786 value_size = get_atomic_type_size(value_akind);
8787 } else if (value_kind == TYPE_POINTER) {
8788 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8789 value_size = get_type_size(type_void_ptr);
8794 if (value_flags != flags || value_size != size)
8798 } while (expression->kind == EXPR_UNARY_CAST);
8802 if (!is_lvalue(expression)) {
8803 errorf(&expression->base.source_position,
8804 "asm output argument is not an lvalue");
8807 if (argument->constraints.begin[0] == '=')
8808 determine_lhs_ent(expression, NULL);
8810 mark_vars_read(expression, NULL);
8812 mark_vars_read(expression, NULL);
8814 argument->expression = expression;
8817 set_address_taken(expression, true);
8820 anchor = &argument->next;
8830 * Parse a asm statement clobber specification.
8832 static asm_clobber_t *parse_asm_clobbers(void)
8834 asm_clobber_t *result = NULL;
8835 asm_clobber_t **anchor = &result;
8837 while (token.kind == T_STRING_LITERAL) {
8838 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8839 clobber->clobber = parse_string_literals();
8842 anchor = &clobber->next;
8852 * Parse an asm statement.
8854 static statement_t *parse_asm_statement(void)
8856 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8857 asm_statement_t *asm_statement = &statement->asms;
8861 if (next_if(T_volatile))
8862 asm_statement->is_volatile = true;
8865 add_anchor_token(')');
8866 if (token.kind != T_STRING_LITERAL) {
8867 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8870 asm_statement->asm_text = parse_string_literals();
8872 add_anchor_token(':');
8873 if (!next_if(':')) {
8874 rem_anchor_token(':');
8878 asm_statement->outputs = parse_asm_arguments(true);
8879 if (!next_if(':')) {
8880 rem_anchor_token(':');
8884 asm_statement->inputs = parse_asm_arguments(false);
8885 if (!next_if(':')) {
8886 rem_anchor_token(':');
8889 rem_anchor_token(':');
8891 asm_statement->clobbers = parse_asm_clobbers();
8894 rem_anchor_token(')');
8898 if (asm_statement->outputs == NULL) {
8899 /* GCC: An 'asm' instruction without any output operands will be treated
8900 * identically to a volatile 'asm' instruction. */
8901 asm_statement->is_volatile = true;
8907 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8909 statement_t *inner_stmt;
8910 switch (token.kind) {
8912 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8913 inner_stmt = create_error_statement();
8917 if (label->kind == STATEMENT_LABEL) {
8918 /* Eat an empty statement here, to avoid the warning about an empty
8919 * statement after a label. label:; is commonly used to have a label
8920 * before a closing brace. */
8921 inner_stmt = create_empty_statement();
8928 inner_stmt = parse_statement();
8929 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8930 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8931 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8932 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8940 * Parse a case statement.
8942 static statement_t *parse_case_statement(void)
8944 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8945 source_position_t *const pos = &statement->base.source_position;
8948 add_anchor_token(':');
8950 expression_t *expression = parse_expression();
8951 type_t *expression_type = expression->base.type;
8952 type_t *skipped = skip_typeref(expression_type);
8953 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8954 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8955 expression, expression_type);
8958 type_t *type = expression_type;
8959 if (current_switch != NULL) {
8960 type_t *switch_type = current_switch->expression->base.type;
8961 if (is_type_valid(switch_type)) {
8962 expression = create_implicit_cast(expression, switch_type);
8966 statement->case_label.expression = expression;
8967 expression_classification_t const expr_class = is_constant_expression(expression);
8968 if (expr_class != EXPR_CLASS_CONSTANT) {
8969 if (expr_class != EXPR_CLASS_ERROR) {
8970 errorf(pos, "case label does not reduce to an integer constant");
8972 statement->case_label.is_bad = true;
8974 long const val = fold_constant_to_int(expression);
8975 statement->case_label.first_case = val;
8976 statement->case_label.last_case = val;
8980 if (next_if(T_DOTDOTDOT)) {
8981 expression_t *end_range = parse_expression();
8982 expression_type = expression->base.type;
8983 skipped = skip_typeref(expression_type);
8984 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8985 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8986 expression, expression_type);
8989 end_range = create_implicit_cast(end_range, type);
8990 statement->case_label.end_range = end_range;
8991 expression_classification_t const end_class = is_constant_expression(end_range);
8992 if (end_class != EXPR_CLASS_CONSTANT) {
8993 if (end_class != EXPR_CLASS_ERROR) {
8994 errorf(pos, "case range does not reduce to an integer constant");
8996 statement->case_label.is_bad = true;
8998 long const val = fold_constant_to_int(end_range);
8999 statement->case_label.last_case = val;
9001 if (val < statement->case_label.first_case) {
9002 statement->case_label.is_empty_range = true;
9003 warningf(WARN_OTHER, pos, "empty range specified");
9009 PUSH_PARENT(statement);
9011 rem_anchor_token(':');
9014 if (current_switch != NULL) {
9015 if (! statement->case_label.is_bad) {
9016 /* Check for duplicate case values */
9017 case_label_statement_t *c = &statement->case_label;
9018 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9019 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9022 if (c->last_case < l->first_case || c->first_case > l->last_case)
9025 errorf(pos, "duplicate case value (previously used %P)",
9026 &l->base.source_position);
9030 /* link all cases into the switch statement */
9031 if (current_switch->last_case == NULL) {
9032 current_switch->first_case = &statement->case_label;
9034 current_switch->last_case->next = &statement->case_label;
9036 current_switch->last_case = &statement->case_label;
9038 errorf(pos, "case label not within a switch statement");
9041 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9048 * Parse a default statement.
9050 static statement_t *parse_default_statement(void)
9052 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9056 PUSH_PARENT(statement);
9060 if (current_switch != NULL) {
9061 const case_label_statement_t *def_label = current_switch->default_label;
9062 if (def_label != NULL) {
9063 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9065 current_switch->default_label = &statement->case_label;
9067 /* link all cases into the switch statement */
9068 if (current_switch->last_case == NULL) {
9069 current_switch->first_case = &statement->case_label;
9071 current_switch->last_case->next = &statement->case_label;
9073 current_switch->last_case = &statement->case_label;
9076 errorf(&statement->base.source_position,
9077 "'default' label not within a switch statement");
9080 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9087 * Parse a label statement.
9089 static statement_t *parse_label_statement(void)
9091 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9092 label_t *const label = get_label();
9093 statement->label.label = label;
9095 PUSH_PARENT(statement);
9097 /* if statement is already set then the label is defined twice,
9098 * otherwise it was just mentioned in a goto/local label declaration so far
9100 source_position_t const* const pos = &statement->base.source_position;
9101 if (label->statement != NULL) {
9102 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9104 label->base.source_position = *pos;
9105 label->statement = statement;
9110 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9111 parse_attributes(NULL); // TODO process attributes
9114 statement->label.statement = parse_label_inner_statement(statement, "label");
9116 /* remember the labels in a list for later checking */
9117 *label_anchor = &statement->label;
9118 label_anchor = &statement->label.next;
9124 static statement_t *parse_inner_statement(void)
9126 statement_t *const stmt = parse_statement();
9127 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9128 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9129 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9130 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9136 * Parse an expression in parentheses and mark its variables as read.
9138 static expression_t *parse_condition(void)
9141 add_anchor_token(')');
9142 expression_t *const expr = parse_expression();
9143 mark_vars_read(expr, NULL);
9144 rem_anchor_token(')');
9150 * Parse an if statement.
9152 static statement_t *parse_if(void)
9154 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9158 PUSH_PARENT(statement);
9159 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9161 add_anchor_token(T_else);
9163 expression_t *const expr = parse_condition();
9164 statement->ifs.condition = expr;
9165 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9167 semantic_condition(expr, "condition of 'if'-statment");
9169 statement_t *const true_stmt = parse_inner_statement();
9170 statement->ifs.true_statement = true_stmt;
9171 rem_anchor_token(T_else);
9173 if (true_stmt->kind == STATEMENT_EMPTY) {
9174 warningf(WARN_EMPTY_BODY, HERE,
9175 "suggest braces around empty body in an ‘if’ statement");
9178 if (next_if(T_else)) {
9179 statement->ifs.false_statement = parse_inner_statement();
9181 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9182 warningf(WARN_EMPTY_BODY, HERE,
9183 "suggest braces around empty body in an ‘if’ statement");
9185 } else if (true_stmt->kind == STATEMENT_IF &&
9186 true_stmt->ifs.false_statement != NULL) {
9187 source_position_t const *const pos = &true_stmt->base.source_position;
9188 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9197 * Check that all enums are handled in a switch.
9199 * @param statement the switch statement to check
9201 static void check_enum_cases(const switch_statement_t *statement)
9203 if (!is_warn_on(WARN_SWITCH_ENUM))
9205 const type_t *type = skip_typeref(statement->expression->base.type);
9206 if (! is_type_enum(type))
9208 const enum_type_t *enumt = &type->enumt;
9210 /* if we have a default, no warnings */
9211 if (statement->default_label != NULL)
9214 /* FIXME: calculation of value should be done while parsing */
9215 /* TODO: quadratic algorithm here. Change to an n log n one */
9216 long last_value = -1;
9217 const entity_t *entry = enumt->enume->base.next;
9218 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9219 entry = entry->base.next) {
9220 const expression_t *expression = entry->enum_value.value;
9221 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9223 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9224 if (l->expression == NULL)
9226 if (l->first_case <= value && value <= l->last_case) {
9232 source_position_t const *const pos = &statement->base.source_position;
9233 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9240 * Parse a switch statement.
9242 static statement_t *parse_switch(void)
9244 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9248 PUSH_PARENT(statement);
9249 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9251 expression_t *const expr = parse_condition();
9252 type_t * type = skip_typeref(expr->base.type);
9253 if (is_type_integer(type)) {
9254 type = promote_integer(type);
9255 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9256 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9258 } else if (is_type_valid(type)) {
9259 errorf(&expr->base.source_position,
9260 "switch quantity is not an integer, but '%T'", type);
9261 type = type_error_type;
9263 statement->switchs.expression = create_implicit_cast(expr, type);
9265 switch_statement_t *rem = current_switch;
9266 current_switch = &statement->switchs;
9267 statement->switchs.body = parse_inner_statement();
9268 current_switch = rem;
9270 if (statement->switchs.default_label == NULL) {
9271 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9273 check_enum_cases(&statement->switchs);
9280 static statement_t *parse_loop_body(statement_t *const loop)
9282 statement_t *const rem = current_loop;
9283 current_loop = loop;
9285 statement_t *const body = parse_inner_statement();
9292 * Parse a while statement.
9294 static statement_t *parse_while(void)
9296 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9300 PUSH_PARENT(statement);
9301 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9303 expression_t *const cond = parse_condition();
9304 statement->whiles.condition = cond;
9305 /* §6.8.5:2 The controlling expression of an iteration statement shall
9306 * have scalar type. */
9307 semantic_condition(cond, "condition of 'while'-statement");
9309 statement->whiles.body = parse_loop_body(statement);
9317 * Parse a do statement.
9319 static statement_t *parse_do(void)
9321 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9325 PUSH_PARENT(statement);
9326 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9328 add_anchor_token(T_while);
9329 statement->do_while.body = parse_loop_body(statement);
9330 rem_anchor_token(T_while);
9333 expression_t *const cond = parse_condition();
9334 statement->do_while.condition = cond;
9335 /* §6.8.5:2 The controlling expression of an iteration statement shall
9336 * have scalar type. */
9337 semantic_condition(cond, "condition of 'do-while'-statement");
9346 * Parse a for statement.
9348 static statement_t *parse_for(void)
9350 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9354 PUSH_PARENT(statement);
9355 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9358 add_anchor_token(')');
9363 } else if (is_declaration_specifier(&token)) {
9364 parse_declaration(record_entity, DECL_FLAGS_NONE);
9366 add_anchor_token(';');
9367 expression_t *const init = parse_expression();
9368 statement->fors.initialisation = init;
9369 mark_vars_read(init, ENT_ANY);
9370 if (!expression_has_effect(init)) {
9371 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9373 rem_anchor_token(';');
9379 if (token.kind != ';') {
9380 add_anchor_token(';');
9381 expression_t *const cond = parse_expression();
9382 statement->fors.condition = cond;
9383 /* §6.8.5:2 The controlling expression of an iteration statement
9384 * shall have scalar type. */
9385 semantic_condition(cond, "condition of 'for'-statement");
9386 mark_vars_read(cond, NULL);
9387 rem_anchor_token(';');
9390 if (token.kind != ')') {
9391 expression_t *const step = parse_expression();
9392 statement->fors.step = step;
9393 mark_vars_read(step, ENT_ANY);
9394 if (!expression_has_effect(step)) {
9395 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9398 rem_anchor_token(')');
9400 statement->fors.body = parse_loop_body(statement);
9408 * Parse a goto statement.
9410 static statement_t *parse_goto(void)
9412 statement_t *statement;
9413 if (GNU_MODE && look_ahead(1)->kind == '*') {
9414 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9418 expression_t *expression = parse_expression();
9419 mark_vars_read(expression, NULL);
9421 /* Argh: although documentation says the expression must be of type void*,
9422 * gcc accepts anything that can be casted into void* without error */
9423 type_t *type = expression->base.type;
9425 if (type != type_error_type) {
9426 if (!is_type_pointer(type) && !is_type_integer(type)) {
9427 errorf(&expression->base.source_position,
9428 "cannot convert to a pointer type");
9429 } else if (type != type_void_ptr) {
9430 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9432 expression = create_implicit_cast(expression, type_void_ptr);
9435 statement->computed_goto.expression = expression;
9437 statement = allocate_statement_zero(STATEMENT_GOTO);
9439 if (token.kind == T_IDENTIFIER) {
9440 label_t *const label = get_label();
9442 statement->gotos.label = label;
9444 /* remember the goto's in a list for later checking */
9445 *goto_anchor = &statement->gotos;
9446 goto_anchor = &statement->gotos.next;
9449 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9451 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9453 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9462 * Parse a continue statement.
9464 static statement_t *parse_continue(void)
9466 if (current_loop == NULL) {
9467 errorf(HERE, "continue statement not within loop");
9470 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9478 * Parse a break statement.
9480 static statement_t *parse_break(void)
9482 if (current_switch == NULL && current_loop == NULL) {
9483 errorf(HERE, "break statement not within loop or switch");
9486 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9494 * Parse a __leave statement.
9496 static statement_t *parse_leave_statement(void)
9498 if (current_try == NULL) {
9499 errorf(HERE, "__leave statement not within __try");
9502 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9510 * Check if a given entity represents a local variable.
9512 static bool is_local_variable(const entity_t *entity)
9514 if (entity->kind != ENTITY_VARIABLE)
9517 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9518 case STORAGE_CLASS_AUTO:
9519 case STORAGE_CLASS_REGISTER: {
9520 const type_t *type = skip_typeref(entity->declaration.type);
9521 if (is_type_function(type)) {
9533 * Check if a given expression represents a local variable.
9535 static bool expression_is_local_variable(const expression_t *expression)
9537 if (expression->base.kind != EXPR_REFERENCE) {
9540 const entity_t *entity = expression->reference.entity;
9541 return is_local_variable(entity);
9545 * Check if a given expression represents a local variable and
9546 * return its declaration then, else return NULL.
9548 entity_t *expression_is_variable(const expression_t *expression)
9550 if (expression->base.kind != EXPR_REFERENCE) {
9553 entity_t *entity = expression->reference.entity;
9554 if (entity->kind != ENTITY_VARIABLE)
9560 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9562 if (c_mode & _CXX || strict_mode) {
9565 warningf(WARN_OTHER, pos, msg);
9570 * Parse a return statement.
9572 static statement_t *parse_return(void)
9574 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9577 expression_t *return_value = NULL;
9578 if (token.kind != ';') {
9579 return_value = parse_expression();
9580 mark_vars_read(return_value, NULL);
9583 const type_t *const func_type = skip_typeref(current_function->base.type);
9584 assert(is_type_function(func_type));
9585 type_t *const return_type = skip_typeref(func_type->function.return_type);
9587 source_position_t const *const pos = &statement->base.source_position;
9588 if (return_value != NULL) {
9589 type_t *return_value_type = skip_typeref(return_value->base.type);
9591 if (is_type_void(return_type)) {
9592 if (!is_type_void(return_value_type)) {
9593 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9594 /* Only warn in C mode, because GCC does the same */
9595 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9596 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9597 /* Only warn in C mode, because GCC does the same */
9598 err_or_warn(pos, "'return' with expression in function returning 'void'");
9601 assign_error_t error = semantic_assign(return_type, return_value);
9602 report_assign_error(error, return_type, return_value, "'return'",
9605 return_value = create_implicit_cast(return_value, return_type);
9606 /* check for returning address of a local var */
9607 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9608 const expression_t *expression = return_value->unary.value;
9609 if (expression_is_local_variable(expression)) {
9610 warningf(WARN_OTHER, pos, "function returns address of local variable");
9613 } else if (!is_type_void(return_type)) {
9614 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9615 err_or_warn(pos, "'return' without value, in function returning non-void");
9617 statement->returns.value = return_value;
9624 * Parse a declaration statement.
9626 static statement_t *parse_declaration_statement(void)
9628 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9630 entity_t *before = current_scope->last_entity;
9632 parse_external_declaration();
9634 parse_declaration(record_entity, DECL_FLAGS_NONE);
9637 declaration_statement_t *const decl = &statement->declaration;
9638 entity_t *const begin =
9639 before != NULL ? before->base.next : current_scope->entities;
9640 decl->declarations_begin = begin;
9641 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9647 * Parse an expression statement, ie. expr ';'.
9649 static statement_t *parse_expression_statement(void)
9651 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9653 expression_t *const expr = parse_expression();
9654 statement->expression.expression = expr;
9655 mark_vars_read(expr, ENT_ANY);
9662 * Parse a microsoft __try { } __finally { } or
9663 * __try{ } __except() { }
9665 static statement_t *parse_ms_try_statment(void)
9667 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9670 PUSH_PARENT(statement);
9672 ms_try_statement_t *rem = current_try;
9673 current_try = &statement->ms_try;
9674 statement->ms_try.try_statement = parse_compound_statement(false);
9679 if (next_if(T___except)) {
9680 expression_t *const expr = parse_condition();
9681 type_t * type = skip_typeref(expr->base.type);
9682 if (is_type_integer(type)) {
9683 type = promote_integer(type);
9684 } else if (is_type_valid(type)) {
9685 errorf(&expr->base.source_position,
9686 "__expect expression is not an integer, but '%T'", type);
9687 type = type_error_type;
9689 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9690 } else if (!next_if(T__finally)) {
9691 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9693 statement->ms_try.final_statement = parse_compound_statement(false);
9697 static statement_t *parse_empty_statement(void)
9699 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9700 statement_t *const statement = create_empty_statement();
9705 static statement_t *parse_local_label_declaration(void)
9707 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9711 entity_t *begin = NULL;
9712 entity_t *end = NULL;
9713 entity_t **anchor = &begin;
9715 source_position_t pos;
9716 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9720 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9721 if (entity != NULL && entity->base.parent_scope == current_scope) {
9722 source_position_t const *const ppos = &entity->base.source_position;
9723 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9725 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9726 entity->base.parent_scope = current_scope;
9729 anchor = &entity->base.next;
9732 environment_push(entity);
9734 } while (next_if(','));
9737 statement->declaration.declarations_begin = begin;
9738 statement->declaration.declarations_end = end;
9742 static void parse_namespace_definition(void)
9746 entity_t *entity = NULL;
9747 symbol_t *symbol = NULL;
9749 if (token.kind == T_IDENTIFIER) {
9750 symbol = token.identifier.symbol;
9753 entity = get_entity(symbol, NAMESPACE_NORMAL);
9755 && entity->kind != ENTITY_NAMESPACE
9756 && entity->base.parent_scope == current_scope) {
9757 if (is_entity_valid(entity)) {
9758 error_redefined_as_different_kind(&token.base.source_position,
9759 entity, ENTITY_NAMESPACE);
9765 if (entity == NULL) {
9766 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9767 entity->base.parent_scope = current_scope;
9770 if (token.kind == '=') {
9771 /* TODO: parse namespace alias */
9772 panic("namespace alias definition not supported yet");
9775 environment_push(entity);
9776 append_entity(current_scope, entity);
9778 PUSH_SCOPE(&entity->namespacee.members);
9779 PUSH_CURRENT_ENTITY(entity);
9781 add_anchor_token('}');
9784 rem_anchor_token('}');
9787 POP_CURRENT_ENTITY();
9792 * Parse a statement.
9793 * There's also parse_statement() which additionally checks for
9794 * "statement has no effect" warnings
9796 static statement_t *intern_parse_statement(void)
9798 /* declaration or statement */
9799 statement_t *statement;
9800 switch (token.kind) {
9801 case T_IDENTIFIER: {
9802 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9803 if (la1_type == ':') {
9804 statement = parse_label_statement();
9805 } else if (is_typedef_symbol(token.identifier.symbol)) {
9806 statement = parse_declaration_statement();
9808 /* it's an identifier, the grammar says this must be an
9809 * expression statement. However it is common that users mistype
9810 * declaration types, so we guess a bit here to improve robustness
9811 * for incorrect programs */
9815 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9817 statement = parse_expression_statement();
9821 statement = parse_declaration_statement();
9829 case T___extension__: {
9830 /* This can be a prefix to a declaration or an expression statement.
9831 * We simply eat it now and parse the rest with tail recursion. */
9833 statement = intern_parse_statement();
9839 statement = parse_declaration_statement();
9843 statement = parse_local_label_declaration();
9846 case ';': statement = parse_empty_statement(); break;
9847 case '{': statement = parse_compound_statement(false); break;
9848 case T___leave: statement = parse_leave_statement(); break;
9849 case T___try: statement = parse_ms_try_statment(); break;
9850 case T_asm: statement = parse_asm_statement(); break;
9851 case T_break: statement = parse_break(); break;
9852 case T_case: statement = parse_case_statement(); break;
9853 case T_continue: statement = parse_continue(); break;
9854 case T_default: statement = parse_default_statement(); break;
9855 case T_do: statement = parse_do(); break;
9856 case T_for: statement = parse_for(); break;
9857 case T_goto: statement = parse_goto(); break;
9858 case T_if: statement = parse_if(); break;
9859 case T_return: statement = parse_return(); break;
9860 case T_switch: statement = parse_switch(); break;
9861 case T_while: statement = parse_while(); break;
9864 statement = parse_expression_statement();
9868 errorf(HERE, "unexpected token %K while parsing statement", &token);
9869 statement = create_error_statement();
9878 * parse a statement and emits "statement has no effect" warning if needed
9879 * (This is really a wrapper around intern_parse_statement with check for 1
9880 * single warning. It is needed, because for statement expressions we have
9881 * to avoid the warning on the last statement)
9883 static statement_t *parse_statement(void)
9885 statement_t *statement = intern_parse_statement();
9887 if (statement->kind == STATEMENT_EXPRESSION) {
9888 expression_t *expression = statement->expression.expression;
9889 if (!expression_has_effect(expression)) {
9890 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9898 * Parse a compound statement.
9900 static statement_t *parse_compound_statement(bool inside_expression_statement)
9902 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9904 PUSH_PARENT(statement);
9905 PUSH_SCOPE(&statement->compound.scope);
9908 add_anchor_token('}');
9909 /* tokens, which can start a statement */
9910 /* TODO MS, __builtin_FOO */
9911 add_anchor_token('!');
9912 add_anchor_token('&');
9913 add_anchor_token('(');
9914 add_anchor_token('*');
9915 add_anchor_token('+');
9916 add_anchor_token('-');
9917 add_anchor_token(';');
9918 add_anchor_token('{');
9919 add_anchor_token('~');
9920 add_anchor_token(T_CHARACTER_CONSTANT);
9921 add_anchor_token(T_COLONCOLON);
9922 add_anchor_token(T_FLOATINGPOINT);
9923 add_anchor_token(T_IDENTIFIER);
9924 add_anchor_token(T_INTEGER);
9925 add_anchor_token(T_MINUSMINUS);
9926 add_anchor_token(T_PLUSPLUS);
9927 add_anchor_token(T_STRING_LITERAL);
9928 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
9929 add_anchor_token(T_WIDE_STRING_LITERAL);
9930 add_anchor_token(T__Bool);
9931 add_anchor_token(T__Complex);
9932 add_anchor_token(T__Imaginary);
9933 add_anchor_token(T___FUNCTION__);
9934 add_anchor_token(T___PRETTY_FUNCTION__);
9935 add_anchor_token(T___alignof__);
9936 add_anchor_token(T___attribute__);
9937 add_anchor_token(T___builtin_va_start);
9938 add_anchor_token(T___extension__);
9939 add_anchor_token(T___func__);
9940 add_anchor_token(T___imag__);
9941 add_anchor_token(T___label__);
9942 add_anchor_token(T___real__);
9943 add_anchor_token(T___thread);
9944 add_anchor_token(T_asm);
9945 add_anchor_token(T_auto);
9946 add_anchor_token(T_bool);
9947 add_anchor_token(T_break);
9948 add_anchor_token(T_case);
9949 add_anchor_token(T_char);
9950 add_anchor_token(T_class);
9951 add_anchor_token(T_const);
9952 add_anchor_token(T_const_cast);
9953 add_anchor_token(T_continue);
9954 add_anchor_token(T_default);
9955 add_anchor_token(T_delete);
9956 add_anchor_token(T_double);
9957 add_anchor_token(T_do);
9958 add_anchor_token(T_dynamic_cast);
9959 add_anchor_token(T_enum);
9960 add_anchor_token(T_extern);
9961 add_anchor_token(T_false);
9962 add_anchor_token(T_float);
9963 add_anchor_token(T_for);
9964 add_anchor_token(T_goto);
9965 add_anchor_token(T_if);
9966 add_anchor_token(T_inline);
9967 add_anchor_token(T_int);
9968 add_anchor_token(T_long);
9969 add_anchor_token(T_new);
9970 add_anchor_token(T_operator);
9971 add_anchor_token(T_register);
9972 add_anchor_token(T_reinterpret_cast);
9973 add_anchor_token(T_restrict);
9974 add_anchor_token(T_return);
9975 add_anchor_token(T_short);
9976 add_anchor_token(T_signed);
9977 add_anchor_token(T_sizeof);
9978 add_anchor_token(T_static);
9979 add_anchor_token(T_static_cast);
9980 add_anchor_token(T_struct);
9981 add_anchor_token(T_switch);
9982 add_anchor_token(T_template);
9983 add_anchor_token(T_this);
9984 add_anchor_token(T_throw);
9985 add_anchor_token(T_true);
9986 add_anchor_token(T_try);
9987 add_anchor_token(T_typedef);
9988 add_anchor_token(T_typeid);
9989 add_anchor_token(T_typename);
9990 add_anchor_token(T_typeof);
9991 add_anchor_token(T_union);
9992 add_anchor_token(T_unsigned);
9993 add_anchor_token(T_using);
9994 add_anchor_token(T_void);
9995 add_anchor_token(T_volatile);
9996 add_anchor_token(T_wchar_t);
9997 add_anchor_token(T_while);
9999 statement_t **anchor = &statement->compound.statements;
10000 bool only_decls_so_far = true;
10001 while (token.kind != '}' && token.kind != T_EOF) {
10002 statement_t *sub_statement = intern_parse_statement();
10003 if (sub_statement->kind == STATEMENT_ERROR) {
10007 if (sub_statement->kind != STATEMENT_DECLARATION) {
10008 only_decls_so_far = false;
10009 } else if (!only_decls_so_far) {
10010 source_position_t const *const pos = &sub_statement->base.source_position;
10011 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10014 *anchor = sub_statement;
10015 anchor = &sub_statement->base.next;
10019 /* look over all statements again to produce no effect warnings */
10020 if (is_warn_on(WARN_UNUSED_VALUE)) {
10021 statement_t *sub_statement = statement->compound.statements;
10022 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10023 if (sub_statement->kind != STATEMENT_EXPRESSION)
10025 /* don't emit a warning for the last expression in an expression
10026 * statement as it has always an effect */
10027 if (inside_expression_statement && sub_statement->base.next == NULL)
10030 expression_t *expression = sub_statement->expression.expression;
10031 if (!expression_has_effect(expression)) {
10032 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10037 rem_anchor_token(T_while);
10038 rem_anchor_token(T_wchar_t);
10039 rem_anchor_token(T_volatile);
10040 rem_anchor_token(T_void);
10041 rem_anchor_token(T_using);
10042 rem_anchor_token(T_unsigned);
10043 rem_anchor_token(T_union);
10044 rem_anchor_token(T_typeof);
10045 rem_anchor_token(T_typename);
10046 rem_anchor_token(T_typeid);
10047 rem_anchor_token(T_typedef);
10048 rem_anchor_token(T_try);
10049 rem_anchor_token(T_true);
10050 rem_anchor_token(T_throw);
10051 rem_anchor_token(T_this);
10052 rem_anchor_token(T_template);
10053 rem_anchor_token(T_switch);
10054 rem_anchor_token(T_struct);
10055 rem_anchor_token(T_static_cast);
10056 rem_anchor_token(T_static);
10057 rem_anchor_token(T_sizeof);
10058 rem_anchor_token(T_signed);
10059 rem_anchor_token(T_short);
10060 rem_anchor_token(T_return);
10061 rem_anchor_token(T_restrict);
10062 rem_anchor_token(T_reinterpret_cast);
10063 rem_anchor_token(T_register);
10064 rem_anchor_token(T_operator);
10065 rem_anchor_token(T_new);
10066 rem_anchor_token(T_long);
10067 rem_anchor_token(T_int);
10068 rem_anchor_token(T_inline);
10069 rem_anchor_token(T_if);
10070 rem_anchor_token(T_goto);
10071 rem_anchor_token(T_for);
10072 rem_anchor_token(T_float);
10073 rem_anchor_token(T_false);
10074 rem_anchor_token(T_extern);
10075 rem_anchor_token(T_enum);
10076 rem_anchor_token(T_dynamic_cast);
10077 rem_anchor_token(T_do);
10078 rem_anchor_token(T_double);
10079 rem_anchor_token(T_delete);
10080 rem_anchor_token(T_default);
10081 rem_anchor_token(T_continue);
10082 rem_anchor_token(T_const_cast);
10083 rem_anchor_token(T_const);
10084 rem_anchor_token(T_class);
10085 rem_anchor_token(T_char);
10086 rem_anchor_token(T_case);
10087 rem_anchor_token(T_break);
10088 rem_anchor_token(T_bool);
10089 rem_anchor_token(T_auto);
10090 rem_anchor_token(T_asm);
10091 rem_anchor_token(T___thread);
10092 rem_anchor_token(T___real__);
10093 rem_anchor_token(T___label__);
10094 rem_anchor_token(T___imag__);
10095 rem_anchor_token(T___func__);
10096 rem_anchor_token(T___extension__);
10097 rem_anchor_token(T___builtin_va_start);
10098 rem_anchor_token(T___attribute__);
10099 rem_anchor_token(T___alignof__);
10100 rem_anchor_token(T___PRETTY_FUNCTION__);
10101 rem_anchor_token(T___FUNCTION__);
10102 rem_anchor_token(T__Imaginary);
10103 rem_anchor_token(T__Complex);
10104 rem_anchor_token(T__Bool);
10105 rem_anchor_token(T_WIDE_STRING_LITERAL);
10106 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10107 rem_anchor_token(T_STRING_LITERAL);
10108 rem_anchor_token(T_PLUSPLUS);
10109 rem_anchor_token(T_MINUSMINUS);
10110 rem_anchor_token(T_INTEGER);
10111 rem_anchor_token(T_IDENTIFIER);
10112 rem_anchor_token(T_FLOATINGPOINT);
10113 rem_anchor_token(T_COLONCOLON);
10114 rem_anchor_token(T_CHARACTER_CONSTANT);
10115 rem_anchor_token('~');
10116 rem_anchor_token('{');
10117 rem_anchor_token(';');
10118 rem_anchor_token('-');
10119 rem_anchor_token('+');
10120 rem_anchor_token('*');
10121 rem_anchor_token('(');
10122 rem_anchor_token('&');
10123 rem_anchor_token('!');
10124 rem_anchor_token('}');
10132 * Check for unused global static functions and variables
10134 static void check_unused_globals(void)
10136 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10139 for (const entity_t *entity = file_scope->entities; entity != NULL;
10140 entity = entity->base.next) {
10141 if (!is_declaration(entity))
10144 const declaration_t *declaration = &entity->declaration;
10145 if (declaration->used ||
10146 declaration->modifiers & DM_UNUSED ||
10147 declaration->modifiers & DM_USED ||
10148 declaration->storage_class != STORAGE_CLASS_STATIC)
10153 if (entity->kind == ENTITY_FUNCTION) {
10154 /* inhibit warning for static inline functions */
10155 if (entity->function.is_inline)
10158 why = WARN_UNUSED_FUNCTION;
10159 s = entity->function.statement != NULL ? "defined" : "declared";
10161 why = WARN_UNUSED_VARIABLE;
10165 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10169 static void parse_global_asm(void)
10171 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10174 add_anchor_token(';');
10175 add_anchor_token(')');
10176 add_anchor_token(T_STRING_LITERAL);
10179 rem_anchor_token(T_STRING_LITERAL);
10180 statement->asms.asm_text = parse_string_literals();
10181 statement->base.next = unit->global_asm;
10182 unit->global_asm = statement;
10184 rem_anchor_token(')');
10186 rem_anchor_token(';');
10190 static void parse_linkage_specification(void)
10194 source_position_t const pos = *HERE;
10195 char const *const linkage = parse_string_literals().begin;
10197 linkage_kind_t old_linkage = current_linkage;
10198 linkage_kind_t new_linkage;
10199 if (streq(linkage, "C")) {
10200 new_linkage = LINKAGE_C;
10201 } else if (streq(linkage, "C++")) {
10202 new_linkage = LINKAGE_CXX;
10204 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10205 new_linkage = LINKAGE_C;
10207 current_linkage = new_linkage;
10209 if (next_if('{')) {
10216 assert(current_linkage == new_linkage);
10217 current_linkage = old_linkage;
10220 static void parse_external(void)
10222 switch (token.kind) {
10224 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10225 parse_linkage_specification();
10227 DECLARATION_START_NO_EXTERN
10229 case T___extension__:
10230 /* tokens below are for implicit int */
10231 case '&': /* & x; -> int& x; (and error later, because C++ has no
10233 case '*': /* * x; -> int* x; */
10234 case '(': /* (x); -> int (x); */
10236 parse_external_declaration();
10242 parse_global_asm();
10246 parse_namespace_definition();
10250 if (!strict_mode) {
10251 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10258 errorf(HERE, "stray %K outside of function", &token);
10259 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10260 eat_until_matching_token(token.kind);
10266 static void parse_externals(void)
10268 add_anchor_token('}');
10269 add_anchor_token(T_EOF);
10272 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10273 unsigned short token_anchor_copy[T_LAST_TOKEN];
10274 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10277 while (token.kind != T_EOF && token.kind != '}') {
10279 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10280 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10282 /* the anchor set and its copy differs */
10283 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10286 if (in_gcc_extension) {
10287 /* an gcc extension scope was not closed */
10288 internal_errorf(HERE, "Leaked __extension__");
10295 rem_anchor_token(T_EOF);
10296 rem_anchor_token('}');
10300 * Parse a translation unit.
10302 static void parse_translation_unit(void)
10304 add_anchor_token(T_EOF);
10309 if (token.kind == T_EOF)
10312 errorf(HERE, "stray %K outside of function", &token);
10313 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10314 eat_until_matching_token(token.kind);
10319 void set_default_visibility(elf_visibility_tag_t visibility)
10321 default_visibility = visibility;
10327 * @return the translation unit or NULL if errors occurred.
10329 void start_parsing(void)
10331 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10332 label_stack = NEW_ARR_F(stack_entry_t, 0);
10333 diagnostic_count = 0;
10337 print_to_file(stderr);
10339 assert(unit == NULL);
10340 unit = allocate_ast_zero(sizeof(unit[0]));
10342 assert(file_scope == NULL);
10343 file_scope = &unit->scope;
10345 assert(current_scope == NULL);
10346 scope_push(&unit->scope);
10348 create_gnu_builtins();
10350 create_microsoft_intrinsics();
10353 translation_unit_t *finish_parsing(void)
10355 assert(current_scope == &unit->scope);
10358 assert(file_scope == &unit->scope);
10359 check_unused_globals();
10362 DEL_ARR_F(environment_stack);
10363 DEL_ARR_F(label_stack);
10365 translation_unit_t *result = unit;
10370 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10371 * are given length one. */
10372 static void complete_incomplete_arrays(void)
10374 size_t n = ARR_LEN(incomplete_arrays);
10375 for (size_t i = 0; i != n; ++i) {
10376 declaration_t *const decl = incomplete_arrays[i];
10377 type_t *const type = skip_typeref(decl->type);
10379 if (!is_type_incomplete(type))
10382 source_position_t const *const pos = &decl->base.source_position;
10383 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10385 type_t *const new_type = duplicate_type(type);
10386 new_type->array.size_constant = true;
10387 new_type->array.has_implicit_size = true;
10388 new_type->array.size = 1;
10390 type_t *const result = identify_new_type(new_type);
10392 decl->type = result;
10396 static void prepare_main_collect2(entity_t *const entity)
10398 PUSH_SCOPE(&entity->function.statement->compound.scope);
10400 // create call to __main
10401 symbol_t *symbol = symbol_table_insert("__main");
10402 entity_t *subsubmain_ent
10403 = create_implicit_function(symbol, &builtin_source_position);
10405 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10406 type_t *ftype = subsubmain_ent->declaration.type;
10407 ref->base.source_position = builtin_source_position;
10408 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10409 ref->reference.entity = subsubmain_ent;
10411 expression_t *call = allocate_expression_zero(EXPR_CALL);
10412 call->base.source_position = builtin_source_position;
10413 call->base.type = type_void;
10414 call->call.function = ref;
10416 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10417 expr_statement->base.source_position = builtin_source_position;
10418 expr_statement->expression.expression = call;
10420 statement_t *statement = entity->function.statement;
10421 assert(statement->kind == STATEMENT_COMPOUND);
10422 compound_statement_t *compounds = &statement->compound;
10424 expr_statement->base.next = compounds->statements;
10425 compounds->statements = expr_statement;
10432 lookahead_bufpos = 0;
10433 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10436 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10437 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10438 parse_translation_unit();
10439 complete_incomplete_arrays();
10440 DEL_ARR_F(incomplete_arrays);
10441 incomplete_arrays = NULL;
10445 * Initialize the parser.
10447 void init_parser(void)
10449 sym_anonymous = symbol_table_insert("<anonymous>");
10451 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10453 init_expression_parsers();
10454 obstack_init(&temp_obst);
10458 * Terminate the parser.
10460 void exit_parser(void)
10462 obstack_free(&temp_obst, NULL);