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: \
254 case T_STRING_LITERAL: \
255 case T_WIDE_CHARACTER_CONSTANT: \
256 case T_WIDE_STRING_LITERAL: \
257 case T___FUNCDNAME__: \
258 case T___FUNCSIG__: \
259 case T___FUNCTION__: \
260 case T___PRETTY_FUNCTION__: \
261 case T___alignof__: \
262 case T___builtin_classify_type: \
263 case T___builtin_constant_p: \
264 case T___builtin_isgreater: \
265 case T___builtin_isgreaterequal: \
266 case T___builtin_isless: \
267 case T___builtin_islessequal: \
268 case T___builtin_islessgreater: \
269 case T___builtin_isunordered: \
270 case T___builtin_offsetof: \
271 case T___builtin_va_arg: \
272 case T___builtin_va_copy: \
273 case T___builtin_va_start: \
284 * Returns the size of a statement node.
286 * @param kind the statement kind
288 static size_t get_statement_struct_size(statement_kind_t kind)
290 static const size_t sizes[] = {
291 [STATEMENT_ERROR] = sizeof(statement_base_t),
292 [STATEMENT_EMPTY] = sizeof(statement_base_t),
293 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
294 [STATEMENT_RETURN] = sizeof(return_statement_t),
295 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
296 [STATEMENT_IF] = sizeof(if_statement_t),
297 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
298 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
299 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
300 [STATEMENT_BREAK] = sizeof(statement_base_t),
301 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
302 [STATEMENT_GOTO] = sizeof(goto_statement_t),
303 [STATEMENT_LABEL] = sizeof(label_statement_t),
304 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
305 [STATEMENT_WHILE] = sizeof(while_statement_t),
306 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
307 [STATEMENT_FOR] = sizeof(for_statement_t),
308 [STATEMENT_ASM] = sizeof(asm_statement_t),
309 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
310 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
312 assert((size_t)kind < lengthof(sizes));
313 assert(sizes[kind] != 0);
318 * Returns the size of an expression node.
320 * @param kind the expression kind
322 static size_t get_expression_struct_size(expression_kind_t kind)
324 static const size_t sizes[] = {
325 [EXPR_ERROR] = sizeof(expression_base_t),
326 [EXPR_REFERENCE] = sizeof(reference_expression_t),
327 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
328 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
332 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
333 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
334 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
335 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
336 [EXPR_CALL] = sizeof(call_expression_t),
337 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
338 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
339 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
340 [EXPR_SELECT] = sizeof(select_expression_t),
341 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
342 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
343 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
344 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
345 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
346 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
347 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
348 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
349 [EXPR_VA_START] = sizeof(va_start_expression_t),
350 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
351 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
352 [EXPR_STATEMENT] = sizeof(statement_expression_t),
353 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
355 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
356 return sizes[EXPR_UNARY_FIRST];
358 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
359 return sizes[EXPR_BINARY_FIRST];
361 assert((size_t)kind < lengthof(sizes));
362 assert(sizes[kind] != 0);
367 * Allocate a statement node of given kind and initialize all
368 * fields with zero. Sets its source position to the position
369 * of the current token.
371 static statement_t *allocate_statement_zero(statement_kind_t kind)
373 size_t size = get_statement_struct_size(kind);
374 statement_t *res = allocate_ast_zero(size);
376 res->base.kind = kind;
377 res->base.parent = current_parent;
378 res->base.source_position = token.base.source_position;
383 * Allocate an expression node of given kind and initialize all
386 * @param kind the kind of the expression to allocate
388 static expression_t *allocate_expression_zero(expression_kind_t kind)
390 size_t size = get_expression_struct_size(kind);
391 expression_t *res = allocate_ast_zero(size);
393 res->base.kind = kind;
394 res->base.type = type_error_type;
395 res->base.source_position = token.base.source_position;
400 * Creates a new invalid expression at the source position
401 * of the current token.
403 static expression_t *create_error_expression(void)
405 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
406 expression->base.type = type_error_type;
411 * Creates a new invalid statement.
413 static statement_t *create_error_statement(void)
415 return allocate_statement_zero(STATEMENT_ERROR);
419 * Allocate a new empty statement.
421 static statement_t *create_empty_statement(void)
423 return allocate_statement_zero(STATEMENT_EMPTY);
427 * Returns the size of an initializer node.
429 * @param kind the initializer kind
431 static size_t get_initializer_size(initializer_kind_t kind)
433 static const size_t sizes[] = {
434 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
435 [INITIALIZER_STRING] = sizeof(initializer_string_t),
436 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
437 [INITIALIZER_LIST] = sizeof(initializer_list_t),
438 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
440 assert((size_t)kind < lengthof(sizes));
441 assert(sizes[kind] != 0);
446 * Allocate an initializer node of given kind and initialize all
449 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
451 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
458 * Returns the index of the top element of the environment stack.
460 static size_t environment_top(void)
462 return ARR_LEN(environment_stack);
466 * Returns the index of the top element of the global label stack.
468 static size_t label_top(void)
470 return ARR_LEN(label_stack);
474 * Return the next token.
476 static inline void next_token(void)
478 token = lookahead_buffer[lookahead_bufpos];
479 lookahead_buffer[lookahead_bufpos] = lexer_token;
482 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
485 print_token(stderr, &token);
486 fprintf(stderr, "\n");
490 static inline bool next_if(token_kind_t const type)
492 if (token.kind == type) {
501 * Return the next token with a given lookahead.
503 static inline const token_t *look_ahead(size_t num)
505 assert(0 < num && num <= MAX_LOOKAHEAD);
506 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
507 return &lookahead_buffer[pos];
511 * Adds a token type to the token type anchor set (a multi-set).
513 static void add_anchor_token(token_kind_t const token_kind)
515 assert(token_kind < T_LAST_TOKEN);
516 ++token_anchor_set[token_kind];
520 * Remove a token type from the token type anchor set (a multi-set).
522 static void rem_anchor_token(token_kind_t const token_kind)
524 assert(token_kind < T_LAST_TOKEN);
525 assert(token_anchor_set[token_kind] != 0);
526 --token_anchor_set[token_kind];
530 * Eat tokens until a matching token type is found.
532 static void eat_until_matching_token(token_kind_t const type)
534 token_kind_t end_token;
536 case '(': end_token = ')'; break;
537 case '{': end_token = '}'; break;
538 case '[': end_token = ']'; break;
539 default: end_token = type; break;
542 unsigned parenthesis_count = 0;
543 unsigned brace_count = 0;
544 unsigned bracket_count = 0;
545 while (token.kind != end_token ||
546 parenthesis_count != 0 ||
548 bracket_count != 0) {
549 switch (token.kind) {
551 case '(': ++parenthesis_count; break;
552 case '{': ++brace_count; break;
553 case '[': ++bracket_count; break;
556 if (parenthesis_count > 0)
566 if (bracket_count > 0)
569 if (token.kind == end_token &&
570 parenthesis_count == 0 &&
584 * Eat input tokens until an anchor is found.
586 static void eat_until_anchor(void)
588 while (token_anchor_set[token.kind] == 0) {
589 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
590 eat_until_matching_token(token.kind);
596 * Eat a whole block from input tokens.
598 static void eat_block(void)
600 eat_until_matching_token('{');
604 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
607 * Report a parse error because an expected token was not found.
610 #if defined __GNUC__ && __GNUC__ >= 4
611 __attribute__((sentinel))
613 void parse_error_expected(const char *message, ...)
615 if (message != NULL) {
616 errorf(HERE, "%s", message);
619 va_start(ap, message);
620 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
625 * Report an incompatible type.
627 static void type_error_incompatible(const char *msg,
628 const source_position_t *source_position, type_t *type1, type_t *type2)
630 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
635 * Expect the current token is the expected token.
636 * If not, generate an error and skip until the next anchor.
638 static void expect(token_kind_t const expected)
640 if (UNLIKELY(token.kind != expected)) {
641 parse_error_expected(NULL, expected, NULL);
642 add_anchor_token(expected);
644 rem_anchor_token(expected);
645 if (token.kind != expected)
651 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
653 if (token.kind != T_IDENTIFIER) {
654 parse_error_expected(context, T_IDENTIFIER, NULL);
655 add_anchor_token(T_IDENTIFIER);
657 rem_anchor_token(T_IDENTIFIER);
658 if (token.kind != T_IDENTIFIER)
661 symbol_t *const sym = token.base.symbol;
669 * Push a given scope on the scope stack and make it the
672 static scope_t *scope_push(scope_t *new_scope)
674 if (current_scope != NULL) {
675 new_scope->depth = current_scope->depth + 1;
678 scope_t *old_scope = current_scope;
679 current_scope = new_scope;
684 * Pop the current scope from the scope stack.
686 static void scope_pop(scope_t *old_scope)
688 current_scope = old_scope;
692 * Search an entity by its symbol in a given namespace.
694 static entity_t *get_entity(const symbol_t *const symbol,
695 namespace_tag_t namespc)
697 entity_t *entity = symbol->entity;
698 for (; entity != NULL; entity = entity->base.symbol_next) {
699 if ((namespace_tag_t)entity->base.namespc == namespc)
706 /* §6.2.3:1 24) There is only one name space for tags even though three are
708 static entity_t *get_tag(symbol_t const *const symbol,
709 entity_kind_tag_t const kind)
711 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
712 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
714 "'%Y' defined as wrong kind of tag (previous definition %P)",
715 symbol, &entity->base.source_position);
722 * pushs an entity on the environment stack and links the corresponding symbol
725 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
727 symbol_t *symbol = entity->base.symbol;
728 entity_namespace_t namespc = entity->base.namespc;
729 assert(namespc != 0);
731 /* replace/add entity into entity list of the symbol */
734 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
739 /* replace an entry? */
740 if (iter->base.namespc == namespc) {
741 entity->base.symbol_next = iter->base.symbol_next;
747 /* remember old declaration */
749 entry.symbol = symbol;
750 entry.old_entity = iter;
751 entry.namespc = namespc;
752 ARR_APP1(stack_entry_t, *stack_ptr, entry);
756 * Push an entity on the environment stack.
758 static void environment_push(entity_t *entity)
760 assert(entity->base.source_position.input_name != NULL);
761 assert(entity->base.parent_scope != NULL);
762 stack_push(&environment_stack, entity);
766 * Push a declaration on the global label stack.
768 * @param declaration the declaration
770 static void label_push(entity_t *label)
772 /* we abuse the parameters scope as parent for the labels */
773 label->base.parent_scope = ¤t_function->parameters;
774 stack_push(&label_stack, label);
778 * pops symbols from the environment stack until @p new_top is the top element
780 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
782 stack_entry_t *stack = *stack_ptr;
783 size_t top = ARR_LEN(stack);
786 assert(new_top <= top);
790 for (i = top; i > new_top; --i) {
791 stack_entry_t *entry = &stack[i - 1];
793 entity_t *old_entity = entry->old_entity;
794 symbol_t *symbol = entry->symbol;
795 entity_namespace_t namespc = entry->namespc;
797 /* replace with old_entity/remove */
800 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
802 assert(iter != NULL);
803 /* replace an entry? */
804 if (iter->base.namespc == namespc)
808 /* restore definition from outer scopes (if there was one) */
809 if (old_entity != NULL) {
810 old_entity->base.symbol_next = iter->base.symbol_next;
811 *anchor = old_entity;
813 /* remove entry from list */
814 *anchor = iter->base.symbol_next;
818 ARR_SHRINKLEN(*stack_ptr, new_top);
822 * Pop all entries from the environment stack until the new_top
825 * @param new_top the new stack top
827 static void environment_pop_to(size_t new_top)
829 stack_pop_to(&environment_stack, new_top);
833 * Pop all entries from the global label stack until the new_top
836 * @param new_top the new stack top
838 static void label_pop_to(size_t new_top)
840 stack_pop_to(&label_stack, new_top);
843 static atomic_type_kind_t get_akind(const type_t *type)
845 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
846 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
847 return type->atomic.akind;
851 * §6.3.1.1:2 Do integer promotion for a given type.
853 * @param type the type to promote
854 * @return the promoted type
856 static type_t *promote_integer(type_t *type)
858 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
865 * Check if a given expression represents a null pointer constant.
867 * @param expression the expression to check
869 static bool is_null_pointer_constant(const expression_t *expression)
871 /* skip void* cast */
872 if (expression->kind == EXPR_UNARY_CAST) {
873 type_t *const type = skip_typeref(expression->base.type);
874 if (types_compatible(type, type_void_ptr))
875 expression = expression->unary.value;
878 type_t *const type = skip_typeref(expression->base.type);
879 if (!is_type_integer(type))
881 switch (is_constant_expression(expression)) {
882 case EXPR_CLASS_ERROR: return true;
883 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
884 default: return false;
889 * Create an implicit cast expression.
891 * @param expression the expression to cast
892 * @param dest_type the destination type
894 static expression_t *create_implicit_cast(expression_t *expression,
897 type_t *const source_type = expression->base.type;
899 if (source_type == dest_type)
902 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
903 cast->unary.value = expression;
904 cast->base.type = dest_type;
905 cast->base.implicit = true;
910 typedef enum assign_error_t {
912 ASSIGN_ERROR_INCOMPATIBLE,
913 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
914 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
915 ASSIGN_WARNING_POINTER_FROM_INT,
916 ASSIGN_WARNING_INT_FROM_POINTER
919 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)
921 type_t *const orig_type_right = right->base.type;
922 type_t *const type_left = skip_typeref(orig_type_left);
923 type_t *const type_right = skip_typeref(orig_type_right);
928 case ASSIGN_ERROR_INCOMPATIBLE:
929 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
932 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
933 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
934 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
936 /* the left type has all qualifiers from the right type */
937 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
938 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);
942 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
943 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
946 case ASSIGN_WARNING_POINTER_FROM_INT:
947 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
950 case ASSIGN_WARNING_INT_FROM_POINTER:
951 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
955 panic("invalid error value");
959 /** Implements the rules from §6.5.16.1 */
960 static assign_error_t semantic_assign(type_t *orig_type_left,
961 const expression_t *const right)
963 type_t *const orig_type_right = right->base.type;
964 type_t *const type_left = skip_typeref(orig_type_left);
965 type_t *const type_right = skip_typeref(orig_type_right);
967 if (is_type_pointer(type_left)) {
968 if (is_null_pointer_constant(right)) {
969 return ASSIGN_SUCCESS;
970 } else if (is_type_pointer(type_right)) {
971 type_t *points_to_left
972 = skip_typeref(type_left->pointer.points_to);
973 type_t *points_to_right
974 = skip_typeref(type_right->pointer.points_to);
975 assign_error_t res = ASSIGN_SUCCESS;
977 /* the left type has all qualifiers from the right type */
978 unsigned missing_qualifiers
979 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
980 if (missing_qualifiers != 0) {
981 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
984 points_to_left = get_unqualified_type(points_to_left);
985 points_to_right = get_unqualified_type(points_to_right);
987 if (is_type_void(points_to_left))
990 if (is_type_void(points_to_right)) {
991 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
992 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
995 if (!types_compatible(points_to_left, points_to_right)) {
996 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1000 } else if (is_type_integer(type_right)) {
1001 return ASSIGN_WARNING_POINTER_FROM_INT;
1003 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1004 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1005 && is_type_pointer(type_right))) {
1006 return ASSIGN_SUCCESS;
1007 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1008 type_t *const unqual_type_left = get_unqualified_type(type_left);
1009 type_t *const unqual_type_right = get_unqualified_type(type_right);
1010 if (types_compatible(unqual_type_left, unqual_type_right)) {
1011 return ASSIGN_SUCCESS;
1013 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1014 return ASSIGN_WARNING_INT_FROM_POINTER;
1017 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1018 return ASSIGN_SUCCESS;
1020 return ASSIGN_ERROR_INCOMPATIBLE;
1023 static expression_t *parse_constant_expression(void)
1025 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1027 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1028 errorf(&result->base.source_position,
1029 "expression '%E' is not constant", result);
1035 static expression_t *parse_assignment_expression(void)
1037 return parse_subexpression(PREC_ASSIGNMENT);
1040 static void warn_string_concat(const source_position_t *pos)
1042 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1045 static string_t parse_string_literals(void)
1047 assert(token.kind == T_STRING_LITERAL);
1048 string_t result = token.string.string;
1052 while (token.kind == T_STRING_LITERAL) {
1053 warn_string_concat(&token.base.source_position);
1054 result = concat_strings(&result, &token.string.string);
1061 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1063 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1064 attribute->kind = kind;
1065 attribute->source_position = *HERE;
1070 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1073 * __attribute__ ( ( attribute-list ) )
1077 * attribute_list , attrib
1082 * any-word ( identifier )
1083 * any-word ( identifier , nonempty-expr-list )
1084 * any-word ( expr-list )
1086 * where the "identifier" must not be declared as a type, and
1087 * "any-word" may be any identifier (including one declared as a
1088 * type), a reserved word storage class specifier, type specifier or
1089 * type qualifier. ??? This still leaves out most reserved keywords
1090 * (following the old parser), shouldn't we include them, and why not
1091 * allow identifiers declared as types to start the arguments?
1093 * Matze: this all looks confusing and little systematic, so we're even less
1094 * strict and parse any list of things which are identifiers or
1095 * (assignment-)expressions.
1097 static attribute_argument_t *parse_attribute_arguments(void)
1099 attribute_argument_t *first = NULL;
1100 attribute_argument_t **anchor = &first;
1101 if (token.kind != ')') do {
1102 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1104 /* is it an identifier */
1105 if (token.kind == T_IDENTIFIER
1106 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1107 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1108 argument->v.symbol = token.base.symbol;
1111 /* must be an expression */
1112 expression_t *expression = parse_assignment_expression();
1114 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1115 argument->v.expression = expression;
1118 /* append argument */
1120 anchor = &argument->next;
1121 } while (next_if(','));
1126 static attribute_t *parse_attribute_asm(void)
1128 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1131 attribute->a.arguments = parse_attribute_arguments();
1135 static attribute_t *parse_attribute_gnu_single(void)
1137 /* parse "any-word" */
1138 symbol_t *const symbol = token.base.symbol;
1139 if (symbol == NULL) {
1140 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1144 attribute_kind_t kind;
1145 char const *const name = symbol->string;
1146 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1147 if (kind > ATTRIBUTE_GNU_LAST) {
1148 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1149 /* TODO: we should still save the attribute in the list... */
1150 kind = ATTRIBUTE_UNKNOWN;
1154 const char *attribute_name = get_attribute_name(kind);
1155 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1159 attribute_t *attribute = allocate_attribute_zero(kind);
1162 /* parse arguments */
1164 attribute->a.arguments = parse_attribute_arguments();
1169 static attribute_t *parse_attribute_gnu(void)
1171 attribute_t *first = NULL;
1172 attribute_t **anchor = &first;
1174 eat(T___attribute__);
1178 add_anchor_token(')');
1179 add_anchor_token(',');
1180 if (token.kind != ')') do {
1181 attribute_t *attribute = parse_attribute_gnu_single();
1183 *anchor = attribute;
1184 anchor = &attribute->next;
1186 } while (next_if(','));
1187 rem_anchor_token(',');
1188 rem_anchor_token(')');
1195 /** Parse attributes. */
1196 static attribute_t *parse_attributes(attribute_t *first)
1198 attribute_t **anchor = &first;
1200 while (*anchor != NULL)
1201 anchor = &(*anchor)->next;
1203 attribute_t *attribute;
1204 switch (token.kind) {
1205 case T___attribute__:
1206 attribute = parse_attribute_gnu();
1207 if (attribute == NULL)
1212 attribute = parse_attribute_asm();
1216 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1221 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1225 case T__forceinline:
1226 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1227 eat(T__forceinline);
1231 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1236 /* TODO record modifier */
1237 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1238 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1246 *anchor = attribute;
1247 anchor = &attribute->next;
1251 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1253 static entity_t *determine_lhs_ent(expression_t *const expr,
1256 switch (expr->kind) {
1257 case EXPR_REFERENCE: {
1258 entity_t *const entity = expr->reference.entity;
1259 /* we should only find variables as lvalues... */
1260 if (entity->base.kind != ENTITY_VARIABLE
1261 && entity->base.kind != ENTITY_PARAMETER)
1267 case EXPR_ARRAY_ACCESS: {
1268 expression_t *const ref = expr->array_access.array_ref;
1269 entity_t * ent = NULL;
1270 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1271 ent = determine_lhs_ent(ref, lhs_ent);
1274 mark_vars_read(ref, lhs_ent);
1276 mark_vars_read(expr->array_access.index, lhs_ent);
1281 mark_vars_read(expr->select.compound, lhs_ent);
1282 if (is_type_compound(skip_typeref(expr->base.type)))
1283 return determine_lhs_ent(expr->select.compound, lhs_ent);
1287 case EXPR_UNARY_DEREFERENCE: {
1288 expression_t *const val = expr->unary.value;
1289 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1291 return determine_lhs_ent(val->unary.value, lhs_ent);
1293 mark_vars_read(val, NULL);
1299 mark_vars_read(expr, NULL);
1304 #define ENT_ANY ((entity_t*)-1)
1307 * Mark declarations, which are read. This is used to detect variables, which
1311 * x is not marked as "read", because it is only read to calculate its own new
1315 * x and y are not detected as "not read", because multiple variables are
1318 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1320 switch (expr->kind) {
1321 case EXPR_REFERENCE: {
1322 entity_t *const entity = expr->reference.entity;
1323 if (entity->kind != ENTITY_VARIABLE
1324 && entity->kind != ENTITY_PARAMETER)
1327 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1328 if (entity->kind == ENTITY_VARIABLE) {
1329 entity->variable.read = true;
1331 entity->parameter.read = true;
1338 // TODO respect pure/const
1339 mark_vars_read(expr->call.function, NULL);
1340 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1341 mark_vars_read(arg->expression, NULL);
1345 case EXPR_CONDITIONAL:
1346 // TODO lhs_decl should depend on whether true/false have an effect
1347 mark_vars_read(expr->conditional.condition, NULL);
1348 if (expr->conditional.true_expression != NULL)
1349 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1350 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1354 if (lhs_ent == ENT_ANY
1355 && !is_type_compound(skip_typeref(expr->base.type)))
1357 mark_vars_read(expr->select.compound, lhs_ent);
1360 case EXPR_ARRAY_ACCESS: {
1361 mark_vars_read(expr->array_access.index, lhs_ent);
1362 expression_t *const ref = expr->array_access.array_ref;
1363 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1364 if (lhs_ent == ENT_ANY)
1367 mark_vars_read(ref, lhs_ent);
1372 mark_vars_read(expr->va_arge.ap, lhs_ent);
1376 mark_vars_read(expr->va_copye.src, lhs_ent);
1379 case EXPR_UNARY_CAST:
1380 /* Special case: Use void cast to mark a variable as "read" */
1381 if (is_type_void(skip_typeref(expr->base.type)))
1386 case EXPR_UNARY_THROW:
1387 if (expr->unary.value == NULL)
1390 case EXPR_UNARY_DEREFERENCE:
1391 case EXPR_UNARY_DELETE:
1392 case EXPR_UNARY_DELETE_ARRAY:
1393 if (lhs_ent == ENT_ANY)
1397 case EXPR_UNARY_NEGATE:
1398 case EXPR_UNARY_PLUS:
1399 case EXPR_UNARY_BITWISE_NEGATE:
1400 case EXPR_UNARY_NOT:
1401 case EXPR_UNARY_TAKE_ADDRESS:
1402 case EXPR_UNARY_POSTFIX_INCREMENT:
1403 case EXPR_UNARY_POSTFIX_DECREMENT:
1404 case EXPR_UNARY_PREFIX_INCREMENT:
1405 case EXPR_UNARY_PREFIX_DECREMENT:
1406 case EXPR_UNARY_ASSUME:
1408 mark_vars_read(expr->unary.value, lhs_ent);
1411 case EXPR_BINARY_ADD:
1412 case EXPR_BINARY_SUB:
1413 case EXPR_BINARY_MUL:
1414 case EXPR_BINARY_DIV:
1415 case EXPR_BINARY_MOD:
1416 case EXPR_BINARY_EQUAL:
1417 case EXPR_BINARY_NOTEQUAL:
1418 case EXPR_BINARY_LESS:
1419 case EXPR_BINARY_LESSEQUAL:
1420 case EXPR_BINARY_GREATER:
1421 case EXPR_BINARY_GREATEREQUAL:
1422 case EXPR_BINARY_BITWISE_AND:
1423 case EXPR_BINARY_BITWISE_OR:
1424 case EXPR_BINARY_BITWISE_XOR:
1425 case EXPR_BINARY_LOGICAL_AND:
1426 case EXPR_BINARY_LOGICAL_OR:
1427 case EXPR_BINARY_SHIFTLEFT:
1428 case EXPR_BINARY_SHIFTRIGHT:
1429 case EXPR_BINARY_COMMA:
1430 case EXPR_BINARY_ISGREATER:
1431 case EXPR_BINARY_ISGREATEREQUAL:
1432 case EXPR_BINARY_ISLESS:
1433 case EXPR_BINARY_ISLESSEQUAL:
1434 case EXPR_BINARY_ISLESSGREATER:
1435 case EXPR_BINARY_ISUNORDERED:
1436 mark_vars_read(expr->binary.left, lhs_ent);
1437 mark_vars_read(expr->binary.right, lhs_ent);
1440 case EXPR_BINARY_ASSIGN:
1441 case EXPR_BINARY_MUL_ASSIGN:
1442 case EXPR_BINARY_DIV_ASSIGN:
1443 case EXPR_BINARY_MOD_ASSIGN:
1444 case EXPR_BINARY_ADD_ASSIGN:
1445 case EXPR_BINARY_SUB_ASSIGN:
1446 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1447 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1448 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1449 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1450 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1451 if (lhs_ent == ENT_ANY)
1453 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1454 mark_vars_read(expr->binary.right, lhs_ent);
1459 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1462 case EXPR_LITERAL_CASES:
1464 case EXPR_STRING_LITERAL:
1465 case EXPR_WIDE_STRING_LITERAL:
1466 case EXPR_COMPOUND_LITERAL: // TODO init?
1468 case EXPR_CLASSIFY_TYPE:
1471 case EXPR_BUILTIN_CONSTANT_P:
1472 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1474 case EXPR_STATEMENT: // TODO
1475 case EXPR_LABEL_ADDRESS:
1476 case EXPR_ENUM_CONSTANT:
1480 panic("unhandled expression");
1483 static designator_t *parse_designation(void)
1485 designator_t *result = NULL;
1486 designator_t **anchor = &result;
1489 designator_t *designator;
1490 switch (token.kind) {
1492 designator = allocate_ast_zero(sizeof(designator[0]));
1493 designator->source_position = token.base.source_position;
1495 add_anchor_token(']');
1496 designator->array_index = parse_constant_expression();
1497 rem_anchor_token(']');
1501 designator = allocate_ast_zero(sizeof(designator[0]));
1502 designator->source_position = token.base.source_position;
1504 designator->symbol = expect_identifier("while parsing designator", NULL);
1505 if (!designator->symbol)
1513 assert(designator != NULL);
1514 *anchor = designator;
1515 anchor = &designator->next;
1519 static initializer_t *initializer_from_string(array_type_t *const type,
1520 const string_t *const string)
1522 /* TODO: check len vs. size of array type */
1525 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1526 initializer->string.string = *string;
1531 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1532 const string_t *const string)
1534 /* TODO: check len vs. size of array type */
1537 initializer_t *const initializer =
1538 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1539 initializer->wide_string.string = *string;
1545 * Build an initializer from a given expression.
1547 static initializer_t *initializer_from_expression(type_t *orig_type,
1548 expression_t *expression)
1550 /* TODO check that expression is a constant expression */
1552 /* §6.7.8.14/15 char array may be initialized by string literals */
1553 type_t *type = skip_typeref(orig_type);
1554 type_t *expr_type_orig = expression->base.type;
1555 type_t *expr_type = skip_typeref(expr_type_orig);
1557 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1558 array_type_t *const array_type = &type->array;
1559 type_t *const element_type = skip_typeref(array_type->element_type);
1561 if (element_type->kind == TYPE_ATOMIC) {
1562 atomic_type_kind_t akind = element_type->atomic.akind;
1563 switch (expression->kind) {
1564 case EXPR_STRING_LITERAL:
1565 if (akind == ATOMIC_TYPE_CHAR
1566 || akind == ATOMIC_TYPE_SCHAR
1567 || akind == ATOMIC_TYPE_UCHAR) {
1568 return initializer_from_string(array_type,
1569 &expression->string_literal.value);
1573 case EXPR_WIDE_STRING_LITERAL: {
1574 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1575 if (get_unqualified_type(element_type) == bare_wchar_type) {
1576 return initializer_from_wide_string(array_type,
1577 &expression->string_literal.value);
1588 assign_error_t error = semantic_assign(type, expression);
1589 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1591 report_assign_error(error, type, expression, "initializer",
1592 &expression->base.source_position);
1594 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1595 result->value.value = create_implicit_cast(expression, type);
1601 * Parses an scalar initializer.
1603 * §6.7.8.11; eat {} without warning
1605 static initializer_t *parse_scalar_initializer(type_t *type,
1606 bool must_be_constant)
1608 /* there might be extra {} hierarchies */
1610 if (token.kind == '{') {
1611 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1615 } while (token.kind == '{');
1618 expression_t *expression = parse_assignment_expression();
1619 mark_vars_read(expression, NULL);
1620 if (must_be_constant && !is_linker_constant(expression)) {
1621 errorf(&expression->base.source_position,
1622 "initialisation expression '%E' is not constant",
1626 initializer_t *initializer = initializer_from_expression(type, expression);
1628 if (initializer == NULL) {
1629 errorf(&expression->base.source_position,
1630 "expression '%E' (type '%T') doesn't match expected type '%T'",
1631 expression, expression->base.type, type);
1636 bool additional_warning_displayed = false;
1637 while (braces > 0) {
1639 if (token.kind != '}') {
1640 if (!additional_warning_displayed) {
1641 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1642 additional_warning_displayed = true;
1653 * An entry in the type path.
1655 typedef struct type_path_entry_t type_path_entry_t;
1656 struct type_path_entry_t {
1657 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1659 size_t index; /**< For array types: the current index. */
1660 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1665 * A type path expression a position inside compound or array types.
1667 typedef struct type_path_t type_path_t;
1668 struct type_path_t {
1669 type_path_entry_t *path; /**< An flexible array containing the current path. */
1670 type_t *top_type; /**< type of the element the path points */
1671 size_t max_index; /**< largest index in outermost array */
1675 * Prints a type path for debugging.
1677 static __attribute__((unused)) void debug_print_type_path(
1678 const type_path_t *path)
1680 size_t len = ARR_LEN(path->path);
1682 for (size_t i = 0; i < len; ++i) {
1683 const type_path_entry_t *entry = & path->path[i];
1685 type_t *type = skip_typeref(entry->type);
1686 if (is_type_compound(type)) {
1687 /* in gcc mode structs can have no members */
1688 if (entry->v.compound_entry == NULL) {
1692 fprintf(stderr, ".%s",
1693 entry->v.compound_entry->base.symbol->string);
1694 } else if (is_type_array(type)) {
1695 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1697 fprintf(stderr, "-INVALID-");
1700 if (path->top_type != NULL) {
1701 fprintf(stderr, " (");
1702 print_type(path->top_type);
1703 fprintf(stderr, ")");
1708 * Return the top type path entry, ie. in a path
1709 * (type).a.b returns the b.
1711 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1713 size_t len = ARR_LEN(path->path);
1715 return &path->path[len-1];
1719 * Enlarge the type path by an (empty) element.
1721 static type_path_entry_t *append_to_type_path(type_path_t *path)
1723 size_t len = ARR_LEN(path->path);
1724 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1726 type_path_entry_t *result = & path->path[len];
1727 memset(result, 0, sizeof(result[0]));
1732 * Descending into a sub-type. Enter the scope of the current top_type.
1734 static void descend_into_subtype(type_path_t *path)
1736 type_t *orig_top_type = path->top_type;
1737 type_t *top_type = skip_typeref(orig_top_type);
1739 type_path_entry_t *top = append_to_type_path(path);
1740 top->type = top_type;
1742 if (is_type_compound(top_type)) {
1743 compound_t *const compound = top_type->compound.compound;
1744 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1746 if (entry != NULL) {
1747 top->v.compound_entry = &entry->declaration;
1748 path->top_type = entry->declaration.type;
1750 path->top_type = NULL;
1752 } else if (is_type_array(top_type)) {
1754 path->top_type = top_type->array.element_type;
1756 assert(!is_type_valid(top_type));
1761 * Pop an entry from the given type path, ie. returning from
1762 * (type).a.b to (type).a
1764 static void ascend_from_subtype(type_path_t *path)
1766 type_path_entry_t *top = get_type_path_top(path);
1768 path->top_type = top->type;
1770 size_t len = ARR_LEN(path->path);
1771 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1775 * Pop entries from the given type path until the given
1776 * path level is reached.
1778 static void ascend_to(type_path_t *path, size_t top_path_level)
1780 size_t len = ARR_LEN(path->path);
1782 while (len > top_path_level) {
1783 ascend_from_subtype(path);
1784 len = ARR_LEN(path->path);
1788 static bool walk_designator(type_path_t *path, const designator_t *designator,
1789 bool used_in_offsetof)
1791 for (; designator != NULL; designator = designator->next) {
1792 type_path_entry_t *top = get_type_path_top(path);
1793 type_t *orig_type = top->type;
1795 type_t *type = skip_typeref(orig_type);
1797 if (designator->symbol != NULL) {
1798 symbol_t *symbol = designator->symbol;
1799 if (!is_type_compound(type)) {
1800 if (is_type_valid(type)) {
1801 errorf(&designator->source_position,
1802 "'.%Y' designator used for non-compound type '%T'",
1806 top->type = type_error_type;
1807 top->v.compound_entry = NULL;
1808 orig_type = type_error_type;
1810 compound_t *compound = type->compound.compound;
1811 entity_t *iter = compound->members.entities;
1812 for (; iter != NULL; iter = iter->base.next) {
1813 if (iter->base.symbol == symbol) {
1818 errorf(&designator->source_position,
1819 "'%T' has no member named '%Y'", orig_type, symbol);
1822 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1823 if (used_in_offsetof && iter->compound_member.bitfield) {
1824 errorf(&designator->source_position,
1825 "offsetof designator '%Y' must not specify bitfield",
1830 top->type = orig_type;
1831 top->v.compound_entry = &iter->declaration;
1832 orig_type = iter->declaration.type;
1835 expression_t *array_index = designator->array_index;
1836 assert(designator->array_index != NULL);
1838 if (!is_type_array(type)) {
1839 if (is_type_valid(type)) {
1840 errorf(&designator->source_position,
1841 "[%E] designator used for non-array type '%T'",
1842 array_index, orig_type);
1847 long index = fold_constant_to_int(array_index);
1848 if (!used_in_offsetof) {
1850 errorf(&designator->source_position,
1851 "array index [%E] must be positive", array_index);
1852 } else if (type->array.size_constant) {
1853 long array_size = type->array.size;
1854 if (index >= array_size) {
1855 errorf(&designator->source_position,
1856 "designator [%E] (%d) exceeds array size %d",
1857 array_index, index, array_size);
1862 top->type = orig_type;
1863 top->v.index = (size_t) index;
1864 orig_type = type->array.element_type;
1866 path->top_type = orig_type;
1868 if (designator->next != NULL) {
1869 descend_into_subtype(path);
1875 static void advance_current_object(type_path_t *path, size_t top_path_level)
1877 type_path_entry_t *top = get_type_path_top(path);
1879 type_t *type = skip_typeref(top->type);
1880 if (is_type_union(type)) {
1881 /* in unions only the first element is initialized */
1882 top->v.compound_entry = NULL;
1883 } else if (is_type_struct(type)) {
1884 declaration_t *entry = top->v.compound_entry;
1886 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1887 if (next_entity != NULL) {
1888 assert(is_declaration(next_entity));
1889 entry = &next_entity->declaration;
1894 top->v.compound_entry = entry;
1895 if (entry != NULL) {
1896 path->top_type = entry->type;
1899 } else if (is_type_array(type)) {
1900 assert(is_type_array(type));
1904 if (!type->array.size_constant || top->v.index < type->array.size) {
1908 assert(!is_type_valid(type));
1912 /* we're past the last member of the current sub-aggregate, try if we
1913 * can ascend in the type hierarchy and continue with another subobject */
1914 size_t len = ARR_LEN(path->path);
1916 if (len > top_path_level) {
1917 ascend_from_subtype(path);
1918 advance_current_object(path, top_path_level);
1920 path->top_type = NULL;
1925 * skip any {...} blocks until a closing bracket is reached.
1927 static void skip_initializers(void)
1931 while (token.kind != '}') {
1932 if (token.kind == T_EOF)
1934 if (token.kind == '{') {
1942 static initializer_t *create_empty_initializer(void)
1944 static initializer_t empty_initializer
1945 = { .list = { { INITIALIZER_LIST }, 0 } };
1946 return &empty_initializer;
1950 * Parse a part of an initialiser for a struct or union,
1952 static initializer_t *parse_sub_initializer(type_path_t *path,
1953 type_t *outer_type, size_t top_path_level,
1954 parse_initializer_env_t *env)
1956 if (token.kind == '}') {
1957 /* empty initializer */
1958 return create_empty_initializer();
1961 type_t *orig_type = path->top_type;
1962 type_t *type = NULL;
1964 if (orig_type == NULL) {
1965 /* We are initializing an empty compound. */
1967 type = skip_typeref(orig_type);
1970 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1973 designator_t *designator = NULL;
1974 if (token.kind == '.' || token.kind == '[') {
1975 designator = parse_designation();
1976 goto finish_designator;
1977 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1978 /* GNU-style designator ("identifier: value") */
1979 designator = allocate_ast_zero(sizeof(designator[0]));
1980 designator->source_position = token.base.source_position;
1981 designator->symbol = token.base.symbol;
1986 /* reset path to toplevel, evaluate designator from there */
1987 ascend_to(path, top_path_level);
1988 if (!walk_designator(path, designator, false)) {
1989 /* can't continue after designation error */
1993 initializer_t *designator_initializer
1994 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1995 designator_initializer->designator.designator = designator;
1996 ARR_APP1(initializer_t*, initializers, designator_initializer);
1998 orig_type = path->top_type;
1999 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2004 if (token.kind == '{') {
2005 if (type != NULL && is_type_scalar(type)) {
2006 sub = parse_scalar_initializer(type, env->must_be_constant);
2009 if (env->entity != NULL) {
2011 "extra brace group at end of initializer for '%Y'",
2012 env->entity->base.symbol);
2014 errorf(HERE, "extra brace group at end of initializer");
2019 descend_into_subtype(path);
2022 add_anchor_token('}');
2023 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2025 rem_anchor_token('}');
2030 goto error_parse_next;
2032 ascend_from_subtype(path);
2035 /* must be an expression */
2036 expression_t *expression = parse_assignment_expression();
2037 mark_vars_read(expression, NULL);
2039 if (env->must_be_constant && !is_linker_constant(expression)) {
2040 errorf(&expression->base.source_position,
2041 "Initialisation expression '%E' is not constant",
2046 /* we are already outside, ... */
2047 if (outer_type == NULL)
2048 goto error_parse_next;
2049 type_t *const outer_type_skip = skip_typeref(outer_type);
2050 if (is_type_compound(outer_type_skip) &&
2051 !outer_type_skip->compound.compound->complete) {
2052 goto error_parse_next;
2055 source_position_t const* const pos = &expression->base.source_position;
2056 if (env->entity != NULL) {
2057 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2059 warningf(WARN_OTHER, pos, "excess elements in initializer");
2061 goto error_parse_next;
2064 /* handle { "string" } special case */
2065 if ((expression->kind == EXPR_STRING_LITERAL
2066 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2067 && outer_type != NULL) {
2068 sub = initializer_from_expression(outer_type, expression);
2071 if (token.kind != '}') {
2072 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2074 /* TODO: eat , ... */
2079 /* descend into subtypes until expression matches type */
2081 orig_type = path->top_type;
2082 type = skip_typeref(orig_type);
2084 sub = initializer_from_expression(orig_type, expression);
2088 if (!is_type_valid(type)) {
2091 if (is_type_scalar(type)) {
2092 errorf(&expression->base.source_position,
2093 "expression '%E' doesn't match expected type '%T'",
2094 expression, orig_type);
2098 descend_into_subtype(path);
2102 /* update largest index of top array */
2103 const type_path_entry_t *first = &path->path[0];
2104 type_t *first_type = first->type;
2105 first_type = skip_typeref(first_type);
2106 if (is_type_array(first_type)) {
2107 size_t index = first->v.index;
2108 if (index > path->max_index)
2109 path->max_index = index;
2112 /* append to initializers list */
2113 ARR_APP1(initializer_t*, initializers, sub);
2116 if (token.kind == '}') {
2119 add_anchor_token('}');
2121 rem_anchor_token('}');
2122 if (token.kind == '}') {
2127 /* advance to the next declaration if we are not at the end */
2128 advance_current_object(path, top_path_level);
2129 orig_type = path->top_type;
2130 if (orig_type != NULL)
2131 type = skip_typeref(orig_type);
2137 size_t len = ARR_LEN(initializers);
2138 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2139 initializer_t *result = allocate_ast_zero(size);
2140 result->kind = INITIALIZER_LIST;
2141 result->list.len = len;
2142 memcpy(&result->list.initializers, initializers,
2143 len * sizeof(initializers[0]));
2145 DEL_ARR_F(initializers);
2146 ascend_to(path, top_path_level+1);
2151 skip_initializers();
2152 DEL_ARR_F(initializers);
2153 ascend_to(path, top_path_level+1);
2157 static expression_t *make_size_literal(size_t value)
2159 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2160 literal->base.type = type_size_t;
2163 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2164 literal->literal.value = make_string(buf);
2170 * Parses an initializer. Parsers either a compound literal
2171 * (env->declaration == NULL) or an initializer of a declaration.
2173 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2175 type_t *type = skip_typeref(env->type);
2176 size_t max_index = 0;
2177 initializer_t *result;
2179 if (is_type_scalar(type)) {
2180 result = parse_scalar_initializer(type, env->must_be_constant);
2181 } else if (token.kind == '{') {
2185 memset(&path, 0, sizeof(path));
2186 path.top_type = env->type;
2187 path.path = NEW_ARR_F(type_path_entry_t, 0);
2189 descend_into_subtype(&path);
2191 add_anchor_token('}');
2192 result = parse_sub_initializer(&path, env->type, 1, env);
2193 rem_anchor_token('}');
2195 max_index = path.max_index;
2196 DEL_ARR_F(path.path);
2200 /* parse_scalar_initializer() also works in this case: we simply
2201 * have an expression without {} around it */
2202 result = parse_scalar_initializer(type, env->must_be_constant);
2205 /* §6.7.8:22 array initializers for arrays with unknown size determine
2206 * the array type size */
2207 if (is_type_array(type) && type->array.size_expression == NULL
2208 && result != NULL) {
2210 switch (result->kind) {
2211 case INITIALIZER_LIST:
2212 assert(max_index != 0xdeadbeaf);
2213 size = max_index + 1;
2216 case INITIALIZER_STRING:
2217 size = result->string.string.size;
2220 case INITIALIZER_WIDE_STRING:
2221 size = result->wide_string.string.size;
2224 case INITIALIZER_DESIGNATOR:
2225 case INITIALIZER_VALUE:
2226 /* can happen for parse errors */
2231 internal_errorf(HERE, "invalid initializer type");
2234 type_t *new_type = duplicate_type(type);
2236 new_type->array.size_expression = make_size_literal(size);
2237 new_type->array.size_constant = true;
2238 new_type->array.has_implicit_size = true;
2239 new_type->array.size = size;
2240 env->type = new_type;
2246 static void append_entity(scope_t *scope, entity_t *entity)
2248 if (scope->last_entity != NULL) {
2249 scope->last_entity->base.next = entity;
2251 scope->entities = entity;
2253 entity->base.parent_entity = current_entity;
2254 scope->last_entity = entity;
2258 static compound_t *parse_compound_type_specifier(bool is_struct)
2260 source_position_t const pos = *HERE;
2261 eat(is_struct ? T_struct : T_union);
2263 symbol_t *symbol = NULL;
2264 entity_t *entity = NULL;
2265 attribute_t *attributes = NULL;
2267 if (token.kind == T___attribute__) {
2268 attributes = parse_attributes(NULL);
2271 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2272 if (token.kind == T_IDENTIFIER) {
2273 /* the compound has a name, check if we have seen it already */
2274 symbol = token.base.symbol;
2275 entity = get_tag(symbol, kind);
2278 if (entity != NULL) {
2279 if (entity->base.parent_scope != current_scope &&
2280 (token.kind == '{' || token.kind == ';')) {
2281 /* we're in an inner scope and have a definition. Shadow
2282 * existing definition in outer scope */
2284 } else if (entity->compound.complete && token.kind == '{') {
2285 source_position_t const *const ppos = &entity->base.source_position;
2286 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2287 /* clear members in the hope to avoid further errors */
2288 entity->compound.members.entities = NULL;
2291 } else if (token.kind != '{') {
2292 char const *const msg =
2293 is_struct ? "while parsing struct type specifier" :
2294 "while parsing union type specifier";
2295 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2300 if (entity == NULL) {
2301 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2302 entity->compound.alignment = 1;
2303 entity->base.parent_scope = current_scope;
2304 if (symbol != NULL) {
2305 environment_push(entity);
2307 append_entity(current_scope, entity);
2310 if (token.kind == '{') {
2311 parse_compound_type_entries(&entity->compound);
2313 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2314 if (symbol == NULL) {
2315 assert(anonymous_entity == NULL);
2316 anonymous_entity = entity;
2320 if (attributes != NULL) {
2321 handle_entity_attributes(attributes, entity);
2324 return &entity->compound;
2327 static void parse_enum_entries(type_t *const enum_type)
2331 if (token.kind == '}') {
2332 errorf(HERE, "empty enum not allowed");
2337 add_anchor_token('}');
2338 add_anchor_token(',');
2340 add_anchor_token('=');
2341 source_position_t pos;
2342 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2343 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2344 entity->enum_value.enum_type = enum_type;
2345 rem_anchor_token('=');
2348 expression_t *value = parse_constant_expression();
2350 value = create_implicit_cast(value, enum_type);
2351 entity->enum_value.value = value;
2356 record_entity(entity, false);
2357 } while (next_if(',') && token.kind != '}');
2358 rem_anchor_token(',');
2359 rem_anchor_token('}');
2364 static type_t *parse_enum_specifier(void)
2366 source_position_t const pos = *HERE;
2371 switch (token.kind) {
2373 symbol = token.base.symbol;
2374 entity = get_tag(symbol, ENTITY_ENUM);
2377 if (entity != NULL) {
2378 if (entity->base.parent_scope != current_scope &&
2379 (token.kind == '{' || token.kind == ';')) {
2380 /* we're in an inner scope and have a definition. Shadow
2381 * existing definition in outer scope */
2383 } else if (entity->enume.complete && token.kind == '{') {
2384 source_position_t const *const ppos = &entity->base.source_position;
2385 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2396 parse_error_expected("while parsing enum type specifier",
2397 T_IDENTIFIER, '{', NULL);
2401 if (entity == NULL) {
2402 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2403 entity->base.parent_scope = current_scope;
2406 type_t *const type = allocate_type_zero(TYPE_ENUM);
2407 type->enumt.enume = &entity->enume;
2408 type->enumt.base.akind = ATOMIC_TYPE_INT;
2410 if (token.kind == '{') {
2411 if (symbol != NULL) {
2412 environment_push(entity);
2414 append_entity(current_scope, entity);
2415 entity->enume.complete = true;
2417 parse_enum_entries(type);
2418 parse_attributes(NULL);
2420 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2421 if (symbol == NULL) {
2422 assert(anonymous_entity == NULL);
2423 anonymous_entity = entity;
2425 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2426 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2433 * if a symbol is a typedef to another type, return true
2435 static bool is_typedef_symbol(symbol_t *symbol)
2437 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2438 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2441 static type_t *parse_typeof(void)
2448 add_anchor_token(')');
2450 expression_t *expression = NULL;
2452 switch (token.kind) {
2454 if (is_typedef_symbol(token.base.symbol)) {
2456 type = parse_typename();
2459 expression = parse_expression();
2460 type = revert_automatic_type_conversion(expression);
2465 rem_anchor_token(')');
2468 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2469 typeof_type->typeoft.expression = expression;
2470 typeof_type->typeoft.typeof_type = type;
2475 typedef enum specifiers_t {
2476 SPECIFIER_SIGNED = 1 << 0,
2477 SPECIFIER_UNSIGNED = 1 << 1,
2478 SPECIFIER_LONG = 1 << 2,
2479 SPECIFIER_INT = 1 << 3,
2480 SPECIFIER_DOUBLE = 1 << 4,
2481 SPECIFIER_CHAR = 1 << 5,
2482 SPECIFIER_WCHAR_T = 1 << 6,
2483 SPECIFIER_SHORT = 1 << 7,
2484 SPECIFIER_LONG_LONG = 1 << 8,
2485 SPECIFIER_FLOAT = 1 << 9,
2486 SPECIFIER_BOOL = 1 << 10,
2487 SPECIFIER_VOID = 1 << 11,
2488 SPECIFIER_INT8 = 1 << 12,
2489 SPECIFIER_INT16 = 1 << 13,
2490 SPECIFIER_INT32 = 1 << 14,
2491 SPECIFIER_INT64 = 1 << 15,
2492 SPECIFIER_INT128 = 1 << 16,
2493 SPECIFIER_COMPLEX = 1 << 17,
2494 SPECIFIER_IMAGINARY = 1 << 18,
2497 static type_t *get_typedef_type(symbol_t *symbol)
2499 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2500 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2503 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2504 type->typedeft.typedefe = &entity->typedefe;
2509 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2511 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2515 add_anchor_token(')');
2516 add_anchor_token(',');
2518 add_anchor_token('=');
2519 source_position_t pos;
2520 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2521 rem_anchor_token('=');
2523 symbol_t **prop = NULL;
2525 if (streq(prop_sym->string, "put")) {
2526 prop = &property->put_symbol;
2527 } else if (streq(prop_sym->string, "get")) {
2528 prop = &property->get_symbol;
2530 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2534 add_anchor_token(T_IDENTIFIER);
2536 rem_anchor_token(T_IDENTIFIER);
2538 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2540 *prop = sym ? sym : sym_anonymous;
2541 } while (next_if(','));
2542 rem_anchor_token(',');
2543 rem_anchor_token(')');
2545 attribute->a.property = property;
2551 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2553 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2554 if (next_if(T_restrict)) {
2555 kind = ATTRIBUTE_MS_RESTRICT;
2556 } else if (token.kind == T_IDENTIFIER) {
2557 char const *const name = token.base.symbol->string;
2558 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2560 const char *attribute_name = get_attribute_name(k);
2561 if (attribute_name != NULL && streq(attribute_name, name)) {
2567 if (kind == ATTRIBUTE_UNKNOWN) {
2568 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2571 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2575 attribute_t *attribute = allocate_attribute_zero(kind);
2578 if (kind == ATTRIBUTE_MS_PROPERTY) {
2579 return parse_attribute_ms_property(attribute);
2582 /* parse arguments */
2584 attribute->a.arguments = parse_attribute_arguments();
2589 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2594 if (token.kind != ')') {
2595 add_anchor_token(')');
2597 attribute_t **anchor = &first;
2599 while (*anchor != NULL)
2600 anchor = &(*anchor)->next;
2602 attribute_t *attribute
2603 = parse_microsoft_extended_decl_modifier_single();
2604 if (attribute == NULL)
2607 *anchor = attribute;
2608 anchor = &attribute->next;
2609 } while (next_if(','));
2611 rem_anchor_token(')');
2617 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2619 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2620 if (is_declaration(entity)) {
2621 entity->declaration.type = type_error_type;
2622 entity->declaration.implicit = true;
2623 } else if (kind == ENTITY_TYPEDEF) {
2624 entity->typedefe.type = type_error_type;
2625 entity->typedefe.builtin = true;
2627 if (kind != ENTITY_COMPOUND_MEMBER)
2628 record_entity(entity, false);
2632 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2634 type_t *type = NULL;
2635 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2636 unsigned type_specifiers = 0;
2637 bool newtype = false;
2638 bool saw_error = false;
2640 memset(specifiers, 0, sizeof(*specifiers));
2641 specifiers->source_position = token.base.source_position;
2644 specifiers->attributes = parse_attributes(specifiers->attributes);
2646 switch (token.kind) {
2648 #define MATCH_STORAGE_CLASS(token, class) \
2650 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2651 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2653 specifiers->storage_class = class; \
2654 if (specifiers->thread_local) \
2655 goto check_thread_storage_class; \
2659 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2660 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2661 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2662 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2663 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2666 specifiers->attributes
2667 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2671 if (specifiers->thread_local) {
2672 errorf(HERE, "duplicate '__thread'");
2674 specifiers->thread_local = true;
2675 check_thread_storage_class:
2676 switch (specifiers->storage_class) {
2677 case STORAGE_CLASS_EXTERN:
2678 case STORAGE_CLASS_NONE:
2679 case STORAGE_CLASS_STATIC:
2683 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2684 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2685 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2686 wrong_thread_storage_class:
2687 errorf(HERE, "'__thread' used with '%s'", wrong);
2694 /* type qualifiers */
2695 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2697 qualifiers |= qualifier; \
2701 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2702 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2703 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2704 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2705 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2706 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2707 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2708 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2710 /* type specifiers */
2711 #define MATCH_SPECIFIER(token, specifier, name) \
2713 if (type_specifiers & specifier) { \
2714 errorf(HERE, "multiple " name " type specifiers given"); \
2716 type_specifiers |= specifier; \
2721 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2722 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2723 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2724 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2725 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2726 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2727 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2728 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2729 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2730 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2731 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2732 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2733 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2734 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2735 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2736 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2737 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2738 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2742 specifiers->is_inline = true;
2746 case T__forceinline:
2748 specifiers->modifiers |= DM_FORCEINLINE;
2753 if (type_specifiers & SPECIFIER_LONG_LONG) {
2754 errorf(HERE, "too many long type specifiers given");
2755 } else if (type_specifiers & SPECIFIER_LONG) {
2756 type_specifiers |= SPECIFIER_LONG_LONG;
2758 type_specifiers |= SPECIFIER_LONG;
2763 #define CHECK_DOUBLE_TYPE() \
2764 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2767 CHECK_DOUBLE_TYPE();
2768 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2770 type->compound.compound = parse_compound_type_specifier(true);
2773 CHECK_DOUBLE_TYPE();
2774 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2775 type->compound.compound = parse_compound_type_specifier(false);
2778 CHECK_DOUBLE_TYPE();
2779 type = parse_enum_specifier();
2782 CHECK_DOUBLE_TYPE();
2783 type = parse_typeof();
2785 case T___builtin_va_list:
2786 CHECK_DOUBLE_TYPE();
2787 type = duplicate_type(type_valist);
2791 case T_IDENTIFIER: {
2792 /* only parse identifier if we haven't found a type yet */
2793 if (type != NULL || type_specifiers != 0) {
2794 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2795 * declaration, so it doesn't generate errors about expecting '(' or
2797 switch (look_ahead(1)->kind) {
2804 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2808 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2813 goto finish_specifiers;
2817 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2818 if (typedef_type == NULL) {
2819 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2820 * declaration, so it doesn't generate 'implicit int' followed by more
2821 * errors later on. */
2822 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2828 errorf(HERE, "%K does not name a type", &token);
2830 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2832 type = allocate_type_zero(TYPE_TYPEDEF);
2833 type->typedeft.typedefe = &entity->typedefe;
2841 goto finish_specifiers;
2846 type = typedef_type;
2850 /* function specifier */
2852 goto finish_specifiers;
2857 specifiers->attributes = parse_attributes(specifiers->attributes);
2859 if (type == NULL || (saw_error && type_specifiers != 0)) {
2860 atomic_type_kind_t atomic_type;
2862 /* match valid basic types */
2863 switch (type_specifiers) {
2864 case SPECIFIER_VOID:
2865 atomic_type = ATOMIC_TYPE_VOID;
2867 case SPECIFIER_WCHAR_T:
2868 atomic_type = ATOMIC_TYPE_WCHAR_T;
2870 case SPECIFIER_CHAR:
2871 atomic_type = ATOMIC_TYPE_CHAR;
2873 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2874 atomic_type = ATOMIC_TYPE_SCHAR;
2876 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2877 atomic_type = ATOMIC_TYPE_UCHAR;
2879 case SPECIFIER_SHORT:
2880 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2881 case SPECIFIER_SHORT | SPECIFIER_INT:
2882 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2883 atomic_type = ATOMIC_TYPE_SHORT;
2885 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2886 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2887 atomic_type = ATOMIC_TYPE_USHORT;
2890 case SPECIFIER_SIGNED:
2891 case SPECIFIER_SIGNED | SPECIFIER_INT:
2892 atomic_type = ATOMIC_TYPE_INT;
2894 case SPECIFIER_UNSIGNED:
2895 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2896 atomic_type = ATOMIC_TYPE_UINT;
2898 case SPECIFIER_LONG:
2899 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2900 case SPECIFIER_LONG | SPECIFIER_INT:
2901 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2902 atomic_type = ATOMIC_TYPE_LONG;
2904 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2905 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2906 atomic_type = ATOMIC_TYPE_ULONG;
2909 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2910 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2911 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2912 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2914 atomic_type = ATOMIC_TYPE_LONGLONG;
2915 goto warn_about_long_long;
2917 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2918 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2920 atomic_type = ATOMIC_TYPE_ULONGLONG;
2921 warn_about_long_long:
2922 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2925 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2926 atomic_type = unsigned_int8_type_kind;
2929 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2930 atomic_type = unsigned_int16_type_kind;
2933 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2934 atomic_type = unsigned_int32_type_kind;
2937 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2938 atomic_type = unsigned_int64_type_kind;
2941 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2942 atomic_type = unsigned_int128_type_kind;
2945 case SPECIFIER_INT8:
2946 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2947 atomic_type = int8_type_kind;
2950 case SPECIFIER_INT16:
2951 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2952 atomic_type = int16_type_kind;
2955 case SPECIFIER_INT32:
2956 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2957 atomic_type = int32_type_kind;
2960 case SPECIFIER_INT64:
2961 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2962 atomic_type = int64_type_kind;
2965 case SPECIFIER_INT128:
2966 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2967 atomic_type = int128_type_kind;
2970 case SPECIFIER_FLOAT:
2971 atomic_type = ATOMIC_TYPE_FLOAT;
2973 case SPECIFIER_DOUBLE:
2974 atomic_type = ATOMIC_TYPE_DOUBLE;
2976 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2977 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2979 case SPECIFIER_BOOL:
2980 atomic_type = ATOMIC_TYPE_BOOL;
2982 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2983 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2984 atomic_type = ATOMIC_TYPE_FLOAT;
2986 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2987 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2988 atomic_type = ATOMIC_TYPE_DOUBLE;
2990 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2991 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2992 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2995 /* invalid specifier combination, give an error message */
2996 source_position_t const* const pos = &specifiers->source_position;
2997 if (type_specifiers == 0) {
2999 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3000 if (!(c_mode & _CXX) && !strict_mode) {
3001 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3002 atomic_type = ATOMIC_TYPE_INT;
3005 errorf(pos, "no type specifiers given in declaration");
3008 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3009 (type_specifiers & SPECIFIER_UNSIGNED)) {
3010 errorf(pos, "signed and unsigned specifiers given");
3011 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3012 errorf(pos, "only integer types can be signed or unsigned");
3014 errorf(pos, "multiple datatypes in declaration");
3020 if (type_specifiers & SPECIFIER_COMPLEX) {
3021 type = allocate_type_zero(TYPE_COMPLEX);
3022 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3023 type = allocate_type_zero(TYPE_IMAGINARY);
3025 type = allocate_type_zero(TYPE_ATOMIC);
3027 type->atomic.akind = atomic_type;
3029 } else if (type_specifiers != 0) {
3030 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3033 /* FIXME: check type qualifiers here */
3034 type->base.qualifiers = qualifiers;
3037 type = identify_new_type(type);
3039 type = typehash_insert(type);
3042 if (specifiers->attributes != NULL)
3043 type = handle_type_attributes(specifiers->attributes, type);
3044 specifiers->type = type;
3048 specifiers->type = type_error_type;
3051 static type_qualifiers_t parse_type_qualifiers(void)
3053 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3056 switch (token.kind) {
3057 /* type qualifiers */
3058 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3059 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3060 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3061 /* microsoft extended type modifiers */
3062 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3063 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3064 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3065 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3066 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3075 * Parses an K&R identifier list
3077 static void parse_identifier_list(scope_t *scope)
3079 assert(token.kind == T_IDENTIFIER);
3081 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3082 /* a K&R parameter has no type, yet */
3086 append_entity(scope, entity);
3087 } while (next_if(',') && token.kind == T_IDENTIFIER);
3090 static entity_t *parse_parameter(void)
3092 declaration_specifiers_t specifiers;
3093 parse_declaration_specifiers(&specifiers);
3095 entity_t *entity = parse_declarator(&specifiers,
3096 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3097 anonymous_entity = NULL;
3101 static void semantic_parameter_incomplete(const entity_t *entity)
3103 assert(entity->kind == ENTITY_PARAMETER);
3105 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3106 * list in a function declarator that is part of a
3107 * definition of that function shall not have
3108 * incomplete type. */
3109 type_t *type = skip_typeref(entity->declaration.type);
3110 if (is_type_incomplete(type)) {
3111 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3115 static bool has_parameters(void)
3117 /* func(void) is not a parameter */
3118 if (look_ahead(1)->kind != ')')
3120 if (token.kind == T_IDENTIFIER) {
3121 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3124 if (entity->kind != ENTITY_TYPEDEF)
3126 type_t const *const type = skip_typeref(entity->typedefe.type);
3127 if (!is_type_void(type))
3129 if (c_mode & _CXX) {
3130 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3131 * is not allowed. */
3132 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3133 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3134 /* §6.7.5.3:10 Qualification is not allowed here. */
3135 errorf(HERE, "'void' as parameter must not have type qualifiers");
3137 } else if (token.kind != T_void) {
3145 * Parses function type parameters (and optionally creates variable_t entities
3146 * for them in a scope)
3148 static void parse_parameters(function_type_t *type, scope_t *scope)
3151 add_anchor_token(')');
3153 if (token.kind == T_IDENTIFIER &&
3154 !is_typedef_symbol(token.base.symbol) &&
3155 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3156 type->kr_style_parameters = true;
3157 parse_identifier_list(scope);
3158 } else if (token.kind == ')') {
3159 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3160 if (!(c_mode & _CXX))
3161 type->unspecified_parameters = true;
3162 } else if (has_parameters()) {
3163 function_parameter_t **anchor = &type->parameters;
3164 add_anchor_token(',');
3166 switch (token.kind) {
3169 type->variadic = true;
3170 goto parameters_finished;
3175 entity_t *entity = parse_parameter();
3176 if (entity->kind == ENTITY_TYPEDEF) {
3177 errorf(&entity->base.source_position,
3178 "typedef not allowed as function parameter");
3181 assert(is_declaration(entity));
3183 semantic_parameter_incomplete(entity);
3185 function_parameter_t *const parameter =
3186 allocate_parameter(entity->declaration.type);
3188 if (scope != NULL) {
3189 append_entity(scope, entity);
3192 *anchor = parameter;
3193 anchor = ¶meter->next;
3198 goto parameters_finished;
3200 } while (next_if(','));
3201 parameters_finished:
3202 rem_anchor_token(',');
3205 rem_anchor_token(')');
3209 typedef enum construct_type_kind_t {
3210 CONSTRUCT_POINTER = 1,
3211 CONSTRUCT_REFERENCE,
3214 } construct_type_kind_t;
3216 typedef union construct_type_t construct_type_t;
3218 typedef struct construct_type_base_t {
3219 construct_type_kind_t kind;
3220 source_position_t pos;
3221 construct_type_t *next;
3222 } construct_type_base_t;
3224 typedef struct parsed_pointer_t {
3225 construct_type_base_t base;
3226 type_qualifiers_t type_qualifiers;
3227 variable_t *base_variable; /**< MS __based extension. */
3230 typedef struct parsed_reference_t {
3231 construct_type_base_t base;
3232 } parsed_reference_t;
3234 typedef struct construct_function_type_t {
3235 construct_type_base_t base;
3236 type_t *function_type;
3237 } construct_function_type_t;
3239 typedef struct parsed_array_t {
3240 construct_type_base_t base;
3241 type_qualifiers_t type_qualifiers;
3247 union construct_type_t {
3248 construct_type_kind_t kind;
3249 construct_type_base_t base;
3250 parsed_pointer_t pointer;
3251 parsed_reference_t reference;
3252 construct_function_type_t function;
3253 parsed_array_t array;
3256 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3258 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3259 memset(cons, 0, size);
3261 cons->base.pos = *HERE;
3266 static construct_type_t *parse_pointer_declarator(void)
3268 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3270 cons->pointer.type_qualifiers = parse_type_qualifiers();
3271 //cons->pointer.base_variable = base_variable;
3276 /* ISO/IEC 14882:1998(E) §8.3.2 */
3277 static construct_type_t *parse_reference_declarator(void)
3279 if (!(c_mode & _CXX))
3280 errorf(HERE, "references are only available for C++");
3282 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3289 static construct_type_t *parse_array_declarator(void)
3291 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3292 parsed_array_t *const array = &cons->array;
3295 add_anchor_token(']');
3297 bool is_static = next_if(T_static);
3299 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3302 is_static = next_if(T_static);
3304 array->type_qualifiers = type_qualifiers;
3305 array->is_static = is_static;
3307 expression_t *size = NULL;
3308 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3309 array->is_variable = true;
3311 } else if (token.kind != ']') {
3312 size = parse_assignment_expression();
3314 /* §6.7.5.2:1 Array size must have integer type */
3315 type_t *const orig_type = size->base.type;
3316 type_t *const type = skip_typeref(orig_type);
3317 if (!is_type_integer(type) && is_type_valid(type)) {
3318 errorf(&size->base.source_position,
3319 "array size '%E' must have integer type but has type '%T'",
3324 mark_vars_read(size, NULL);
3327 if (is_static && size == NULL)
3328 errorf(&array->base.pos, "static array parameters require a size");
3330 rem_anchor_token(']');
3336 static construct_type_t *parse_function_declarator(scope_t *scope)
3338 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3340 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3341 function_type_t *ftype = &type->function;
3343 ftype->linkage = current_linkage;
3344 ftype->calling_convention = CC_DEFAULT;
3346 parse_parameters(ftype, scope);
3348 cons->function.function_type = type;
3353 typedef struct parse_declarator_env_t {
3354 bool may_be_abstract : 1;
3355 bool must_be_abstract : 1;
3356 decl_modifiers_t modifiers;
3358 source_position_t source_position;
3360 attribute_t *attributes;
3361 } parse_declarator_env_t;
3364 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3366 /* construct a single linked list of construct_type_t's which describe
3367 * how to construct the final declarator type */
3368 construct_type_t *first = NULL;
3369 construct_type_t **anchor = &first;
3371 env->attributes = parse_attributes(env->attributes);
3374 construct_type_t *type;
3375 //variable_t *based = NULL; /* MS __based extension */
3376 switch (token.kind) {
3378 type = parse_reference_declarator();
3382 panic("based not supported anymore");
3387 type = parse_pointer_declarator();
3391 goto ptr_operator_end;
3395 anchor = &type->base.next;
3397 /* TODO: find out if this is correct */
3398 env->attributes = parse_attributes(env->attributes);
3402 construct_type_t *inner_types = NULL;
3404 switch (token.kind) {
3406 if (env->must_be_abstract) {
3407 errorf(HERE, "no identifier expected in typename");
3409 env->symbol = token.base.symbol;
3410 env->source_position = token.base.source_position;
3416 /* Parenthesized declarator or function declarator? */
3417 token_t const *const la1 = look_ahead(1);
3418 switch (la1->kind) {
3420 if (is_typedef_symbol(la1->base.symbol)) {
3422 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3423 * interpreted as ``function with no parameter specification'', rather
3424 * than redundant parentheses around the omitted identifier. */
3426 /* Function declarator. */
3427 if (!env->may_be_abstract) {
3428 errorf(HERE, "function declarator must have a name");
3435 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3436 /* Paranthesized declarator. */
3438 add_anchor_token(')');
3439 inner_types = parse_inner_declarator(env);
3440 if (inner_types != NULL) {
3441 /* All later declarators only modify the return type */
3442 env->must_be_abstract = true;
3444 rem_anchor_token(')');
3453 if (env->may_be_abstract)
3455 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3460 construct_type_t **const p = anchor;
3463 construct_type_t *type;
3464 switch (token.kind) {
3466 scope_t *scope = NULL;
3467 if (!env->must_be_abstract) {
3468 scope = &env->parameters;
3471 type = parse_function_declarator(scope);
3475 type = parse_array_declarator();
3478 goto declarator_finished;
3481 /* insert in the middle of the list (at p) */
3482 type->base.next = *p;
3485 anchor = &type->base.next;
3488 declarator_finished:
3489 /* append inner_types at the end of the list, we don't to set anchor anymore
3490 * as it's not needed anymore */
3491 *anchor = inner_types;
3496 static type_t *construct_declarator_type(construct_type_t *construct_list,
3499 construct_type_t *iter = construct_list;
3500 for (; iter != NULL; iter = iter->base.next) {
3501 source_position_t const* const pos = &iter->base.pos;
3502 switch (iter->kind) {
3503 case CONSTRUCT_FUNCTION: {
3504 construct_function_type_t *function = &iter->function;
3505 type_t *function_type = function->function_type;
3507 function_type->function.return_type = type;
3509 type_t *skipped_return_type = skip_typeref(type);
3511 if (is_type_function(skipped_return_type)) {
3512 errorf(pos, "function returning function is not allowed");
3513 } else if (is_type_array(skipped_return_type)) {
3514 errorf(pos, "function returning array is not allowed");
3516 if (skipped_return_type->base.qualifiers != 0) {
3517 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3521 /* The function type was constructed earlier. Freeing it here will
3522 * destroy other types. */
3523 type = typehash_insert(function_type);
3527 case CONSTRUCT_POINTER: {
3528 if (is_type_reference(skip_typeref(type)))
3529 errorf(pos, "cannot declare a pointer to reference");
3531 parsed_pointer_t *pointer = &iter->pointer;
3532 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3536 case CONSTRUCT_REFERENCE:
3537 if (is_type_reference(skip_typeref(type)))
3538 errorf(pos, "cannot declare a reference to reference");
3540 type = make_reference_type(type);
3543 case CONSTRUCT_ARRAY: {
3544 if (is_type_reference(skip_typeref(type)))
3545 errorf(pos, "cannot declare an array of references");
3547 parsed_array_t *array = &iter->array;
3548 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3550 expression_t *size_expression = array->size;
3551 if (size_expression != NULL) {
3553 = create_implicit_cast(size_expression, type_size_t);
3556 array_type->base.qualifiers = array->type_qualifiers;
3557 array_type->array.element_type = type;
3558 array_type->array.is_static = array->is_static;
3559 array_type->array.is_variable = array->is_variable;
3560 array_type->array.size_expression = size_expression;
3562 if (size_expression != NULL) {
3563 switch (is_constant_expression(size_expression)) {
3564 case EXPR_CLASS_CONSTANT: {
3565 long const size = fold_constant_to_int(size_expression);
3566 array_type->array.size = size;
3567 array_type->array.size_constant = true;
3568 /* §6.7.5.2:1 If the expression is a constant expression,
3569 * it shall have a value greater than zero. */
3571 errorf(&size_expression->base.source_position,
3572 "size of array must be greater than zero");
3573 } else if (size == 0 && !GNU_MODE) {
3574 errorf(&size_expression->base.source_position,
3575 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3580 case EXPR_CLASS_VARIABLE:
3581 array_type->array.is_vla = true;
3584 case EXPR_CLASS_ERROR:
3589 type_t *skipped_type = skip_typeref(type);
3591 if (is_type_incomplete(skipped_type)) {
3592 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3593 } else if (is_type_function(skipped_type)) {
3594 errorf(pos, "array of functions is not allowed");
3596 type = identify_new_type(array_type);
3600 internal_errorf(pos, "invalid type construction found");
3606 static type_t *automatic_type_conversion(type_t *orig_type);
3608 static type_t *semantic_parameter(const source_position_t *pos,
3610 const declaration_specifiers_t *specifiers,
3611 entity_t const *const param)
3613 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3614 * shall be adjusted to ``qualified pointer to type'',
3616 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3617 * type'' shall be adjusted to ``pointer to function
3618 * returning type'', as in 6.3.2.1. */
3619 type = automatic_type_conversion(type);
3621 if (specifiers->is_inline && is_type_valid(type)) {
3622 errorf(pos, "'%N' declared 'inline'", param);
3625 /* §6.9.1:6 The declarations in the declaration list shall contain
3626 * no storage-class specifier other than register and no
3627 * initializations. */
3628 if (specifiers->thread_local || (
3629 specifiers->storage_class != STORAGE_CLASS_NONE &&
3630 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3632 errorf(pos, "invalid storage class for '%N'", param);
3635 /* delay test for incomplete type, because we might have (void)
3636 * which is legal but incomplete... */
3641 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3642 declarator_flags_t flags)
3644 parse_declarator_env_t env;
3645 memset(&env, 0, sizeof(env));
3646 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3648 construct_type_t *construct_type = parse_inner_declarator(&env);
3650 construct_declarator_type(construct_type, specifiers->type);
3651 type_t *type = skip_typeref(orig_type);
3653 if (construct_type != NULL) {
3654 obstack_free(&temp_obst, construct_type);
3657 attribute_t *attributes = parse_attributes(env.attributes);
3658 /* append (shared) specifier attribute behind attributes of this
3660 attribute_t **anchor = &attributes;
3661 while (*anchor != NULL)
3662 anchor = &(*anchor)->next;
3663 *anchor = specifiers->attributes;
3666 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3667 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3668 entity->typedefe.type = orig_type;
3670 if (anonymous_entity != NULL) {
3671 if (is_type_compound(type)) {
3672 assert(anonymous_entity->compound.alias == NULL);
3673 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3674 anonymous_entity->kind == ENTITY_UNION);
3675 anonymous_entity->compound.alias = entity;
3676 anonymous_entity = NULL;
3677 } else if (is_type_enum(type)) {
3678 assert(anonymous_entity->enume.alias == NULL);
3679 assert(anonymous_entity->kind == ENTITY_ENUM);
3680 anonymous_entity->enume.alias = entity;
3681 anonymous_entity = NULL;
3685 /* create a declaration type entity */
3686 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3687 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3688 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3690 if (env.symbol != NULL) {
3691 if (specifiers->is_inline && is_type_valid(type)) {
3692 errorf(&env.source_position,
3693 "compound member '%Y' declared 'inline'", env.symbol);
3696 if (specifiers->thread_local ||
3697 specifiers->storage_class != STORAGE_CLASS_NONE) {
3698 errorf(&env.source_position,
3699 "compound member '%Y' must have no storage class",
3703 } else if (flags & DECL_IS_PARAMETER) {
3704 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3705 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3706 } else if (is_type_function(type)) {
3707 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3708 entity->function.is_inline = specifiers->is_inline;
3709 entity->function.elf_visibility = default_visibility;
3710 entity->function.parameters = env.parameters;
3712 if (env.symbol != NULL) {
3713 /* this needs fixes for C++ */
3714 bool in_function_scope = current_function != NULL;
3716 if (specifiers->thread_local || (
3717 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3718 specifiers->storage_class != STORAGE_CLASS_NONE &&
3719 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3721 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3725 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3726 entity->variable.elf_visibility = default_visibility;
3727 entity->variable.thread_local = specifiers->thread_local;
3729 if (env.symbol != NULL) {
3730 if (specifiers->is_inline && is_type_valid(type)) {
3731 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3734 bool invalid_storage_class = false;
3735 if (current_scope == file_scope) {
3736 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3737 specifiers->storage_class != STORAGE_CLASS_NONE &&
3738 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3739 invalid_storage_class = true;
3742 if (specifiers->thread_local &&
3743 specifiers->storage_class == STORAGE_CLASS_NONE) {
3744 invalid_storage_class = true;
3747 if (invalid_storage_class) {
3748 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3753 entity->declaration.type = orig_type;
3754 entity->declaration.alignment = get_type_alignment(orig_type);
3755 entity->declaration.modifiers = env.modifiers;
3756 entity->declaration.attributes = attributes;
3758 storage_class_t storage_class = specifiers->storage_class;
3759 entity->declaration.declared_storage_class = storage_class;
3761 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3762 storage_class = STORAGE_CLASS_AUTO;
3763 entity->declaration.storage_class = storage_class;
3766 if (attributes != NULL) {
3767 handle_entity_attributes(attributes, entity);
3770 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3771 adapt_special_functions(&entity->function);
3777 static type_t *parse_abstract_declarator(type_t *base_type)
3779 parse_declarator_env_t env;
3780 memset(&env, 0, sizeof(env));
3781 env.may_be_abstract = true;
3782 env.must_be_abstract = true;
3784 construct_type_t *construct_type = parse_inner_declarator(&env);
3786 type_t *result = construct_declarator_type(construct_type, base_type);
3787 if (construct_type != NULL) {
3788 obstack_free(&temp_obst, construct_type);
3790 result = handle_type_attributes(env.attributes, result);
3796 * Check if the declaration of main is suspicious. main should be a
3797 * function with external linkage, returning int, taking either zero
3798 * arguments, two, or three arguments of appropriate types, ie.
3800 * int main([ int argc, char **argv [, char **env ] ]).
3802 * @param decl the declaration to check
3803 * @param type the function type of the declaration
3805 static void check_main(const entity_t *entity)
3807 const source_position_t *pos = &entity->base.source_position;
3808 if (entity->kind != ENTITY_FUNCTION) {
3809 warningf(WARN_MAIN, pos, "'main' is not a function");
3813 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3814 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3817 type_t *type = skip_typeref(entity->declaration.type);
3818 assert(is_type_function(type));
3820 function_type_t const *const func_type = &type->function;
3821 type_t *const ret_type = func_type->return_type;
3822 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3823 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3825 const function_parameter_t *parm = func_type->parameters;
3827 type_t *const first_type = skip_typeref(parm->type);
3828 type_t *const first_type_unqual = get_unqualified_type(first_type);
3829 if (!types_compatible(first_type_unqual, type_int)) {
3830 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3834 type_t *const second_type = skip_typeref(parm->type);
3835 type_t *const second_type_unqual
3836 = get_unqualified_type(second_type);
3837 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3838 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3842 type_t *const third_type = skip_typeref(parm->type);
3843 type_t *const third_type_unqual
3844 = get_unqualified_type(third_type);
3845 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3846 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3850 goto warn_arg_count;
3854 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3859 static void error_redefined_as_different_kind(const source_position_t *pos,
3860 const entity_t *old, entity_kind_t new_kind)
3862 char const *const what = get_entity_kind_name(new_kind);
3863 source_position_t const *const ppos = &old->base.source_position;
3864 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3867 static bool is_entity_valid(entity_t *const ent)
3869 if (is_declaration(ent)) {
3870 return is_type_valid(skip_typeref(ent->declaration.type));
3871 } else if (ent->kind == ENTITY_TYPEDEF) {
3872 return is_type_valid(skip_typeref(ent->typedefe.type));
3877 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3879 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3880 if (attributes_equal(tattr, attr))
3887 * test wether new_list contains any attributes not included in old_list
3889 static bool has_new_attributes(const attribute_t *old_list,
3890 const attribute_t *new_list)
3892 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3893 if (!contains_attribute(old_list, attr))
3900 * Merge in attributes from an attribute list (probably from a previous
3901 * declaration with the same name). Warning: destroys the old structure
3902 * of the attribute list - don't reuse attributes after this call.
3904 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3907 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3909 if (contains_attribute(decl->attributes, attr))
3912 /* move attribute to new declarations attributes list */
3913 attr->next = decl->attributes;
3914 decl->attributes = attr;
3918 static bool is_main(entity_t*);
3921 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3922 * for various problems that occur for multiple definitions
3924 entity_t *record_entity(entity_t *entity, const bool is_definition)
3926 const symbol_t *const symbol = entity->base.symbol;
3927 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3928 const source_position_t *pos = &entity->base.source_position;
3930 /* can happen in error cases */
3934 assert(!entity->base.parent_scope);
3935 assert(current_scope);
3936 entity->base.parent_scope = current_scope;
3938 entity_t *const previous_entity = get_entity(symbol, namespc);
3939 /* pushing the same entity twice will break the stack structure */
3940 assert(previous_entity != entity);
3942 if (entity->kind == ENTITY_FUNCTION) {
3943 type_t *const orig_type = entity->declaration.type;
3944 type_t *const type = skip_typeref(orig_type);
3946 assert(is_type_function(type));
3947 if (type->function.unspecified_parameters &&
3948 previous_entity == NULL &&
3949 !entity->declaration.implicit) {
3950 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3953 if (is_main(entity)) {
3958 if (is_declaration(entity) &&
3959 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3960 current_scope != file_scope &&
3961 !entity->declaration.implicit) {
3962 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3965 if (previous_entity != NULL) {
3966 source_position_t const *const ppos = &previous_entity->base.source_position;
3968 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3969 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3970 assert(previous_entity->kind == ENTITY_PARAMETER);
3971 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3975 if (previous_entity->base.parent_scope == current_scope) {
3976 if (previous_entity->kind != entity->kind) {
3977 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3978 error_redefined_as_different_kind(pos, previous_entity,
3983 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3984 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3987 if (previous_entity->kind == ENTITY_TYPEDEF) {
3988 type_t *const type = skip_typeref(entity->typedefe.type);
3989 type_t *const prev_type
3990 = skip_typeref(previous_entity->typedefe.type);
3991 if (c_mode & _CXX) {
3992 /* C++ allows double typedef if they are identical
3993 * (after skipping typedefs) */
3994 if (type == prev_type)
3997 /* GCC extension: redef in system headers is allowed */
3998 if ((pos->is_system_header || ppos->is_system_header) &&
3999 types_compatible(type, prev_type))
4002 errorf(pos, "redefinition of '%N' (declared %P)",
4007 /* at this point we should have only VARIABLES or FUNCTIONS */
4008 assert(is_declaration(previous_entity) && is_declaration(entity));
4010 declaration_t *const prev_decl = &previous_entity->declaration;
4011 declaration_t *const decl = &entity->declaration;
4013 /* can happen for K&R style declarations */
4014 if (prev_decl->type == NULL &&
4015 previous_entity->kind == ENTITY_PARAMETER &&
4016 entity->kind == ENTITY_PARAMETER) {
4017 prev_decl->type = decl->type;
4018 prev_decl->storage_class = decl->storage_class;
4019 prev_decl->declared_storage_class = decl->declared_storage_class;
4020 prev_decl->modifiers = decl->modifiers;
4021 return previous_entity;
4024 type_t *const type = skip_typeref(decl->type);
4025 type_t *const prev_type = skip_typeref(prev_decl->type);
4027 if (!types_compatible(type, prev_type)) {
4028 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4030 unsigned old_storage_class = prev_decl->storage_class;
4032 if (is_definition &&
4034 !(prev_decl->modifiers & DM_USED) &&
4035 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4036 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4039 storage_class_t new_storage_class = decl->storage_class;
4041 /* pretend no storage class means extern for function
4042 * declarations (except if the previous declaration is neither
4043 * none nor extern) */
4044 if (entity->kind == ENTITY_FUNCTION) {
4045 /* the previous declaration could have unspecified parameters or
4046 * be a typedef, so use the new type */
4047 if (prev_type->function.unspecified_parameters || is_definition)
4048 prev_decl->type = type;
4050 switch (old_storage_class) {
4051 case STORAGE_CLASS_NONE:
4052 old_storage_class = STORAGE_CLASS_EXTERN;
4055 case STORAGE_CLASS_EXTERN:
4056 if (is_definition) {
4057 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4058 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4060 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4061 new_storage_class = STORAGE_CLASS_EXTERN;
4068 } else if (is_type_incomplete(prev_type)) {
4069 prev_decl->type = type;
4072 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4073 new_storage_class == STORAGE_CLASS_EXTERN) {
4075 warn_redundant_declaration: ;
4077 = has_new_attributes(prev_decl->attributes,
4079 if (has_new_attrs) {
4080 merge_in_attributes(decl, prev_decl->attributes);
4081 } else if (!is_definition &&
4082 is_type_valid(prev_type) &&
4083 !pos->is_system_header) {
4084 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4086 } else if (current_function == NULL) {
4087 if (old_storage_class != STORAGE_CLASS_STATIC &&
4088 new_storage_class == STORAGE_CLASS_STATIC) {
4089 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4090 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4091 prev_decl->storage_class = STORAGE_CLASS_NONE;
4092 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4094 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4096 goto error_redeclaration;
4097 goto warn_redundant_declaration;
4099 } else if (is_type_valid(prev_type)) {
4100 if (old_storage_class == new_storage_class) {
4101 error_redeclaration:
4102 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4104 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4109 prev_decl->modifiers |= decl->modifiers;
4110 if (entity->kind == ENTITY_FUNCTION) {
4111 previous_entity->function.is_inline |= entity->function.is_inline;
4113 return previous_entity;
4117 if (is_warn_on(why = WARN_SHADOW) ||
4118 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4119 char const *const what = get_entity_kind_name(previous_entity->kind);
4120 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4124 if (entity->kind == ENTITY_FUNCTION) {
4125 if (is_definition &&
4126 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4128 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4129 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4131 goto warn_missing_declaration;
4134 } else if (entity->kind == ENTITY_VARIABLE) {
4135 if (current_scope == file_scope &&
4136 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4137 !entity->declaration.implicit) {
4138 warn_missing_declaration:
4139 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4144 environment_push(entity);
4145 append_entity(current_scope, entity);
4150 static void parser_error_multiple_definition(entity_t *entity,
4151 const source_position_t *source_position)
4153 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4154 entity->base.symbol, &entity->base.source_position);
4157 static bool is_declaration_specifier(const token_t *token)
4159 switch (token->kind) {
4163 return is_typedef_symbol(token->base.symbol);
4170 static void parse_init_declarator_rest(entity_t *entity)
4172 type_t *orig_type = type_error_type;
4174 if (entity->base.kind == ENTITY_TYPEDEF) {
4175 source_position_t const *const pos = &entity->base.source_position;
4176 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4178 assert(is_declaration(entity));
4179 orig_type = entity->declaration.type;
4182 type_t *type = skip_typeref(orig_type);
4184 if (entity->kind == ENTITY_VARIABLE
4185 && entity->variable.initializer != NULL) {
4186 parser_error_multiple_definition(entity, HERE);
4190 declaration_t *const declaration = &entity->declaration;
4191 bool must_be_constant = false;
4192 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4193 entity->base.parent_scope == file_scope) {
4194 must_be_constant = true;
4197 if (is_type_function(type)) {
4198 source_position_t const *const pos = &entity->base.source_position;
4199 errorf(pos, "'%N' is initialized like a variable", entity);
4200 orig_type = type_error_type;
4203 parse_initializer_env_t env;
4204 env.type = orig_type;
4205 env.must_be_constant = must_be_constant;
4206 env.entity = entity;
4208 initializer_t *initializer = parse_initializer(&env);
4210 if (entity->kind == ENTITY_VARIABLE) {
4211 /* §6.7.5:22 array initializers for arrays with unknown size
4212 * determine the array type size */
4213 declaration->type = env.type;
4214 entity->variable.initializer = initializer;
4218 /* parse rest of a declaration without any declarator */
4219 static void parse_anonymous_declaration_rest(
4220 const declaration_specifiers_t *specifiers)
4223 anonymous_entity = NULL;
4225 source_position_t const *const pos = &specifiers->source_position;
4226 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4227 specifiers->thread_local) {
4228 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4231 type_t *type = specifiers->type;
4232 switch (type->kind) {
4233 case TYPE_COMPOUND_STRUCT:
4234 case TYPE_COMPOUND_UNION: {
4235 if (type->compound.compound->base.symbol == NULL) {
4236 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4245 warningf(WARN_OTHER, pos, "empty declaration");
4250 static void check_variable_type_complete(entity_t *ent)
4252 if (ent->kind != ENTITY_VARIABLE)
4255 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4256 * type for the object shall be complete [...] */
4257 declaration_t *decl = &ent->declaration;
4258 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4259 decl->storage_class == STORAGE_CLASS_STATIC)
4262 type_t *const type = skip_typeref(decl->type);
4263 if (!is_type_incomplete(type))
4266 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4267 * are given length one. */
4268 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4269 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4273 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4277 static void parse_declaration_rest(entity_t *ndeclaration,
4278 const declaration_specifiers_t *specifiers,
4279 parsed_declaration_func finished_declaration,
4280 declarator_flags_t flags)
4282 add_anchor_token(';');
4283 add_anchor_token(',');
4285 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4287 if (token.kind == '=') {
4288 parse_init_declarator_rest(entity);
4289 } else if (entity->kind == ENTITY_VARIABLE) {
4290 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4291 * [...] where the extern specifier is explicitly used. */
4292 declaration_t *decl = &entity->declaration;
4293 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4294 is_type_reference(skip_typeref(decl->type))) {
4295 source_position_t const *const pos = &entity->base.source_position;
4296 errorf(pos, "reference '%#N' must be initialized", entity);
4300 check_variable_type_complete(entity);
4305 add_anchor_token('=');
4306 ndeclaration = parse_declarator(specifiers, flags);
4307 rem_anchor_token('=');
4309 rem_anchor_token(',');
4310 rem_anchor_token(';');
4313 anonymous_entity = NULL;
4316 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4318 symbol_t *symbol = entity->base.symbol;
4322 assert(entity->base.namespc == NAMESPACE_NORMAL);
4323 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4324 if (previous_entity == NULL
4325 || previous_entity->base.parent_scope != current_scope) {
4326 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4331 if (is_definition) {
4332 errorf(HERE, "'%N' is initialised", entity);
4335 return record_entity(entity, false);
4338 static void parse_declaration(parsed_declaration_func finished_declaration,
4339 declarator_flags_t flags)
4341 add_anchor_token(';');
4342 declaration_specifiers_t specifiers;
4343 parse_declaration_specifiers(&specifiers);
4344 rem_anchor_token(';');
4346 if (token.kind == ';') {
4347 parse_anonymous_declaration_rest(&specifiers);
4349 entity_t *entity = parse_declarator(&specifiers, flags);
4350 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4355 static type_t *get_default_promoted_type(type_t *orig_type)
4357 type_t *result = orig_type;
4359 type_t *type = skip_typeref(orig_type);
4360 if (is_type_integer(type)) {
4361 result = promote_integer(type);
4362 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4363 result = type_double;
4369 static void parse_kr_declaration_list(entity_t *entity)
4371 if (entity->kind != ENTITY_FUNCTION)
4374 type_t *type = skip_typeref(entity->declaration.type);
4375 assert(is_type_function(type));
4376 if (!type->function.kr_style_parameters)
4379 add_anchor_token('{');
4381 PUSH_SCOPE(&entity->function.parameters);
4383 entity_t *parameter = entity->function.parameters.entities;
4384 for ( ; parameter != NULL; parameter = parameter->base.next) {
4385 assert(parameter->base.parent_scope == NULL);
4386 parameter->base.parent_scope = current_scope;
4387 environment_push(parameter);
4390 /* parse declaration list */
4392 switch (token.kind) {
4394 /* This covers symbols, which are no type, too, and results in
4395 * better error messages. The typical cases are misspelled type
4396 * names and missing includes. */
4398 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4408 /* update function type */
4409 type_t *new_type = duplicate_type(type);
4411 function_parameter_t *parameters = NULL;
4412 function_parameter_t **anchor = ¶meters;
4414 /* did we have an earlier prototype? */
4415 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4416 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4419 function_parameter_t *proto_parameter = NULL;
4420 if (proto_type != NULL) {
4421 type_t *proto_type_type = proto_type->declaration.type;
4422 proto_parameter = proto_type_type->function.parameters;
4423 /* If a K&R function definition has a variadic prototype earlier, then
4424 * make the function definition variadic, too. This should conform to
4425 * §6.7.5.3:15 and §6.9.1:8. */
4426 new_type->function.variadic = proto_type_type->function.variadic;
4428 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4430 new_type->function.unspecified_parameters = true;
4433 bool need_incompatible_warning = false;
4434 parameter = entity->function.parameters.entities;
4435 for (; parameter != NULL; parameter = parameter->base.next,
4437 proto_parameter == NULL ? NULL : proto_parameter->next) {
4438 if (parameter->kind != ENTITY_PARAMETER)
4441 type_t *parameter_type = parameter->declaration.type;
4442 if (parameter_type == NULL) {
4443 source_position_t const* const pos = ¶meter->base.source_position;
4445 errorf(pos, "no type specified for function '%N'", parameter);
4446 parameter_type = type_error_type;
4448 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4449 parameter_type = type_int;
4451 parameter->declaration.type = parameter_type;
4454 semantic_parameter_incomplete(parameter);
4456 /* we need the default promoted types for the function type */
4457 type_t *not_promoted = parameter_type;
4458 parameter_type = get_default_promoted_type(parameter_type);
4460 /* gcc special: if the type of the prototype matches the unpromoted
4461 * type don't promote */
4462 if (!strict_mode && proto_parameter != NULL) {
4463 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4464 type_t *promo_skip = skip_typeref(parameter_type);
4465 type_t *param_skip = skip_typeref(not_promoted);
4466 if (!types_compatible(proto_p_type, promo_skip)
4467 && types_compatible(proto_p_type, param_skip)) {
4469 need_incompatible_warning = true;
4470 parameter_type = not_promoted;
4473 function_parameter_t *const function_parameter
4474 = allocate_parameter(parameter_type);
4476 *anchor = function_parameter;
4477 anchor = &function_parameter->next;
4480 new_type->function.parameters = parameters;
4481 new_type = identify_new_type(new_type);
4483 if (need_incompatible_warning) {
4484 symbol_t const *const sym = entity->base.symbol;
4485 source_position_t const *const pos = &entity->base.source_position;
4486 source_position_t const *const ppos = &proto_type->base.source_position;
4487 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4489 entity->declaration.type = new_type;
4491 rem_anchor_token('{');
4494 static bool first_err = true;
4497 * When called with first_err set, prints the name of the current function,
4500 static void print_in_function(void)
4504 char const *const file = current_function->base.base.source_position.input_name;
4505 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4510 * Check if all labels are defined in the current function.
4511 * Check if all labels are used in the current function.
4513 static void check_labels(void)
4515 for (const goto_statement_t *goto_statement = goto_first;
4516 goto_statement != NULL;
4517 goto_statement = goto_statement->next) {
4518 label_t *label = goto_statement->label;
4519 if (label->base.source_position.input_name == NULL) {
4520 print_in_function();
4521 source_position_t const *const pos = &goto_statement->base.source_position;
4522 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4526 if (is_warn_on(WARN_UNUSED_LABEL)) {
4527 for (const label_statement_t *label_statement = label_first;
4528 label_statement != NULL;
4529 label_statement = label_statement->next) {
4530 label_t *label = label_statement->label;
4532 if (! label->used) {
4533 print_in_function();
4534 source_position_t const *const pos = &label_statement->base.source_position;
4535 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4541 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4543 entity_t const *const end = last != NULL ? last->base.next : NULL;
4544 for (; entity != end; entity = entity->base.next) {
4545 if (!is_declaration(entity))
4548 declaration_t *declaration = &entity->declaration;
4549 if (declaration->implicit)
4552 if (!declaration->used) {
4553 print_in_function();
4554 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4555 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4556 print_in_function();
4557 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4562 static void check_unused_variables(statement_t *const stmt, void *const env)
4566 switch (stmt->kind) {
4567 case STATEMENT_DECLARATION: {
4568 declaration_statement_t const *const decls = &stmt->declaration;
4569 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4574 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4583 * Check declarations of current_function for unused entities.
4585 static void check_declarations(void)
4587 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4588 const scope_t *scope = ¤t_function->parameters;
4589 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4591 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4592 walk_statements(current_function->statement, check_unused_variables,
4597 static int determine_truth(expression_t const* const cond)
4600 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4601 fold_constant_to_bool(cond) ? 1 :
4605 static void check_reachable(statement_t *);
4606 static bool reaches_end;
4608 static bool expression_returns(expression_t const *const expr)
4610 switch (expr->kind) {
4612 expression_t const *const func = expr->call.function;
4613 type_t const *const type = skip_typeref(func->base.type);
4614 if (type->kind == TYPE_POINTER) {
4615 type_t const *const points_to
4616 = skip_typeref(type->pointer.points_to);
4617 if (points_to->kind == TYPE_FUNCTION
4618 && points_to->function.modifiers & DM_NORETURN)
4622 if (!expression_returns(func))
4625 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4626 if (!expression_returns(arg->expression))
4633 case EXPR_REFERENCE:
4634 case EXPR_ENUM_CONSTANT:
4635 case EXPR_LITERAL_CASES:
4636 case EXPR_STRING_LITERAL:
4637 case EXPR_WIDE_STRING_LITERAL:
4638 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4639 case EXPR_LABEL_ADDRESS:
4640 case EXPR_CLASSIFY_TYPE:
4641 case EXPR_SIZEOF: // TODO handle obscure VLA case
4644 case EXPR_BUILTIN_CONSTANT_P:
4645 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4650 case EXPR_STATEMENT: {
4651 bool old_reaches_end = reaches_end;
4652 reaches_end = false;
4653 check_reachable(expr->statement.statement);
4654 bool returns = reaches_end;
4655 reaches_end = old_reaches_end;
4659 case EXPR_CONDITIONAL:
4660 // TODO handle constant expression
4662 if (!expression_returns(expr->conditional.condition))
4665 if (expr->conditional.true_expression != NULL
4666 && expression_returns(expr->conditional.true_expression))
4669 return expression_returns(expr->conditional.false_expression);
4672 return expression_returns(expr->select.compound);
4674 case EXPR_ARRAY_ACCESS:
4676 expression_returns(expr->array_access.array_ref) &&
4677 expression_returns(expr->array_access.index);
4680 return expression_returns(expr->va_starte.ap);
4683 return expression_returns(expr->va_arge.ap);
4686 return expression_returns(expr->va_copye.src);
4688 case EXPR_UNARY_CASES_MANDATORY:
4689 return expression_returns(expr->unary.value);
4691 case EXPR_UNARY_THROW:
4694 case EXPR_BINARY_CASES:
4695 // TODO handle constant lhs of && and ||
4697 expression_returns(expr->binary.left) &&
4698 expression_returns(expr->binary.right);
4701 panic("unhandled expression");
4704 static bool initializer_returns(initializer_t const *const init)
4706 switch (init->kind) {
4707 case INITIALIZER_VALUE:
4708 return expression_returns(init->value.value);
4710 case INITIALIZER_LIST: {
4711 initializer_t * const* i = init->list.initializers;
4712 initializer_t * const* const end = i + init->list.len;
4713 bool returns = true;
4714 for (; i != end; ++i) {
4715 if (!initializer_returns(*i))
4721 case INITIALIZER_STRING:
4722 case INITIALIZER_WIDE_STRING:
4723 case INITIALIZER_DESIGNATOR: // designators have no payload
4726 panic("unhandled initializer");
4729 static bool noreturn_candidate;
4731 static void check_reachable(statement_t *const stmt)
4733 if (stmt->base.reachable)
4735 if (stmt->kind != STATEMENT_DO_WHILE)
4736 stmt->base.reachable = true;
4738 statement_t *last = stmt;
4740 switch (stmt->kind) {
4741 case STATEMENT_ERROR:
4742 case STATEMENT_EMPTY:
4744 next = stmt->base.next;
4747 case STATEMENT_DECLARATION: {
4748 declaration_statement_t const *const decl = &stmt->declaration;
4749 entity_t const * ent = decl->declarations_begin;
4750 entity_t const *const last_decl = decl->declarations_end;
4752 for (;; ent = ent->base.next) {
4753 if (ent->kind == ENTITY_VARIABLE &&
4754 ent->variable.initializer != NULL &&
4755 !initializer_returns(ent->variable.initializer)) {
4758 if (ent == last_decl)
4762 next = stmt->base.next;
4766 case STATEMENT_COMPOUND:
4767 next = stmt->compound.statements;
4769 next = stmt->base.next;
4772 case STATEMENT_RETURN: {
4773 expression_t const *const val = stmt->returns.value;
4774 if (val == NULL || expression_returns(val))
4775 noreturn_candidate = false;
4779 case STATEMENT_IF: {
4780 if_statement_t const *const ifs = &stmt->ifs;
4781 expression_t const *const cond = ifs->condition;
4783 if (!expression_returns(cond))
4786 int const val = determine_truth(cond);
4789 check_reachable(ifs->true_statement);
4794 if (ifs->false_statement != NULL) {
4795 check_reachable(ifs->false_statement);
4799 next = stmt->base.next;
4803 case STATEMENT_SWITCH: {
4804 switch_statement_t const *const switchs = &stmt->switchs;
4805 expression_t const *const expr = switchs->expression;
4807 if (!expression_returns(expr))
4810 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4811 long const val = fold_constant_to_int(expr);
4812 case_label_statement_t * defaults = NULL;
4813 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4814 if (i->expression == NULL) {
4819 if (i->first_case <= val && val <= i->last_case) {
4820 check_reachable((statement_t*)i);
4825 if (defaults != NULL) {
4826 check_reachable((statement_t*)defaults);
4830 bool has_default = false;
4831 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4832 if (i->expression == NULL)
4835 check_reachable((statement_t*)i);
4842 next = stmt->base.next;
4846 case STATEMENT_EXPRESSION: {
4847 /* Check for noreturn function call */
4848 expression_t const *const expr = stmt->expression.expression;
4849 if (!expression_returns(expr))
4852 next = stmt->base.next;
4856 case STATEMENT_CONTINUE:
4857 for (statement_t *parent = stmt;;) {
4858 parent = parent->base.parent;
4859 if (parent == NULL) /* continue not within loop */
4863 switch (parent->kind) {
4864 case STATEMENT_WHILE: goto continue_while;
4865 case STATEMENT_DO_WHILE: goto continue_do_while;
4866 case STATEMENT_FOR: goto continue_for;
4872 case STATEMENT_BREAK:
4873 for (statement_t *parent = stmt;;) {
4874 parent = parent->base.parent;
4875 if (parent == NULL) /* break not within loop/switch */
4878 switch (parent->kind) {
4879 case STATEMENT_SWITCH:
4880 case STATEMENT_WHILE:
4881 case STATEMENT_DO_WHILE:
4884 next = parent->base.next;
4885 goto found_break_parent;
4893 case STATEMENT_COMPUTED_GOTO: {
4894 if (!expression_returns(stmt->computed_goto.expression))
4897 statement_t *parent = stmt->base.parent;
4898 if (parent == NULL) /* top level goto */
4904 case STATEMENT_GOTO:
4905 next = stmt->gotos.label->statement;
4906 if (next == NULL) /* missing label */
4910 case STATEMENT_LABEL:
4911 next = stmt->label.statement;
4914 case STATEMENT_CASE_LABEL:
4915 next = stmt->case_label.statement;
4918 case STATEMENT_WHILE: {
4919 while_statement_t const *const whiles = &stmt->whiles;
4920 expression_t const *const cond = whiles->condition;
4922 if (!expression_returns(cond))
4925 int const val = determine_truth(cond);
4928 check_reachable(whiles->body);
4933 next = stmt->base.next;
4937 case STATEMENT_DO_WHILE:
4938 next = stmt->do_while.body;
4941 case STATEMENT_FOR: {
4942 for_statement_t *const fors = &stmt->fors;
4944 if (fors->condition_reachable)
4946 fors->condition_reachable = true;
4948 expression_t const *const cond = fors->condition;
4953 } else if (expression_returns(cond)) {
4954 val = determine_truth(cond);
4960 check_reachable(fors->body);
4965 next = stmt->base.next;
4969 case STATEMENT_MS_TRY: {
4970 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4971 check_reachable(ms_try->try_statement);
4972 next = ms_try->final_statement;
4976 case STATEMENT_LEAVE: {
4977 statement_t *parent = stmt;
4979 parent = parent->base.parent;
4980 if (parent == NULL) /* __leave not within __try */
4983 if (parent->kind == STATEMENT_MS_TRY) {
4985 next = parent->ms_try.final_statement;
4993 panic("invalid statement kind");
4996 while (next == NULL) {
4997 next = last->base.parent;
4999 noreturn_candidate = false;
5001 type_t *const type = skip_typeref(current_function->base.type);
5002 assert(is_type_function(type));
5003 type_t *const ret = skip_typeref(type->function.return_type);
5004 if (!is_type_void(ret) &&
5005 is_type_valid(ret) &&
5006 !is_main(current_entity)) {
5007 source_position_t const *const pos = &stmt->base.source_position;
5008 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5013 switch (next->kind) {
5014 case STATEMENT_ERROR:
5015 case STATEMENT_EMPTY:
5016 case STATEMENT_DECLARATION:
5017 case STATEMENT_EXPRESSION:
5019 case STATEMENT_RETURN:
5020 case STATEMENT_CONTINUE:
5021 case STATEMENT_BREAK:
5022 case STATEMENT_COMPUTED_GOTO:
5023 case STATEMENT_GOTO:
5024 case STATEMENT_LEAVE:
5025 panic("invalid control flow in function");
5027 case STATEMENT_COMPOUND:
5028 if (next->compound.stmt_expr) {
5034 case STATEMENT_SWITCH:
5035 case STATEMENT_LABEL:
5036 case STATEMENT_CASE_LABEL:
5038 next = next->base.next;
5041 case STATEMENT_WHILE: {
5043 if (next->base.reachable)
5045 next->base.reachable = true;
5047 while_statement_t const *const whiles = &next->whiles;
5048 expression_t const *const cond = whiles->condition;
5050 if (!expression_returns(cond))
5053 int const val = determine_truth(cond);
5056 check_reachable(whiles->body);
5062 next = next->base.next;
5066 case STATEMENT_DO_WHILE: {
5068 if (next->base.reachable)
5070 next->base.reachable = true;
5072 do_while_statement_t const *const dw = &next->do_while;
5073 expression_t const *const cond = dw->condition;
5075 if (!expression_returns(cond))
5078 int const val = determine_truth(cond);
5081 check_reachable(dw->body);
5087 next = next->base.next;
5091 case STATEMENT_FOR: {
5093 for_statement_t *const fors = &next->fors;
5095 fors->step_reachable = true;
5097 if (fors->condition_reachable)
5099 fors->condition_reachable = true;
5101 expression_t const *const cond = fors->condition;
5106 } else if (expression_returns(cond)) {
5107 val = determine_truth(cond);
5113 check_reachable(fors->body);
5119 next = next->base.next;
5123 case STATEMENT_MS_TRY:
5125 next = next->ms_try.final_statement;
5130 check_reachable(next);
5133 static void check_unreachable(statement_t* const stmt, void *const env)
5137 switch (stmt->kind) {
5138 case STATEMENT_DO_WHILE:
5139 if (!stmt->base.reachable) {
5140 expression_t const *const cond = stmt->do_while.condition;
5141 if (determine_truth(cond) >= 0) {
5142 source_position_t const *const pos = &cond->base.source_position;
5143 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5148 case STATEMENT_FOR: {
5149 for_statement_t const* const fors = &stmt->fors;
5151 // if init and step are unreachable, cond is unreachable, too
5152 if (!stmt->base.reachable && !fors->step_reachable) {
5153 goto warn_unreachable;
5155 if (!stmt->base.reachable && fors->initialisation != NULL) {
5156 source_position_t const *const pos = &fors->initialisation->base.source_position;
5157 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5160 if (!fors->condition_reachable && fors->condition != NULL) {
5161 source_position_t const *const pos = &fors->condition->base.source_position;
5162 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5165 if (!fors->step_reachable && fors->step != NULL) {
5166 source_position_t const *const pos = &fors->step->base.source_position;
5167 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5173 case STATEMENT_COMPOUND:
5174 if (stmt->compound.statements != NULL)
5176 goto warn_unreachable;
5178 case STATEMENT_DECLARATION: {
5179 /* Only warn if there is at least one declarator with an initializer.
5180 * This typically occurs in switch statements. */
5181 declaration_statement_t const *const decl = &stmt->declaration;
5182 entity_t const * ent = decl->declarations_begin;
5183 entity_t const *const last = decl->declarations_end;
5185 for (;; ent = ent->base.next) {
5186 if (ent->kind == ENTITY_VARIABLE &&
5187 ent->variable.initializer != NULL) {
5188 goto warn_unreachable;
5198 if (!stmt->base.reachable) {
5199 source_position_t const *const pos = &stmt->base.source_position;
5200 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5206 static bool is_main(entity_t *entity)
5208 static symbol_t *sym_main = NULL;
5209 if (sym_main == NULL) {
5210 sym_main = symbol_table_insert("main");
5213 if (entity->base.symbol != sym_main)
5215 /* must be in outermost scope */
5216 if (entity->base.parent_scope != file_scope)
5222 static void prepare_main_collect2(entity_t*);
5224 static void parse_external_declaration(void)
5226 /* function-definitions and declarations both start with declaration
5228 add_anchor_token(';');
5229 declaration_specifiers_t specifiers;
5230 parse_declaration_specifiers(&specifiers);
5231 rem_anchor_token(';');
5233 /* must be a declaration */
5234 if (token.kind == ';') {
5235 parse_anonymous_declaration_rest(&specifiers);
5239 add_anchor_token(',');
5240 add_anchor_token('=');
5241 add_anchor_token(';');
5242 add_anchor_token('{');
5244 /* declarator is common to both function-definitions and declarations */
5245 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5247 rem_anchor_token('{');
5248 rem_anchor_token(';');
5249 rem_anchor_token('=');
5250 rem_anchor_token(',');
5252 /* must be a declaration */
5253 switch (token.kind) {
5257 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5262 /* must be a function definition */
5263 parse_kr_declaration_list(ndeclaration);
5265 if (token.kind != '{') {
5266 parse_error_expected("while parsing function definition", '{', NULL);
5267 eat_until_matching_token(';');
5271 assert(is_declaration(ndeclaration));
5272 type_t *const orig_type = ndeclaration->declaration.type;
5273 type_t * type = skip_typeref(orig_type);
5275 if (!is_type_function(type)) {
5276 if (is_type_valid(type)) {
5277 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5283 source_position_t const *const pos = &ndeclaration->base.source_position;
5284 if (is_typeref(orig_type)) {
5286 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5289 if (is_type_compound(skip_typeref(type->function.return_type))) {
5290 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5292 if (type->function.unspecified_parameters) {
5293 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5295 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5298 /* §6.7.5.3:14 a function definition with () means no
5299 * parameters (and not unspecified parameters) */
5300 if (type->function.unspecified_parameters &&
5301 type->function.parameters == NULL) {
5302 type_t *copy = duplicate_type(type);
5303 copy->function.unspecified_parameters = false;
5304 type = identify_new_type(copy);
5306 ndeclaration->declaration.type = type;
5309 entity_t *const entity = record_entity(ndeclaration, true);
5310 assert(entity->kind == ENTITY_FUNCTION);
5311 assert(ndeclaration->kind == ENTITY_FUNCTION);
5313 function_t *const function = &entity->function;
5314 if (ndeclaration != entity) {
5315 function->parameters = ndeclaration->function.parameters;
5318 PUSH_SCOPE(&function->parameters);
5320 entity_t *parameter = function->parameters.entities;
5321 for (; parameter != NULL; parameter = parameter->base.next) {
5322 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5323 parameter->base.parent_scope = current_scope;
5325 assert(parameter->base.parent_scope == NULL
5326 || parameter->base.parent_scope == current_scope);
5327 parameter->base.parent_scope = current_scope;
5328 if (parameter->base.symbol == NULL) {
5329 errorf(¶meter->base.source_position, "parameter name omitted");
5332 environment_push(parameter);
5335 if (function->statement != NULL) {
5336 parser_error_multiple_definition(entity, HERE);
5339 /* parse function body */
5340 int label_stack_top = label_top();
5341 function_t *old_current_function = current_function;
5342 current_function = function;
5343 PUSH_CURRENT_ENTITY(entity);
5347 goto_anchor = &goto_first;
5349 label_anchor = &label_first;
5351 statement_t *const body = parse_compound_statement(false);
5352 function->statement = body;
5355 check_declarations();
5356 if (is_warn_on(WARN_RETURN_TYPE) ||
5357 is_warn_on(WARN_UNREACHABLE_CODE) ||
5358 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5359 noreturn_candidate = true;
5360 check_reachable(body);
5361 if (is_warn_on(WARN_UNREACHABLE_CODE))
5362 walk_statements(body, check_unreachable, NULL);
5363 if (noreturn_candidate &&
5364 !(function->base.modifiers & DM_NORETURN)) {
5365 source_position_t const *const pos = &body->base.source_position;
5366 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5370 if (is_main(entity)) {
5371 /* Force main to C linkage. */
5372 type_t *const type = entity->declaration.type;
5373 assert(is_type_function(type));
5374 if (type->function.linkage != LINKAGE_C) {
5375 type_t *new_type = duplicate_type(type);
5376 new_type->function.linkage = LINKAGE_C;
5377 entity->declaration.type = identify_new_type(new_type);
5380 if (enable_main_collect2_hack)
5381 prepare_main_collect2(entity);
5384 POP_CURRENT_ENTITY();
5386 assert(current_function == function);
5387 current_function = old_current_function;
5388 label_pop_to(label_stack_top);
5394 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5396 entity_t *iter = compound->members.entities;
5397 for (; iter != NULL; iter = iter->base.next) {
5398 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5401 if (iter->base.symbol == symbol) {
5403 } else if (iter->base.symbol == NULL) {
5404 /* search in anonymous structs and unions */
5405 type_t *type = skip_typeref(iter->declaration.type);
5406 if (is_type_compound(type)) {
5407 if (find_compound_entry(type->compound.compound, symbol)
5418 static void check_deprecated(const source_position_t *source_position,
5419 const entity_t *entity)
5421 if (!is_declaration(entity))
5423 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5426 source_position_t const *const epos = &entity->base.source_position;
5427 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5429 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5431 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5436 static expression_t *create_select(const source_position_t *pos,
5438 type_qualifiers_t qualifiers,
5441 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5443 check_deprecated(pos, entry);
5445 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5446 select->select.compound = addr;
5447 select->select.compound_entry = entry;
5449 type_t *entry_type = entry->declaration.type;
5450 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5452 /* bitfields need special treatment */
5453 if (entry->compound_member.bitfield) {
5454 unsigned bit_size = entry->compound_member.bit_size;
5455 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5456 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5457 res_type = type_int;
5461 /* we always do the auto-type conversions; the & and sizeof parser contains
5462 * code to revert this! */
5463 select->base.type = automatic_type_conversion(res_type);
5470 * Find entry with symbol in compound. Search anonymous structs and unions and
5471 * creates implicit select expressions for them.
5472 * Returns the adress for the innermost compound.
5474 static expression_t *find_create_select(const source_position_t *pos,
5476 type_qualifiers_t qualifiers,
5477 compound_t *compound, symbol_t *symbol)
5479 entity_t *iter = compound->members.entities;
5480 for (; iter != NULL; iter = iter->base.next) {
5481 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5484 symbol_t *iter_symbol = iter->base.symbol;
5485 if (iter_symbol == NULL) {
5486 type_t *type = iter->declaration.type;
5487 if (type->kind != TYPE_COMPOUND_STRUCT
5488 && type->kind != TYPE_COMPOUND_UNION)
5491 compound_t *sub_compound = type->compound.compound;
5493 if (find_compound_entry(sub_compound, symbol) == NULL)
5496 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5497 sub_addr->base.source_position = *pos;
5498 sub_addr->base.implicit = true;
5499 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5503 if (iter_symbol == symbol) {
5504 return create_select(pos, addr, qualifiers, iter);
5511 static void parse_bitfield_member(entity_t *entity)
5515 expression_t *size = parse_constant_expression();
5518 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5519 type_t *type = entity->declaration.type;
5520 if (!is_type_integer(skip_typeref(type))) {
5521 errorf(HERE, "bitfield base type '%T' is not an integer type",
5525 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5526 /* error already reported by parse_constant_expression */
5527 size_long = get_type_size(type) * 8;
5529 size_long = fold_constant_to_int(size);
5531 const symbol_t *symbol = entity->base.symbol;
5532 const symbol_t *user_symbol
5533 = symbol == NULL ? sym_anonymous : symbol;
5534 unsigned bit_size = get_type_size(type) * 8;
5535 if (size_long < 0) {
5536 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5537 } else if (size_long == 0 && symbol != NULL) {
5538 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5539 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5540 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5543 /* hope that people don't invent crazy types with more bits
5544 * than our struct can hold */
5546 (1 << sizeof(entity->compound_member.bit_size)*8));
5550 entity->compound_member.bitfield = true;
5551 entity->compound_member.bit_size = (unsigned char)size_long;
5554 static void parse_compound_declarators(compound_t *compound,
5555 const declaration_specifiers_t *specifiers)
5557 add_anchor_token(';');
5558 add_anchor_token(',');
5562 if (token.kind == ':') {
5563 /* anonymous bitfield */
5564 type_t *type = specifiers->type;
5565 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5566 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5567 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5568 entity->declaration.type = type;
5570 parse_bitfield_member(entity);
5572 attribute_t *attributes = parse_attributes(NULL);
5573 attribute_t **anchor = &attributes;
5574 while (*anchor != NULL)
5575 anchor = &(*anchor)->next;
5576 *anchor = specifiers->attributes;
5577 if (attributes != NULL) {
5578 handle_entity_attributes(attributes, entity);
5580 entity->declaration.attributes = attributes;
5582 append_entity(&compound->members, entity);
5584 entity = parse_declarator(specifiers,
5585 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5586 source_position_t const *const pos = &entity->base.source_position;
5587 if (entity->kind == ENTITY_TYPEDEF) {
5588 errorf(pos, "typedef not allowed as compound member");
5590 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5592 /* make sure we don't define a symbol multiple times */
5593 symbol_t *symbol = entity->base.symbol;
5594 if (symbol != NULL) {
5595 entity_t *prev = find_compound_entry(compound, symbol);
5597 source_position_t const *const ppos = &prev->base.source_position;
5598 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5602 if (token.kind == ':') {
5603 parse_bitfield_member(entity);
5605 attribute_t *attributes = parse_attributes(NULL);
5606 handle_entity_attributes(attributes, entity);
5608 type_t *orig_type = entity->declaration.type;
5609 type_t *type = skip_typeref(orig_type);
5610 if (is_type_function(type)) {
5611 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5612 } else if (is_type_incomplete(type)) {
5613 /* §6.7.2.1:16 flexible array member */
5614 if (!is_type_array(type) ||
5615 token.kind != ';' ||
5616 look_ahead(1)->kind != '}') {
5617 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5618 } else if (compound->members.entities == NULL) {
5619 errorf(pos, "flexible array member in otherwise empty struct");
5624 append_entity(&compound->members, entity);
5627 } while (next_if(','));
5628 rem_anchor_token(',');
5629 rem_anchor_token(';');
5632 anonymous_entity = NULL;
5635 static void parse_compound_type_entries(compound_t *compound)
5638 add_anchor_token('}');
5641 switch (token.kind) {
5643 case T___extension__:
5644 case T_IDENTIFIER: {
5646 declaration_specifiers_t specifiers;
5647 parse_declaration_specifiers(&specifiers);
5648 parse_compound_declarators(compound, &specifiers);
5654 rem_anchor_token('}');
5657 compound->complete = true;
5663 static type_t *parse_typename(void)
5665 declaration_specifiers_t specifiers;
5666 parse_declaration_specifiers(&specifiers);
5667 if (specifiers.storage_class != STORAGE_CLASS_NONE
5668 || specifiers.thread_local) {
5669 /* TODO: improve error message, user does probably not know what a
5670 * storage class is...
5672 errorf(&specifiers.source_position, "typename must not have a storage class");
5675 type_t *result = parse_abstract_declarator(specifiers.type);
5683 typedef expression_t* (*parse_expression_function)(void);
5684 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5686 typedef struct expression_parser_function_t expression_parser_function_t;
5687 struct expression_parser_function_t {
5688 parse_expression_function parser;
5689 precedence_t infix_precedence;
5690 parse_expression_infix_function infix_parser;
5693 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5695 static type_t *get_string_type(void)
5697 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5700 static type_t *get_wide_string_type(void)
5702 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5706 * Parse a string constant.
5708 static expression_t *parse_string_literal(void)
5710 source_position_t begin = token.base.source_position;
5711 string_t res = token.string.string;
5712 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5715 while (token.kind == T_STRING_LITERAL
5716 || token.kind == T_WIDE_STRING_LITERAL) {
5717 warn_string_concat(&token.base.source_position);
5718 res = concat_strings(&res, &token.string.string);
5720 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5723 expression_t *literal;
5725 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5726 literal->base.type = get_wide_string_type();
5728 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5729 literal->base.type = get_string_type();
5731 literal->base.source_position = begin;
5732 literal->literal.value = res;
5738 * Parse a boolean constant.
5740 static expression_t *parse_boolean_literal(bool value)
5742 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5743 literal->base.type = type_bool;
5744 literal->literal.value.begin = value ? "true" : "false";
5745 literal->literal.value.size = value ? 4 : 5;
5751 static void warn_traditional_suffix(void)
5753 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5754 &token.number.suffix);
5757 static void check_integer_suffix(void)
5759 const string_t *suffix = &token.number.suffix;
5760 if (suffix->size == 0)
5763 bool not_traditional = false;
5764 const char *c = suffix->begin;
5765 if (*c == 'l' || *c == 'L') {
5768 not_traditional = true;
5770 if (*c == 'u' || *c == 'U') {
5773 } else if (*c == 'u' || *c == 'U') {
5774 not_traditional = true;
5777 } else if (*c == 'u' || *c == 'U') {
5778 not_traditional = true;
5780 if (*c == 'l' || *c == 'L') {
5788 errorf(&token.base.source_position,
5789 "invalid suffix '%S' on integer constant", suffix);
5790 } else if (not_traditional) {
5791 warn_traditional_suffix();
5795 static type_t *check_floatingpoint_suffix(void)
5797 const string_t *suffix = &token.number.suffix;
5798 type_t *type = type_double;
5799 if (suffix->size == 0)
5802 bool not_traditional = false;
5803 const char *c = suffix->begin;
5804 if (*c == 'f' || *c == 'F') {
5807 } else if (*c == 'l' || *c == 'L') {
5809 type = type_long_double;
5812 errorf(&token.base.source_position,
5813 "invalid suffix '%S' on floatingpoint constant", suffix);
5814 } else if (not_traditional) {
5815 warn_traditional_suffix();
5822 * Parse an integer constant.
5824 static expression_t *parse_number_literal(void)
5826 expression_kind_t kind;
5829 switch (token.kind) {
5831 kind = EXPR_LITERAL_INTEGER;
5832 check_integer_suffix();
5836 case T_FLOATINGPOINT:
5837 kind = EXPR_LITERAL_FLOATINGPOINT;
5838 type = check_floatingpoint_suffix();
5842 panic("unexpected token type in parse_number_literal");
5845 expression_t *literal = allocate_expression_zero(kind);
5846 literal->base.type = type;
5847 literal->literal.value = token.number.number;
5848 literal->literal.suffix = token.number.suffix;
5851 /* integer type depends on the size of the number and the size
5852 * representable by the types. The backend/codegeneration has to determine
5855 determine_literal_type(&literal->literal);
5860 * Parse a character constant.
5862 static expression_t *parse_character_constant(void)
5864 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5865 literal->base.type = c_mode & _CXX ? type_char : type_int;
5866 literal->literal.value = token.string.string;
5868 size_t len = literal->literal.value.size;
5870 if (!GNU_MODE && !(c_mode & _C99)) {
5871 errorf(HERE, "more than 1 character in character constant");
5873 literal->base.type = type_int;
5874 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5883 * Parse a wide character constant.
5885 static expression_t *parse_wide_character_constant(void)
5887 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5888 literal->base.type = type_int;
5889 literal->literal.value = token.string.string;
5891 size_t len = wstrlen(&literal->literal.value);
5893 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5900 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5902 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5903 ntype->function.return_type = type_int;
5904 ntype->function.unspecified_parameters = true;
5905 ntype->function.linkage = LINKAGE_C;
5906 type_t *type = identify_new_type(ntype);
5908 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5909 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5910 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5911 entity->declaration.type = type;
5912 entity->declaration.implicit = true;
5914 if (current_scope != NULL)
5915 record_entity(entity, false);
5921 * Performs automatic type cast as described in §6.3.2.1.
5923 * @param orig_type the original type
5925 static type_t *automatic_type_conversion(type_t *orig_type)
5927 type_t *type = skip_typeref(orig_type);
5928 if (is_type_array(type)) {
5929 array_type_t *array_type = &type->array;
5930 type_t *element_type = array_type->element_type;
5931 unsigned qualifiers = array_type->base.qualifiers;
5933 return make_pointer_type(element_type, qualifiers);
5936 if (is_type_function(type)) {
5937 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5944 * reverts the automatic casts of array to pointer types and function
5945 * to function-pointer types as defined §6.3.2.1
5947 type_t *revert_automatic_type_conversion(const expression_t *expression)
5949 switch (expression->kind) {
5950 case EXPR_REFERENCE: {
5951 entity_t *entity = expression->reference.entity;
5952 if (is_declaration(entity)) {
5953 return entity->declaration.type;
5954 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5955 return entity->enum_value.enum_type;
5957 panic("no declaration or enum in reference");
5962 entity_t *entity = expression->select.compound_entry;
5963 assert(is_declaration(entity));
5964 type_t *type = entity->declaration.type;
5965 return get_qualified_type(type, expression->base.type->base.qualifiers);
5968 case EXPR_UNARY_DEREFERENCE: {
5969 const expression_t *const value = expression->unary.value;
5970 type_t *const type = skip_typeref(value->base.type);
5971 if (!is_type_pointer(type))
5972 return type_error_type;
5973 return type->pointer.points_to;
5976 case EXPR_ARRAY_ACCESS: {
5977 const expression_t *array_ref = expression->array_access.array_ref;
5978 type_t *type_left = skip_typeref(array_ref->base.type);
5979 if (!is_type_pointer(type_left))
5980 return type_error_type;
5981 return type_left->pointer.points_to;
5984 case EXPR_STRING_LITERAL: {
5985 size_t size = expression->string_literal.value.size;
5986 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5989 case EXPR_WIDE_STRING_LITERAL: {
5990 size_t size = wstrlen(&expression->string_literal.value);
5991 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5994 case EXPR_COMPOUND_LITERAL:
5995 return expression->compound_literal.type;
6000 return expression->base.type;
6004 * Find an entity matching a symbol in a scope.
6005 * Uses current scope if scope is NULL
6007 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6008 namespace_tag_t namespc)
6010 if (scope == NULL) {
6011 return get_entity(symbol, namespc);
6014 /* we should optimize here, if scope grows above a certain size we should
6015 construct a hashmap here... */
6016 entity_t *entity = scope->entities;
6017 for ( ; entity != NULL; entity = entity->base.next) {
6018 if (entity->base.symbol == symbol
6019 && (namespace_tag_t)entity->base.namespc == namespc)
6026 static entity_t *parse_qualified_identifier(void)
6028 /* namespace containing the symbol */
6030 source_position_t pos;
6031 const scope_t *lookup_scope = NULL;
6033 if (next_if(T_COLONCOLON))
6034 lookup_scope = &unit->scope;
6038 symbol = expect_identifier("while parsing identifier", &pos);
6040 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6043 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6045 if (!next_if(T_COLONCOLON))
6048 switch (entity->kind) {
6049 case ENTITY_NAMESPACE:
6050 lookup_scope = &entity->namespacee.members;
6055 lookup_scope = &entity->compound.members;
6058 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6059 symbol, get_entity_kind_name(entity->kind));
6061 /* skip further qualifications */
6062 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6064 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6068 if (entity == NULL) {
6069 if (!strict_mode && token.kind == '(') {
6070 /* an implicitly declared function */
6071 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6072 "implicit declaration of function '%Y'", symbol);
6073 entity = create_implicit_function(symbol, &pos);
6075 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6076 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6083 static expression_t *parse_reference(void)
6085 source_position_t const pos = token.base.source_position;
6086 entity_t *const entity = parse_qualified_identifier();
6089 if (is_declaration(entity)) {
6090 orig_type = entity->declaration.type;
6091 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6092 orig_type = entity->enum_value.enum_type;
6094 panic("expected declaration or enum value in reference");
6097 /* we always do the auto-type conversions; the & and sizeof parser contains
6098 * code to revert this! */
6099 type_t *type = automatic_type_conversion(orig_type);
6101 expression_kind_t kind = EXPR_REFERENCE;
6102 if (entity->kind == ENTITY_ENUM_VALUE)
6103 kind = EXPR_ENUM_CONSTANT;
6105 expression_t *expression = allocate_expression_zero(kind);
6106 expression->base.source_position = pos;
6107 expression->base.type = type;
6108 expression->reference.entity = entity;
6110 /* this declaration is used */
6111 if (is_declaration(entity)) {
6112 entity->declaration.used = true;
6115 if (entity->base.parent_scope != file_scope
6116 && (current_function != NULL
6117 && entity->base.parent_scope->depth < current_function->parameters.depth)
6118 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6119 if (entity->kind == ENTITY_VARIABLE) {
6120 /* access of a variable from an outer function */
6121 entity->variable.address_taken = true;
6122 } else if (entity->kind == ENTITY_PARAMETER) {
6123 entity->parameter.address_taken = true;
6125 current_function->need_closure = true;
6128 check_deprecated(&pos, entity);
6133 static bool semantic_cast(expression_t *cast)
6135 expression_t *expression = cast->unary.value;
6136 type_t *orig_dest_type = cast->base.type;
6137 type_t *orig_type_right = expression->base.type;
6138 type_t const *dst_type = skip_typeref(orig_dest_type);
6139 type_t const *src_type = skip_typeref(orig_type_right);
6140 source_position_t const *pos = &cast->base.source_position;
6142 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6143 if (is_type_void(dst_type))
6146 /* only integer and pointer can be casted to pointer */
6147 if (is_type_pointer(dst_type) &&
6148 !is_type_pointer(src_type) &&
6149 !is_type_integer(src_type) &&
6150 is_type_valid(src_type)) {
6151 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6155 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6156 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6160 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6161 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6165 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6166 type_t *src = skip_typeref(src_type->pointer.points_to);
6167 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6168 unsigned missing_qualifiers =
6169 src->base.qualifiers & ~dst->base.qualifiers;
6170 if (missing_qualifiers != 0) {
6171 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6177 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6179 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6180 expression->base.source_position = *pos;
6182 parse_initializer_env_t env;
6185 env.must_be_constant = false;
6186 initializer_t *initializer = parse_initializer(&env);
6189 expression->compound_literal.initializer = initializer;
6190 expression->compound_literal.type = type;
6191 expression->base.type = automatic_type_conversion(type);
6197 * Parse a cast expression.
6199 static expression_t *parse_cast(void)
6201 source_position_t const pos = *HERE;
6204 add_anchor_token(')');
6206 type_t *type = parse_typename();
6208 rem_anchor_token(')');
6211 if (token.kind == '{') {
6212 return parse_compound_literal(&pos, type);
6215 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6216 cast->base.source_position = pos;
6218 expression_t *value = parse_subexpression(PREC_CAST);
6219 cast->base.type = type;
6220 cast->unary.value = value;
6222 if (! semantic_cast(cast)) {
6223 /* TODO: record the error in the AST. else it is impossible to detect it */
6230 * Parse a statement expression.
6232 static expression_t *parse_statement_expression(void)
6234 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6237 add_anchor_token(')');
6239 statement_t *statement = parse_compound_statement(true);
6240 statement->compound.stmt_expr = true;
6241 expression->statement.statement = statement;
6243 /* find last statement and use its type */
6244 type_t *type = type_void;
6245 const statement_t *stmt = statement->compound.statements;
6247 while (stmt->base.next != NULL)
6248 stmt = stmt->base.next;
6250 if (stmt->kind == STATEMENT_EXPRESSION) {
6251 type = stmt->expression.expression->base.type;
6254 source_position_t const *const pos = &expression->base.source_position;
6255 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6257 expression->base.type = type;
6259 rem_anchor_token(')');
6265 * Parse a parenthesized expression.
6267 static expression_t *parse_parenthesized_expression(void)
6269 token_t const* const la1 = look_ahead(1);
6270 switch (la1->kind) {
6272 /* gcc extension: a statement expression */
6273 return parse_statement_expression();
6276 if (is_typedef_symbol(la1->base.symbol)) {
6278 return parse_cast();
6283 add_anchor_token(')');
6284 expression_t *result = parse_expression();
6285 result->base.parenthesized = true;
6286 rem_anchor_token(')');
6292 static expression_t *parse_function_keyword(void)
6296 if (current_function == NULL) {
6297 errorf(HERE, "'__func__' used outside of a function");
6300 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6301 expression->base.type = type_char_ptr;
6302 expression->funcname.kind = FUNCNAME_FUNCTION;
6309 static expression_t *parse_pretty_function_keyword(void)
6311 if (current_function == NULL) {
6312 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6315 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6316 expression->base.type = type_char_ptr;
6317 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6319 eat(T___PRETTY_FUNCTION__);
6324 static expression_t *parse_funcsig_keyword(void)
6326 if (current_function == NULL) {
6327 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6330 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6331 expression->base.type = type_char_ptr;
6332 expression->funcname.kind = FUNCNAME_FUNCSIG;
6339 static expression_t *parse_funcdname_keyword(void)
6341 if (current_function == NULL) {
6342 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6345 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6346 expression->base.type = type_char_ptr;
6347 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6349 eat(T___FUNCDNAME__);
6354 static designator_t *parse_designator(void)
6356 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6357 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6358 if (!result->symbol)
6361 designator_t *last_designator = result;
6364 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6365 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6366 if (!designator->symbol)
6369 last_designator->next = designator;
6370 last_designator = designator;
6374 add_anchor_token(']');
6375 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6376 designator->source_position = *HERE;
6377 designator->array_index = parse_expression();
6378 rem_anchor_token(']');
6380 if (designator->array_index == NULL) {
6384 last_designator->next = designator;
6385 last_designator = designator;
6395 * Parse the __builtin_offsetof() expression.
6397 static expression_t *parse_offsetof(void)
6399 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6400 expression->base.type = type_size_t;
6402 eat(T___builtin_offsetof);
6405 add_anchor_token(')');
6406 add_anchor_token(',');
6407 type_t *type = parse_typename();
6408 rem_anchor_token(',');
6410 designator_t *designator = parse_designator();
6411 rem_anchor_token(')');
6414 expression->offsetofe.type = type;
6415 expression->offsetofe.designator = designator;
6418 memset(&path, 0, sizeof(path));
6419 path.top_type = type;
6420 path.path = NEW_ARR_F(type_path_entry_t, 0);
6422 descend_into_subtype(&path);
6424 if (!walk_designator(&path, designator, true)) {
6425 return create_error_expression();
6428 DEL_ARR_F(path.path);
6434 * Parses a _builtin_va_start() expression.
6436 static expression_t *parse_va_start(void)
6438 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6440 eat(T___builtin_va_start);
6443 add_anchor_token(')');
6444 add_anchor_token(',');
6445 expression->va_starte.ap = parse_assignment_expression();
6446 rem_anchor_token(',');
6448 expression_t *const expr = parse_assignment_expression();
6449 if (expr->kind == EXPR_REFERENCE) {
6450 entity_t *const entity = expr->reference.entity;
6451 if (!current_function->base.type->function.variadic) {
6452 errorf(&expr->base.source_position,
6453 "'va_start' used in non-variadic function");
6454 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6455 entity->base.next != NULL ||
6456 entity->kind != ENTITY_PARAMETER) {
6457 errorf(&expr->base.source_position,
6458 "second argument of 'va_start' must be last parameter of the current function");
6460 expression->va_starte.parameter = &entity->variable;
6463 expression = create_error_expression();
6465 rem_anchor_token(')');
6471 * Parses a __builtin_va_arg() expression.
6473 static expression_t *parse_va_arg(void)
6475 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6477 eat(T___builtin_va_arg);
6480 add_anchor_token(')');
6481 add_anchor_token(',');
6483 ap.expression = parse_assignment_expression();
6484 expression->va_arge.ap = ap.expression;
6485 check_call_argument(type_valist, &ap, 1);
6487 rem_anchor_token(',');
6489 expression->base.type = parse_typename();
6490 rem_anchor_token(')');
6497 * Parses a __builtin_va_copy() expression.
6499 static expression_t *parse_va_copy(void)
6501 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6503 eat(T___builtin_va_copy);
6506 add_anchor_token(')');
6507 add_anchor_token(',');
6508 expression_t *dst = parse_assignment_expression();
6509 assign_error_t error = semantic_assign(type_valist, dst);
6510 report_assign_error(error, type_valist, dst, "call argument 1",
6511 &dst->base.source_position);
6512 expression->va_copye.dst = dst;
6514 rem_anchor_token(',');
6517 call_argument_t src;
6518 src.expression = parse_assignment_expression();
6519 check_call_argument(type_valist, &src, 2);
6520 expression->va_copye.src = src.expression;
6521 rem_anchor_token(')');
6528 * Parses a __builtin_constant_p() expression.
6530 static expression_t *parse_builtin_constant(void)
6532 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6534 eat(T___builtin_constant_p);
6537 add_anchor_token(')');
6538 expression->builtin_constant.value = parse_assignment_expression();
6539 rem_anchor_token(')');
6541 expression->base.type = type_int;
6547 * Parses a __builtin_types_compatible_p() expression.
6549 static expression_t *parse_builtin_types_compatible(void)
6551 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6553 eat(T___builtin_types_compatible_p);
6556 add_anchor_token(')');
6557 add_anchor_token(',');
6558 expression->builtin_types_compatible.left = parse_typename();
6559 rem_anchor_token(',');
6561 expression->builtin_types_compatible.right = parse_typename();
6562 rem_anchor_token(')');
6564 expression->base.type = type_int;
6570 * Parses a __builtin_is_*() compare expression.
6572 static expression_t *parse_compare_builtin(void)
6574 expression_t *expression;
6576 switch (token.kind) {
6577 case T___builtin_isgreater:
6578 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6580 case T___builtin_isgreaterequal:
6581 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6583 case T___builtin_isless:
6584 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6586 case T___builtin_islessequal:
6587 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6589 case T___builtin_islessgreater:
6590 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6592 case T___builtin_isunordered:
6593 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6596 internal_errorf(HERE, "invalid compare builtin found");
6598 expression->base.source_position = *HERE;
6602 add_anchor_token(')');
6603 add_anchor_token(',');
6604 expression->binary.left = parse_assignment_expression();
6605 rem_anchor_token(',');
6607 expression->binary.right = parse_assignment_expression();
6608 rem_anchor_token(')');
6611 type_t *const orig_type_left = expression->binary.left->base.type;
6612 type_t *const orig_type_right = expression->binary.right->base.type;
6614 type_t *const type_left = skip_typeref(orig_type_left);
6615 type_t *const type_right = skip_typeref(orig_type_right);
6616 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6617 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6618 type_error_incompatible("invalid operands in comparison",
6619 &expression->base.source_position, orig_type_left, orig_type_right);
6622 semantic_comparison(&expression->binary);
6629 * Parses a MS assume() expression.
6631 static expression_t *parse_assume(void)
6633 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6638 add_anchor_token(')');
6639 expression->unary.value = parse_assignment_expression();
6640 rem_anchor_token(')');
6643 expression->base.type = type_void;
6648 * Return the label for the current symbol or create a new one.
6650 static label_t *get_label(void)
6652 assert(token.kind == T_IDENTIFIER);
6653 assert(current_function != NULL);
6655 entity_t *label = get_entity(token.base.symbol, NAMESPACE_LABEL);
6656 /* If we find a local label, we already created the declaration. */
6657 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6658 if (label->base.parent_scope != current_scope) {
6659 assert(label->base.parent_scope->depth < current_scope->depth);
6660 current_function->goto_to_outer = true;
6662 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6663 /* There is no matching label in the same function, so create a new one. */
6664 source_position_t const nowhere = { NULL, 0, 0, false };
6665 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.base.symbol, &nowhere);
6670 return &label->label;
6674 * Parses a GNU && label address expression.
6676 static expression_t *parse_label_address(void)
6678 source_position_t source_position = token.base.source_position;
6680 if (token.kind != T_IDENTIFIER) {
6681 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6682 return create_error_expression();
6685 label_t *const label = get_label();
6687 label->address_taken = true;
6689 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6690 expression->base.source_position = source_position;
6692 /* label address is treated as a void pointer */
6693 expression->base.type = type_void_ptr;
6694 expression->label_address.label = label;
6699 * Parse a microsoft __noop expression.
6701 static expression_t *parse_noop_expression(void)
6703 /* the result is a (int)0 */
6704 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6705 literal->base.type = type_int;
6706 literal->literal.value.begin = "__noop";
6707 literal->literal.value.size = 6;
6711 if (token.kind == '(') {
6712 /* parse arguments */
6714 add_anchor_token(')');
6715 add_anchor_token(',');
6717 if (token.kind != ')') do {
6718 (void)parse_assignment_expression();
6719 } while (next_if(','));
6721 rem_anchor_token(',');
6722 rem_anchor_token(')');
6730 * Parses a primary expression.
6732 static expression_t *parse_primary_expression(void)
6734 switch (token.kind) {
6735 case T_false: return parse_boolean_literal(false);
6736 case T_true: return parse_boolean_literal(true);
6738 case T_FLOATINGPOINT: return parse_number_literal();
6739 case T_CHARACTER_CONSTANT: return parse_character_constant();
6740 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6741 case T_STRING_LITERAL:
6742 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6743 case T___FUNCTION__:
6744 case T___func__: return parse_function_keyword();
6745 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6746 case T___FUNCSIG__: return parse_funcsig_keyword();
6747 case T___FUNCDNAME__: return parse_funcdname_keyword();
6748 case T___builtin_offsetof: return parse_offsetof();
6749 case T___builtin_va_start: return parse_va_start();
6750 case T___builtin_va_arg: return parse_va_arg();
6751 case T___builtin_va_copy: return parse_va_copy();
6752 case T___builtin_isgreater:
6753 case T___builtin_isgreaterequal:
6754 case T___builtin_isless:
6755 case T___builtin_islessequal:
6756 case T___builtin_islessgreater:
6757 case T___builtin_isunordered: return parse_compare_builtin();
6758 case T___builtin_constant_p: return parse_builtin_constant();
6759 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6760 case T__assume: return parse_assume();
6763 return parse_label_address();
6766 case '(': return parse_parenthesized_expression();
6767 case T___noop: return parse_noop_expression();
6769 /* Gracefully handle type names while parsing expressions. */
6771 return parse_reference();
6773 if (!is_typedef_symbol(token.base.symbol)) {
6774 return parse_reference();
6778 source_position_t const pos = *HERE;
6779 declaration_specifiers_t specifiers;
6780 parse_declaration_specifiers(&specifiers);
6781 type_t const *const type = parse_abstract_declarator(specifiers.type);
6782 errorf(&pos, "encountered type '%T' while parsing expression", type);
6783 return create_error_expression();
6787 errorf(HERE, "unexpected token %K, expected an expression", &token);
6789 return create_error_expression();
6792 static expression_t *parse_array_expression(expression_t *left)
6794 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6795 array_access_expression_t *const arr = &expr->array_access;
6798 add_anchor_token(']');
6800 expression_t *const inside = parse_expression();
6802 type_t *const orig_type_left = left->base.type;
6803 type_t *const orig_type_inside = inside->base.type;
6805 type_t *const type_left = skip_typeref(orig_type_left);
6806 type_t *const type_inside = skip_typeref(orig_type_inside);
6812 if (is_type_pointer(type_left)) {
6815 idx_type = type_inside;
6816 res_type = type_left->pointer.points_to;
6818 } else if (is_type_pointer(type_inside)) {
6819 arr->flipped = true;
6822 idx_type = type_left;
6823 res_type = type_inside->pointer.points_to;
6825 res_type = automatic_type_conversion(res_type);
6826 if (!is_type_integer(idx_type)) {
6827 errorf(&idx->base.source_position, "array subscript must have integer type");
6828 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6829 source_position_t const *const pos = &idx->base.source_position;
6830 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6833 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6834 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6836 res_type = type_error_type;
6841 arr->array_ref = ref;
6843 arr->base.type = res_type;
6845 rem_anchor_token(']');
6850 static bool is_bitfield(const expression_t *expression)
6852 return expression->kind == EXPR_SELECT
6853 && expression->select.compound_entry->compound_member.bitfield;
6856 static expression_t *parse_typeprop(expression_kind_t const kind)
6858 expression_t *tp_expression = allocate_expression_zero(kind);
6859 tp_expression->base.type = type_size_t;
6861 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6864 expression_t *expression;
6865 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6866 source_position_t const pos = *HERE;
6868 add_anchor_token(')');
6869 orig_type = parse_typename();
6870 rem_anchor_token(')');
6873 if (token.kind == '{') {
6874 /* It was not sizeof(type) after all. It is sizeof of an expression
6875 * starting with a compound literal */
6876 expression = parse_compound_literal(&pos, orig_type);
6877 goto typeprop_expression;
6880 expression = parse_subexpression(PREC_UNARY);
6882 typeprop_expression:
6883 if (is_bitfield(expression)) {
6884 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6885 errorf(&tp_expression->base.source_position,
6886 "operand of %s expression must not be a bitfield", what);
6889 tp_expression->typeprop.tp_expression = expression;
6891 orig_type = revert_automatic_type_conversion(expression);
6892 expression->base.type = orig_type;
6895 tp_expression->typeprop.type = orig_type;
6896 type_t const* const type = skip_typeref(orig_type);
6897 char const* wrong_type = NULL;
6898 if (is_type_incomplete(type)) {
6899 if (!is_type_void(type) || !GNU_MODE)
6900 wrong_type = "incomplete";
6901 } else if (type->kind == TYPE_FUNCTION) {
6903 /* function types are allowed (and return 1) */
6904 source_position_t const *const pos = &tp_expression->base.source_position;
6905 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6906 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6908 wrong_type = "function";
6912 if (wrong_type != NULL) {
6913 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6914 errorf(&tp_expression->base.source_position,
6915 "operand of %s expression must not be of %s type '%T'",
6916 what, wrong_type, orig_type);
6919 return tp_expression;
6922 static expression_t *parse_sizeof(void)
6924 return parse_typeprop(EXPR_SIZEOF);
6927 static expression_t *parse_alignof(void)
6929 return parse_typeprop(EXPR_ALIGNOF);
6932 static expression_t *parse_select_expression(expression_t *addr)
6934 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6935 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6936 source_position_t const pos = *HERE;
6939 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6941 return create_error_expression();
6943 type_t *const orig_type = addr->base.type;
6944 type_t *const type = skip_typeref(orig_type);
6947 bool saw_error = false;
6948 if (is_type_pointer(type)) {
6949 if (!select_left_arrow) {
6951 "request for member '%Y' in something not a struct or union, but '%T'",
6955 type_left = skip_typeref(type->pointer.points_to);
6957 if (select_left_arrow && is_type_valid(type)) {
6958 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6964 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6965 type_left->kind != TYPE_COMPOUND_UNION) {
6967 if (is_type_valid(type_left) && !saw_error) {
6969 "request for member '%Y' in something not a struct or union, but '%T'",
6972 return create_error_expression();
6975 compound_t *compound = type_left->compound.compound;
6976 if (!compound->complete) {
6977 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6979 return create_error_expression();
6982 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6983 expression_t *result =
6984 find_create_select(&pos, addr, qualifiers, compound, symbol);
6986 if (result == NULL) {
6987 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6988 return create_error_expression();
6994 static void check_call_argument(type_t *expected_type,
6995 call_argument_t *argument, unsigned pos)
6997 type_t *expected_type_skip = skip_typeref(expected_type);
6998 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6999 expression_t *arg_expr = argument->expression;
7000 type_t *arg_type = skip_typeref(arg_expr->base.type);
7002 /* handle transparent union gnu extension */
7003 if (is_type_union(expected_type_skip)
7004 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7005 compound_t *union_decl = expected_type_skip->compound.compound;
7006 type_t *best_type = NULL;
7007 entity_t *entry = union_decl->members.entities;
7008 for ( ; entry != NULL; entry = entry->base.next) {
7009 assert(is_declaration(entry));
7010 type_t *decl_type = entry->declaration.type;
7011 error = semantic_assign(decl_type, arg_expr);
7012 if (error == ASSIGN_ERROR_INCOMPATIBLE
7013 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7016 if (error == ASSIGN_SUCCESS) {
7017 best_type = decl_type;
7018 } else if (best_type == NULL) {
7019 best_type = decl_type;
7023 if (best_type != NULL) {
7024 expected_type = best_type;
7028 error = semantic_assign(expected_type, arg_expr);
7029 argument->expression = create_implicit_cast(arg_expr, expected_type);
7031 if (error != ASSIGN_SUCCESS) {
7032 /* report exact scope in error messages (like "in argument 3") */
7034 snprintf(buf, sizeof(buf), "call argument %u", pos);
7035 report_assign_error(error, expected_type, arg_expr, buf,
7036 &arg_expr->base.source_position);
7038 type_t *const promoted_type = get_default_promoted_type(arg_type);
7039 if (!types_compatible(expected_type_skip, promoted_type) &&
7040 !types_compatible(expected_type_skip, type_void_ptr) &&
7041 !types_compatible(type_void_ptr, promoted_type)) {
7042 /* Deliberately show the skipped types in this warning */
7043 source_position_t const *const apos = &arg_expr->base.source_position;
7044 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7050 * Handle the semantic restrictions of builtin calls
7052 static void handle_builtin_argument_restrictions(call_expression_t *call)
7054 entity_t *entity = call->function->reference.entity;
7055 switch (entity->function.btk) {
7057 switch (entity->function.b.firm_builtin_kind) {
7058 case ir_bk_return_address:
7059 case ir_bk_frame_address: {
7060 /* argument must be constant */
7061 call_argument_t *argument = call->arguments;
7063 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7064 errorf(&call->base.source_position,
7065 "argument of '%Y' must be a constant expression",
7066 call->function->reference.entity->base.symbol);
7070 case ir_bk_prefetch:
7071 /* second and third argument must be constant if existent */
7072 if (call->arguments == NULL)
7074 call_argument_t *rw = call->arguments->next;
7075 call_argument_t *locality = NULL;
7078 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7079 errorf(&call->base.source_position,
7080 "second argument of '%Y' must be a constant expression",
7081 call->function->reference.entity->base.symbol);
7083 locality = rw->next;
7085 if (locality != NULL) {
7086 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7087 errorf(&call->base.source_position,
7088 "third argument of '%Y' must be a constant expression",
7089 call->function->reference.entity->base.symbol);
7091 locality = rw->next;
7098 case BUILTIN_OBJECT_SIZE:
7099 if (call->arguments == NULL)
7102 call_argument_t *arg = call->arguments->next;
7103 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7104 errorf(&call->base.source_position,
7105 "second argument of '%Y' must be a constant expression",
7106 call->function->reference.entity->base.symbol);
7115 * Parse a call expression, ie. expression '( ... )'.
7117 * @param expression the function address
7119 static expression_t *parse_call_expression(expression_t *expression)
7121 expression_t *result = allocate_expression_zero(EXPR_CALL);
7122 call_expression_t *call = &result->call;
7123 call->function = expression;
7125 type_t *const orig_type = expression->base.type;
7126 type_t *const type = skip_typeref(orig_type);
7128 function_type_t *function_type = NULL;
7129 if (is_type_pointer(type)) {
7130 type_t *const to_type = skip_typeref(type->pointer.points_to);
7132 if (is_type_function(to_type)) {
7133 function_type = &to_type->function;
7134 call->base.type = function_type->return_type;
7138 if (function_type == NULL && is_type_valid(type)) {
7140 "called object '%E' (type '%T') is not a pointer to a function",
7141 expression, orig_type);
7144 /* parse arguments */
7146 add_anchor_token(')');
7147 add_anchor_token(',');
7149 if (token.kind != ')') {
7150 call_argument_t **anchor = &call->arguments;
7152 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7153 argument->expression = parse_assignment_expression();
7156 anchor = &argument->next;
7157 } while (next_if(','));
7159 rem_anchor_token(',');
7160 rem_anchor_token(')');
7163 if (function_type == NULL)
7166 /* check type and count of call arguments */
7167 function_parameter_t *parameter = function_type->parameters;
7168 call_argument_t *argument = call->arguments;
7169 if (!function_type->unspecified_parameters) {
7170 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7171 parameter = parameter->next, argument = argument->next) {
7172 check_call_argument(parameter->type, argument, ++pos);
7175 if (parameter != NULL) {
7176 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7177 } else if (argument != NULL && !function_type->variadic) {
7178 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7182 /* do default promotion for other arguments */
7183 for (; argument != NULL; argument = argument->next) {
7184 type_t *argument_type = argument->expression->base.type;
7185 if (!is_type_object(skip_typeref(argument_type))) {
7186 errorf(&argument->expression->base.source_position,
7187 "call argument '%E' must not be void", argument->expression);
7190 argument_type = get_default_promoted_type(argument_type);
7192 argument->expression
7193 = create_implicit_cast(argument->expression, argument_type);
7198 if (is_type_compound(skip_typeref(function_type->return_type))) {
7199 source_position_t const *const pos = &expression->base.source_position;
7200 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7203 if (expression->kind == EXPR_REFERENCE) {
7204 reference_expression_t *reference = &expression->reference;
7205 if (reference->entity->kind == ENTITY_FUNCTION &&
7206 reference->entity->function.btk != BUILTIN_NONE)
7207 handle_builtin_argument_restrictions(call);
7213 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7215 static bool same_compound_type(const type_t *type1, const type_t *type2)
7218 is_type_compound(type1) &&
7219 type1->kind == type2->kind &&
7220 type1->compound.compound == type2->compound.compound;
7223 static expression_t const *get_reference_address(expression_t const *expr)
7225 bool regular_take_address = true;
7227 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7228 expr = expr->unary.value;
7230 regular_take_address = false;
7233 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7236 expr = expr->unary.value;
7239 if (expr->kind != EXPR_REFERENCE)
7242 /* special case for functions which are automatically converted to a
7243 * pointer to function without an extra TAKE_ADDRESS operation */
7244 if (!regular_take_address &&
7245 expr->reference.entity->kind != ENTITY_FUNCTION) {
7252 static void warn_reference_address_as_bool(expression_t const* expr)
7254 expr = get_reference_address(expr);
7256 source_position_t const *const pos = &expr->base.source_position;
7257 entity_t const *const ent = expr->reference.entity;
7258 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7262 static void warn_assignment_in_condition(const expression_t *const expr)
7264 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7266 if (expr->base.parenthesized)
7268 source_position_t const *const pos = &expr->base.source_position;
7269 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7272 static void semantic_condition(expression_t const *const expr,
7273 char const *const context)
7275 type_t *const type = skip_typeref(expr->base.type);
7276 if (is_type_scalar(type)) {
7277 warn_reference_address_as_bool(expr);
7278 warn_assignment_in_condition(expr);
7279 } else if (is_type_valid(type)) {
7280 errorf(&expr->base.source_position,
7281 "%s must have scalar type", context);
7286 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7288 * @param expression the conditional expression
7290 static expression_t *parse_conditional_expression(expression_t *expression)
7292 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7294 conditional_expression_t *conditional = &result->conditional;
7295 conditional->condition = expression;
7298 add_anchor_token(':');
7300 /* §6.5.15:2 The first operand shall have scalar type. */
7301 semantic_condition(expression, "condition of conditional operator");
7303 expression_t *true_expression = expression;
7304 bool gnu_cond = false;
7305 if (GNU_MODE && token.kind == ':') {
7308 true_expression = parse_expression();
7310 rem_anchor_token(':');
7312 expression_t *false_expression =
7313 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7315 type_t *const orig_true_type = true_expression->base.type;
7316 type_t *const orig_false_type = false_expression->base.type;
7317 type_t *const true_type = skip_typeref(orig_true_type);
7318 type_t *const false_type = skip_typeref(orig_false_type);
7321 source_position_t const *const pos = &conditional->base.source_position;
7322 type_t *result_type;
7323 if (is_type_void(true_type) || is_type_void(false_type)) {
7324 /* ISO/IEC 14882:1998(E) §5.16:2 */
7325 if (true_expression->kind == EXPR_UNARY_THROW) {
7326 result_type = false_type;
7327 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7328 result_type = true_type;
7330 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7331 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7333 result_type = type_void;
7335 } else if (is_type_arithmetic(true_type)
7336 && is_type_arithmetic(false_type)) {
7337 result_type = semantic_arithmetic(true_type, false_type);
7338 } else if (same_compound_type(true_type, false_type)) {
7339 /* just take 1 of the 2 types */
7340 result_type = true_type;
7341 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7342 type_t *pointer_type;
7344 expression_t *other_expression;
7345 if (is_type_pointer(true_type) &&
7346 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7347 pointer_type = true_type;
7348 other_type = false_type;
7349 other_expression = false_expression;
7351 pointer_type = false_type;
7352 other_type = true_type;
7353 other_expression = true_expression;
7356 if (is_null_pointer_constant(other_expression)) {
7357 result_type = pointer_type;
7358 } else if (is_type_pointer(other_type)) {
7359 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7360 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7363 if (is_type_void(to1) || is_type_void(to2)) {
7365 } else if (types_compatible(get_unqualified_type(to1),
7366 get_unqualified_type(to2))) {
7369 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7373 type_t *const type =
7374 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7375 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7376 } else if (is_type_integer(other_type)) {
7377 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7378 result_type = pointer_type;
7380 goto types_incompatible;
7384 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7385 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7387 result_type = type_error_type;
7390 conditional->true_expression
7391 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7392 conditional->false_expression
7393 = create_implicit_cast(false_expression, result_type);
7394 conditional->base.type = result_type;
7399 * Parse an extension expression.
7401 static expression_t *parse_extension(void)
7404 expression_t *expression = parse_subexpression(PREC_UNARY);
7410 * Parse a __builtin_classify_type() expression.
7412 static expression_t *parse_builtin_classify_type(void)
7414 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7415 result->base.type = type_int;
7417 eat(T___builtin_classify_type);
7420 add_anchor_token(')');
7421 expression_t *expression = parse_expression();
7422 rem_anchor_token(')');
7424 result->classify_type.type_expression = expression;
7430 * Parse a delete expression
7431 * ISO/IEC 14882:1998(E) §5.3.5
7433 static expression_t *parse_delete(void)
7435 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7436 result->base.type = type_void;
7441 result->kind = EXPR_UNARY_DELETE_ARRAY;
7445 expression_t *const value = parse_subexpression(PREC_CAST);
7446 result->unary.value = value;
7448 type_t *const type = skip_typeref(value->base.type);
7449 if (!is_type_pointer(type)) {
7450 if (is_type_valid(type)) {
7451 errorf(&value->base.source_position,
7452 "operand of delete must have pointer type");
7454 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7455 source_position_t const *const pos = &value->base.source_position;
7456 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7463 * Parse a throw expression
7464 * ISO/IEC 14882:1998(E) §15:1
7466 static expression_t *parse_throw(void)
7468 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7469 result->base.type = type_void;
7473 expression_t *value = NULL;
7474 switch (token.kind) {
7476 value = parse_assignment_expression();
7477 /* ISO/IEC 14882:1998(E) §15.1:3 */
7478 type_t *const orig_type = value->base.type;
7479 type_t *const type = skip_typeref(orig_type);
7480 if (is_type_incomplete(type)) {
7481 errorf(&value->base.source_position,
7482 "cannot throw object of incomplete type '%T'", orig_type);
7483 } else if (is_type_pointer(type)) {
7484 type_t *const points_to = skip_typeref(type->pointer.points_to);
7485 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7486 errorf(&value->base.source_position,
7487 "cannot throw pointer to incomplete type '%T'", orig_type);
7495 result->unary.value = value;
7500 static bool check_pointer_arithmetic(const source_position_t *source_position,
7501 type_t *pointer_type,
7502 type_t *orig_pointer_type)
7504 type_t *points_to = pointer_type->pointer.points_to;
7505 points_to = skip_typeref(points_to);
7507 if (is_type_incomplete(points_to)) {
7508 if (!GNU_MODE || !is_type_void(points_to)) {
7509 errorf(source_position,
7510 "arithmetic with pointer to incomplete type '%T' not allowed",
7514 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7516 } else if (is_type_function(points_to)) {
7518 errorf(source_position,
7519 "arithmetic with pointer to function type '%T' not allowed",
7523 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7529 static bool is_lvalue(const expression_t *expression)
7531 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7532 switch (expression->kind) {
7533 case EXPR_ARRAY_ACCESS:
7534 case EXPR_COMPOUND_LITERAL:
7535 case EXPR_REFERENCE:
7537 case EXPR_UNARY_DEREFERENCE:
7541 type_t *type = skip_typeref(expression->base.type);
7543 /* ISO/IEC 14882:1998(E) §3.10:3 */
7544 is_type_reference(type) ||
7545 /* Claim it is an lvalue, if the type is invalid. There was a parse
7546 * error before, which maybe prevented properly recognizing it as
7548 !is_type_valid(type);
7553 static void semantic_incdec(unary_expression_t *expression)
7555 type_t *const orig_type = expression->value->base.type;
7556 type_t *const type = skip_typeref(orig_type);
7557 if (is_type_pointer(type)) {
7558 if (!check_pointer_arithmetic(&expression->base.source_position,
7562 } else if (!is_type_real(type) && is_type_valid(type)) {
7563 /* TODO: improve error message */
7564 errorf(&expression->base.source_position,
7565 "operation needs an arithmetic or pointer type");
7568 if (!is_lvalue(expression->value)) {
7569 /* TODO: improve error message */
7570 errorf(&expression->base.source_position, "lvalue required as operand");
7572 expression->base.type = orig_type;
7575 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7577 type_t *const res_type = promote_integer(type);
7578 expr->base.type = res_type;
7579 expr->value = create_implicit_cast(expr->value, res_type);
7582 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7584 type_t *const orig_type = expression->value->base.type;
7585 type_t *const type = skip_typeref(orig_type);
7586 if (!is_type_arithmetic(type)) {
7587 if (is_type_valid(type)) {
7588 /* TODO: improve error message */
7589 errorf(&expression->base.source_position,
7590 "operation needs an arithmetic type");
7593 } else if (is_type_integer(type)) {
7594 promote_unary_int_expr(expression, type);
7596 expression->base.type = orig_type;
7600 static void semantic_unexpr_plus(unary_expression_t *expression)
7602 semantic_unexpr_arithmetic(expression);
7603 source_position_t const *const pos = &expression->base.source_position;
7604 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7607 static void semantic_not(unary_expression_t *expression)
7609 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7610 semantic_condition(expression->value, "operand of !");
7611 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7614 static void semantic_unexpr_integer(unary_expression_t *expression)
7616 type_t *const orig_type = expression->value->base.type;
7617 type_t *const type = skip_typeref(orig_type);
7618 if (!is_type_integer(type)) {
7619 if (is_type_valid(type)) {
7620 errorf(&expression->base.source_position,
7621 "operand of ~ must be of integer type");
7626 promote_unary_int_expr(expression, type);
7629 static void semantic_dereference(unary_expression_t *expression)
7631 type_t *const orig_type = expression->value->base.type;
7632 type_t *const type = skip_typeref(orig_type);
7633 if (!is_type_pointer(type)) {
7634 if (is_type_valid(type)) {
7635 errorf(&expression->base.source_position,
7636 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7641 type_t *result_type = type->pointer.points_to;
7642 result_type = automatic_type_conversion(result_type);
7643 expression->base.type = result_type;
7647 * Record that an address is taken (expression represents an lvalue).
7649 * @param expression the expression
7650 * @param may_be_register if true, the expression might be an register
7652 static void set_address_taken(expression_t *expression, bool may_be_register)
7654 if (expression->kind != EXPR_REFERENCE)
7657 entity_t *const entity = expression->reference.entity;
7659 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7662 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7663 && !may_be_register) {
7664 source_position_t const *const pos = &expression->base.source_position;
7665 errorf(pos, "address of register '%N' requested", entity);
7668 if (entity->kind == ENTITY_VARIABLE) {
7669 entity->variable.address_taken = true;
7671 assert(entity->kind == ENTITY_PARAMETER);
7672 entity->parameter.address_taken = true;
7677 * Check the semantic of the address taken expression.
7679 static void semantic_take_addr(unary_expression_t *expression)
7681 expression_t *value = expression->value;
7682 value->base.type = revert_automatic_type_conversion(value);
7684 type_t *orig_type = value->base.type;
7685 type_t *type = skip_typeref(orig_type);
7686 if (!is_type_valid(type))
7690 if (!is_lvalue(value)) {
7691 errorf(&expression->base.source_position, "'&' requires an lvalue");
7693 if (is_bitfield(value)) {
7694 errorf(&expression->base.source_position,
7695 "'&' not allowed on bitfield");
7698 set_address_taken(value, false);
7700 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7703 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7704 static expression_t *parse_##unexpression_type(void) \
7706 expression_t *unary_expression \
7707 = allocate_expression_zero(unexpression_type); \
7709 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7711 sfunc(&unary_expression->unary); \
7713 return unary_expression; \
7716 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7717 semantic_unexpr_arithmetic)
7718 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7719 semantic_unexpr_plus)
7720 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7722 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7723 semantic_dereference)
7724 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7726 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7727 semantic_unexpr_integer)
7728 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7730 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7733 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7735 static expression_t *parse_##unexpression_type(expression_t *left) \
7737 expression_t *unary_expression \
7738 = allocate_expression_zero(unexpression_type); \
7740 unary_expression->unary.value = left; \
7742 sfunc(&unary_expression->unary); \
7744 return unary_expression; \
7747 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7748 EXPR_UNARY_POSTFIX_INCREMENT,
7750 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7751 EXPR_UNARY_POSTFIX_DECREMENT,
7754 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7756 /* TODO: handle complex + imaginary types */
7758 type_left = get_unqualified_type(type_left);
7759 type_right = get_unqualified_type(type_right);
7761 /* §6.3.1.8 Usual arithmetic conversions */
7762 if (type_left == type_long_double || type_right == type_long_double) {
7763 return type_long_double;
7764 } else if (type_left == type_double || type_right == type_double) {
7766 } else if (type_left == type_float || type_right == type_float) {
7770 type_left = promote_integer(type_left);
7771 type_right = promote_integer(type_right);
7773 if (type_left == type_right)
7776 bool const signed_left = is_type_signed(type_left);
7777 bool const signed_right = is_type_signed(type_right);
7778 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7779 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7781 if (signed_left == signed_right)
7782 return rank_left >= rank_right ? type_left : type_right;
7786 atomic_type_kind_t s_akind;
7787 atomic_type_kind_t u_akind;
7792 u_type = type_right;
7794 s_type = type_right;
7797 s_akind = get_akind(s_type);
7798 u_akind = get_akind(u_type);
7799 s_rank = get_akind_rank(s_akind);
7800 u_rank = get_akind_rank(u_akind);
7802 if (u_rank >= s_rank)
7805 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7809 case ATOMIC_TYPE_INT: return type_unsigned_int;
7810 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7811 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7813 default: panic("invalid atomic type");
7818 * Check the semantic restrictions for a binary expression.
7820 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7822 expression_t *const left = expression->left;
7823 expression_t *const right = expression->right;
7824 type_t *const orig_type_left = left->base.type;
7825 type_t *const orig_type_right = right->base.type;
7826 type_t *const type_left = skip_typeref(orig_type_left);
7827 type_t *const type_right = skip_typeref(orig_type_right);
7829 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7830 /* TODO: improve error message */
7831 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7832 errorf(&expression->base.source_position,
7833 "operation needs arithmetic types");
7838 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7839 expression->left = create_implicit_cast(left, arithmetic_type);
7840 expression->right = create_implicit_cast(right, arithmetic_type);
7841 expression->base.type = arithmetic_type;
7844 static void semantic_binexpr_integer(binary_expression_t *const expression)
7846 expression_t *const left = expression->left;
7847 expression_t *const right = expression->right;
7848 type_t *const orig_type_left = left->base.type;
7849 type_t *const orig_type_right = right->base.type;
7850 type_t *const type_left = skip_typeref(orig_type_left);
7851 type_t *const type_right = skip_typeref(orig_type_right);
7853 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7854 /* TODO: improve error message */
7855 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7856 errorf(&expression->base.source_position,
7857 "operation needs integer types");
7862 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7863 expression->left = create_implicit_cast(left, result_type);
7864 expression->right = create_implicit_cast(right, result_type);
7865 expression->base.type = result_type;
7868 static void warn_div_by_zero(binary_expression_t const *const expression)
7870 if (!is_type_integer(expression->base.type))
7873 expression_t const *const right = expression->right;
7874 /* The type of the right operand can be different for /= */
7875 if (is_type_integer(right->base.type) &&
7876 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7877 !fold_constant_to_bool(right)) {
7878 source_position_t const *const pos = &expression->base.source_position;
7879 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7884 * Check the semantic restrictions for a div/mod expression.
7886 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7888 semantic_binexpr_arithmetic(expression);
7889 warn_div_by_zero(expression);
7892 static void warn_addsub_in_shift(const expression_t *const expr)
7894 if (expr->base.parenthesized)
7898 switch (expr->kind) {
7899 case EXPR_BINARY_ADD: op = '+'; break;
7900 case EXPR_BINARY_SUB: op = '-'; break;
7904 source_position_t const *const pos = &expr->base.source_position;
7905 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7908 static bool semantic_shift(binary_expression_t *expression)
7910 expression_t *const left = expression->left;
7911 expression_t *const right = expression->right;
7912 type_t *const orig_type_left = left->base.type;
7913 type_t *const orig_type_right = right->base.type;
7914 type_t * type_left = skip_typeref(orig_type_left);
7915 type_t * type_right = skip_typeref(orig_type_right);
7917 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7918 /* TODO: improve error message */
7919 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7920 errorf(&expression->base.source_position,
7921 "operands of shift operation must have integer types");
7926 type_left = promote_integer(type_left);
7928 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7929 source_position_t const *const pos = &right->base.source_position;
7930 long const count = fold_constant_to_int(right);
7932 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7933 } else if ((unsigned long)count >=
7934 get_atomic_type_size(type_left->atomic.akind) * 8) {
7935 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7939 type_right = promote_integer(type_right);
7940 expression->right = create_implicit_cast(right, type_right);
7945 static void semantic_shift_op(binary_expression_t *expression)
7947 expression_t *const left = expression->left;
7948 expression_t *const right = expression->right;
7950 if (!semantic_shift(expression))
7953 warn_addsub_in_shift(left);
7954 warn_addsub_in_shift(right);
7956 type_t *const orig_type_left = left->base.type;
7957 type_t * type_left = skip_typeref(orig_type_left);
7959 type_left = promote_integer(type_left);
7960 expression->left = create_implicit_cast(left, type_left);
7961 expression->base.type = type_left;
7964 static void semantic_add(binary_expression_t *expression)
7966 expression_t *const left = expression->left;
7967 expression_t *const right = expression->right;
7968 type_t *const orig_type_left = left->base.type;
7969 type_t *const orig_type_right = right->base.type;
7970 type_t *const type_left = skip_typeref(orig_type_left);
7971 type_t *const type_right = skip_typeref(orig_type_right);
7974 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7975 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7976 expression->left = create_implicit_cast(left, arithmetic_type);
7977 expression->right = create_implicit_cast(right, arithmetic_type);
7978 expression->base.type = arithmetic_type;
7979 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7980 check_pointer_arithmetic(&expression->base.source_position,
7981 type_left, orig_type_left);
7982 expression->base.type = type_left;
7983 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7984 check_pointer_arithmetic(&expression->base.source_position,
7985 type_right, orig_type_right);
7986 expression->base.type = type_right;
7987 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7988 errorf(&expression->base.source_position,
7989 "invalid operands to binary + ('%T', '%T')",
7990 orig_type_left, orig_type_right);
7994 static void semantic_sub(binary_expression_t *expression)
7996 expression_t *const left = expression->left;
7997 expression_t *const right = expression->right;
7998 type_t *const orig_type_left = left->base.type;
7999 type_t *const orig_type_right = right->base.type;
8000 type_t *const type_left = skip_typeref(orig_type_left);
8001 type_t *const type_right = skip_typeref(orig_type_right);
8002 source_position_t const *const pos = &expression->base.source_position;
8005 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8006 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8007 expression->left = create_implicit_cast(left, arithmetic_type);
8008 expression->right = create_implicit_cast(right, arithmetic_type);
8009 expression->base.type = arithmetic_type;
8010 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8011 check_pointer_arithmetic(&expression->base.source_position,
8012 type_left, orig_type_left);
8013 expression->base.type = type_left;
8014 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8015 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8016 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8017 if (!types_compatible(unqual_left, unqual_right)) {
8019 "subtracting pointers to incompatible types '%T' and '%T'",
8020 orig_type_left, orig_type_right);
8021 } else if (!is_type_object(unqual_left)) {
8022 if (!is_type_void(unqual_left)) {
8023 errorf(pos, "subtracting pointers to non-object types '%T'",
8026 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8029 expression->base.type = type_ptrdiff_t;
8030 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8031 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8032 orig_type_left, orig_type_right);
8036 static void warn_string_literal_address(expression_t const* expr)
8038 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8039 expr = expr->unary.value;
8040 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8042 expr = expr->unary.value;
8045 if (expr->kind == EXPR_STRING_LITERAL
8046 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8047 source_position_t const *const pos = &expr->base.source_position;
8048 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8052 static bool maybe_negative(expression_t const *const expr)
8054 switch (is_constant_expression(expr)) {
8055 case EXPR_CLASS_ERROR: return false;
8056 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8057 default: return true;
8061 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8063 warn_string_literal_address(expr);
8065 expression_t const* const ref = get_reference_address(expr);
8066 if (ref != NULL && is_null_pointer_constant(other)) {
8067 entity_t const *const ent = ref->reference.entity;
8068 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8071 if (!expr->base.parenthesized) {
8072 switch (expr->base.kind) {
8073 case EXPR_BINARY_LESS:
8074 case EXPR_BINARY_GREATER:
8075 case EXPR_BINARY_LESSEQUAL:
8076 case EXPR_BINARY_GREATEREQUAL:
8077 case EXPR_BINARY_NOTEQUAL:
8078 case EXPR_BINARY_EQUAL:
8079 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8088 * Check the semantics of comparison expressions.
8090 * @param expression The expression to check.
8092 static void semantic_comparison(binary_expression_t *expression)
8094 source_position_t const *const pos = &expression->base.source_position;
8095 expression_t *const left = expression->left;
8096 expression_t *const right = expression->right;
8098 warn_comparison(pos, left, right);
8099 warn_comparison(pos, right, left);
8101 type_t *orig_type_left = left->base.type;
8102 type_t *orig_type_right = right->base.type;
8103 type_t *type_left = skip_typeref(orig_type_left);
8104 type_t *type_right = skip_typeref(orig_type_right);
8106 /* TODO non-arithmetic types */
8107 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8108 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8110 /* test for signed vs unsigned compares */
8111 if (is_type_integer(arithmetic_type)) {
8112 bool const signed_left = is_type_signed(type_left);
8113 bool const signed_right = is_type_signed(type_right);
8114 if (signed_left != signed_right) {
8115 /* FIXME long long needs better const folding magic */
8116 /* TODO check whether constant value can be represented by other type */
8117 if ((signed_left && maybe_negative(left)) ||
8118 (signed_right && maybe_negative(right))) {
8119 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8124 expression->left = create_implicit_cast(left, arithmetic_type);
8125 expression->right = create_implicit_cast(right, arithmetic_type);
8126 expression->base.type = arithmetic_type;
8127 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8128 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8129 is_type_float(arithmetic_type)) {
8130 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8132 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8133 /* TODO check compatibility */
8134 } else if (is_type_pointer(type_left)) {
8135 expression->right = create_implicit_cast(right, type_left);
8136 } else if (is_type_pointer(type_right)) {
8137 expression->left = create_implicit_cast(left, type_right);
8138 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8139 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8141 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8145 * Checks if a compound type has constant fields.
8147 static bool has_const_fields(const compound_type_t *type)
8149 compound_t *compound = type->compound;
8150 entity_t *entry = compound->members.entities;
8152 for (; entry != NULL; entry = entry->base.next) {
8153 if (!is_declaration(entry))
8156 const type_t *decl_type = skip_typeref(entry->declaration.type);
8157 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8164 static bool is_valid_assignment_lhs(expression_t const* const left)
8166 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8167 type_t *const type_left = skip_typeref(orig_type_left);
8169 if (!is_lvalue(left)) {
8170 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8175 if (left->kind == EXPR_REFERENCE
8176 && left->reference.entity->kind == ENTITY_FUNCTION) {
8177 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8181 if (is_type_array(type_left)) {
8182 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8185 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8186 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8190 if (is_type_incomplete(type_left)) {
8191 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8192 left, orig_type_left);
8195 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8196 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8197 left, orig_type_left);
8204 static void semantic_arithmetic_assign(binary_expression_t *expression)
8206 expression_t *left = expression->left;
8207 expression_t *right = expression->right;
8208 type_t *orig_type_left = left->base.type;
8209 type_t *orig_type_right = right->base.type;
8211 if (!is_valid_assignment_lhs(left))
8214 type_t *type_left = skip_typeref(orig_type_left);
8215 type_t *type_right = skip_typeref(orig_type_right);
8217 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8218 /* TODO: improve error message */
8219 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8220 errorf(&expression->base.source_position,
8221 "operation needs arithmetic types");
8226 /* combined instructions are tricky. We can't create an implicit cast on
8227 * the left side, because we need the uncasted form for the store.
8228 * The ast2firm pass has to know that left_type must be right_type
8229 * for the arithmetic operation and create a cast by itself */
8230 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8231 expression->right = create_implicit_cast(right, arithmetic_type);
8232 expression->base.type = type_left;
8235 static void semantic_divmod_assign(binary_expression_t *expression)
8237 semantic_arithmetic_assign(expression);
8238 warn_div_by_zero(expression);
8241 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8243 expression_t *const left = expression->left;
8244 expression_t *const right = expression->right;
8245 type_t *const orig_type_left = left->base.type;
8246 type_t *const orig_type_right = right->base.type;
8247 type_t *const type_left = skip_typeref(orig_type_left);
8248 type_t *const type_right = skip_typeref(orig_type_right);
8250 if (!is_valid_assignment_lhs(left))
8253 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8254 /* combined instructions are tricky. We can't create an implicit cast on
8255 * the left side, because we need the uncasted form for the store.
8256 * The ast2firm pass has to know that left_type must be right_type
8257 * for the arithmetic operation and create a cast by itself */
8258 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8259 expression->right = create_implicit_cast(right, arithmetic_type);
8260 expression->base.type = type_left;
8261 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8262 check_pointer_arithmetic(&expression->base.source_position,
8263 type_left, orig_type_left);
8264 expression->base.type = type_left;
8265 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8266 errorf(&expression->base.source_position,
8267 "incompatible types '%T' and '%T' in assignment",
8268 orig_type_left, orig_type_right);
8272 static void semantic_integer_assign(binary_expression_t *expression)
8274 expression_t *left = expression->left;
8275 expression_t *right = expression->right;
8276 type_t *orig_type_left = left->base.type;
8277 type_t *orig_type_right = right->base.type;
8279 if (!is_valid_assignment_lhs(left))
8282 type_t *type_left = skip_typeref(orig_type_left);
8283 type_t *type_right = skip_typeref(orig_type_right);
8285 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8286 /* TODO: improve error message */
8287 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8288 errorf(&expression->base.source_position,
8289 "operation needs integer types");
8294 /* combined instructions are tricky. We can't create an implicit cast on
8295 * the left side, because we need the uncasted form for the store.
8296 * The ast2firm pass has to know that left_type must be right_type
8297 * for the arithmetic operation and create a cast by itself */
8298 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8299 expression->right = create_implicit_cast(right, arithmetic_type);
8300 expression->base.type = type_left;
8303 static void semantic_shift_assign(binary_expression_t *expression)
8305 expression_t *left = expression->left;
8307 if (!is_valid_assignment_lhs(left))
8310 if (!semantic_shift(expression))
8313 expression->base.type = skip_typeref(left->base.type);
8316 static void warn_logical_and_within_or(const expression_t *const expr)
8318 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8320 if (expr->base.parenthesized)
8322 source_position_t const *const pos = &expr->base.source_position;
8323 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8327 * Check the semantic restrictions of a logical expression.
8329 static void semantic_logical_op(binary_expression_t *expression)
8331 /* §6.5.13:2 Each of the operands shall have scalar type.
8332 * §6.5.14:2 Each of the operands shall have scalar type. */
8333 semantic_condition(expression->left, "left operand of logical operator");
8334 semantic_condition(expression->right, "right operand of logical operator");
8335 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8336 warn_logical_and_within_or(expression->left);
8337 warn_logical_and_within_or(expression->right);
8339 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8343 * Check the semantic restrictions of a binary assign expression.
8345 static void semantic_binexpr_assign(binary_expression_t *expression)
8347 expression_t *left = expression->left;
8348 type_t *orig_type_left = left->base.type;
8350 if (!is_valid_assignment_lhs(left))
8353 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8354 report_assign_error(error, orig_type_left, expression->right,
8355 "assignment", &left->base.source_position);
8356 expression->right = create_implicit_cast(expression->right, orig_type_left);
8357 expression->base.type = orig_type_left;
8361 * Determine if the outermost operation (or parts thereof) of the given
8362 * expression has no effect in order to generate a warning about this fact.
8363 * Therefore in some cases this only examines some of the operands of the
8364 * expression (see comments in the function and examples below).
8366 * f() + 23; // warning, because + has no effect
8367 * x || f(); // no warning, because x controls execution of f()
8368 * x ? y : f(); // warning, because y has no effect
8369 * (void)x; // no warning to be able to suppress the warning
8370 * This function can NOT be used for an "expression has definitely no effect"-
8372 static bool expression_has_effect(const expression_t *const expr)
8374 switch (expr->kind) {
8375 case EXPR_ERROR: return true; /* do NOT warn */
8376 case EXPR_REFERENCE: return false;
8377 case EXPR_ENUM_CONSTANT: return false;
8378 case EXPR_LABEL_ADDRESS: return false;
8380 /* suppress the warning for microsoft __noop operations */
8381 case EXPR_LITERAL_MS_NOOP: return true;
8382 case EXPR_LITERAL_BOOLEAN:
8383 case EXPR_LITERAL_CHARACTER:
8384 case EXPR_LITERAL_WIDE_CHARACTER:
8385 case EXPR_LITERAL_INTEGER:
8386 case EXPR_LITERAL_FLOATINGPOINT:
8387 case EXPR_STRING_LITERAL: return false;
8388 case EXPR_WIDE_STRING_LITERAL: return false;
8391 const call_expression_t *const call = &expr->call;
8392 if (call->function->kind != EXPR_REFERENCE)
8395 switch (call->function->reference.entity->function.btk) {
8396 /* FIXME: which builtins have no effect? */
8397 default: return true;
8401 /* Generate the warning if either the left or right hand side of a
8402 * conditional expression has no effect */
8403 case EXPR_CONDITIONAL: {
8404 conditional_expression_t const *const cond = &expr->conditional;
8405 expression_t const *const t = cond->true_expression;
8407 (t == NULL || expression_has_effect(t)) &&
8408 expression_has_effect(cond->false_expression);
8411 case EXPR_SELECT: return false;
8412 case EXPR_ARRAY_ACCESS: return false;
8413 case EXPR_SIZEOF: return false;
8414 case EXPR_CLASSIFY_TYPE: return false;
8415 case EXPR_ALIGNOF: return false;
8417 case EXPR_FUNCNAME: return false;
8418 case EXPR_BUILTIN_CONSTANT_P: return false;
8419 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8420 case EXPR_OFFSETOF: return false;
8421 case EXPR_VA_START: return true;
8422 case EXPR_VA_ARG: return true;
8423 case EXPR_VA_COPY: return true;
8424 case EXPR_STATEMENT: return true; // TODO
8425 case EXPR_COMPOUND_LITERAL: return false;
8427 case EXPR_UNARY_NEGATE: return false;
8428 case EXPR_UNARY_PLUS: return false;
8429 case EXPR_UNARY_BITWISE_NEGATE: return false;
8430 case EXPR_UNARY_NOT: return false;
8431 case EXPR_UNARY_DEREFERENCE: return false;
8432 case EXPR_UNARY_TAKE_ADDRESS: return false;
8433 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8434 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8435 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8436 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8438 /* Treat void casts as if they have an effect in order to being able to
8439 * suppress the warning */
8440 case EXPR_UNARY_CAST: {
8441 type_t *const type = skip_typeref(expr->base.type);
8442 return is_type_void(type);
8445 case EXPR_UNARY_ASSUME: return true;
8446 case EXPR_UNARY_DELETE: return true;
8447 case EXPR_UNARY_DELETE_ARRAY: return true;
8448 case EXPR_UNARY_THROW: return true;
8450 case EXPR_BINARY_ADD: return false;
8451 case EXPR_BINARY_SUB: return false;
8452 case EXPR_BINARY_MUL: return false;
8453 case EXPR_BINARY_DIV: return false;
8454 case EXPR_BINARY_MOD: return false;
8455 case EXPR_BINARY_EQUAL: return false;
8456 case EXPR_BINARY_NOTEQUAL: return false;
8457 case EXPR_BINARY_LESS: return false;
8458 case EXPR_BINARY_LESSEQUAL: return false;
8459 case EXPR_BINARY_GREATER: return false;
8460 case EXPR_BINARY_GREATEREQUAL: return false;
8461 case EXPR_BINARY_BITWISE_AND: return false;
8462 case EXPR_BINARY_BITWISE_OR: return false;
8463 case EXPR_BINARY_BITWISE_XOR: return false;
8464 case EXPR_BINARY_SHIFTLEFT: return false;
8465 case EXPR_BINARY_SHIFTRIGHT: return false;
8466 case EXPR_BINARY_ASSIGN: return true;
8467 case EXPR_BINARY_MUL_ASSIGN: return true;
8468 case EXPR_BINARY_DIV_ASSIGN: return true;
8469 case EXPR_BINARY_MOD_ASSIGN: return true;
8470 case EXPR_BINARY_ADD_ASSIGN: return true;
8471 case EXPR_BINARY_SUB_ASSIGN: return true;
8472 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8473 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8474 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8475 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8476 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8478 /* Only examine the right hand side of && and ||, because the left hand
8479 * side already has the effect of controlling the execution of the right
8481 case EXPR_BINARY_LOGICAL_AND:
8482 case EXPR_BINARY_LOGICAL_OR:
8483 /* Only examine the right hand side of a comma expression, because the left
8484 * hand side has a separate warning */
8485 case EXPR_BINARY_COMMA:
8486 return expression_has_effect(expr->binary.right);
8488 case EXPR_BINARY_ISGREATER: return false;
8489 case EXPR_BINARY_ISGREATEREQUAL: return false;
8490 case EXPR_BINARY_ISLESS: return false;
8491 case EXPR_BINARY_ISLESSEQUAL: return false;
8492 case EXPR_BINARY_ISLESSGREATER: return false;
8493 case EXPR_BINARY_ISUNORDERED: return false;
8496 internal_errorf(HERE, "unexpected expression");
8499 static void semantic_comma(binary_expression_t *expression)
8501 const expression_t *const left = expression->left;
8502 if (!expression_has_effect(left)) {
8503 source_position_t const *const pos = &left->base.source_position;
8504 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8506 expression->base.type = expression->right->base.type;
8510 * @param prec_r precedence of the right operand
8512 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8513 static expression_t *parse_##binexpression_type(expression_t *left) \
8515 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8516 binexpr->binary.left = left; \
8519 expression_t *right = parse_subexpression(prec_r); \
8521 binexpr->binary.right = right; \
8522 sfunc(&binexpr->binary); \
8527 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8528 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8529 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8530 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8531 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8532 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8533 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8534 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8535 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8536 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8537 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8538 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8539 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8540 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8541 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8542 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8543 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8544 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8545 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8546 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8547 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8548 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8549 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8550 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8551 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8552 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8553 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8554 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8555 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8556 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8559 static expression_t *parse_subexpression(precedence_t precedence)
8561 expression_parser_function_t *parser
8562 = &expression_parsers[token.kind];
8565 if (parser->parser != NULL) {
8566 left = parser->parser();
8568 left = parse_primary_expression();
8570 assert(left != NULL);
8573 parser = &expression_parsers[token.kind];
8574 if (parser->infix_parser == NULL)
8576 if (parser->infix_precedence < precedence)
8579 left = parser->infix_parser(left);
8581 assert(left != NULL);
8588 * Parse an expression.
8590 static expression_t *parse_expression(void)
8592 return parse_subexpression(PREC_EXPRESSION);
8596 * Register a parser for a prefix-like operator.
8598 * @param parser the parser function
8599 * @param token_kind the token type of the prefix token
8601 static void register_expression_parser(parse_expression_function parser,
8604 expression_parser_function_t *entry = &expression_parsers[token_kind];
8606 if (entry->parser != NULL) {
8607 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8608 panic("trying to register multiple expression parsers for a token");
8610 entry->parser = parser;
8614 * Register a parser for an infix operator with given precedence.
8616 * @param parser the parser function
8617 * @param token_kind the token type of the infix operator
8618 * @param precedence the precedence of the operator
8620 static void register_infix_parser(parse_expression_infix_function parser,
8621 int token_kind, precedence_t precedence)
8623 expression_parser_function_t *entry = &expression_parsers[token_kind];
8625 if (entry->infix_parser != NULL) {
8626 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8627 panic("trying to register multiple infix expression parsers for a "
8630 entry->infix_parser = parser;
8631 entry->infix_precedence = precedence;
8635 * Initialize the expression parsers.
8637 static void init_expression_parsers(void)
8639 memset(&expression_parsers, 0, sizeof(expression_parsers));
8641 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8642 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8643 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8644 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8645 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8646 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8647 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8648 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8649 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8650 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8651 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8652 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8653 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8654 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8655 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8656 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8657 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8658 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8659 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8660 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8661 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8662 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8663 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8664 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8665 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8666 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8667 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8668 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8669 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8670 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8671 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8672 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8673 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8674 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8675 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8676 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8677 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8679 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8680 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8681 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8682 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8683 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8684 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8685 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8686 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8687 register_expression_parser(parse_sizeof, T_sizeof);
8688 register_expression_parser(parse_alignof, T___alignof__);
8689 register_expression_parser(parse_extension, T___extension__);
8690 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8691 register_expression_parser(parse_delete, T_delete);
8692 register_expression_parser(parse_throw, T_throw);
8696 * Parse a asm statement arguments specification.
8698 static asm_argument_t *parse_asm_arguments(bool is_out)
8700 asm_argument_t *result = NULL;
8701 asm_argument_t **anchor = &result;
8703 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8704 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8707 add_anchor_token(']');
8708 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8709 rem_anchor_token(']');
8711 if (!argument->symbol)
8715 argument->constraints = parse_string_literals();
8717 add_anchor_token(')');
8718 expression_t *expression = parse_expression();
8719 rem_anchor_token(')');
8721 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8722 * change size or type representation (e.g. int -> long is ok, but
8723 * int -> float is not) */
8724 if (expression->kind == EXPR_UNARY_CAST) {
8725 type_t *const type = expression->base.type;
8726 type_kind_t const kind = type->kind;
8727 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8730 if (kind == TYPE_ATOMIC) {
8731 atomic_type_kind_t const akind = type->atomic.akind;
8732 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8733 size = get_atomic_type_size(akind);
8735 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8736 size = get_type_size(type_void_ptr);
8740 expression_t *const value = expression->unary.value;
8741 type_t *const value_type = value->base.type;
8742 type_kind_t const value_kind = value_type->kind;
8744 unsigned value_flags;
8745 unsigned value_size;
8746 if (value_kind == TYPE_ATOMIC) {
8747 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8748 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8749 value_size = get_atomic_type_size(value_akind);
8750 } else if (value_kind == TYPE_POINTER) {
8751 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8752 value_size = get_type_size(type_void_ptr);
8757 if (value_flags != flags || value_size != size)
8761 } while (expression->kind == EXPR_UNARY_CAST);
8765 if (!is_lvalue(expression)) {
8766 errorf(&expression->base.source_position,
8767 "asm output argument is not an lvalue");
8770 if (argument->constraints.begin[0] == '=')
8771 determine_lhs_ent(expression, NULL);
8773 mark_vars_read(expression, NULL);
8775 mark_vars_read(expression, NULL);
8777 argument->expression = expression;
8780 set_address_taken(expression, true);
8783 anchor = &argument->next;
8793 * Parse a asm statement clobber specification.
8795 static asm_clobber_t *parse_asm_clobbers(void)
8797 asm_clobber_t *result = NULL;
8798 asm_clobber_t **anchor = &result;
8800 while (token.kind == T_STRING_LITERAL) {
8801 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8802 clobber->clobber = parse_string_literals();
8805 anchor = &clobber->next;
8815 * Parse an asm statement.
8817 static statement_t *parse_asm_statement(void)
8819 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8820 asm_statement_t *asm_statement = &statement->asms;
8824 if (next_if(T_volatile))
8825 asm_statement->is_volatile = true;
8828 add_anchor_token(')');
8829 if (token.kind != T_STRING_LITERAL) {
8830 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8833 asm_statement->asm_text = parse_string_literals();
8835 add_anchor_token(':');
8836 if (!next_if(':')) {
8837 rem_anchor_token(':');
8841 asm_statement->outputs = parse_asm_arguments(true);
8842 if (!next_if(':')) {
8843 rem_anchor_token(':');
8847 asm_statement->inputs = parse_asm_arguments(false);
8848 if (!next_if(':')) {
8849 rem_anchor_token(':');
8852 rem_anchor_token(':');
8854 asm_statement->clobbers = parse_asm_clobbers();
8857 rem_anchor_token(')');
8861 if (asm_statement->outputs == NULL) {
8862 /* GCC: An 'asm' instruction without any output operands will be treated
8863 * identically to a volatile 'asm' instruction. */
8864 asm_statement->is_volatile = true;
8870 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8872 statement_t *inner_stmt;
8873 switch (token.kind) {
8875 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8876 inner_stmt = create_error_statement();
8880 if (label->kind == STATEMENT_LABEL) {
8881 /* Eat an empty statement here, to avoid the warning about an empty
8882 * statement after a label. label:; is commonly used to have a label
8883 * before a closing brace. */
8884 inner_stmt = create_empty_statement();
8891 inner_stmt = parse_statement();
8892 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8893 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8894 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8895 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8903 * Parse a case statement.
8905 static statement_t *parse_case_statement(void)
8907 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8908 source_position_t *const pos = &statement->base.source_position;
8911 add_anchor_token(':');
8913 expression_t *expression = parse_expression();
8914 type_t *expression_type = expression->base.type;
8915 type_t *skipped = skip_typeref(expression_type);
8916 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8917 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8918 expression, expression_type);
8921 type_t *type = expression_type;
8922 if (current_switch != NULL) {
8923 type_t *switch_type = current_switch->expression->base.type;
8924 if (is_type_valid(switch_type)) {
8925 expression = create_implicit_cast(expression, switch_type);
8929 statement->case_label.expression = expression;
8930 expression_classification_t const expr_class = is_constant_expression(expression);
8931 if (expr_class != EXPR_CLASS_CONSTANT) {
8932 if (expr_class != EXPR_CLASS_ERROR) {
8933 errorf(pos, "case label does not reduce to an integer constant");
8935 statement->case_label.is_bad = true;
8937 long const val = fold_constant_to_int(expression);
8938 statement->case_label.first_case = val;
8939 statement->case_label.last_case = val;
8943 if (next_if(T_DOTDOTDOT)) {
8944 expression_t *end_range = parse_expression();
8945 expression_type = expression->base.type;
8946 skipped = skip_typeref(expression_type);
8947 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8948 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8949 expression, expression_type);
8952 end_range = create_implicit_cast(end_range, type);
8953 statement->case_label.end_range = end_range;
8954 expression_classification_t const end_class = is_constant_expression(end_range);
8955 if (end_class != EXPR_CLASS_CONSTANT) {
8956 if (end_class != EXPR_CLASS_ERROR) {
8957 errorf(pos, "case range does not reduce to an integer constant");
8959 statement->case_label.is_bad = true;
8961 long const val = fold_constant_to_int(end_range);
8962 statement->case_label.last_case = val;
8964 if (val < statement->case_label.first_case) {
8965 statement->case_label.is_empty_range = true;
8966 warningf(WARN_OTHER, pos, "empty range specified");
8972 PUSH_PARENT(statement);
8974 rem_anchor_token(':');
8977 if (current_switch != NULL) {
8978 if (! statement->case_label.is_bad) {
8979 /* Check for duplicate case values */
8980 case_label_statement_t *c = &statement->case_label;
8981 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8982 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8985 if (c->last_case < l->first_case || c->first_case > l->last_case)
8988 errorf(pos, "duplicate case value (previously used %P)",
8989 &l->base.source_position);
8993 /* link all cases into the switch statement */
8994 if (current_switch->last_case == NULL) {
8995 current_switch->first_case = &statement->case_label;
8997 current_switch->last_case->next = &statement->case_label;
8999 current_switch->last_case = &statement->case_label;
9001 errorf(pos, "case label not within a switch statement");
9004 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9011 * Parse a default statement.
9013 static statement_t *parse_default_statement(void)
9015 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9019 PUSH_PARENT(statement);
9023 if (current_switch != NULL) {
9024 const case_label_statement_t *def_label = current_switch->default_label;
9025 if (def_label != NULL) {
9026 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9028 current_switch->default_label = &statement->case_label;
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;
9039 errorf(&statement->base.source_position,
9040 "'default' label not within a switch statement");
9043 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9050 * Parse a label statement.
9052 static statement_t *parse_label_statement(void)
9054 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9055 label_t *const label = get_label();
9056 statement->label.label = label;
9058 PUSH_PARENT(statement);
9060 /* if statement is already set then the label is defined twice,
9061 * otherwise it was just mentioned in a goto/local label declaration so far
9063 source_position_t const* const pos = &statement->base.source_position;
9064 if (label->statement != NULL) {
9065 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9067 label->base.source_position = *pos;
9068 label->statement = statement;
9073 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9074 parse_attributes(NULL); // TODO process attributes
9077 statement->label.statement = parse_label_inner_statement(statement, "label");
9079 /* remember the labels in a list for later checking */
9080 *label_anchor = &statement->label;
9081 label_anchor = &statement->label.next;
9087 static statement_t *parse_inner_statement(void)
9089 statement_t *const stmt = parse_statement();
9090 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9091 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9092 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9093 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9099 * Parse an expression in parentheses and mark its variables as read.
9101 static expression_t *parse_condition(void)
9104 add_anchor_token(')');
9105 expression_t *const expr = parse_expression();
9106 mark_vars_read(expr, NULL);
9107 rem_anchor_token(')');
9113 * Parse an if statement.
9115 static statement_t *parse_if(void)
9117 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9121 PUSH_PARENT(statement);
9122 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9124 add_anchor_token(T_else);
9126 expression_t *const expr = parse_condition();
9127 statement->ifs.condition = expr;
9128 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9130 semantic_condition(expr, "condition of 'if'-statment");
9132 statement_t *const true_stmt = parse_inner_statement();
9133 statement->ifs.true_statement = true_stmt;
9134 rem_anchor_token(T_else);
9136 if (true_stmt->kind == STATEMENT_EMPTY) {
9137 warningf(WARN_EMPTY_BODY, HERE,
9138 "suggest braces around empty body in an ‘if’ statement");
9141 if (next_if(T_else)) {
9142 statement->ifs.false_statement = parse_inner_statement();
9144 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9145 warningf(WARN_EMPTY_BODY, HERE,
9146 "suggest braces around empty body in an ‘if’ statement");
9148 } else if (true_stmt->kind == STATEMENT_IF &&
9149 true_stmt->ifs.false_statement != NULL) {
9150 source_position_t const *const pos = &true_stmt->base.source_position;
9151 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9160 * Check that all enums are handled in a switch.
9162 * @param statement the switch statement to check
9164 static void check_enum_cases(const switch_statement_t *statement)
9166 if (!is_warn_on(WARN_SWITCH_ENUM))
9168 const type_t *type = skip_typeref(statement->expression->base.type);
9169 if (! is_type_enum(type))
9171 const enum_type_t *enumt = &type->enumt;
9173 /* if we have a default, no warnings */
9174 if (statement->default_label != NULL)
9177 /* FIXME: calculation of value should be done while parsing */
9178 /* TODO: quadratic algorithm here. Change to an n log n one */
9179 long last_value = -1;
9180 const entity_t *entry = enumt->enume->base.next;
9181 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9182 entry = entry->base.next) {
9183 const expression_t *expression = entry->enum_value.value;
9184 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9186 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9187 if (l->expression == NULL)
9189 if (l->first_case <= value && value <= l->last_case) {
9195 source_position_t const *const pos = &statement->base.source_position;
9196 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9203 * Parse a switch statement.
9205 static statement_t *parse_switch(void)
9207 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9211 PUSH_PARENT(statement);
9212 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9214 expression_t *const expr = parse_condition();
9215 type_t * type = skip_typeref(expr->base.type);
9216 if (is_type_integer(type)) {
9217 type = promote_integer(type);
9218 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9219 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9221 } else if (is_type_valid(type)) {
9222 errorf(&expr->base.source_position,
9223 "switch quantity is not an integer, but '%T'", type);
9224 type = type_error_type;
9226 statement->switchs.expression = create_implicit_cast(expr, type);
9228 switch_statement_t *rem = current_switch;
9229 current_switch = &statement->switchs;
9230 statement->switchs.body = parse_inner_statement();
9231 current_switch = rem;
9233 if (statement->switchs.default_label == NULL) {
9234 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9236 check_enum_cases(&statement->switchs);
9243 static statement_t *parse_loop_body(statement_t *const loop)
9245 statement_t *const rem = current_loop;
9246 current_loop = loop;
9248 statement_t *const body = parse_inner_statement();
9255 * Parse a while statement.
9257 static statement_t *parse_while(void)
9259 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9263 PUSH_PARENT(statement);
9264 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9266 expression_t *const cond = parse_condition();
9267 statement->whiles.condition = cond;
9268 /* §6.8.5:2 The controlling expression of an iteration statement shall
9269 * have scalar type. */
9270 semantic_condition(cond, "condition of 'while'-statement");
9272 statement->whiles.body = parse_loop_body(statement);
9280 * Parse a do statement.
9282 static statement_t *parse_do(void)
9284 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9288 PUSH_PARENT(statement);
9289 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9291 add_anchor_token(T_while);
9292 statement->do_while.body = parse_loop_body(statement);
9293 rem_anchor_token(T_while);
9296 expression_t *const cond = parse_condition();
9297 statement->do_while.condition = cond;
9298 /* §6.8.5:2 The controlling expression of an iteration statement shall
9299 * have scalar type. */
9300 semantic_condition(cond, "condition of 'do-while'-statement");
9309 * Parse a for statement.
9311 static statement_t *parse_for(void)
9313 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9317 PUSH_PARENT(statement);
9318 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9321 add_anchor_token(')');
9326 } else if (is_declaration_specifier(&token)) {
9327 parse_declaration(record_entity, DECL_FLAGS_NONE);
9329 add_anchor_token(';');
9330 expression_t *const init = parse_expression();
9331 statement->fors.initialisation = init;
9332 mark_vars_read(init, ENT_ANY);
9333 if (!expression_has_effect(init)) {
9334 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9336 rem_anchor_token(';');
9342 if (token.kind != ';') {
9343 add_anchor_token(';');
9344 expression_t *const cond = parse_expression();
9345 statement->fors.condition = cond;
9346 /* §6.8.5:2 The controlling expression of an iteration statement
9347 * shall have scalar type. */
9348 semantic_condition(cond, "condition of 'for'-statement");
9349 mark_vars_read(cond, NULL);
9350 rem_anchor_token(';');
9353 if (token.kind != ')') {
9354 expression_t *const step = parse_expression();
9355 statement->fors.step = step;
9356 mark_vars_read(step, ENT_ANY);
9357 if (!expression_has_effect(step)) {
9358 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9361 rem_anchor_token(')');
9363 statement->fors.body = parse_loop_body(statement);
9371 * Parse a goto statement.
9373 static statement_t *parse_goto(void)
9375 statement_t *statement;
9376 if (GNU_MODE && look_ahead(1)->kind == '*') {
9377 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9381 expression_t *expression = parse_expression();
9382 mark_vars_read(expression, NULL);
9384 /* Argh: although documentation says the expression must be of type void*,
9385 * gcc accepts anything that can be casted into void* without error */
9386 type_t *type = expression->base.type;
9388 if (type != type_error_type) {
9389 if (!is_type_pointer(type) && !is_type_integer(type)) {
9390 errorf(&expression->base.source_position,
9391 "cannot convert to a pointer type");
9392 } else if (type != type_void_ptr) {
9393 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9395 expression = create_implicit_cast(expression, type_void_ptr);
9398 statement->computed_goto.expression = expression;
9400 statement = allocate_statement_zero(STATEMENT_GOTO);
9402 if (token.kind == T_IDENTIFIER) {
9403 label_t *const label = get_label();
9405 statement->gotos.label = label;
9407 /* remember the goto's in a list for later checking */
9408 *goto_anchor = &statement->gotos;
9409 goto_anchor = &statement->gotos.next;
9412 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9414 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9416 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9425 * Parse a continue statement.
9427 static statement_t *parse_continue(void)
9429 if (current_loop == NULL) {
9430 errorf(HERE, "continue statement not within loop");
9433 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9441 * Parse a break statement.
9443 static statement_t *parse_break(void)
9445 if (current_switch == NULL && current_loop == NULL) {
9446 errorf(HERE, "break statement not within loop or switch");
9449 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9457 * Parse a __leave statement.
9459 static statement_t *parse_leave_statement(void)
9461 if (current_try == NULL) {
9462 errorf(HERE, "__leave statement not within __try");
9465 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9473 * Check if a given entity represents a local variable.
9475 static bool is_local_variable(const entity_t *entity)
9477 if (entity->kind != ENTITY_VARIABLE)
9480 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9481 case STORAGE_CLASS_AUTO:
9482 case STORAGE_CLASS_REGISTER: {
9483 const type_t *type = skip_typeref(entity->declaration.type);
9484 if (is_type_function(type)) {
9496 * Check if a given expression represents a local variable.
9498 static bool expression_is_local_variable(const expression_t *expression)
9500 if (expression->base.kind != EXPR_REFERENCE) {
9503 const entity_t *entity = expression->reference.entity;
9504 return is_local_variable(entity);
9508 * Check if a given expression represents a local variable and
9509 * return its declaration then, else return NULL.
9511 entity_t *expression_is_variable(const expression_t *expression)
9513 if (expression->base.kind != EXPR_REFERENCE) {
9516 entity_t *entity = expression->reference.entity;
9517 if (entity->kind != ENTITY_VARIABLE)
9523 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9525 if (c_mode & _CXX || strict_mode) {
9528 warningf(WARN_OTHER, pos, msg);
9533 * Parse a return statement.
9535 static statement_t *parse_return(void)
9537 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9540 expression_t *return_value = NULL;
9541 if (token.kind != ';') {
9542 return_value = parse_expression();
9543 mark_vars_read(return_value, NULL);
9546 const type_t *const func_type = skip_typeref(current_function->base.type);
9547 assert(is_type_function(func_type));
9548 type_t *const return_type = skip_typeref(func_type->function.return_type);
9550 source_position_t const *const pos = &statement->base.source_position;
9551 if (return_value != NULL) {
9552 type_t *return_value_type = skip_typeref(return_value->base.type);
9554 if (is_type_void(return_type)) {
9555 if (!is_type_void(return_value_type)) {
9556 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9557 /* Only warn in C mode, because GCC does the same */
9558 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9559 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9560 /* Only warn in C mode, because GCC does the same */
9561 err_or_warn(pos, "'return' with expression in function returning 'void'");
9564 assign_error_t error = semantic_assign(return_type, return_value);
9565 report_assign_error(error, return_type, return_value, "'return'",
9568 return_value = create_implicit_cast(return_value, return_type);
9569 /* check for returning address of a local var */
9570 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9571 const expression_t *expression = return_value->unary.value;
9572 if (expression_is_local_variable(expression)) {
9573 warningf(WARN_OTHER, pos, "function returns address of local variable");
9576 } else if (!is_type_void(return_type)) {
9577 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9578 err_or_warn(pos, "'return' without value, in function returning non-void");
9580 statement->returns.value = return_value;
9587 * Parse a declaration statement.
9589 static statement_t *parse_declaration_statement(void)
9591 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9593 entity_t *before = current_scope->last_entity;
9595 parse_external_declaration();
9597 parse_declaration(record_entity, DECL_FLAGS_NONE);
9600 declaration_statement_t *const decl = &statement->declaration;
9601 entity_t *const begin =
9602 before != NULL ? before->base.next : current_scope->entities;
9603 decl->declarations_begin = begin;
9604 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9610 * Parse an expression statement, ie. expr ';'.
9612 static statement_t *parse_expression_statement(void)
9614 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9616 expression_t *const expr = parse_expression();
9617 statement->expression.expression = expr;
9618 mark_vars_read(expr, ENT_ANY);
9625 * Parse a microsoft __try { } __finally { } or
9626 * __try{ } __except() { }
9628 static statement_t *parse_ms_try_statment(void)
9630 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9633 PUSH_PARENT(statement);
9635 ms_try_statement_t *rem = current_try;
9636 current_try = &statement->ms_try;
9637 statement->ms_try.try_statement = parse_compound_statement(false);
9642 if (next_if(T___except)) {
9643 expression_t *const expr = parse_condition();
9644 type_t * type = skip_typeref(expr->base.type);
9645 if (is_type_integer(type)) {
9646 type = promote_integer(type);
9647 } else if (is_type_valid(type)) {
9648 errorf(&expr->base.source_position,
9649 "__expect expression is not an integer, but '%T'", type);
9650 type = type_error_type;
9652 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9653 } else if (!next_if(T__finally)) {
9654 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9656 statement->ms_try.final_statement = parse_compound_statement(false);
9660 static statement_t *parse_empty_statement(void)
9662 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9663 statement_t *const statement = create_empty_statement();
9668 static statement_t *parse_local_label_declaration(void)
9670 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9674 entity_t *begin = NULL;
9675 entity_t *end = NULL;
9676 entity_t **anchor = &begin;
9678 source_position_t pos;
9679 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9683 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9684 if (entity != NULL && entity->base.parent_scope == current_scope) {
9685 source_position_t const *const ppos = &entity->base.source_position;
9686 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9688 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9689 entity->base.parent_scope = current_scope;
9692 anchor = &entity->base.next;
9695 environment_push(entity);
9697 } while (next_if(','));
9700 statement->declaration.declarations_begin = begin;
9701 statement->declaration.declarations_end = end;
9705 static void parse_namespace_definition(void)
9709 entity_t *entity = NULL;
9710 symbol_t *symbol = NULL;
9712 if (token.kind == T_IDENTIFIER) {
9713 symbol = token.base.symbol;
9716 entity = get_entity(symbol, NAMESPACE_NORMAL);
9718 && entity->kind != ENTITY_NAMESPACE
9719 && entity->base.parent_scope == current_scope) {
9720 if (is_entity_valid(entity)) {
9721 error_redefined_as_different_kind(&token.base.source_position,
9722 entity, ENTITY_NAMESPACE);
9728 if (entity == NULL) {
9729 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9730 entity->base.parent_scope = current_scope;
9733 if (token.kind == '=') {
9734 /* TODO: parse namespace alias */
9735 panic("namespace alias definition not supported yet");
9738 environment_push(entity);
9739 append_entity(current_scope, entity);
9741 PUSH_SCOPE(&entity->namespacee.members);
9742 PUSH_CURRENT_ENTITY(entity);
9744 add_anchor_token('}');
9747 rem_anchor_token('}');
9750 POP_CURRENT_ENTITY();
9755 * Parse a statement.
9756 * There's also parse_statement() which additionally checks for
9757 * "statement has no effect" warnings
9759 static statement_t *intern_parse_statement(void)
9761 /* declaration or statement */
9762 statement_t *statement;
9763 switch (token.kind) {
9764 case T_IDENTIFIER: {
9765 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9766 if (la1_type == ':') {
9767 statement = parse_label_statement();
9768 } else if (is_typedef_symbol(token.base.symbol)) {
9769 statement = parse_declaration_statement();
9771 /* it's an identifier, the grammar says this must be an
9772 * expression statement. However it is common that users mistype
9773 * declaration types, so we guess a bit here to improve robustness
9774 * for incorrect programs */
9778 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9780 statement = parse_expression_statement();
9784 statement = parse_declaration_statement();
9792 case T___extension__: {
9793 /* This can be a prefix to a declaration or an expression statement.
9794 * We simply eat it now and parse the rest with tail recursion. */
9796 statement = intern_parse_statement();
9802 statement = parse_declaration_statement();
9806 statement = parse_local_label_declaration();
9809 case ';': statement = parse_empty_statement(); break;
9810 case '{': statement = parse_compound_statement(false); break;
9811 case T___leave: statement = parse_leave_statement(); break;
9812 case T___try: statement = parse_ms_try_statment(); break;
9813 case T_asm: statement = parse_asm_statement(); break;
9814 case T_break: statement = parse_break(); break;
9815 case T_case: statement = parse_case_statement(); break;
9816 case T_continue: statement = parse_continue(); break;
9817 case T_default: statement = parse_default_statement(); break;
9818 case T_do: statement = parse_do(); break;
9819 case T_for: statement = parse_for(); break;
9820 case T_goto: statement = parse_goto(); break;
9821 case T_if: statement = parse_if(); break;
9822 case T_return: statement = parse_return(); break;
9823 case T_switch: statement = parse_switch(); break;
9824 case T_while: statement = parse_while(); break;
9827 statement = parse_expression_statement();
9831 errorf(HERE, "unexpected token %K while parsing statement", &token);
9832 statement = create_error_statement();
9841 * parse a statement and emits "statement has no effect" warning if needed
9842 * (This is really a wrapper around intern_parse_statement with check for 1
9843 * single warning. It is needed, because for statement expressions we have
9844 * to avoid the warning on the last statement)
9846 static statement_t *parse_statement(void)
9848 statement_t *statement = intern_parse_statement();
9850 if (statement->kind == STATEMENT_EXPRESSION) {
9851 expression_t *expression = statement->expression.expression;
9852 if (!expression_has_effect(expression)) {
9853 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9861 * Parse a compound statement.
9863 static statement_t *parse_compound_statement(bool inside_expression_statement)
9865 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9867 PUSH_PARENT(statement);
9868 PUSH_SCOPE(&statement->compound.scope);
9871 add_anchor_token('}');
9872 /* tokens, which can start a statement */
9873 /* TODO MS, __builtin_FOO */
9874 add_anchor_token('!');
9875 add_anchor_token('&');
9876 add_anchor_token('(');
9877 add_anchor_token('*');
9878 add_anchor_token('+');
9879 add_anchor_token('-');
9880 add_anchor_token(';');
9881 add_anchor_token('{');
9882 add_anchor_token('~');
9883 add_anchor_token(T_CHARACTER_CONSTANT);
9884 add_anchor_token(T_COLONCOLON);
9885 add_anchor_token(T_FLOATINGPOINT);
9886 add_anchor_token(T_IDENTIFIER);
9887 add_anchor_token(T_INTEGER);
9888 add_anchor_token(T_MINUSMINUS);
9889 add_anchor_token(T_PLUSPLUS);
9890 add_anchor_token(T_STRING_LITERAL);
9891 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
9892 add_anchor_token(T_WIDE_STRING_LITERAL);
9893 add_anchor_token(T__Bool);
9894 add_anchor_token(T__Complex);
9895 add_anchor_token(T__Imaginary);
9896 add_anchor_token(T___FUNCTION__);
9897 add_anchor_token(T___PRETTY_FUNCTION__);
9898 add_anchor_token(T___alignof__);
9899 add_anchor_token(T___attribute__);
9900 add_anchor_token(T___builtin_va_start);
9901 add_anchor_token(T___extension__);
9902 add_anchor_token(T___func__);
9903 add_anchor_token(T___imag__);
9904 add_anchor_token(T___label__);
9905 add_anchor_token(T___real__);
9906 add_anchor_token(T___thread);
9907 add_anchor_token(T_asm);
9908 add_anchor_token(T_auto);
9909 add_anchor_token(T_bool);
9910 add_anchor_token(T_break);
9911 add_anchor_token(T_case);
9912 add_anchor_token(T_char);
9913 add_anchor_token(T_class);
9914 add_anchor_token(T_const);
9915 add_anchor_token(T_const_cast);
9916 add_anchor_token(T_continue);
9917 add_anchor_token(T_default);
9918 add_anchor_token(T_delete);
9919 add_anchor_token(T_double);
9920 add_anchor_token(T_do);
9921 add_anchor_token(T_dynamic_cast);
9922 add_anchor_token(T_enum);
9923 add_anchor_token(T_extern);
9924 add_anchor_token(T_false);
9925 add_anchor_token(T_float);
9926 add_anchor_token(T_for);
9927 add_anchor_token(T_goto);
9928 add_anchor_token(T_if);
9929 add_anchor_token(T_inline);
9930 add_anchor_token(T_int);
9931 add_anchor_token(T_long);
9932 add_anchor_token(T_new);
9933 add_anchor_token(T_operator);
9934 add_anchor_token(T_register);
9935 add_anchor_token(T_reinterpret_cast);
9936 add_anchor_token(T_restrict);
9937 add_anchor_token(T_return);
9938 add_anchor_token(T_short);
9939 add_anchor_token(T_signed);
9940 add_anchor_token(T_sizeof);
9941 add_anchor_token(T_static);
9942 add_anchor_token(T_static_cast);
9943 add_anchor_token(T_struct);
9944 add_anchor_token(T_switch);
9945 add_anchor_token(T_template);
9946 add_anchor_token(T_this);
9947 add_anchor_token(T_throw);
9948 add_anchor_token(T_true);
9949 add_anchor_token(T_try);
9950 add_anchor_token(T_typedef);
9951 add_anchor_token(T_typeid);
9952 add_anchor_token(T_typename);
9953 add_anchor_token(T_typeof);
9954 add_anchor_token(T_union);
9955 add_anchor_token(T_unsigned);
9956 add_anchor_token(T_using);
9957 add_anchor_token(T_void);
9958 add_anchor_token(T_volatile);
9959 add_anchor_token(T_wchar_t);
9960 add_anchor_token(T_while);
9962 statement_t **anchor = &statement->compound.statements;
9963 bool only_decls_so_far = true;
9964 while (token.kind != '}' && token.kind != T_EOF) {
9965 statement_t *sub_statement = intern_parse_statement();
9966 if (sub_statement->kind == STATEMENT_ERROR) {
9970 if (sub_statement->kind != STATEMENT_DECLARATION) {
9971 only_decls_so_far = false;
9972 } else if (!only_decls_so_far) {
9973 source_position_t const *const pos = &sub_statement->base.source_position;
9974 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9977 *anchor = sub_statement;
9978 anchor = &sub_statement->base.next;
9982 /* look over all statements again to produce no effect warnings */
9983 if (is_warn_on(WARN_UNUSED_VALUE)) {
9984 statement_t *sub_statement = statement->compound.statements;
9985 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9986 if (sub_statement->kind != STATEMENT_EXPRESSION)
9988 /* don't emit a warning for the last expression in an expression
9989 * statement as it has always an effect */
9990 if (inside_expression_statement && sub_statement->base.next == NULL)
9993 expression_t *expression = sub_statement->expression.expression;
9994 if (!expression_has_effect(expression)) {
9995 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10000 rem_anchor_token(T_while);
10001 rem_anchor_token(T_wchar_t);
10002 rem_anchor_token(T_volatile);
10003 rem_anchor_token(T_void);
10004 rem_anchor_token(T_using);
10005 rem_anchor_token(T_unsigned);
10006 rem_anchor_token(T_union);
10007 rem_anchor_token(T_typeof);
10008 rem_anchor_token(T_typename);
10009 rem_anchor_token(T_typeid);
10010 rem_anchor_token(T_typedef);
10011 rem_anchor_token(T_try);
10012 rem_anchor_token(T_true);
10013 rem_anchor_token(T_throw);
10014 rem_anchor_token(T_this);
10015 rem_anchor_token(T_template);
10016 rem_anchor_token(T_switch);
10017 rem_anchor_token(T_struct);
10018 rem_anchor_token(T_static_cast);
10019 rem_anchor_token(T_static);
10020 rem_anchor_token(T_sizeof);
10021 rem_anchor_token(T_signed);
10022 rem_anchor_token(T_short);
10023 rem_anchor_token(T_return);
10024 rem_anchor_token(T_restrict);
10025 rem_anchor_token(T_reinterpret_cast);
10026 rem_anchor_token(T_register);
10027 rem_anchor_token(T_operator);
10028 rem_anchor_token(T_new);
10029 rem_anchor_token(T_long);
10030 rem_anchor_token(T_int);
10031 rem_anchor_token(T_inline);
10032 rem_anchor_token(T_if);
10033 rem_anchor_token(T_goto);
10034 rem_anchor_token(T_for);
10035 rem_anchor_token(T_float);
10036 rem_anchor_token(T_false);
10037 rem_anchor_token(T_extern);
10038 rem_anchor_token(T_enum);
10039 rem_anchor_token(T_dynamic_cast);
10040 rem_anchor_token(T_do);
10041 rem_anchor_token(T_double);
10042 rem_anchor_token(T_delete);
10043 rem_anchor_token(T_default);
10044 rem_anchor_token(T_continue);
10045 rem_anchor_token(T_const_cast);
10046 rem_anchor_token(T_const);
10047 rem_anchor_token(T_class);
10048 rem_anchor_token(T_char);
10049 rem_anchor_token(T_case);
10050 rem_anchor_token(T_break);
10051 rem_anchor_token(T_bool);
10052 rem_anchor_token(T_auto);
10053 rem_anchor_token(T_asm);
10054 rem_anchor_token(T___thread);
10055 rem_anchor_token(T___real__);
10056 rem_anchor_token(T___label__);
10057 rem_anchor_token(T___imag__);
10058 rem_anchor_token(T___func__);
10059 rem_anchor_token(T___extension__);
10060 rem_anchor_token(T___builtin_va_start);
10061 rem_anchor_token(T___attribute__);
10062 rem_anchor_token(T___alignof__);
10063 rem_anchor_token(T___PRETTY_FUNCTION__);
10064 rem_anchor_token(T___FUNCTION__);
10065 rem_anchor_token(T__Imaginary);
10066 rem_anchor_token(T__Complex);
10067 rem_anchor_token(T__Bool);
10068 rem_anchor_token(T_WIDE_STRING_LITERAL);
10069 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10070 rem_anchor_token(T_STRING_LITERAL);
10071 rem_anchor_token(T_PLUSPLUS);
10072 rem_anchor_token(T_MINUSMINUS);
10073 rem_anchor_token(T_INTEGER);
10074 rem_anchor_token(T_IDENTIFIER);
10075 rem_anchor_token(T_FLOATINGPOINT);
10076 rem_anchor_token(T_COLONCOLON);
10077 rem_anchor_token(T_CHARACTER_CONSTANT);
10078 rem_anchor_token('~');
10079 rem_anchor_token('{');
10080 rem_anchor_token(';');
10081 rem_anchor_token('-');
10082 rem_anchor_token('+');
10083 rem_anchor_token('*');
10084 rem_anchor_token('(');
10085 rem_anchor_token('&');
10086 rem_anchor_token('!');
10087 rem_anchor_token('}');
10095 * Check for unused global static functions and variables
10097 static void check_unused_globals(void)
10099 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10102 for (const entity_t *entity = file_scope->entities; entity != NULL;
10103 entity = entity->base.next) {
10104 if (!is_declaration(entity))
10107 const declaration_t *declaration = &entity->declaration;
10108 if (declaration->used ||
10109 declaration->modifiers & DM_UNUSED ||
10110 declaration->modifiers & DM_USED ||
10111 declaration->storage_class != STORAGE_CLASS_STATIC)
10116 if (entity->kind == ENTITY_FUNCTION) {
10117 /* inhibit warning for static inline functions */
10118 if (entity->function.is_inline)
10121 why = WARN_UNUSED_FUNCTION;
10122 s = entity->function.statement != NULL ? "defined" : "declared";
10124 why = WARN_UNUSED_VARIABLE;
10128 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10132 static void parse_global_asm(void)
10134 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10137 add_anchor_token(';');
10138 add_anchor_token(')');
10139 add_anchor_token(T_STRING_LITERAL);
10142 rem_anchor_token(T_STRING_LITERAL);
10143 statement->asms.asm_text = parse_string_literals();
10144 statement->base.next = unit->global_asm;
10145 unit->global_asm = statement;
10147 rem_anchor_token(')');
10149 rem_anchor_token(';');
10153 static void parse_linkage_specification(void)
10157 source_position_t const pos = *HERE;
10158 char const *const linkage = parse_string_literals().begin;
10160 linkage_kind_t old_linkage = current_linkage;
10161 linkage_kind_t new_linkage;
10162 if (streq(linkage, "C")) {
10163 new_linkage = LINKAGE_C;
10164 } else if (streq(linkage, "C++")) {
10165 new_linkage = LINKAGE_CXX;
10167 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10168 new_linkage = LINKAGE_C;
10170 current_linkage = new_linkage;
10172 if (next_if('{')) {
10179 assert(current_linkage == new_linkage);
10180 current_linkage = old_linkage;
10183 static void parse_external(void)
10185 switch (token.kind) {
10187 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10188 parse_linkage_specification();
10190 DECLARATION_START_NO_EXTERN
10192 case T___extension__:
10193 /* tokens below are for implicit int */
10194 case '&': /* & x; -> int& x; (and error later, because C++ has no
10196 case '*': /* * x; -> int* x; */
10197 case '(': /* (x); -> int (x); */
10199 parse_external_declaration();
10205 parse_global_asm();
10209 parse_namespace_definition();
10213 if (!strict_mode) {
10214 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10221 errorf(HERE, "stray %K outside of function", &token);
10222 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10223 eat_until_matching_token(token.kind);
10229 static void parse_externals(void)
10231 add_anchor_token('}');
10232 add_anchor_token(T_EOF);
10235 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10236 unsigned short token_anchor_copy[T_LAST_TOKEN];
10237 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10240 while (token.kind != T_EOF && token.kind != '}') {
10242 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10243 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10245 /* the anchor set and its copy differs */
10246 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10249 if (in_gcc_extension) {
10250 /* an gcc extension scope was not closed */
10251 internal_errorf(HERE, "Leaked __extension__");
10258 rem_anchor_token(T_EOF);
10259 rem_anchor_token('}');
10263 * Parse a translation unit.
10265 static void parse_translation_unit(void)
10267 add_anchor_token(T_EOF);
10272 if (token.kind == T_EOF)
10275 errorf(HERE, "stray %K outside of function", &token);
10276 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10277 eat_until_matching_token(token.kind);
10282 void set_default_visibility(elf_visibility_tag_t visibility)
10284 default_visibility = visibility;
10290 * @return the translation unit or NULL if errors occurred.
10292 void start_parsing(void)
10294 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10295 label_stack = NEW_ARR_F(stack_entry_t, 0);
10296 diagnostic_count = 0;
10300 print_to_file(stderr);
10302 assert(unit == NULL);
10303 unit = allocate_ast_zero(sizeof(unit[0]));
10305 assert(file_scope == NULL);
10306 file_scope = &unit->scope;
10308 assert(current_scope == NULL);
10309 scope_push(&unit->scope);
10311 create_gnu_builtins();
10313 create_microsoft_intrinsics();
10316 translation_unit_t *finish_parsing(void)
10318 assert(current_scope == &unit->scope);
10321 assert(file_scope == &unit->scope);
10322 check_unused_globals();
10325 DEL_ARR_F(environment_stack);
10326 DEL_ARR_F(label_stack);
10328 translation_unit_t *result = unit;
10333 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10334 * are given length one. */
10335 static void complete_incomplete_arrays(void)
10337 size_t n = ARR_LEN(incomplete_arrays);
10338 for (size_t i = 0; i != n; ++i) {
10339 declaration_t *const decl = incomplete_arrays[i];
10340 type_t *const type = skip_typeref(decl->type);
10342 if (!is_type_incomplete(type))
10345 source_position_t const *const pos = &decl->base.source_position;
10346 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10348 type_t *const new_type = duplicate_type(type);
10349 new_type->array.size_constant = true;
10350 new_type->array.has_implicit_size = true;
10351 new_type->array.size = 1;
10353 type_t *const result = identify_new_type(new_type);
10355 decl->type = result;
10359 static void prepare_main_collect2(entity_t *const entity)
10361 PUSH_SCOPE(&entity->function.statement->compound.scope);
10363 // create call to __main
10364 symbol_t *symbol = symbol_table_insert("__main");
10365 entity_t *subsubmain_ent
10366 = create_implicit_function(symbol, &builtin_source_position);
10368 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10369 type_t *ftype = subsubmain_ent->declaration.type;
10370 ref->base.source_position = builtin_source_position;
10371 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10372 ref->reference.entity = subsubmain_ent;
10374 expression_t *call = allocate_expression_zero(EXPR_CALL);
10375 call->base.source_position = builtin_source_position;
10376 call->base.type = type_void;
10377 call->call.function = ref;
10379 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10380 expr_statement->base.source_position = builtin_source_position;
10381 expr_statement->expression.expression = call;
10383 statement_t *statement = entity->function.statement;
10384 assert(statement->kind == STATEMENT_COMPOUND);
10385 compound_statement_t *compounds = &statement->compound;
10387 expr_statement->base.next = compounds->statements;
10388 compounds->statements = expr_statement;
10395 lookahead_bufpos = 0;
10396 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10399 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10400 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10401 parse_translation_unit();
10402 complete_incomplete_arrays();
10403 DEL_ARR_F(incomplete_arrays);
10404 incomplete_arrays = NULL;
10408 * Initialize the parser.
10410 void init_parser(void)
10412 sym_anonymous = symbol_table_insert("<anonymous>");
10414 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10416 init_expression_parsers();
10417 obstack_init(&temp_obst);
10421 * Terminate the parser.
10423 void exit_parser(void)
10425 obstack_free(&temp_obst, NULL);