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.identifier.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 symbol_t *symbol = token.identifier.symbol;
1108 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1109 argument->v.symbol = symbol;
1112 /* must be an expression */
1113 expression_t *expression = parse_assignment_expression();
1115 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1116 argument->v.expression = expression;
1119 /* append argument */
1121 anchor = &argument->next;
1122 } while (next_if(','));
1127 static attribute_t *parse_attribute_asm(void)
1129 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1132 attribute->a.arguments = parse_attribute_arguments();
1136 static symbol_t *get_symbol_from_token(void)
1138 switch(token.kind) {
1139 case T_CHARACTER_CONSTANT:
1141 case T_FLOATINGPOINT:
1143 case T_STRING_LITERAL:
1144 case T_WIDE_CHARACTER_CONSTANT:
1145 case T_WIDE_STRING_LITERAL:
1149 return token.identifier.symbol;
1153 static attribute_t *parse_attribute_gnu_single(void)
1155 /* parse "any-word" */
1156 symbol_t *symbol = get_symbol_from_token();
1157 if (symbol == NULL) {
1158 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1162 attribute_kind_t kind;
1163 char const *const name = symbol->string;
1164 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1165 if (kind > ATTRIBUTE_GNU_LAST) {
1166 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1167 /* TODO: we should still save the attribute in the list... */
1168 kind = ATTRIBUTE_UNKNOWN;
1172 const char *attribute_name = get_attribute_name(kind);
1173 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1177 attribute_t *attribute = allocate_attribute_zero(kind);
1180 /* parse arguments */
1182 attribute->a.arguments = parse_attribute_arguments();
1187 static attribute_t *parse_attribute_gnu(void)
1189 attribute_t *first = NULL;
1190 attribute_t **anchor = &first;
1192 eat(T___attribute__);
1196 add_anchor_token(')');
1197 add_anchor_token(',');
1198 if (token.kind != ')') do {
1199 attribute_t *attribute = parse_attribute_gnu_single();
1201 *anchor = attribute;
1202 anchor = &attribute->next;
1204 } while (next_if(','));
1205 rem_anchor_token(',');
1206 rem_anchor_token(')');
1213 /** Parse attributes. */
1214 static attribute_t *parse_attributes(attribute_t *first)
1216 attribute_t **anchor = &first;
1218 while (*anchor != NULL)
1219 anchor = &(*anchor)->next;
1221 attribute_t *attribute;
1222 switch (token.kind) {
1223 case T___attribute__:
1224 attribute = parse_attribute_gnu();
1225 if (attribute == NULL)
1230 attribute = parse_attribute_asm();
1234 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1239 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1243 case T__forceinline:
1244 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1245 eat(T__forceinline);
1249 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1254 /* TODO record modifier */
1255 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1256 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1264 *anchor = attribute;
1265 anchor = &attribute->next;
1269 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1271 static entity_t *determine_lhs_ent(expression_t *const expr,
1274 switch (expr->kind) {
1275 case EXPR_REFERENCE: {
1276 entity_t *const entity = expr->reference.entity;
1277 /* we should only find variables as lvalues... */
1278 if (entity->base.kind != ENTITY_VARIABLE
1279 && entity->base.kind != ENTITY_PARAMETER)
1285 case EXPR_ARRAY_ACCESS: {
1286 expression_t *const ref = expr->array_access.array_ref;
1287 entity_t * ent = NULL;
1288 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1289 ent = determine_lhs_ent(ref, lhs_ent);
1292 mark_vars_read(ref, lhs_ent);
1294 mark_vars_read(expr->array_access.index, lhs_ent);
1299 mark_vars_read(expr->select.compound, lhs_ent);
1300 if (is_type_compound(skip_typeref(expr->base.type)))
1301 return determine_lhs_ent(expr->select.compound, lhs_ent);
1305 case EXPR_UNARY_DEREFERENCE: {
1306 expression_t *const val = expr->unary.value;
1307 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1309 return determine_lhs_ent(val->unary.value, lhs_ent);
1311 mark_vars_read(val, NULL);
1317 mark_vars_read(expr, NULL);
1322 #define ENT_ANY ((entity_t*)-1)
1325 * Mark declarations, which are read. This is used to detect variables, which
1329 * x is not marked as "read", because it is only read to calculate its own new
1333 * x and y are not detected as "not read", because multiple variables are
1336 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1338 switch (expr->kind) {
1339 case EXPR_REFERENCE: {
1340 entity_t *const entity = expr->reference.entity;
1341 if (entity->kind != ENTITY_VARIABLE
1342 && entity->kind != ENTITY_PARAMETER)
1345 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1346 if (entity->kind == ENTITY_VARIABLE) {
1347 entity->variable.read = true;
1349 entity->parameter.read = true;
1356 // TODO respect pure/const
1357 mark_vars_read(expr->call.function, NULL);
1358 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1359 mark_vars_read(arg->expression, NULL);
1363 case EXPR_CONDITIONAL:
1364 // TODO lhs_decl should depend on whether true/false have an effect
1365 mark_vars_read(expr->conditional.condition, NULL);
1366 if (expr->conditional.true_expression != NULL)
1367 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1368 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1372 if (lhs_ent == ENT_ANY
1373 && !is_type_compound(skip_typeref(expr->base.type)))
1375 mark_vars_read(expr->select.compound, lhs_ent);
1378 case EXPR_ARRAY_ACCESS: {
1379 mark_vars_read(expr->array_access.index, lhs_ent);
1380 expression_t *const ref = expr->array_access.array_ref;
1381 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1382 if (lhs_ent == ENT_ANY)
1385 mark_vars_read(ref, lhs_ent);
1390 mark_vars_read(expr->va_arge.ap, lhs_ent);
1394 mark_vars_read(expr->va_copye.src, lhs_ent);
1397 case EXPR_UNARY_CAST:
1398 /* Special case: Use void cast to mark a variable as "read" */
1399 if (is_type_void(skip_typeref(expr->base.type)))
1404 case EXPR_UNARY_THROW:
1405 if (expr->unary.value == NULL)
1408 case EXPR_UNARY_DEREFERENCE:
1409 case EXPR_UNARY_DELETE:
1410 case EXPR_UNARY_DELETE_ARRAY:
1411 if (lhs_ent == ENT_ANY)
1415 case EXPR_UNARY_NEGATE:
1416 case EXPR_UNARY_PLUS:
1417 case EXPR_UNARY_BITWISE_NEGATE:
1418 case EXPR_UNARY_NOT:
1419 case EXPR_UNARY_TAKE_ADDRESS:
1420 case EXPR_UNARY_POSTFIX_INCREMENT:
1421 case EXPR_UNARY_POSTFIX_DECREMENT:
1422 case EXPR_UNARY_PREFIX_INCREMENT:
1423 case EXPR_UNARY_PREFIX_DECREMENT:
1424 case EXPR_UNARY_ASSUME:
1426 mark_vars_read(expr->unary.value, lhs_ent);
1429 case EXPR_BINARY_ADD:
1430 case EXPR_BINARY_SUB:
1431 case EXPR_BINARY_MUL:
1432 case EXPR_BINARY_DIV:
1433 case EXPR_BINARY_MOD:
1434 case EXPR_BINARY_EQUAL:
1435 case EXPR_BINARY_NOTEQUAL:
1436 case EXPR_BINARY_LESS:
1437 case EXPR_BINARY_LESSEQUAL:
1438 case EXPR_BINARY_GREATER:
1439 case EXPR_BINARY_GREATEREQUAL:
1440 case EXPR_BINARY_BITWISE_AND:
1441 case EXPR_BINARY_BITWISE_OR:
1442 case EXPR_BINARY_BITWISE_XOR:
1443 case EXPR_BINARY_LOGICAL_AND:
1444 case EXPR_BINARY_LOGICAL_OR:
1445 case EXPR_BINARY_SHIFTLEFT:
1446 case EXPR_BINARY_SHIFTRIGHT:
1447 case EXPR_BINARY_COMMA:
1448 case EXPR_BINARY_ISGREATER:
1449 case EXPR_BINARY_ISGREATEREQUAL:
1450 case EXPR_BINARY_ISLESS:
1451 case EXPR_BINARY_ISLESSEQUAL:
1452 case EXPR_BINARY_ISLESSGREATER:
1453 case EXPR_BINARY_ISUNORDERED:
1454 mark_vars_read(expr->binary.left, lhs_ent);
1455 mark_vars_read(expr->binary.right, lhs_ent);
1458 case EXPR_BINARY_ASSIGN:
1459 case EXPR_BINARY_MUL_ASSIGN:
1460 case EXPR_BINARY_DIV_ASSIGN:
1461 case EXPR_BINARY_MOD_ASSIGN:
1462 case EXPR_BINARY_ADD_ASSIGN:
1463 case EXPR_BINARY_SUB_ASSIGN:
1464 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1465 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1466 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1467 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1468 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1469 if (lhs_ent == ENT_ANY)
1471 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1472 mark_vars_read(expr->binary.right, lhs_ent);
1477 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1480 case EXPR_LITERAL_CASES:
1482 case EXPR_STRING_LITERAL:
1483 case EXPR_WIDE_STRING_LITERAL:
1484 case EXPR_COMPOUND_LITERAL: // TODO init?
1486 case EXPR_CLASSIFY_TYPE:
1489 case EXPR_BUILTIN_CONSTANT_P:
1490 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1492 case EXPR_STATEMENT: // TODO
1493 case EXPR_LABEL_ADDRESS:
1494 case EXPR_ENUM_CONSTANT:
1498 panic("unhandled expression");
1501 static designator_t *parse_designation(void)
1503 designator_t *result = NULL;
1504 designator_t **anchor = &result;
1507 designator_t *designator;
1508 switch (token.kind) {
1510 designator = allocate_ast_zero(sizeof(designator[0]));
1511 designator->source_position = token.base.source_position;
1513 add_anchor_token(']');
1514 designator->array_index = parse_constant_expression();
1515 rem_anchor_token(']');
1519 designator = allocate_ast_zero(sizeof(designator[0]));
1520 designator->source_position = token.base.source_position;
1522 designator->symbol = expect_identifier("while parsing designator", NULL);
1523 if (!designator->symbol)
1531 assert(designator != NULL);
1532 *anchor = designator;
1533 anchor = &designator->next;
1537 static initializer_t *initializer_from_string(array_type_t *const type,
1538 const string_t *const string)
1540 /* TODO: check len vs. size of array type */
1543 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1544 initializer->string.string = *string;
1549 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1550 const string_t *const string)
1552 /* TODO: check len vs. size of array type */
1555 initializer_t *const initializer =
1556 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1557 initializer->wide_string.string = *string;
1563 * Build an initializer from a given expression.
1565 static initializer_t *initializer_from_expression(type_t *orig_type,
1566 expression_t *expression)
1568 /* TODO check that expression is a constant expression */
1570 /* §6.7.8.14/15 char array may be initialized by string literals */
1571 type_t *type = skip_typeref(orig_type);
1572 type_t *expr_type_orig = expression->base.type;
1573 type_t *expr_type = skip_typeref(expr_type_orig);
1575 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1576 array_type_t *const array_type = &type->array;
1577 type_t *const element_type = skip_typeref(array_type->element_type);
1579 if (element_type->kind == TYPE_ATOMIC) {
1580 atomic_type_kind_t akind = element_type->atomic.akind;
1581 switch (expression->kind) {
1582 case EXPR_STRING_LITERAL:
1583 if (akind == ATOMIC_TYPE_CHAR
1584 || akind == ATOMIC_TYPE_SCHAR
1585 || akind == ATOMIC_TYPE_UCHAR) {
1586 return initializer_from_string(array_type,
1587 &expression->string_literal.value);
1591 case EXPR_WIDE_STRING_LITERAL: {
1592 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1593 if (get_unqualified_type(element_type) == bare_wchar_type) {
1594 return initializer_from_wide_string(array_type,
1595 &expression->string_literal.value);
1606 assign_error_t error = semantic_assign(type, expression);
1607 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1609 report_assign_error(error, type, expression, "initializer",
1610 &expression->base.source_position);
1612 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1613 result->value.value = create_implicit_cast(expression, type);
1619 * Parses an scalar initializer.
1621 * §6.7.8.11; eat {} without warning
1623 static initializer_t *parse_scalar_initializer(type_t *type,
1624 bool must_be_constant)
1626 /* there might be extra {} hierarchies */
1628 if (token.kind == '{') {
1629 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1633 } while (token.kind == '{');
1636 expression_t *expression = parse_assignment_expression();
1637 mark_vars_read(expression, NULL);
1638 if (must_be_constant && !is_linker_constant(expression)) {
1639 errorf(&expression->base.source_position,
1640 "initialisation expression '%E' is not constant",
1644 initializer_t *initializer = initializer_from_expression(type, expression);
1646 if (initializer == NULL) {
1647 errorf(&expression->base.source_position,
1648 "expression '%E' (type '%T') doesn't match expected type '%T'",
1649 expression, expression->base.type, type);
1654 bool additional_warning_displayed = false;
1655 while (braces > 0) {
1657 if (token.kind != '}') {
1658 if (!additional_warning_displayed) {
1659 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1660 additional_warning_displayed = true;
1671 * An entry in the type path.
1673 typedef struct type_path_entry_t type_path_entry_t;
1674 struct type_path_entry_t {
1675 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1677 size_t index; /**< For array types: the current index. */
1678 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1683 * A type path expression a position inside compound or array types.
1685 typedef struct type_path_t type_path_t;
1686 struct type_path_t {
1687 type_path_entry_t *path; /**< An flexible array containing the current path. */
1688 type_t *top_type; /**< type of the element the path points */
1689 size_t max_index; /**< largest index in outermost array */
1693 * Prints a type path for debugging.
1695 static __attribute__((unused)) void debug_print_type_path(
1696 const type_path_t *path)
1698 size_t len = ARR_LEN(path->path);
1700 for (size_t i = 0; i < len; ++i) {
1701 const type_path_entry_t *entry = & path->path[i];
1703 type_t *type = skip_typeref(entry->type);
1704 if (is_type_compound(type)) {
1705 /* in gcc mode structs can have no members */
1706 if (entry->v.compound_entry == NULL) {
1710 fprintf(stderr, ".%s",
1711 entry->v.compound_entry->base.symbol->string);
1712 } else if (is_type_array(type)) {
1713 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1715 fprintf(stderr, "-INVALID-");
1718 if (path->top_type != NULL) {
1719 fprintf(stderr, " (");
1720 print_type(path->top_type);
1721 fprintf(stderr, ")");
1726 * Return the top type path entry, ie. in a path
1727 * (type).a.b returns the b.
1729 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1731 size_t len = ARR_LEN(path->path);
1733 return &path->path[len-1];
1737 * Enlarge the type path by an (empty) element.
1739 static type_path_entry_t *append_to_type_path(type_path_t *path)
1741 size_t len = ARR_LEN(path->path);
1742 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1744 type_path_entry_t *result = & path->path[len];
1745 memset(result, 0, sizeof(result[0]));
1750 * Descending into a sub-type. Enter the scope of the current top_type.
1752 static void descend_into_subtype(type_path_t *path)
1754 type_t *orig_top_type = path->top_type;
1755 type_t *top_type = skip_typeref(orig_top_type);
1757 type_path_entry_t *top = append_to_type_path(path);
1758 top->type = top_type;
1760 if (is_type_compound(top_type)) {
1761 compound_t *const compound = top_type->compound.compound;
1762 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1764 if (entry != NULL) {
1765 top->v.compound_entry = &entry->declaration;
1766 path->top_type = entry->declaration.type;
1768 path->top_type = NULL;
1770 } else if (is_type_array(top_type)) {
1772 path->top_type = top_type->array.element_type;
1774 assert(!is_type_valid(top_type));
1779 * Pop an entry from the given type path, ie. returning from
1780 * (type).a.b to (type).a
1782 static void ascend_from_subtype(type_path_t *path)
1784 type_path_entry_t *top = get_type_path_top(path);
1786 path->top_type = top->type;
1788 size_t len = ARR_LEN(path->path);
1789 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1793 * Pop entries from the given type path until the given
1794 * path level is reached.
1796 static void ascend_to(type_path_t *path, size_t top_path_level)
1798 size_t len = ARR_LEN(path->path);
1800 while (len > top_path_level) {
1801 ascend_from_subtype(path);
1802 len = ARR_LEN(path->path);
1806 static bool walk_designator(type_path_t *path, const designator_t *designator,
1807 bool used_in_offsetof)
1809 for (; designator != NULL; designator = designator->next) {
1810 type_path_entry_t *top = get_type_path_top(path);
1811 type_t *orig_type = top->type;
1813 type_t *type = skip_typeref(orig_type);
1815 if (designator->symbol != NULL) {
1816 symbol_t *symbol = designator->symbol;
1817 if (!is_type_compound(type)) {
1818 if (is_type_valid(type)) {
1819 errorf(&designator->source_position,
1820 "'.%Y' designator used for non-compound type '%T'",
1824 top->type = type_error_type;
1825 top->v.compound_entry = NULL;
1826 orig_type = type_error_type;
1828 compound_t *compound = type->compound.compound;
1829 entity_t *iter = compound->members.entities;
1830 for (; iter != NULL; iter = iter->base.next) {
1831 if (iter->base.symbol == symbol) {
1836 errorf(&designator->source_position,
1837 "'%T' has no member named '%Y'", orig_type, symbol);
1840 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1841 if (used_in_offsetof && iter->compound_member.bitfield) {
1842 errorf(&designator->source_position,
1843 "offsetof designator '%Y' must not specify bitfield",
1848 top->type = orig_type;
1849 top->v.compound_entry = &iter->declaration;
1850 orig_type = iter->declaration.type;
1853 expression_t *array_index = designator->array_index;
1854 assert(designator->array_index != NULL);
1856 if (!is_type_array(type)) {
1857 if (is_type_valid(type)) {
1858 errorf(&designator->source_position,
1859 "[%E] designator used for non-array type '%T'",
1860 array_index, orig_type);
1865 long index = fold_constant_to_int(array_index);
1866 if (!used_in_offsetof) {
1868 errorf(&designator->source_position,
1869 "array index [%E] must be positive", array_index);
1870 } else if (type->array.size_constant) {
1871 long array_size = type->array.size;
1872 if (index >= array_size) {
1873 errorf(&designator->source_position,
1874 "designator [%E] (%d) exceeds array size %d",
1875 array_index, index, array_size);
1880 top->type = orig_type;
1881 top->v.index = (size_t) index;
1882 orig_type = type->array.element_type;
1884 path->top_type = orig_type;
1886 if (designator->next != NULL) {
1887 descend_into_subtype(path);
1893 static void advance_current_object(type_path_t *path, size_t top_path_level)
1895 type_path_entry_t *top = get_type_path_top(path);
1897 type_t *type = skip_typeref(top->type);
1898 if (is_type_union(type)) {
1899 /* in unions only the first element is initialized */
1900 top->v.compound_entry = NULL;
1901 } else if (is_type_struct(type)) {
1902 declaration_t *entry = top->v.compound_entry;
1904 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1905 if (next_entity != NULL) {
1906 assert(is_declaration(next_entity));
1907 entry = &next_entity->declaration;
1912 top->v.compound_entry = entry;
1913 if (entry != NULL) {
1914 path->top_type = entry->type;
1917 } else if (is_type_array(type)) {
1918 assert(is_type_array(type));
1922 if (!type->array.size_constant || top->v.index < type->array.size) {
1926 assert(!is_type_valid(type));
1930 /* we're past the last member of the current sub-aggregate, try if we
1931 * can ascend in the type hierarchy and continue with another subobject */
1932 size_t len = ARR_LEN(path->path);
1934 if (len > top_path_level) {
1935 ascend_from_subtype(path);
1936 advance_current_object(path, top_path_level);
1938 path->top_type = NULL;
1943 * skip any {...} blocks until a closing bracket is reached.
1945 static void skip_initializers(void)
1949 while (token.kind != '}') {
1950 if (token.kind == T_EOF)
1952 if (token.kind == '{') {
1960 static initializer_t *create_empty_initializer(void)
1962 static initializer_t empty_initializer
1963 = { .list = { { INITIALIZER_LIST }, 0 } };
1964 return &empty_initializer;
1968 * Parse a part of an initialiser for a struct or union,
1970 static initializer_t *parse_sub_initializer(type_path_t *path,
1971 type_t *outer_type, size_t top_path_level,
1972 parse_initializer_env_t *env)
1974 if (token.kind == '}') {
1975 /* empty initializer */
1976 return create_empty_initializer();
1979 type_t *orig_type = path->top_type;
1980 type_t *type = NULL;
1982 if (orig_type == NULL) {
1983 /* We are initializing an empty compound. */
1985 type = skip_typeref(orig_type);
1988 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1991 designator_t *designator = NULL;
1992 if (token.kind == '.' || token.kind == '[') {
1993 designator = parse_designation();
1994 goto finish_designator;
1995 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1996 /* GNU-style designator ("identifier: value") */
1997 designator = allocate_ast_zero(sizeof(designator[0]));
1998 designator->source_position = token.base.source_position;
1999 designator->symbol = token.identifier.symbol;
2004 /* reset path to toplevel, evaluate designator from there */
2005 ascend_to(path, top_path_level);
2006 if (!walk_designator(path, designator, false)) {
2007 /* can't continue after designation error */
2011 initializer_t *designator_initializer
2012 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2013 designator_initializer->designator.designator = designator;
2014 ARR_APP1(initializer_t*, initializers, designator_initializer);
2016 orig_type = path->top_type;
2017 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2022 if (token.kind == '{') {
2023 if (type != NULL && is_type_scalar(type)) {
2024 sub = parse_scalar_initializer(type, env->must_be_constant);
2027 if (env->entity != NULL) {
2029 "extra brace group at end of initializer for '%Y'",
2030 env->entity->base.symbol);
2032 errorf(HERE, "extra brace group at end of initializer");
2037 descend_into_subtype(path);
2040 add_anchor_token('}');
2041 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2043 rem_anchor_token('}');
2048 goto error_parse_next;
2050 ascend_from_subtype(path);
2053 /* must be an expression */
2054 expression_t *expression = parse_assignment_expression();
2055 mark_vars_read(expression, NULL);
2057 if (env->must_be_constant && !is_linker_constant(expression)) {
2058 errorf(&expression->base.source_position,
2059 "Initialisation expression '%E' is not constant",
2064 /* we are already outside, ... */
2065 if (outer_type == NULL)
2066 goto error_parse_next;
2067 type_t *const outer_type_skip = skip_typeref(outer_type);
2068 if (is_type_compound(outer_type_skip) &&
2069 !outer_type_skip->compound.compound->complete) {
2070 goto error_parse_next;
2073 source_position_t const* const pos = &expression->base.source_position;
2074 if (env->entity != NULL) {
2075 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2077 warningf(WARN_OTHER, pos, "excess elements in initializer");
2079 goto error_parse_next;
2082 /* handle { "string" } special case */
2083 if ((expression->kind == EXPR_STRING_LITERAL
2084 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2085 && outer_type != NULL) {
2086 sub = initializer_from_expression(outer_type, expression);
2089 if (token.kind != '}') {
2090 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2092 /* TODO: eat , ... */
2097 /* descend into subtypes until expression matches type */
2099 orig_type = path->top_type;
2100 type = skip_typeref(orig_type);
2102 sub = initializer_from_expression(orig_type, expression);
2106 if (!is_type_valid(type)) {
2109 if (is_type_scalar(type)) {
2110 errorf(&expression->base.source_position,
2111 "expression '%E' doesn't match expected type '%T'",
2112 expression, orig_type);
2116 descend_into_subtype(path);
2120 /* update largest index of top array */
2121 const type_path_entry_t *first = &path->path[0];
2122 type_t *first_type = first->type;
2123 first_type = skip_typeref(first_type);
2124 if (is_type_array(first_type)) {
2125 size_t index = first->v.index;
2126 if (index > path->max_index)
2127 path->max_index = index;
2130 /* append to initializers list */
2131 ARR_APP1(initializer_t*, initializers, sub);
2134 if (token.kind == '}') {
2137 add_anchor_token('}');
2139 rem_anchor_token('}');
2140 if (token.kind == '}') {
2145 /* advance to the next declaration if we are not at the end */
2146 advance_current_object(path, top_path_level);
2147 orig_type = path->top_type;
2148 if (orig_type != NULL)
2149 type = skip_typeref(orig_type);
2155 size_t len = ARR_LEN(initializers);
2156 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2157 initializer_t *result = allocate_ast_zero(size);
2158 result->kind = INITIALIZER_LIST;
2159 result->list.len = len;
2160 memcpy(&result->list.initializers, initializers,
2161 len * sizeof(initializers[0]));
2163 DEL_ARR_F(initializers);
2164 ascend_to(path, top_path_level+1);
2169 skip_initializers();
2170 DEL_ARR_F(initializers);
2171 ascend_to(path, top_path_level+1);
2175 static expression_t *make_size_literal(size_t value)
2177 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2178 literal->base.type = type_size_t;
2181 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2182 literal->literal.value = make_string(buf);
2188 * Parses an initializer. Parsers either a compound literal
2189 * (env->declaration == NULL) or an initializer of a declaration.
2191 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2193 type_t *type = skip_typeref(env->type);
2194 size_t max_index = 0;
2195 initializer_t *result;
2197 if (is_type_scalar(type)) {
2198 result = parse_scalar_initializer(type, env->must_be_constant);
2199 } else if (token.kind == '{') {
2203 memset(&path, 0, sizeof(path));
2204 path.top_type = env->type;
2205 path.path = NEW_ARR_F(type_path_entry_t, 0);
2207 descend_into_subtype(&path);
2209 add_anchor_token('}');
2210 result = parse_sub_initializer(&path, env->type, 1, env);
2211 rem_anchor_token('}');
2213 max_index = path.max_index;
2214 DEL_ARR_F(path.path);
2218 /* parse_scalar_initializer() also works in this case: we simply
2219 * have an expression without {} around it */
2220 result = parse_scalar_initializer(type, env->must_be_constant);
2223 /* §6.7.8:22 array initializers for arrays with unknown size determine
2224 * the array type size */
2225 if (is_type_array(type) && type->array.size_expression == NULL
2226 && result != NULL) {
2228 switch (result->kind) {
2229 case INITIALIZER_LIST:
2230 assert(max_index != 0xdeadbeaf);
2231 size = max_index + 1;
2234 case INITIALIZER_STRING:
2235 size = result->string.string.size;
2238 case INITIALIZER_WIDE_STRING:
2239 size = result->wide_string.string.size;
2242 case INITIALIZER_DESIGNATOR:
2243 case INITIALIZER_VALUE:
2244 /* can happen for parse errors */
2249 internal_errorf(HERE, "invalid initializer type");
2252 type_t *new_type = duplicate_type(type);
2254 new_type->array.size_expression = make_size_literal(size);
2255 new_type->array.size_constant = true;
2256 new_type->array.has_implicit_size = true;
2257 new_type->array.size = size;
2258 env->type = new_type;
2264 static void append_entity(scope_t *scope, entity_t *entity)
2266 if (scope->last_entity != NULL) {
2267 scope->last_entity->base.next = entity;
2269 scope->entities = entity;
2271 entity->base.parent_entity = current_entity;
2272 scope->last_entity = entity;
2276 static compound_t *parse_compound_type_specifier(bool is_struct)
2278 source_position_t const pos = *HERE;
2279 eat(is_struct ? T_struct : T_union);
2281 symbol_t *symbol = NULL;
2282 entity_t *entity = NULL;
2283 attribute_t *attributes = NULL;
2285 if (token.kind == T___attribute__) {
2286 attributes = parse_attributes(NULL);
2289 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2290 if (token.kind == T_IDENTIFIER) {
2291 /* the compound has a name, check if we have seen it already */
2292 symbol = token.identifier.symbol;
2293 entity = get_tag(symbol, kind);
2296 if (entity != NULL) {
2297 if (entity->base.parent_scope != current_scope &&
2298 (token.kind == '{' || token.kind == ';')) {
2299 /* we're in an inner scope and have a definition. Shadow
2300 * existing definition in outer scope */
2302 } else if (entity->compound.complete && token.kind == '{') {
2303 source_position_t const *const ppos = &entity->base.source_position;
2304 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2305 /* clear members in the hope to avoid further errors */
2306 entity->compound.members.entities = NULL;
2309 } else if (token.kind != '{') {
2310 char const *const msg =
2311 is_struct ? "while parsing struct type specifier" :
2312 "while parsing union type specifier";
2313 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2318 if (entity == NULL) {
2319 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2320 entity->compound.alignment = 1;
2321 entity->base.parent_scope = current_scope;
2322 if (symbol != NULL) {
2323 environment_push(entity);
2325 append_entity(current_scope, entity);
2328 if (token.kind == '{') {
2329 parse_compound_type_entries(&entity->compound);
2331 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2332 if (symbol == NULL) {
2333 assert(anonymous_entity == NULL);
2334 anonymous_entity = entity;
2338 if (attributes != NULL) {
2339 handle_entity_attributes(attributes, entity);
2342 return &entity->compound;
2345 static void parse_enum_entries(type_t *const enum_type)
2349 if (token.kind == '}') {
2350 errorf(HERE, "empty enum not allowed");
2355 add_anchor_token('}');
2356 add_anchor_token(',');
2358 add_anchor_token('=');
2359 source_position_t pos;
2360 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2361 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2362 entity->enum_value.enum_type = enum_type;
2363 rem_anchor_token('=');
2366 expression_t *value = parse_constant_expression();
2368 value = create_implicit_cast(value, enum_type);
2369 entity->enum_value.value = value;
2374 record_entity(entity, false);
2375 } while (next_if(',') && token.kind != '}');
2376 rem_anchor_token(',');
2377 rem_anchor_token('}');
2382 static type_t *parse_enum_specifier(void)
2384 source_position_t const pos = *HERE;
2389 switch (token.kind) {
2391 symbol = token.identifier.symbol;
2392 entity = get_tag(symbol, ENTITY_ENUM);
2395 if (entity != NULL) {
2396 if (entity->base.parent_scope != current_scope &&
2397 (token.kind == '{' || token.kind == ';')) {
2398 /* we're in an inner scope and have a definition. Shadow
2399 * existing definition in outer scope */
2401 } else if (entity->enume.complete && token.kind == '{') {
2402 source_position_t const *const ppos = &entity->base.source_position;
2403 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2414 parse_error_expected("while parsing enum type specifier",
2415 T_IDENTIFIER, '{', NULL);
2419 if (entity == NULL) {
2420 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2421 entity->base.parent_scope = current_scope;
2424 type_t *const type = allocate_type_zero(TYPE_ENUM);
2425 type->enumt.enume = &entity->enume;
2426 type->enumt.base.akind = ATOMIC_TYPE_INT;
2428 if (token.kind == '{') {
2429 if (symbol != NULL) {
2430 environment_push(entity);
2432 append_entity(current_scope, entity);
2433 entity->enume.complete = true;
2435 parse_enum_entries(type);
2436 parse_attributes(NULL);
2438 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2439 if (symbol == NULL) {
2440 assert(anonymous_entity == NULL);
2441 anonymous_entity = entity;
2443 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2444 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2451 * if a symbol is a typedef to another type, return true
2453 static bool is_typedef_symbol(symbol_t *symbol)
2455 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2456 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2459 static type_t *parse_typeof(void)
2466 add_anchor_token(')');
2468 expression_t *expression = NULL;
2470 switch (token.kind) {
2472 if (is_typedef_symbol(token.identifier.symbol)) {
2474 type = parse_typename();
2477 expression = parse_expression();
2478 type = revert_automatic_type_conversion(expression);
2483 rem_anchor_token(')');
2486 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2487 typeof_type->typeoft.expression = expression;
2488 typeof_type->typeoft.typeof_type = type;
2493 typedef enum specifiers_t {
2494 SPECIFIER_SIGNED = 1 << 0,
2495 SPECIFIER_UNSIGNED = 1 << 1,
2496 SPECIFIER_LONG = 1 << 2,
2497 SPECIFIER_INT = 1 << 3,
2498 SPECIFIER_DOUBLE = 1 << 4,
2499 SPECIFIER_CHAR = 1 << 5,
2500 SPECIFIER_WCHAR_T = 1 << 6,
2501 SPECIFIER_SHORT = 1 << 7,
2502 SPECIFIER_LONG_LONG = 1 << 8,
2503 SPECIFIER_FLOAT = 1 << 9,
2504 SPECIFIER_BOOL = 1 << 10,
2505 SPECIFIER_VOID = 1 << 11,
2506 SPECIFIER_INT8 = 1 << 12,
2507 SPECIFIER_INT16 = 1 << 13,
2508 SPECIFIER_INT32 = 1 << 14,
2509 SPECIFIER_INT64 = 1 << 15,
2510 SPECIFIER_INT128 = 1 << 16,
2511 SPECIFIER_COMPLEX = 1 << 17,
2512 SPECIFIER_IMAGINARY = 1 << 18,
2515 static type_t *get_typedef_type(symbol_t *symbol)
2517 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2518 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2521 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2522 type->typedeft.typedefe = &entity->typedefe;
2527 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2529 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2533 add_anchor_token(')');
2534 add_anchor_token(',');
2536 add_anchor_token('=');
2537 source_position_t pos;
2538 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2539 rem_anchor_token('=');
2541 symbol_t **prop = NULL;
2543 if (streq(prop_sym->string, "put")) {
2544 prop = &property->put_symbol;
2545 } else if (streq(prop_sym->string, "get")) {
2546 prop = &property->get_symbol;
2548 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2552 add_anchor_token(T_IDENTIFIER);
2554 rem_anchor_token(T_IDENTIFIER);
2556 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2558 *prop = sym ? sym : sym_anonymous;
2559 } while (next_if(','));
2560 rem_anchor_token(',');
2561 rem_anchor_token(')');
2563 attribute->a.property = property;
2569 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2571 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2572 if (next_if(T_restrict)) {
2573 kind = ATTRIBUTE_MS_RESTRICT;
2574 } else if (token.kind == T_IDENTIFIER) {
2575 const char *name = token.identifier.symbol->string;
2576 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2578 const char *attribute_name = get_attribute_name(k);
2579 if (attribute_name != NULL && streq(attribute_name, name)) {
2585 if (kind == ATTRIBUTE_UNKNOWN) {
2586 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2589 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2593 attribute_t *attribute = allocate_attribute_zero(kind);
2596 if (kind == ATTRIBUTE_MS_PROPERTY) {
2597 return parse_attribute_ms_property(attribute);
2600 /* parse arguments */
2602 attribute->a.arguments = parse_attribute_arguments();
2607 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2612 if (token.kind != ')') {
2613 add_anchor_token(')');
2615 attribute_t **anchor = &first;
2617 while (*anchor != NULL)
2618 anchor = &(*anchor)->next;
2620 attribute_t *attribute
2621 = parse_microsoft_extended_decl_modifier_single();
2622 if (attribute == NULL)
2625 *anchor = attribute;
2626 anchor = &attribute->next;
2627 } while (next_if(','));
2629 rem_anchor_token(')');
2635 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2637 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2638 if (is_declaration(entity)) {
2639 entity->declaration.type = type_error_type;
2640 entity->declaration.implicit = true;
2641 } else if (kind == ENTITY_TYPEDEF) {
2642 entity->typedefe.type = type_error_type;
2643 entity->typedefe.builtin = true;
2645 if (kind != ENTITY_COMPOUND_MEMBER)
2646 record_entity(entity, false);
2650 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2652 type_t *type = NULL;
2653 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2654 unsigned type_specifiers = 0;
2655 bool newtype = false;
2656 bool saw_error = false;
2658 memset(specifiers, 0, sizeof(*specifiers));
2659 specifiers->source_position = token.base.source_position;
2662 specifiers->attributes = parse_attributes(specifiers->attributes);
2664 switch (token.kind) {
2666 #define MATCH_STORAGE_CLASS(token, class) \
2668 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2669 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2671 specifiers->storage_class = class; \
2672 if (specifiers->thread_local) \
2673 goto check_thread_storage_class; \
2677 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2678 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2679 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2680 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2681 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2684 specifiers->attributes
2685 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2689 if (specifiers->thread_local) {
2690 errorf(HERE, "duplicate '__thread'");
2692 specifiers->thread_local = true;
2693 check_thread_storage_class:
2694 switch (specifiers->storage_class) {
2695 case STORAGE_CLASS_EXTERN:
2696 case STORAGE_CLASS_NONE:
2697 case STORAGE_CLASS_STATIC:
2701 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2702 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2703 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2704 wrong_thread_storage_class:
2705 errorf(HERE, "'__thread' used with '%s'", wrong);
2712 /* type qualifiers */
2713 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2715 qualifiers |= qualifier; \
2719 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2720 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2721 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2722 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2723 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2724 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2725 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2726 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2728 /* type specifiers */
2729 #define MATCH_SPECIFIER(token, specifier, name) \
2731 if (type_specifiers & specifier) { \
2732 errorf(HERE, "multiple " name " type specifiers given"); \
2734 type_specifiers |= specifier; \
2739 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2740 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2741 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2742 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2743 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2744 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2745 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2746 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2747 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2748 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2749 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2750 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2751 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2752 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2753 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2754 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2755 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2756 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2760 specifiers->is_inline = true;
2764 case T__forceinline:
2766 specifiers->modifiers |= DM_FORCEINLINE;
2771 if (type_specifiers & SPECIFIER_LONG_LONG) {
2772 errorf(HERE, "too many long type specifiers given");
2773 } else if (type_specifiers & SPECIFIER_LONG) {
2774 type_specifiers |= SPECIFIER_LONG_LONG;
2776 type_specifiers |= SPECIFIER_LONG;
2781 #define CHECK_DOUBLE_TYPE() \
2782 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2785 CHECK_DOUBLE_TYPE();
2786 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2788 type->compound.compound = parse_compound_type_specifier(true);
2791 CHECK_DOUBLE_TYPE();
2792 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2793 type->compound.compound = parse_compound_type_specifier(false);
2796 CHECK_DOUBLE_TYPE();
2797 type = parse_enum_specifier();
2800 CHECK_DOUBLE_TYPE();
2801 type = parse_typeof();
2803 case T___builtin_va_list:
2804 CHECK_DOUBLE_TYPE();
2805 type = duplicate_type(type_valist);
2809 case T_IDENTIFIER: {
2810 /* only parse identifier if we haven't found a type yet */
2811 if (type != NULL || type_specifiers != 0) {
2812 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2813 * declaration, so it doesn't generate errors about expecting '(' or
2815 switch (look_ahead(1)->kind) {
2822 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2826 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2831 goto finish_specifiers;
2835 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2836 if (typedef_type == NULL) {
2837 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2838 * declaration, so it doesn't generate 'implicit int' followed by more
2839 * errors later on. */
2840 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2846 errorf(HERE, "%K does not name a type", &token);
2848 symbol_t *symbol = token.identifier.symbol;
2850 = create_error_entity(symbol, ENTITY_TYPEDEF);
2852 type = allocate_type_zero(TYPE_TYPEDEF);
2853 type->typedeft.typedefe = &entity->typedefe;
2861 goto finish_specifiers;
2866 type = typedef_type;
2870 /* function specifier */
2872 goto finish_specifiers;
2877 specifiers->attributes = parse_attributes(specifiers->attributes);
2879 if (type == NULL || (saw_error && type_specifiers != 0)) {
2880 atomic_type_kind_t atomic_type;
2882 /* match valid basic types */
2883 switch (type_specifiers) {
2884 case SPECIFIER_VOID:
2885 atomic_type = ATOMIC_TYPE_VOID;
2887 case SPECIFIER_WCHAR_T:
2888 atomic_type = ATOMIC_TYPE_WCHAR_T;
2890 case SPECIFIER_CHAR:
2891 atomic_type = ATOMIC_TYPE_CHAR;
2893 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2894 atomic_type = ATOMIC_TYPE_SCHAR;
2896 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2897 atomic_type = ATOMIC_TYPE_UCHAR;
2899 case SPECIFIER_SHORT:
2900 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2901 case SPECIFIER_SHORT | SPECIFIER_INT:
2902 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2903 atomic_type = ATOMIC_TYPE_SHORT;
2905 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2906 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2907 atomic_type = ATOMIC_TYPE_USHORT;
2910 case SPECIFIER_SIGNED:
2911 case SPECIFIER_SIGNED | SPECIFIER_INT:
2912 atomic_type = ATOMIC_TYPE_INT;
2914 case SPECIFIER_UNSIGNED:
2915 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2916 atomic_type = ATOMIC_TYPE_UINT;
2918 case SPECIFIER_LONG:
2919 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2920 case SPECIFIER_LONG | SPECIFIER_INT:
2921 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2922 atomic_type = ATOMIC_TYPE_LONG;
2924 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2925 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2926 atomic_type = ATOMIC_TYPE_ULONG;
2929 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2930 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2931 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2932 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2934 atomic_type = ATOMIC_TYPE_LONGLONG;
2935 goto warn_about_long_long;
2937 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2938 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2940 atomic_type = ATOMIC_TYPE_ULONGLONG;
2941 warn_about_long_long:
2942 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2945 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2946 atomic_type = unsigned_int8_type_kind;
2949 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2950 atomic_type = unsigned_int16_type_kind;
2953 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2954 atomic_type = unsigned_int32_type_kind;
2957 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2958 atomic_type = unsigned_int64_type_kind;
2961 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2962 atomic_type = unsigned_int128_type_kind;
2965 case SPECIFIER_INT8:
2966 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2967 atomic_type = int8_type_kind;
2970 case SPECIFIER_INT16:
2971 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2972 atomic_type = int16_type_kind;
2975 case SPECIFIER_INT32:
2976 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2977 atomic_type = int32_type_kind;
2980 case SPECIFIER_INT64:
2981 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2982 atomic_type = int64_type_kind;
2985 case SPECIFIER_INT128:
2986 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2987 atomic_type = int128_type_kind;
2990 case SPECIFIER_FLOAT:
2991 atomic_type = ATOMIC_TYPE_FLOAT;
2993 case SPECIFIER_DOUBLE:
2994 atomic_type = ATOMIC_TYPE_DOUBLE;
2996 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2997 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2999 case SPECIFIER_BOOL:
3000 atomic_type = ATOMIC_TYPE_BOOL;
3002 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3003 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3004 atomic_type = ATOMIC_TYPE_FLOAT;
3006 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3007 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3008 atomic_type = ATOMIC_TYPE_DOUBLE;
3010 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3011 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3012 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3015 /* invalid specifier combination, give an error message */
3016 source_position_t const* const pos = &specifiers->source_position;
3017 if (type_specifiers == 0) {
3019 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3020 if (!(c_mode & _CXX) && !strict_mode) {
3021 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3022 atomic_type = ATOMIC_TYPE_INT;
3025 errorf(pos, "no type specifiers given in declaration");
3028 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3029 (type_specifiers & SPECIFIER_UNSIGNED)) {
3030 errorf(pos, "signed and unsigned specifiers given");
3031 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3032 errorf(pos, "only integer types can be signed or unsigned");
3034 errorf(pos, "multiple datatypes in declaration");
3040 if (type_specifiers & SPECIFIER_COMPLEX) {
3041 type = allocate_type_zero(TYPE_COMPLEX);
3042 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3043 type = allocate_type_zero(TYPE_IMAGINARY);
3045 type = allocate_type_zero(TYPE_ATOMIC);
3047 type->atomic.akind = atomic_type;
3049 } else if (type_specifiers != 0) {
3050 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3053 /* FIXME: check type qualifiers here */
3054 type->base.qualifiers = qualifiers;
3057 type = identify_new_type(type);
3059 type = typehash_insert(type);
3062 if (specifiers->attributes != NULL)
3063 type = handle_type_attributes(specifiers->attributes, type);
3064 specifiers->type = type;
3068 specifiers->type = type_error_type;
3071 static type_qualifiers_t parse_type_qualifiers(void)
3073 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3076 switch (token.kind) {
3077 /* type qualifiers */
3078 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3079 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3080 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3081 /* microsoft extended type modifiers */
3082 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3083 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3084 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3085 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3086 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3095 * Parses an K&R identifier list
3097 static void parse_identifier_list(scope_t *scope)
3099 assert(token.kind == T_IDENTIFIER);
3101 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3102 /* a K&R parameter has no type, yet */
3106 append_entity(scope, entity);
3107 } while (next_if(',') && token.kind == T_IDENTIFIER);
3110 static entity_t *parse_parameter(void)
3112 declaration_specifiers_t specifiers;
3113 parse_declaration_specifiers(&specifiers);
3115 entity_t *entity = parse_declarator(&specifiers,
3116 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3117 anonymous_entity = NULL;
3121 static void semantic_parameter_incomplete(const entity_t *entity)
3123 assert(entity->kind == ENTITY_PARAMETER);
3125 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3126 * list in a function declarator that is part of a
3127 * definition of that function shall not have
3128 * incomplete type. */
3129 type_t *type = skip_typeref(entity->declaration.type);
3130 if (is_type_incomplete(type)) {
3131 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3135 static bool has_parameters(void)
3137 /* func(void) is not a parameter */
3138 if (look_ahead(1)->kind != ')')
3140 if (token.kind == T_IDENTIFIER) {
3141 entity_t const *const entity
3142 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3145 if (entity->kind != ENTITY_TYPEDEF)
3147 type_t const *const type = skip_typeref(entity->typedefe.type);
3148 if (!is_type_void(type))
3150 if (c_mode & _CXX) {
3151 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3152 * is not allowed. */
3153 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3154 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3155 /* §6.7.5.3:10 Qualification is not allowed here. */
3156 errorf(HERE, "'void' as parameter must not have type qualifiers");
3158 } else if (token.kind != T_void) {
3166 * Parses function type parameters (and optionally creates variable_t entities
3167 * for them in a scope)
3169 static void parse_parameters(function_type_t *type, scope_t *scope)
3172 add_anchor_token(')');
3174 if (token.kind == T_IDENTIFIER &&
3175 !is_typedef_symbol(token.identifier.symbol) &&
3176 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3177 type->kr_style_parameters = true;
3178 parse_identifier_list(scope);
3179 } else if (token.kind == ')') {
3180 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3181 if (!(c_mode & _CXX))
3182 type->unspecified_parameters = true;
3183 } else if (has_parameters()) {
3184 function_parameter_t **anchor = &type->parameters;
3185 add_anchor_token(',');
3187 switch (token.kind) {
3190 type->variadic = true;
3191 goto parameters_finished;
3196 entity_t *entity = parse_parameter();
3197 if (entity->kind == ENTITY_TYPEDEF) {
3198 errorf(&entity->base.source_position,
3199 "typedef not allowed as function parameter");
3202 assert(is_declaration(entity));
3204 semantic_parameter_incomplete(entity);
3206 function_parameter_t *const parameter =
3207 allocate_parameter(entity->declaration.type);
3209 if (scope != NULL) {
3210 append_entity(scope, entity);
3213 *anchor = parameter;
3214 anchor = ¶meter->next;
3219 goto parameters_finished;
3221 } while (next_if(','));
3222 parameters_finished:
3223 rem_anchor_token(',');
3226 rem_anchor_token(')');
3230 typedef enum construct_type_kind_t {
3231 CONSTRUCT_POINTER = 1,
3232 CONSTRUCT_REFERENCE,
3235 } construct_type_kind_t;
3237 typedef union construct_type_t construct_type_t;
3239 typedef struct construct_type_base_t {
3240 construct_type_kind_t kind;
3241 source_position_t pos;
3242 construct_type_t *next;
3243 } construct_type_base_t;
3245 typedef struct parsed_pointer_t {
3246 construct_type_base_t base;
3247 type_qualifiers_t type_qualifiers;
3248 variable_t *base_variable; /**< MS __based extension. */
3251 typedef struct parsed_reference_t {
3252 construct_type_base_t base;
3253 } parsed_reference_t;
3255 typedef struct construct_function_type_t {
3256 construct_type_base_t base;
3257 type_t *function_type;
3258 } construct_function_type_t;
3260 typedef struct parsed_array_t {
3261 construct_type_base_t base;
3262 type_qualifiers_t type_qualifiers;
3268 union construct_type_t {
3269 construct_type_kind_t kind;
3270 construct_type_base_t base;
3271 parsed_pointer_t pointer;
3272 parsed_reference_t reference;
3273 construct_function_type_t function;
3274 parsed_array_t array;
3277 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3279 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3280 memset(cons, 0, size);
3282 cons->base.pos = *HERE;
3287 static construct_type_t *parse_pointer_declarator(void)
3289 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3291 cons->pointer.type_qualifiers = parse_type_qualifiers();
3292 //cons->pointer.base_variable = base_variable;
3297 /* ISO/IEC 14882:1998(E) §8.3.2 */
3298 static construct_type_t *parse_reference_declarator(void)
3300 if (!(c_mode & _CXX))
3301 errorf(HERE, "references are only available for C++");
3303 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3310 static construct_type_t *parse_array_declarator(void)
3312 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3313 parsed_array_t *const array = &cons->array;
3316 add_anchor_token(']');
3318 bool is_static = next_if(T_static);
3320 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3323 is_static = next_if(T_static);
3325 array->type_qualifiers = type_qualifiers;
3326 array->is_static = is_static;
3328 expression_t *size = NULL;
3329 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3330 array->is_variable = true;
3332 } else if (token.kind != ']') {
3333 size = parse_assignment_expression();
3335 /* §6.7.5.2:1 Array size must have integer type */
3336 type_t *const orig_type = size->base.type;
3337 type_t *const type = skip_typeref(orig_type);
3338 if (!is_type_integer(type) && is_type_valid(type)) {
3339 errorf(&size->base.source_position,
3340 "array size '%E' must have integer type but has type '%T'",
3345 mark_vars_read(size, NULL);
3348 if (is_static && size == NULL)
3349 errorf(&array->base.pos, "static array parameters require a size");
3351 rem_anchor_token(']');
3357 static construct_type_t *parse_function_declarator(scope_t *scope)
3359 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3361 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3362 function_type_t *ftype = &type->function;
3364 ftype->linkage = current_linkage;
3365 ftype->calling_convention = CC_DEFAULT;
3367 parse_parameters(ftype, scope);
3369 cons->function.function_type = type;
3374 typedef struct parse_declarator_env_t {
3375 bool may_be_abstract : 1;
3376 bool must_be_abstract : 1;
3377 decl_modifiers_t modifiers;
3379 source_position_t source_position;
3381 attribute_t *attributes;
3382 } parse_declarator_env_t;
3385 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3387 /* construct a single linked list of construct_type_t's which describe
3388 * how to construct the final declarator type */
3389 construct_type_t *first = NULL;
3390 construct_type_t **anchor = &first;
3392 env->attributes = parse_attributes(env->attributes);
3395 construct_type_t *type;
3396 //variable_t *based = NULL; /* MS __based extension */
3397 switch (token.kind) {
3399 type = parse_reference_declarator();
3403 panic("based not supported anymore");
3408 type = parse_pointer_declarator();
3412 goto ptr_operator_end;
3416 anchor = &type->base.next;
3418 /* TODO: find out if this is correct */
3419 env->attributes = parse_attributes(env->attributes);
3423 construct_type_t *inner_types = NULL;
3425 switch (token.kind) {
3427 if (env->must_be_abstract) {
3428 errorf(HERE, "no identifier expected in typename");
3430 env->symbol = token.identifier.symbol;
3431 env->source_position = token.base.source_position;
3437 /* Parenthesized declarator or function declarator? */
3438 token_t const *const la1 = look_ahead(1);
3439 switch (la1->kind) {
3441 if (is_typedef_symbol(la1->identifier.symbol)) {
3443 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3444 * interpreted as ``function with no parameter specification'', rather
3445 * than redundant parentheses around the omitted identifier. */
3447 /* Function declarator. */
3448 if (!env->may_be_abstract) {
3449 errorf(HERE, "function declarator must have a name");
3456 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3457 /* Paranthesized declarator. */
3459 add_anchor_token(')');
3460 inner_types = parse_inner_declarator(env);
3461 if (inner_types != NULL) {
3462 /* All later declarators only modify the return type */
3463 env->must_be_abstract = true;
3465 rem_anchor_token(')');
3474 if (env->may_be_abstract)
3476 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3481 construct_type_t **const p = anchor;
3484 construct_type_t *type;
3485 switch (token.kind) {
3487 scope_t *scope = NULL;
3488 if (!env->must_be_abstract) {
3489 scope = &env->parameters;
3492 type = parse_function_declarator(scope);
3496 type = parse_array_declarator();
3499 goto declarator_finished;
3502 /* insert in the middle of the list (at p) */
3503 type->base.next = *p;
3506 anchor = &type->base.next;
3509 declarator_finished:
3510 /* append inner_types at the end of the list, we don't to set anchor anymore
3511 * as it's not needed anymore */
3512 *anchor = inner_types;
3517 static type_t *construct_declarator_type(construct_type_t *construct_list,
3520 construct_type_t *iter = construct_list;
3521 for (; iter != NULL; iter = iter->base.next) {
3522 source_position_t const* const pos = &iter->base.pos;
3523 switch (iter->kind) {
3524 case CONSTRUCT_FUNCTION: {
3525 construct_function_type_t *function = &iter->function;
3526 type_t *function_type = function->function_type;
3528 function_type->function.return_type = type;
3530 type_t *skipped_return_type = skip_typeref(type);
3532 if (is_type_function(skipped_return_type)) {
3533 errorf(pos, "function returning function is not allowed");
3534 } else if (is_type_array(skipped_return_type)) {
3535 errorf(pos, "function returning array is not allowed");
3537 if (skipped_return_type->base.qualifiers != 0) {
3538 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3542 /* The function type was constructed earlier. Freeing it here will
3543 * destroy other types. */
3544 type = typehash_insert(function_type);
3548 case CONSTRUCT_POINTER: {
3549 if (is_type_reference(skip_typeref(type)))
3550 errorf(pos, "cannot declare a pointer to reference");
3552 parsed_pointer_t *pointer = &iter->pointer;
3553 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3557 case CONSTRUCT_REFERENCE:
3558 if (is_type_reference(skip_typeref(type)))
3559 errorf(pos, "cannot declare a reference to reference");
3561 type = make_reference_type(type);
3564 case CONSTRUCT_ARRAY: {
3565 if (is_type_reference(skip_typeref(type)))
3566 errorf(pos, "cannot declare an array of references");
3568 parsed_array_t *array = &iter->array;
3569 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3571 expression_t *size_expression = array->size;
3572 if (size_expression != NULL) {
3574 = create_implicit_cast(size_expression, type_size_t);
3577 array_type->base.qualifiers = array->type_qualifiers;
3578 array_type->array.element_type = type;
3579 array_type->array.is_static = array->is_static;
3580 array_type->array.is_variable = array->is_variable;
3581 array_type->array.size_expression = size_expression;
3583 if (size_expression != NULL) {
3584 switch (is_constant_expression(size_expression)) {
3585 case EXPR_CLASS_CONSTANT: {
3586 long const size = fold_constant_to_int(size_expression);
3587 array_type->array.size = size;
3588 array_type->array.size_constant = true;
3589 /* §6.7.5.2:1 If the expression is a constant expression,
3590 * it shall have a value greater than zero. */
3592 errorf(&size_expression->base.source_position,
3593 "size of array must be greater than zero");
3594 } else if (size == 0 && !GNU_MODE) {
3595 errorf(&size_expression->base.source_position,
3596 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3601 case EXPR_CLASS_VARIABLE:
3602 array_type->array.is_vla = true;
3605 case EXPR_CLASS_ERROR:
3610 type_t *skipped_type = skip_typeref(type);
3612 if (is_type_incomplete(skipped_type)) {
3613 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3614 } else if (is_type_function(skipped_type)) {
3615 errorf(pos, "array of functions is not allowed");
3617 type = identify_new_type(array_type);
3621 internal_errorf(pos, "invalid type construction found");
3627 static type_t *automatic_type_conversion(type_t *orig_type);
3629 static type_t *semantic_parameter(const source_position_t *pos,
3631 const declaration_specifiers_t *specifiers,
3632 entity_t const *const param)
3634 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3635 * shall be adjusted to ``qualified pointer to type'',
3637 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3638 * type'' shall be adjusted to ``pointer to function
3639 * returning type'', as in 6.3.2.1. */
3640 type = automatic_type_conversion(type);
3642 if (specifiers->is_inline && is_type_valid(type)) {
3643 errorf(pos, "'%N' declared 'inline'", param);
3646 /* §6.9.1:6 The declarations in the declaration list shall contain
3647 * no storage-class specifier other than register and no
3648 * initializations. */
3649 if (specifiers->thread_local || (
3650 specifiers->storage_class != STORAGE_CLASS_NONE &&
3651 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3653 errorf(pos, "invalid storage class for '%N'", param);
3656 /* delay test for incomplete type, because we might have (void)
3657 * which is legal but incomplete... */
3662 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3663 declarator_flags_t flags)
3665 parse_declarator_env_t env;
3666 memset(&env, 0, sizeof(env));
3667 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3669 construct_type_t *construct_type = parse_inner_declarator(&env);
3671 construct_declarator_type(construct_type, specifiers->type);
3672 type_t *type = skip_typeref(orig_type);
3674 if (construct_type != NULL) {
3675 obstack_free(&temp_obst, construct_type);
3678 attribute_t *attributes = parse_attributes(env.attributes);
3679 /* append (shared) specifier attribute behind attributes of this
3681 attribute_t **anchor = &attributes;
3682 while (*anchor != NULL)
3683 anchor = &(*anchor)->next;
3684 *anchor = specifiers->attributes;
3687 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3688 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3689 entity->typedefe.type = orig_type;
3691 if (anonymous_entity != NULL) {
3692 if (is_type_compound(type)) {
3693 assert(anonymous_entity->compound.alias == NULL);
3694 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3695 anonymous_entity->kind == ENTITY_UNION);
3696 anonymous_entity->compound.alias = entity;
3697 anonymous_entity = NULL;
3698 } else if (is_type_enum(type)) {
3699 assert(anonymous_entity->enume.alias == NULL);
3700 assert(anonymous_entity->kind == ENTITY_ENUM);
3701 anonymous_entity->enume.alias = entity;
3702 anonymous_entity = NULL;
3706 /* create a declaration type entity */
3707 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3708 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3709 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3711 if (env.symbol != NULL) {
3712 if (specifiers->is_inline && is_type_valid(type)) {
3713 errorf(&env.source_position,
3714 "compound member '%Y' declared 'inline'", env.symbol);
3717 if (specifiers->thread_local ||
3718 specifiers->storage_class != STORAGE_CLASS_NONE) {
3719 errorf(&env.source_position,
3720 "compound member '%Y' must have no storage class",
3724 } else if (flags & DECL_IS_PARAMETER) {
3725 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3726 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3727 } else if (is_type_function(type)) {
3728 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3729 entity->function.is_inline = specifiers->is_inline;
3730 entity->function.elf_visibility = default_visibility;
3731 entity->function.parameters = env.parameters;
3733 if (env.symbol != NULL) {
3734 /* this needs fixes for C++ */
3735 bool in_function_scope = current_function != NULL;
3737 if (specifiers->thread_local || (
3738 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3739 specifiers->storage_class != STORAGE_CLASS_NONE &&
3740 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3742 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3746 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3747 entity->variable.elf_visibility = default_visibility;
3748 entity->variable.thread_local = specifiers->thread_local;
3750 if (env.symbol != NULL) {
3751 if (specifiers->is_inline && is_type_valid(type)) {
3752 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3755 bool invalid_storage_class = false;
3756 if (current_scope == file_scope) {
3757 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3758 specifiers->storage_class != STORAGE_CLASS_NONE &&
3759 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3760 invalid_storage_class = true;
3763 if (specifiers->thread_local &&
3764 specifiers->storage_class == STORAGE_CLASS_NONE) {
3765 invalid_storage_class = true;
3768 if (invalid_storage_class) {
3769 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3774 entity->declaration.type = orig_type;
3775 entity->declaration.alignment = get_type_alignment(orig_type);
3776 entity->declaration.modifiers = env.modifiers;
3777 entity->declaration.attributes = attributes;
3779 storage_class_t storage_class = specifiers->storage_class;
3780 entity->declaration.declared_storage_class = storage_class;
3782 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3783 storage_class = STORAGE_CLASS_AUTO;
3784 entity->declaration.storage_class = storage_class;
3787 if (attributes != NULL) {
3788 handle_entity_attributes(attributes, entity);
3791 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3792 adapt_special_functions(&entity->function);
3798 static type_t *parse_abstract_declarator(type_t *base_type)
3800 parse_declarator_env_t env;
3801 memset(&env, 0, sizeof(env));
3802 env.may_be_abstract = true;
3803 env.must_be_abstract = true;
3805 construct_type_t *construct_type = parse_inner_declarator(&env);
3807 type_t *result = construct_declarator_type(construct_type, base_type);
3808 if (construct_type != NULL) {
3809 obstack_free(&temp_obst, construct_type);
3811 result = handle_type_attributes(env.attributes, result);
3817 * Check if the declaration of main is suspicious. main should be a
3818 * function with external linkage, returning int, taking either zero
3819 * arguments, two, or three arguments of appropriate types, ie.
3821 * int main([ int argc, char **argv [, char **env ] ]).
3823 * @param decl the declaration to check
3824 * @param type the function type of the declaration
3826 static void check_main(const entity_t *entity)
3828 const source_position_t *pos = &entity->base.source_position;
3829 if (entity->kind != ENTITY_FUNCTION) {
3830 warningf(WARN_MAIN, pos, "'main' is not a function");
3834 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3835 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3838 type_t *type = skip_typeref(entity->declaration.type);
3839 assert(is_type_function(type));
3841 function_type_t const *const func_type = &type->function;
3842 type_t *const ret_type = func_type->return_type;
3843 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3844 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3846 const function_parameter_t *parm = func_type->parameters;
3848 type_t *const first_type = skip_typeref(parm->type);
3849 type_t *const first_type_unqual = get_unqualified_type(first_type);
3850 if (!types_compatible(first_type_unqual, type_int)) {
3851 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3855 type_t *const second_type = skip_typeref(parm->type);
3856 type_t *const second_type_unqual
3857 = get_unqualified_type(second_type);
3858 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3859 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3863 type_t *const third_type = skip_typeref(parm->type);
3864 type_t *const third_type_unqual
3865 = get_unqualified_type(third_type);
3866 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3867 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3871 goto warn_arg_count;
3875 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3880 static void error_redefined_as_different_kind(const source_position_t *pos,
3881 const entity_t *old, entity_kind_t new_kind)
3883 char const *const what = get_entity_kind_name(new_kind);
3884 source_position_t const *const ppos = &old->base.source_position;
3885 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3888 static bool is_entity_valid(entity_t *const ent)
3890 if (is_declaration(ent)) {
3891 return is_type_valid(skip_typeref(ent->declaration.type));
3892 } else if (ent->kind == ENTITY_TYPEDEF) {
3893 return is_type_valid(skip_typeref(ent->typedefe.type));
3898 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3900 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3901 if (attributes_equal(tattr, attr))
3908 * test wether new_list contains any attributes not included in old_list
3910 static bool has_new_attributes(const attribute_t *old_list,
3911 const attribute_t *new_list)
3913 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3914 if (!contains_attribute(old_list, attr))
3921 * Merge in attributes from an attribute list (probably from a previous
3922 * declaration with the same name). Warning: destroys the old structure
3923 * of the attribute list - don't reuse attributes after this call.
3925 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3928 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3930 if (contains_attribute(decl->attributes, attr))
3933 /* move attribute to new declarations attributes list */
3934 attr->next = decl->attributes;
3935 decl->attributes = attr;
3939 static bool is_main(entity_t*);
3942 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3943 * for various problems that occur for multiple definitions
3945 entity_t *record_entity(entity_t *entity, const bool is_definition)
3947 const symbol_t *const symbol = entity->base.symbol;
3948 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3949 const source_position_t *pos = &entity->base.source_position;
3951 /* can happen in error cases */
3955 assert(!entity->base.parent_scope);
3956 assert(current_scope);
3957 entity->base.parent_scope = current_scope;
3959 entity_t *const previous_entity = get_entity(symbol, namespc);
3960 /* pushing the same entity twice will break the stack structure */
3961 assert(previous_entity != entity);
3963 if (entity->kind == ENTITY_FUNCTION) {
3964 type_t *const orig_type = entity->declaration.type;
3965 type_t *const type = skip_typeref(orig_type);
3967 assert(is_type_function(type));
3968 if (type->function.unspecified_parameters &&
3969 previous_entity == NULL &&
3970 !entity->declaration.implicit) {
3971 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3974 if (is_main(entity)) {
3979 if (is_declaration(entity) &&
3980 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3981 current_scope != file_scope &&
3982 !entity->declaration.implicit) {
3983 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3986 if (previous_entity != NULL) {
3987 source_position_t const *const ppos = &previous_entity->base.source_position;
3989 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3990 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3991 assert(previous_entity->kind == ENTITY_PARAMETER);
3992 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3996 if (previous_entity->base.parent_scope == current_scope) {
3997 if (previous_entity->kind != entity->kind) {
3998 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3999 error_redefined_as_different_kind(pos, previous_entity,
4004 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4005 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4008 if (previous_entity->kind == ENTITY_TYPEDEF) {
4009 type_t *const type = skip_typeref(entity->typedefe.type);
4010 type_t *const prev_type
4011 = skip_typeref(previous_entity->typedefe.type);
4012 if (c_mode & _CXX) {
4013 /* C++ allows double typedef if they are identical
4014 * (after skipping typedefs) */
4015 if (type == prev_type)
4018 /* GCC extension: redef in system headers is allowed */
4019 if ((pos->is_system_header || ppos->is_system_header) &&
4020 types_compatible(type, prev_type))
4023 errorf(pos, "redefinition of '%N' (declared %P)",
4028 /* at this point we should have only VARIABLES or FUNCTIONS */
4029 assert(is_declaration(previous_entity) && is_declaration(entity));
4031 declaration_t *const prev_decl = &previous_entity->declaration;
4032 declaration_t *const decl = &entity->declaration;
4034 /* can happen for K&R style declarations */
4035 if (prev_decl->type == NULL &&
4036 previous_entity->kind == ENTITY_PARAMETER &&
4037 entity->kind == ENTITY_PARAMETER) {
4038 prev_decl->type = decl->type;
4039 prev_decl->storage_class = decl->storage_class;
4040 prev_decl->declared_storage_class = decl->declared_storage_class;
4041 prev_decl->modifiers = decl->modifiers;
4042 return previous_entity;
4045 type_t *const type = skip_typeref(decl->type);
4046 type_t *const prev_type = skip_typeref(prev_decl->type);
4048 if (!types_compatible(type, prev_type)) {
4049 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4051 unsigned old_storage_class = prev_decl->storage_class;
4053 if (is_definition &&
4055 !(prev_decl->modifiers & DM_USED) &&
4056 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4057 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4060 storage_class_t new_storage_class = decl->storage_class;
4062 /* pretend no storage class means extern for function
4063 * declarations (except if the previous declaration is neither
4064 * none nor extern) */
4065 if (entity->kind == ENTITY_FUNCTION) {
4066 /* the previous declaration could have unspecified parameters or
4067 * be a typedef, so use the new type */
4068 if (prev_type->function.unspecified_parameters || is_definition)
4069 prev_decl->type = type;
4071 switch (old_storage_class) {
4072 case STORAGE_CLASS_NONE:
4073 old_storage_class = STORAGE_CLASS_EXTERN;
4076 case STORAGE_CLASS_EXTERN:
4077 if (is_definition) {
4078 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4079 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4081 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4082 new_storage_class = STORAGE_CLASS_EXTERN;
4089 } else if (is_type_incomplete(prev_type)) {
4090 prev_decl->type = type;
4093 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4094 new_storage_class == STORAGE_CLASS_EXTERN) {
4096 warn_redundant_declaration: ;
4098 = has_new_attributes(prev_decl->attributes,
4100 if (has_new_attrs) {
4101 merge_in_attributes(decl, prev_decl->attributes);
4102 } else if (!is_definition &&
4103 is_type_valid(prev_type) &&
4104 !pos->is_system_header) {
4105 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4107 } else if (current_function == NULL) {
4108 if (old_storage_class != STORAGE_CLASS_STATIC &&
4109 new_storage_class == STORAGE_CLASS_STATIC) {
4110 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4111 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4112 prev_decl->storage_class = STORAGE_CLASS_NONE;
4113 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4115 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4117 goto error_redeclaration;
4118 goto warn_redundant_declaration;
4120 } else if (is_type_valid(prev_type)) {
4121 if (old_storage_class == new_storage_class) {
4122 error_redeclaration:
4123 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4125 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4130 prev_decl->modifiers |= decl->modifiers;
4131 if (entity->kind == ENTITY_FUNCTION) {
4132 previous_entity->function.is_inline |= entity->function.is_inline;
4134 return previous_entity;
4138 if (is_warn_on(why = WARN_SHADOW) ||
4139 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4140 char const *const what = get_entity_kind_name(previous_entity->kind);
4141 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4145 if (entity->kind == ENTITY_FUNCTION) {
4146 if (is_definition &&
4147 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4149 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4150 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4152 goto warn_missing_declaration;
4155 } else if (entity->kind == ENTITY_VARIABLE) {
4156 if (current_scope == file_scope &&
4157 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4158 !entity->declaration.implicit) {
4159 warn_missing_declaration:
4160 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4165 environment_push(entity);
4166 append_entity(current_scope, entity);
4171 static void parser_error_multiple_definition(entity_t *entity,
4172 const source_position_t *source_position)
4174 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4175 entity->base.symbol, &entity->base.source_position);
4178 static bool is_declaration_specifier(const token_t *token)
4180 switch (token->kind) {
4184 return is_typedef_symbol(token->identifier.symbol);
4191 static void parse_init_declarator_rest(entity_t *entity)
4193 type_t *orig_type = type_error_type;
4195 if (entity->base.kind == ENTITY_TYPEDEF) {
4196 source_position_t const *const pos = &entity->base.source_position;
4197 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4199 assert(is_declaration(entity));
4200 orig_type = entity->declaration.type;
4203 type_t *type = skip_typeref(orig_type);
4205 if (entity->kind == ENTITY_VARIABLE
4206 && entity->variable.initializer != NULL) {
4207 parser_error_multiple_definition(entity, HERE);
4211 declaration_t *const declaration = &entity->declaration;
4212 bool must_be_constant = false;
4213 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4214 entity->base.parent_scope == file_scope) {
4215 must_be_constant = true;
4218 if (is_type_function(type)) {
4219 source_position_t const *const pos = &entity->base.source_position;
4220 errorf(pos, "'%N' is initialized like a variable", entity);
4221 orig_type = type_error_type;
4224 parse_initializer_env_t env;
4225 env.type = orig_type;
4226 env.must_be_constant = must_be_constant;
4227 env.entity = entity;
4229 initializer_t *initializer = parse_initializer(&env);
4231 if (entity->kind == ENTITY_VARIABLE) {
4232 /* §6.7.5:22 array initializers for arrays with unknown size
4233 * determine the array type size */
4234 declaration->type = env.type;
4235 entity->variable.initializer = initializer;
4239 /* parse rest of a declaration without any declarator */
4240 static void parse_anonymous_declaration_rest(
4241 const declaration_specifiers_t *specifiers)
4244 anonymous_entity = NULL;
4246 source_position_t const *const pos = &specifiers->source_position;
4247 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4248 specifiers->thread_local) {
4249 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4252 type_t *type = specifiers->type;
4253 switch (type->kind) {
4254 case TYPE_COMPOUND_STRUCT:
4255 case TYPE_COMPOUND_UNION: {
4256 if (type->compound.compound->base.symbol == NULL) {
4257 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4266 warningf(WARN_OTHER, pos, "empty declaration");
4271 static void check_variable_type_complete(entity_t *ent)
4273 if (ent->kind != ENTITY_VARIABLE)
4276 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4277 * type for the object shall be complete [...] */
4278 declaration_t *decl = &ent->declaration;
4279 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4280 decl->storage_class == STORAGE_CLASS_STATIC)
4283 type_t *const type = skip_typeref(decl->type);
4284 if (!is_type_incomplete(type))
4287 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4288 * are given length one. */
4289 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4290 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4294 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4298 static void parse_declaration_rest(entity_t *ndeclaration,
4299 const declaration_specifiers_t *specifiers,
4300 parsed_declaration_func finished_declaration,
4301 declarator_flags_t flags)
4303 add_anchor_token(';');
4304 add_anchor_token(',');
4306 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4308 if (token.kind == '=') {
4309 parse_init_declarator_rest(entity);
4310 } else if (entity->kind == ENTITY_VARIABLE) {
4311 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4312 * [...] where the extern specifier is explicitly used. */
4313 declaration_t *decl = &entity->declaration;
4314 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4315 is_type_reference(skip_typeref(decl->type))) {
4316 source_position_t const *const pos = &entity->base.source_position;
4317 errorf(pos, "reference '%#N' must be initialized", entity);
4321 check_variable_type_complete(entity);
4326 add_anchor_token('=');
4327 ndeclaration = parse_declarator(specifiers, flags);
4328 rem_anchor_token('=');
4330 rem_anchor_token(',');
4331 rem_anchor_token(';');
4334 anonymous_entity = NULL;
4337 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4339 symbol_t *symbol = entity->base.symbol;
4343 assert(entity->base.namespc == NAMESPACE_NORMAL);
4344 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4345 if (previous_entity == NULL
4346 || previous_entity->base.parent_scope != current_scope) {
4347 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4352 if (is_definition) {
4353 errorf(HERE, "'%N' is initialised", entity);
4356 return record_entity(entity, false);
4359 static void parse_declaration(parsed_declaration_func finished_declaration,
4360 declarator_flags_t flags)
4362 add_anchor_token(';');
4363 declaration_specifiers_t specifiers;
4364 parse_declaration_specifiers(&specifiers);
4365 rem_anchor_token(';');
4367 if (token.kind == ';') {
4368 parse_anonymous_declaration_rest(&specifiers);
4370 entity_t *entity = parse_declarator(&specifiers, flags);
4371 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4376 static type_t *get_default_promoted_type(type_t *orig_type)
4378 type_t *result = orig_type;
4380 type_t *type = skip_typeref(orig_type);
4381 if (is_type_integer(type)) {
4382 result = promote_integer(type);
4383 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4384 result = type_double;
4390 static void parse_kr_declaration_list(entity_t *entity)
4392 if (entity->kind != ENTITY_FUNCTION)
4395 type_t *type = skip_typeref(entity->declaration.type);
4396 assert(is_type_function(type));
4397 if (!type->function.kr_style_parameters)
4400 add_anchor_token('{');
4402 PUSH_SCOPE(&entity->function.parameters);
4404 entity_t *parameter = entity->function.parameters.entities;
4405 for ( ; parameter != NULL; parameter = parameter->base.next) {
4406 assert(parameter->base.parent_scope == NULL);
4407 parameter->base.parent_scope = current_scope;
4408 environment_push(parameter);
4411 /* parse declaration list */
4413 switch (token.kind) {
4415 /* This covers symbols, which are no type, too, and results in
4416 * better error messages. The typical cases are misspelled type
4417 * names and missing includes. */
4419 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4429 /* update function type */
4430 type_t *new_type = duplicate_type(type);
4432 function_parameter_t *parameters = NULL;
4433 function_parameter_t **anchor = ¶meters;
4435 /* did we have an earlier prototype? */
4436 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4437 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4440 function_parameter_t *proto_parameter = NULL;
4441 if (proto_type != NULL) {
4442 type_t *proto_type_type = proto_type->declaration.type;
4443 proto_parameter = proto_type_type->function.parameters;
4444 /* If a K&R function definition has a variadic prototype earlier, then
4445 * make the function definition variadic, too. This should conform to
4446 * §6.7.5.3:15 and §6.9.1:8. */
4447 new_type->function.variadic = proto_type_type->function.variadic;
4449 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4451 new_type->function.unspecified_parameters = true;
4454 bool need_incompatible_warning = false;
4455 parameter = entity->function.parameters.entities;
4456 for (; parameter != NULL; parameter = parameter->base.next,
4458 proto_parameter == NULL ? NULL : proto_parameter->next) {
4459 if (parameter->kind != ENTITY_PARAMETER)
4462 type_t *parameter_type = parameter->declaration.type;
4463 if (parameter_type == NULL) {
4464 source_position_t const* const pos = ¶meter->base.source_position;
4466 errorf(pos, "no type specified for function '%N'", parameter);
4467 parameter_type = type_error_type;
4469 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4470 parameter_type = type_int;
4472 parameter->declaration.type = parameter_type;
4475 semantic_parameter_incomplete(parameter);
4477 /* we need the default promoted types for the function type */
4478 type_t *not_promoted = parameter_type;
4479 parameter_type = get_default_promoted_type(parameter_type);
4481 /* gcc special: if the type of the prototype matches the unpromoted
4482 * type don't promote */
4483 if (!strict_mode && proto_parameter != NULL) {
4484 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4485 type_t *promo_skip = skip_typeref(parameter_type);
4486 type_t *param_skip = skip_typeref(not_promoted);
4487 if (!types_compatible(proto_p_type, promo_skip)
4488 && types_compatible(proto_p_type, param_skip)) {
4490 need_incompatible_warning = true;
4491 parameter_type = not_promoted;
4494 function_parameter_t *const function_parameter
4495 = allocate_parameter(parameter_type);
4497 *anchor = function_parameter;
4498 anchor = &function_parameter->next;
4501 new_type->function.parameters = parameters;
4502 new_type = identify_new_type(new_type);
4504 if (need_incompatible_warning) {
4505 symbol_t const *const sym = entity->base.symbol;
4506 source_position_t const *const pos = &entity->base.source_position;
4507 source_position_t const *const ppos = &proto_type->base.source_position;
4508 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4510 entity->declaration.type = new_type;
4512 rem_anchor_token('{');
4515 static bool first_err = true;
4518 * When called with first_err set, prints the name of the current function,
4521 static void print_in_function(void)
4525 char const *const file = current_function->base.base.source_position.input_name;
4526 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4531 * Check if all labels are defined in the current function.
4532 * Check if all labels are used in the current function.
4534 static void check_labels(void)
4536 for (const goto_statement_t *goto_statement = goto_first;
4537 goto_statement != NULL;
4538 goto_statement = goto_statement->next) {
4539 label_t *label = goto_statement->label;
4540 if (label->base.source_position.input_name == NULL) {
4541 print_in_function();
4542 source_position_t const *const pos = &goto_statement->base.source_position;
4543 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4547 if (is_warn_on(WARN_UNUSED_LABEL)) {
4548 for (const label_statement_t *label_statement = label_first;
4549 label_statement != NULL;
4550 label_statement = label_statement->next) {
4551 label_t *label = label_statement->label;
4553 if (! label->used) {
4554 print_in_function();
4555 source_position_t const *const pos = &label_statement->base.source_position;
4556 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4562 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4564 entity_t const *const end = last != NULL ? last->base.next : NULL;
4565 for (; entity != end; entity = entity->base.next) {
4566 if (!is_declaration(entity))
4569 declaration_t *declaration = &entity->declaration;
4570 if (declaration->implicit)
4573 if (!declaration->used) {
4574 print_in_function();
4575 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4576 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4577 print_in_function();
4578 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4583 static void check_unused_variables(statement_t *const stmt, void *const env)
4587 switch (stmt->kind) {
4588 case STATEMENT_DECLARATION: {
4589 declaration_statement_t const *const decls = &stmt->declaration;
4590 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4595 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4604 * Check declarations of current_function for unused entities.
4606 static void check_declarations(void)
4608 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4609 const scope_t *scope = ¤t_function->parameters;
4610 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4612 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4613 walk_statements(current_function->statement, check_unused_variables,
4618 static int determine_truth(expression_t const* const cond)
4621 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4622 fold_constant_to_bool(cond) ? 1 :
4626 static void check_reachable(statement_t *);
4627 static bool reaches_end;
4629 static bool expression_returns(expression_t const *const expr)
4631 switch (expr->kind) {
4633 expression_t const *const func = expr->call.function;
4634 type_t const *const type = skip_typeref(func->base.type);
4635 if (type->kind == TYPE_POINTER) {
4636 type_t const *const points_to
4637 = skip_typeref(type->pointer.points_to);
4638 if (points_to->kind == TYPE_FUNCTION
4639 && points_to->function.modifiers & DM_NORETURN)
4643 if (!expression_returns(func))
4646 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4647 if (!expression_returns(arg->expression))
4654 case EXPR_REFERENCE:
4655 case EXPR_ENUM_CONSTANT:
4656 case EXPR_LITERAL_CASES:
4657 case EXPR_STRING_LITERAL:
4658 case EXPR_WIDE_STRING_LITERAL:
4659 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4660 case EXPR_LABEL_ADDRESS:
4661 case EXPR_CLASSIFY_TYPE:
4662 case EXPR_SIZEOF: // TODO handle obscure VLA case
4665 case EXPR_BUILTIN_CONSTANT_P:
4666 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4671 case EXPR_STATEMENT: {
4672 bool old_reaches_end = reaches_end;
4673 reaches_end = false;
4674 check_reachable(expr->statement.statement);
4675 bool returns = reaches_end;
4676 reaches_end = old_reaches_end;
4680 case EXPR_CONDITIONAL:
4681 // TODO handle constant expression
4683 if (!expression_returns(expr->conditional.condition))
4686 if (expr->conditional.true_expression != NULL
4687 && expression_returns(expr->conditional.true_expression))
4690 return expression_returns(expr->conditional.false_expression);
4693 return expression_returns(expr->select.compound);
4695 case EXPR_ARRAY_ACCESS:
4697 expression_returns(expr->array_access.array_ref) &&
4698 expression_returns(expr->array_access.index);
4701 return expression_returns(expr->va_starte.ap);
4704 return expression_returns(expr->va_arge.ap);
4707 return expression_returns(expr->va_copye.src);
4709 case EXPR_UNARY_CASES_MANDATORY:
4710 return expression_returns(expr->unary.value);
4712 case EXPR_UNARY_THROW:
4715 case EXPR_BINARY_CASES:
4716 // TODO handle constant lhs of && and ||
4718 expression_returns(expr->binary.left) &&
4719 expression_returns(expr->binary.right);
4722 panic("unhandled expression");
4725 static bool initializer_returns(initializer_t const *const init)
4727 switch (init->kind) {
4728 case INITIALIZER_VALUE:
4729 return expression_returns(init->value.value);
4731 case INITIALIZER_LIST: {
4732 initializer_t * const* i = init->list.initializers;
4733 initializer_t * const* const end = i + init->list.len;
4734 bool returns = true;
4735 for (; i != end; ++i) {
4736 if (!initializer_returns(*i))
4742 case INITIALIZER_STRING:
4743 case INITIALIZER_WIDE_STRING:
4744 case INITIALIZER_DESIGNATOR: // designators have no payload
4747 panic("unhandled initializer");
4750 static bool noreturn_candidate;
4752 static void check_reachable(statement_t *const stmt)
4754 if (stmt->base.reachable)
4756 if (stmt->kind != STATEMENT_DO_WHILE)
4757 stmt->base.reachable = true;
4759 statement_t *last = stmt;
4761 switch (stmt->kind) {
4762 case STATEMENT_ERROR:
4763 case STATEMENT_EMPTY:
4765 next = stmt->base.next;
4768 case STATEMENT_DECLARATION: {
4769 declaration_statement_t const *const decl = &stmt->declaration;
4770 entity_t const * ent = decl->declarations_begin;
4771 entity_t const *const last_decl = decl->declarations_end;
4773 for (;; ent = ent->base.next) {
4774 if (ent->kind == ENTITY_VARIABLE &&
4775 ent->variable.initializer != NULL &&
4776 !initializer_returns(ent->variable.initializer)) {
4779 if (ent == last_decl)
4783 next = stmt->base.next;
4787 case STATEMENT_COMPOUND:
4788 next = stmt->compound.statements;
4790 next = stmt->base.next;
4793 case STATEMENT_RETURN: {
4794 expression_t const *const val = stmt->returns.value;
4795 if (val == NULL || expression_returns(val))
4796 noreturn_candidate = false;
4800 case STATEMENT_IF: {
4801 if_statement_t const *const ifs = &stmt->ifs;
4802 expression_t const *const cond = ifs->condition;
4804 if (!expression_returns(cond))
4807 int const val = determine_truth(cond);
4810 check_reachable(ifs->true_statement);
4815 if (ifs->false_statement != NULL) {
4816 check_reachable(ifs->false_statement);
4820 next = stmt->base.next;
4824 case STATEMENT_SWITCH: {
4825 switch_statement_t const *const switchs = &stmt->switchs;
4826 expression_t const *const expr = switchs->expression;
4828 if (!expression_returns(expr))
4831 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4832 long const val = fold_constant_to_int(expr);
4833 case_label_statement_t * defaults = NULL;
4834 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4835 if (i->expression == NULL) {
4840 if (i->first_case <= val && val <= i->last_case) {
4841 check_reachable((statement_t*)i);
4846 if (defaults != NULL) {
4847 check_reachable((statement_t*)defaults);
4851 bool has_default = false;
4852 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4853 if (i->expression == NULL)
4856 check_reachable((statement_t*)i);
4863 next = stmt->base.next;
4867 case STATEMENT_EXPRESSION: {
4868 /* Check for noreturn function call */
4869 expression_t const *const expr = stmt->expression.expression;
4870 if (!expression_returns(expr))
4873 next = stmt->base.next;
4877 case STATEMENT_CONTINUE:
4878 for (statement_t *parent = stmt;;) {
4879 parent = parent->base.parent;
4880 if (parent == NULL) /* continue not within loop */
4884 switch (parent->kind) {
4885 case STATEMENT_WHILE: goto continue_while;
4886 case STATEMENT_DO_WHILE: goto continue_do_while;
4887 case STATEMENT_FOR: goto continue_for;
4893 case STATEMENT_BREAK:
4894 for (statement_t *parent = stmt;;) {
4895 parent = parent->base.parent;
4896 if (parent == NULL) /* break not within loop/switch */
4899 switch (parent->kind) {
4900 case STATEMENT_SWITCH:
4901 case STATEMENT_WHILE:
4902 case STATEMENT_DO_WHILE:
4905 next = parent->base.next;
4906 goto found_break_parent;
4914 case STATEMENT_COMPUTED_GOTO: {
4915 if (!expression_returns(stmt->computed_goto.expression))
4918 statement_t *parent = stmt->base.parent;
4919 if (parent == NULL) /* top level goto */
4925 case STATEMENT_GOTO:
4926 next = stmt->gotos.label->statement;
4927 if (next == NULL) /* missing label */
4931 case STATEMENT_LABEL:
4932 next = stmt->label.statement;
4935 case STATEMENT_CASE_LABEL:
4936 next = stmt->case_label.statement;
4939 case STATEMENT_WHILE: {
4940 while_statement_t const *const whiles = &stmt->whiles;
4941 expression_t const *const cond = whiles->condition;
4943 if (!expression_returns(cond))
4946 int const val = determine_truth(cond);
4949 check_reachable(whiles->body);
4954 next = stmt->base.next;
4958 case STATEMENT_DO_WHILE:
4959 next = stmt->do_while.body;
4962 case STATEMENT_FOR: {
4963 for_statement_t *const fors = &stmt->fors;
4965 if (fors->condition_reachable)
4967 fors->condition_reachable = true;
4969 expression_t const *const cond = fors->condition;
4974 } else if (expression_returns(cond)) {
4975 val = determine_truth(cond);
4981 check_reachable(fors->body);
4986 next = stmt->base.next;
4990 case STATEMENT_MS_TRY: {
4991 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4992 check_reachable(ms_try->try_statement);
4993 next = ms_try->final_statement;
4997 case STATEMENT_LEAVE: {
4998 statement_t *parent = stmt;
5000 parent = parent->base.parent;
5001 if (parent == NULL) /* __leave not within __try */
5004 if (parent->kind == STATEMENT_MS_TRY) {
5006 next = parent->ms_try.final_statement;
5014 panic("invalid statement kind");
5017 while (next == NULL) {
5018 next = last->base.parent;
5020 noreturn_candidate = false;
5022 type_t *const type = skip_typeref(current_function->base.type);
5023 assert(is_type_function(type));
5024 type_t *const ret = skip_typeref(type->function.return_type);
5025 if (!is_type_void(ret) &&
5026 is_type_valid(ret) &&
5027 !is_main(current_entity)) {
5028 source_position_t const *const pos = &stmt->base.source_position;
5029 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5034 switch (next->kind) {
5035 case STATEMENT_ERROR:
5036 case STATEMENT_EMPTY:
5037 case STATEMENT_DECLARATION:
5038 case STATEMENT_EXPRESSION:
5040 case STATEMENT_RETURN:
5041 case STATEMENT_CONTINUE:
5042 case STATEMENT_BREAK:
5043 case STATEMENT_COMPUTED_GOTO:
5044 case STATEMENT_GOTO:
5045 case STATEMENT_LEAVE:
5046 panic("invalid control flow in function");
5048 case STATEMENT_COMPOUND:
5049 if (next->compound.stmt_expr) {
5055 case STATEMENT_SWITCH:
5056 case STATEMENT_LABEL:
5057 case STATEMENT_CASE_LABEL:
5059 next = next->base.next;
5062 case STATEMENT_WHILE: {
5064 if (next->base.reachable)
5066 next->base.reachable = true;
5068 while_statement_t const *const whiles = &next->whiles;
5069 expression_t const *const cond = whiles->condition;
5071 if (!expression_returns(cond))
5074 int const val = determine_truth(cond);
5077 check_reachable(whiles->body);
5083 next = next->base.next;
5087 case STATEMENT_DO_WHILE: {
5089 if (next->base.reachable)
5091 next->base.reachable = true;
5093 do_while_statement_t const *const dw = &next->do_while;
5094 expression_t const *const cond = dw->condition;
5096 if (!expression_returns(cond))
5099 int const val = determine_truth(cond);
5102 check_reachable(dw->body);
5108 next = next->base.next;
5112 case STATEMENT_FOR: {
5114 for_statement_t *const fors = &next->fors;
5116 fors->step_reachable = true;
5118 if (fors->condition_reachable)
5120 fors->condition_reachable = true;
5122 expression_t const *const cond = fors->condition;
5127 } else if (expression_returns(cond)) {
5128 val = determine_truth(cond);
5134 check_reachable(fors->body);
5140 next = next->base.next;
5144 case STATEMENT_MS_TRY:
5146 next = next->ms_try.final_statement;
5151 check_reachable(next);
5154 static void check_unreachable(statement_t* const stmt, void *const env)
5158 switch (stmt->kind) {
5159 case STATEMENT_DO_WHILE:
5160 if (!stmt->base.reachable) {
5161 expression_t const *const cond = stmt->do_while.condition;
5162 if (determine_truth(cond) >= 0) {
5163 source_position_t const *const pos = &cond->base.source_position;
5164 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5169 case STATEMENT_FOR: {
5170 for_statement_t const* const fors = &stmt->fors;
5172 // if init and step are unreachable, cond is unreachable, too
5173 if (!stmt->base.reachable && !fors->step_reachable) {
5174 goto warn_unreachable;
5176 if (!stmt->base.reachable && fors->initialisation != NULL) {
5177 source_position_t const *const pos = &fors->initialisation->base.source_position;
5178 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5181 if (!fors->condition_reachable && fors->condition != NULL) {
5182 source_position_t const *const pos = &fors->condition->base.source_position;
5183 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5186 if (!fors->step_reachable && fors->step != NULL) {
5187 source_position_t const *const pos = &fors->step->base.source_position;
5188 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5194 case STATEMENT_COMPOUND:
5195 if (stmt->compound.statements != NULL)
5197 goto warn_unreachable;
5199 case STATEMENT_DECLARATION: {
5200 /* Only warn if there is at least one declarator with an initializer.
5201 * This typically occurs in switch statements. */
5202 declaration_statement_t const *const decl = &stmt->declaration;
5203 entity_t const * ent = decl->declarations_begin;
5204 entity_t const *const last = decl->declarations_end;
5206 for (;; ent = ent->base.next) {
5207 if (ent->kind == ENTITY_VARIABLE &&
5208 ent->variable.initializer != NULL) {
5209 goto warn_unreachable;
5219 if (!stmt->base.reachable) {
5220 source_position_t const *const pos = &stmt->base.source_position;
5221 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5227 static bool is_main(entity_t *entity)
5229 static symbol_t *sym_main = NULL;
5230 if (sym_main == NULL) {
5231 sym_main = symbol_table_insert("main");
5234 if (entity->base.symbol != sym_main)
5236 /* must be in outermost scope */
5237 if (entity->base.parent_scope != file_scope)
5243 static void prepare_main_collect2(entity_t*);
5245 static void parse_external_declaration(void)
5247 /* function-definitions and declarations both start with declaration
5249 add_anchor_token(';');
5250 declaration_specifiers_t specifiers;
5251 parse_declaration_specifiers(&specifiers);
5252 rem_anchor_token(';');
5254 /* must be a declaration */
5255 if (token.kind == ';') {
5256 parse_anonymous_declaration_rest(&specifiers);
5260 add_anchor_token(',');
5261 add_anchor_token('=');
5262 add_anchor_token(';');
5263 add_anchor_token('{');
5265 /* declarator is common to both function-definitions and declarations */
5266 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5268 rem_anchor_token('{');
5269 rem_anchor_token(';');
5270 rem_anchor_token('=');
5271 rem_anchor_token(',');
5273 /* must be a declaration */
5274 switch (token.kind) {
5278 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5283 /* must be a function definition */
5284 parse_kr_declaration_list(ndeclaration);
5286 if (token.kind != '{') {
5287 parse_error_expected("while parsing function definition", '{', NULL);
5288 eat_until_matching_token(';');
5292 assert(is_declaration(ndeclaration));
5293 type_t *const orig_type = ndeclaration->declaration.type;
5294 type_t * type = skip_typeref(orig_type);
5296 if (!is_type_function(type)) {
5297 if (is_type_valid(type)) {
5298 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5304 source_position_t const *const pos = &ndeclaration->base.source_position;
5305 if (is_typeref(orig_type)) {
5307 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5310 if (is_type_compound(skip_typeref(type->function.return_type))) {
5311 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5313 if (type->function.unspecified_parameters) {
5314 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5316 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5319 /* §6.7.5.3:14 a function definition with () means no
5320 * parameters (and not unspecified parameters) */
5321 if (type->function.unspecified_parameters &&
5322 type->function.parameters == NULL) {
5323 type_t *copy = duplicate_type(type);
5324 copy->function.unspecified_parameters = false;
5325 type = identify_new_type(copy);
5327 ndeclaration->declaration.type = type;
5330 entity_t *const entity = record_entity(ndeclaration, true);
5331 assert(entity->kind == ENTITY_FUNCTION);
5332 assert(ndeclaration->kind == ENTITY_FUNCTION);
5334 function_t *const function = &entity->function;
5335 if (ndeclaration != entity) {
5336 function->parameters = ndeclaration->function.parameters;
5339 PUSH_SCOPE(&function->parameters);
5341 entity_t *parameter = function->parameters.entities;
5342 for (; parameter != NULL; parameter = parameter->base.next) {
5343 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5344 parameter->base.parent_scope = current_scope;
5346 assert(parameter->base.parent_scope == NULL
5347 || parameter->base.parent_scope == current_scope);
5348 parameter->base.parent_scope = current_scope;
5349 if (parameter->base.symbol == NULL) {
5350 errorf(¶meter->base.source_position, "parameter name omitted");
5353 environment_push(parameter);
5356 if (function->statement != NULL) {
5357 parser_error_multiple_definition(entity, HERE);
5360 /* parse function body */
5361 int label_stack_top = label_top();
5362 function_t *old_current_function = current_function;
5363 current_function = function;
5364 PUSH_CURRENT_ENTITY(entity);
5368 goto_anchor = &goto_first;
5370 label_anchor = &label_first;
5372 statement_t *const body = parse_compound_statement(false);
5373 function->statement = body;
5376 check_declarations();
5377 if (is_warn_on(WARN_RETURN_TYPE) ||
5378 is_warn_on(WARN_UNREACHABLE_CODE) ||
5379 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5380 noreturn_candidate = true;
5381 check_reachable(body);
5382 if (is_warn_on(WARN_UNREACHABLE_CODE))
5383 walk_statements(body, check_unreachable, NULL);
5384 if (noreturn_candidate &&
5385 !(function->base.modifiers & DM_NORETURN)) {
5386 source_position_t const *const pos = &body->base.source_position;
5387 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5391 if (is_main(entity)) {
5392 /* Force main to C linkage. */
5393 type_t *const type = entity->declaration.type;
5394 assert(is_type_function(type));
5395 if (type->function.linkage != LINKAGE_C) {
5396 type_t *new_type = duplicate_type(type);
5397 new_type->function.linkage = LINKAGE_C;
5398 entity->declaration.type = identify_new_type(new_type);
5401 if (enable_main_collect2_hack)
5402 prepare_main_collect2(entity);
5405 POP_CURRENT_ENTITY();
5407 assert(current_function == function);
5408 current_function = old_current_function;
5409 label_pop_to(label_stack_top);
5415 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5417 entity_t *iter = compound->members.entities;
5418 for (; iter != NULL; iter = iter->base.next) {
5419 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5422 if (iter->base.symbol == symbol) {
5424 } else if (iter->base.symbol == NULL) {
5425 /* search in anonymous structs and unions */
5426 type_t *type = skip_typeref(iter->declaration.type);
5427 if (is_type_compound(type)) {
5428 if (find_compound_entry(type->compound.compound, symbol)
5439 static void check_deprecated(const source_position_t *source_position,
5440 const entity_t *entity)
5442 if (!is_declaration(entity))
5444 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5447 source_position_t const *const epos = &entity->base.source_position;
5448 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5450 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5452 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5457 static expression_t *create_select(const source_position_t *pos,
5459 type_qualifiers_t qualifiers,
5462 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5464 check_deprecated(pos, entry);
5466 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5467 select->select.compound = addr;
5468 select->select.compound_entry = entry;
5470 type_t *entry_type = entry->declaration.type;
5471 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5473 /* bitfields need special treatment */
5474 if (entry->compound_member.bitfield) {
5475 unsigned bit_size = entry->compound_member.bit_size;
5476 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5477 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5478 res_type = type_int;
5482 /* we always do the auto-type conversions; the & and sizeof parser contains
5483 * code to revert this! */
5484 select->base.type = automatic_type_conversion(res_type);
5491 * Find entry with symbol in compound. Search anonymous structs and unions and
5492 * creates implicit select expressions for them.
5493 * Returns the adress for the innermost compound.
5495 static expression_t *find_create_select(const source_position_t *pos,
5497 type_qualifiers_t qualifiers,
5498 compound_t *compound, symbol_t *symbol)
5500 entity_t *iter = compound->members.entities;
5501 for (; iter != NULL; iter = iter->base.next) {
5502 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5505 symbol_t *iter_symbol = iter->base.symbol;
5506 if (iter_symbol == NULL) {
5507 type_t *type = iter->declaration.type;
5508 if (type->kind != TYPE_COMPOUND_STRUCT
5509 && type->kind != TYPE_COMPOUND_UNION)
5512 compound_t *sub_compound = type->compound.compound;
5514 if (find_compound_entry(sub_compound, symbol) == NULL)
5517 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5518 sub_addr->base.source_position = *pos;
5519 sub_addr->base.implicit = true;
5520 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5524 if (iter_symbol == symbol) {
5525 return create_select(pos, addr, qualifiers, iter);
5532 static void parse_bitfield_member(entity_t *entity)
5536 expression_t *size = parse_constant_expression();
5539 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5540 type_t *type = entity->declaration.type;
5541 if (!is_type_integer(skip_typeref(type))) {
5542 errorf(HERE, "bitfield base type '%T' is not an integer type",
5546 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5547 /* error already reported by parse_constant_expression */
5548 size_long = get_type_size(type) * 8;
5550 size_long = fold_constant_to_int(size);
5552 const symbol_t *symbol = entity->base.symbol;
5553 const symbol_t *user_symbol
5554 = symbol == NULL ? sym_anonymous : symbol;
5555 unsigned bit_size = get_type_size(type) * 8;
5556 if (size_long < 0) {
5557 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5558 } else if (size_long == 0 && symbol != NULL) {
5559 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5560 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5561 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5564 /* hope that people don't invent crazy types with more bits
5565 * than our struct can hold */
5567 (1 << sizeof(entity->compound_member.bit_size)*8));
5571 entity->compound_member.bitfield = true;
5572 entity->compound_member.bit_size = (unsigned char)size_long;
5575 static void parse_compound_declarators(compound_t *compound,
5576 const declaration_specifiers_t *specifiers)
5578 add_anchor_token(';');
5579 add_anchor_token(',');
5583 if (token.kind == ':') {
5584 /* anonymous bitfield */
5585 type_t *type = specifiers->type;
5586 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5587 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5588 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5589 entity->declaration.type = type;
5591 parse_bitfield_member(entity);
5593 attribute_t *attributes = parse_attributes(NULL);
5594 attribute_t **anchor = &attributes;
5595 while (*anchor != NULL)
5596 anchor = &(*anchor)->next;
5597 *anchor = specifiers->attributes;
5598 if (attributes != NULL) {
5599 handle_entity_attributes(attributes, entity);
5601 entity->declaration.attributes = attributes;
5603 append_entity(&compound->members, entity);
5605 entity = parse_declarator(specifiers,
5606 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5607 source_position_t const *const pos = &entity->base.source_position;
5608 if (entity->kind == ENTITY_TYPEDEF) {
5609 errorf(pos, "typedef not allowed as compound member");
5611 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5613 /* make sure we don't define a symbol multiple times */
5614 symbol_t *symbol = entity->base.symbol;
5615 if (symbol != NULL) {
5616 entity_t *prev = find_compound_entry(compound, symbol);
5618 source_position_t const *const ppos = &prev->base.source_position;
5619 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5623 if (token.kind == ':') {
5624 parse_bitfield_member(entity);
5626 attribute_t *attributes = parse_attributes(NULL);
5627 handle_entity_attributes(attributes, entity);
5629 type_t *orig_type = entity->declaration.type;
5630 type_t *type = skip_typeref(orig_type);
5631 if (is_type_function(type)) {
5632 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5633 } else if (is_type_incomplete(type)) {
5634 /* §6.7.2.1:16 flexible array member */
5635 if (!is_type_array(type) ||
5636 token.kind != ';' ||
5637 look_ahead(1)->kind != '}') {
5638 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5639 } else if (compound->members.entities == NULL) {
5640 errorf(pos, "flexible array member in otherwise empty struct");
5645 append_entity(&compound->members, entity);
5648 } while (next_if(','));
5649 rem_anchor_token(',');
5650 rem_anchor_token(';');
5653 anonymous_entity = NULL;
5656 static void parse_compound_type_entries(compound_t *compound)
5659 add_anchor_token('}');
5662 switch (token.kind) {
5664 case T___extension__:
5665 case T_IDENTIFIER: {
5667 declaration_specifiers_t specifiers;
5668 parse_declaration_specifiers(&specifiers);
5669 parse_compound_declarators(compound, &specifiers);
5675 rem_anchor_token('}');
5678 compound->complete = true;
5684 static type_t *parse_typename(void)
5686 declaration_specifiers_t specifiers;
5687 parse_declaration_specifiers(&specifiers);
5688 if (specifiers.storage_class != STORAGE_CLASS_NONE
5689 || specifiers.thread_local) {
5690 /* TODO: improve error message, user does probably not know what a
5691 * storage class is...
5693 errorf(&specifiers.source_position, "typename must not have a storage class");
5696 type_t *result = parse_abstract_declarator(specifiers.type);
5704 typedef expression_t* (*parse_expression_function)(void);
5705 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5707 typedef struct expression_parser_function_t expression_parser_function_t;
5708 struct expression_parser_function_t {
5709 parse_expression_function parser;
5710 precedence_t infix_precedence;
5711 parse_expression_infix_function infix_parser;
5714 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5716 static type_t *get_string_type(void)
5718 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5721 static type_t *get_wide_string_type(void)
5723 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5727 * Parse a string constant.
5729 static expression_t *parse_string_literal(void)
5731 source_position_t begin = token.base.source_position;
5732 string_t res = token.string.string;
5733 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5736 while (token.kind == T_STRING_LITERAL
5737 || token.kind == T_WIDE_STRING_LITERAL) {
5738 warn_string_concat(&token.base.source_position);
5739 res = concat_strings(&res, &token.string.string);
5741 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5744 expression_t *literal;
5746 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5747 literal->base.type = get_wide_string_type();
5749 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5750 literal->base.type = get_string_type();
5752 literal->base.source_position = begin;
5753 literal->literal.value = res;
5759 * Parse a boolean constant.
5761 static expression_t *parse_boolean_literal(bool value)
5763 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5764 literal->base.type = type_bool;
5765 literal->literal.value.begin = value ? "true" : "false";
5766 literal->literal.value.size = value ? 4 : 5;
5772 static void warn_traditional_suffix(void)
5774 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5775 &token.number.suffix);
5778 static void check_integer_suffix(void)
5780 const string_t *suffix = &token.number.suffix;
5781 if (suffix->size == 0)
5784 bool not_traditional = false;
5785 const char *c = suffix->begin;
5786 if (*c == 'l' || *c == 'L') {
5789 not_traditional = true;
5791 if (*c == 'u' || *c == 'U') {
5794 } else if (*c == 'u' || *c == 'U') {
5795 not_traditional = true;
5798 } else if (*c == 'u' || *c == 'U') {
5799 not_traditional = true;
5801 if (*c == 'l' || *c == 'L') {
5809 errorf(&token.base.source_position,
5810 "invalid suffix '%S' on integer constant", suffix);
5811 } else if (not_traditional) {
5812 warn_traditional_suffix();
5816 static type_t *check_floatingpoint_suffix(void)
5818 const string_t *suffix = &token.number.suffix;
5819 type_t *type = type_double;
5820 if (suffix->size == 0)
5823 bool not_traditional = false;
5824 const char *c = suffix->begin;
5825 if (*c == 'f' || *c == 'F') {
5828 } else if (*c == 'l' || *c == 'L') {
5830 type = type_long_double;
5833 errorf(&token.base.source_position,
5834 "invalid suffix '%S' on floatingpoint constant", suffix);
5835 } else if (not_traditional) {
5836 warn_traditional_suffix();
5843 * Parse an integer constant.
5845 static expression_t *parse_number_literal(void)
5847 expression_kind_t kind;
5850 switch (token.kind) {
5852 kind = EXPR_LITERAL_INTEGER;
5853 check_integer_suffix();
5857 case T_FLOATINGPOINT:
5858 kind = EXPR_LITERAL_FLOATINGPOINT;
5859 type = check_floatingpoint_suffix();
5863 panic("unexpected token type in parse_number_literal");
5866 expression_t *literal = allocate_expression_zero(kind);
5867 literal->base.type = type;
5868 literal->literal.value = token.number.number;
5869 literal->literal.suffix = token.number.suffix;
5872 /* integer type depends on the size of the number and the size
5873 * representable by the types. The backend/codegeneration has to determine
5876 determine_literal_type(&literal->literal);
5881 * Parse a character constant.
5883 static expression_t *parse_character_constant(void)
5885 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5886 literal->base.type = c_mode & _CXX ? type_char : type_int;
5887 literal->literal.value = token.string.string;
5889 size_t len = literal->literal.value.size;
5891 if (!GNU_MODE && !(c_mode & _C99)) {
5892 errorf(HERE, "more than 1 character in character constant");
5894 literal->base.type = type_int;
5895 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5904 * Parse a wide character constant.
5906 static expression_t *parse_wide_character_constant(void)
5908 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5909 literal->base.type = type_int;
5910 literal->literal.value = token.string.string;
5912 size_t len = wstrlen(&literal->literal.value);
5914 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5921 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5923 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5924 ntype->function.return_type = type_int;
5925 ntype->function.unspecified_parameters = true;
5926 ntype->function.linkage = LINKAGE_C;
5927 type_t *type = identify_new_type(ntype);
5929 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5930 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5931 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5932 entity->declaration.type = type;
5933 entity->declaration.implicit = true;
5935 if (current_scope != NULL)
5936 record_entity(entity, false);
5942 * Performs automatic type cast as described in §6.3.2.1.
5944 * @param orig_type the original type
5946 static type_t *automatic_type_conversion(type_t *orig_type)
5948 type_t *type = skip_typeref(orig_type);
5949 if (is_type_array(type)) {
5950 array_type_t *array_type = &type->array;
5951 type_t *element_type = array_type->element_type;
5952 unsigned qualifiers = array_type->base.qualifiers;
5954 return make_pointer_type(element_type, qualifiers);
5957 if (is_type_function(type)) {
5958 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5965 * reverts the automatic casts of array to pointer types and function
5966 * to function-pointer types as defined §6.3.2.1
5968 type_t *revert_automatic_type_conversion(const expression_t *expression)
5970 switch (expression->kind) {
5971 case EXPR_REFERENCE: {
5972 entity_t *entity = expression->reference.entity;
5973 if (is_declaration(entity)) {
5974 return entity->declaration.type;
5975 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5976 return entity->enum_value.enum_type;
5978 panic("no declaration or enum in reference");
5983 entity_t *entity = expression->select.compound_entry;
5984 assert(is_declaration(entity));
5985 type_t *type = entity->declaration.type;
5986 return get_qualified_type(type, expression->base.type->base.qualifiers);
5989 case EXPR_UNARY_DEREFERENCE: {
5990 const expression_t *const value = expression->unary.value;
5991 type_t *const type = skip_typeref(value->base.type);
5992 if (!is_type_pointer(type))
5993 return type_error_type;
5994 return type->pointer.points_to;
5997 case EXPR_ARRAY_ACCESS: {
5998 const expression_t *array_ref = expression->array_access.array_ref;
5999 type_t *type_left = skip_typeref(array_ref->base.type);
6000 if (!is_type_pointer(type_left))
6001 return type_error_type;
6002 return type_left->pointer.points_to;
6005 case EXPR_STRING_LITERAL: {
6006 size_t size = expression->string_literal.value.size;
6007 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6010 case EXPR_WIDE_STRING_LITERAL: {
6011 size_t size = wstrlen(&expression->string_literal.value);
6012 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6015 case EXPR_COMPOUND_LITERAL:
6016 return expression->compound_literal.type;
6021 return expression->base.type;
6025 * Find an entity matching a symbol in a scope.
6026 * Uses current scope if scope is NULL
6028 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6029 namespace_tag_t namespc)
6031 if (scope == NULL) {
6032 return get_entity(symbol, namespc);
6035 /* we should optimize here, if scope grows above a certain size we should
6036 construct a hashmap here... */
6037 entity_t *entity = scope->entities;
6038 for ( ; entity != NULL; entity = entity->base.next) {
6039 if (entity->base.symbol == symbol
6040 && (namespace_tag_t)entity->base.namespc == namespc)
6047 static entity_t *parse_qualified_identifier(void)
6049 /* namespace containing the symbol */
6051 source_position_t pos;
6052 const scope_t *lookup_scope = NULL;
6054 if (next_if(T_COLONCOLON))
6055 lookup_scope = &unit->scope;
6059 symbol = expect_identifier("while parsing identifier", &pos);
6061 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6064 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6066 if (!next_if(T_COLONCOLON))
6069 switch (entity->kind) {
6070 case ENTITY_NAMESPACE:
6071 lookup_scope = &entity->namespacee.members;
6076 lookup_scope = &entity->compound.members;
6079 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6080 symbol, get_entity_kind_name(entity->kind));
6082 /* skip further qualifications */
6083 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6085 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6089 if (entity == NULL) {
6090 if (!strict_mode && token.kind == '(') {
6091 /* an implicitly declared function */
6092 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6093 "implicit declaration of function '%Y'", symbol);
6094 entity = create_implicit_function(symbol, &pos);
6096 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6097 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6104 static expression_t *parse_reference(void)
6106 source_position_t const pos = token.base.source_position;
6107 entity_t *const entity = parse_qualified_identifier();
6110 if (is_declaration(entity)) {
6111 orig_type = entity->declaration.type;
6112 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6113 orig_type = entity->enum_value.enum_type;
6115 panic("expected declaration or enum value in reference");
6118 /* we always do the auto-type conversions; the & and sizeof parser contains
6119 * code to revert this! */
6120 type_t *type = automatic_type_conversion(orig_type);
6122 expression_kind_t kind = EXPR_REFERENCE;
6123 if (entity->kind == ENTITY_ENUM_VALUE)
6124 kind = EXPR_ENUM_CONSTANT;
6126 expression_t *expression = allocate_expression_zero(kind);
6127 expression->base.source_position = pos;
6128 expression->base.type = type;
6129 expression->reference.entity = entity;
6131 /* this declaration is used */
6132 if (is_declaration(entity)) {
6133 entity->declaration.used = true;
6136 if (entity->base.parent_scope != file_scope
6137 && (current_function != NULL
6138 && entity->base.parent_scope->depth < current_function->parameters.depth)
6139 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6140 if (entity->kind == ENTITY_VARIABLE) {
6141 /* access of a variable from an outer function */
6142 entity->variable.address_taken = true;
6143 } else if (entity->kind == ENTITY_PARAMETER) {
6144 entity->parameter.address_taken = true;
6146 current_function->need_closure = true;
6149 check_deprecated(&pos, entity);
6154 static bool semantic_cast(expression_t *cast)
6156 expression_t *expression = cast->unary.value;
6157 type_t *orig_dest_type = cast->base.type;
6158 type_t *orig_type_right = expression->base.type;
6159 type_t const *dst_type = skip_typeref(orig_dest_type);
6160 type_t const *src_type = skip_typeref(orig_type_right);
6161 source_position_t const *pos = &cast->base.source_position;
6163 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6164 if (is_type_void(dst_type))
6167 /* only integer and pointer can be casted to pointer */
6168 if (is_type_pointer(dst_type) &&
6169 !is_type_pointer(src_type) &&
6170 !is_type_integer(src_type) &&
6171 is_type_valid(src_type)) {
6172 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6176 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6177 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6181 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6182 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6186 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6187 type_t *src = skip_typeref(src_type->pointer.points_to);
6188 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6189 unsigned missing_qualifiers =
6190 src->base.qualifiers & ~dst->base.qualifiers;
6191 if (missing_qualifiers != 0) {
6192 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6198 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6200 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6201 expression->base.source_position = *pos;
6203 parse_initializer_env_t env;
6206 env.must_be_constant = false;
6207 initializer_t *initializer = parse_initializer(&env);
6210 expression->compound_literal.initializer = initializer;
6211 expression->compound_literal.type = type;
6212 expression->base.type = automatic_type_conversion(type);
6218 * Parse a cast expression.
6220 static expression_t *parse_cast(void)
6222 source_position_t const pos = *HERE;
6225 add_anchor_token(')');
6227 type_t *type = parse_typename();
6229 rem_anchor_token(')');
6232 if (token.kind == '{') {
6233 return parse_compound_literal(&pos, type);
6236 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6237 cast->base.source_position = pos;
6239 expression_t *value = parse_subexpression(PREC_CAST);
6240 cast->base.type = type;
6241 cast->unary.value = value;
6243 if (! semantic_cast(cast)) {
6244 /* TODO: record the error in the AST. else it is impossible to detect it */
6251 * Parse a statement expression.
6253 static expression_t *parse_statement_expression(void)
6255 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6258 add_anchor_token(')');
6260 statement_t *statement = parse_compound_statement(true);
6261 statement->compound.stmt_expr = true;
6262 expression->statement.statement = statement;
6264 /* find last statement and use its type */
6265 type_t *type = type_void;
6266 const statement_t *stmt = statement->compound.statements;
6268 while (stmt->base.next != NULL)
6269 stmt = stmt->base.next;
6271 if (stmt->kind == STATEMENT_EXPRESSION) {
6272 type = stmt->expression.expression->base.type;
6275 source_position_t const *const pos = &expression->base.source_position;
6276 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6278 expression->base.type = type;
6280 rem_anchor_token(')');
6286 * Parse a parenthesized expression.
6288 static expression_t *parse_parenthesized_expression(void)
6290 token_t const* const la1 = look_ahead(1);
6291 switch (la1->kind) {
6293 /* gcc extension: a statement expression */
6294 return parse_statement_expression();
6297 if (is_typedef_symbol(la1->identifier.symbol)) {
6299 return parse_cast();
6304 add_anchor_token(')');
6305 expression_t *result = parse_expression();
6306 result->base.parenthesized = true;
6307 rem_anchor_token(')');
6313 static expression_t *parse_function_keyword(void)
6317 if (current_function == NULL) {
6318 errorf(HERE, "'__func__' used outside of a function");
6321 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6322 expression->base.type = type_char_ptr;
6323 expression->funcname.kind = FUNCNAME_FUNCTION;
6330 static expression_t *parse_pretty_function_keyword(void)
6332 if (current_function == NULL) {
6333 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6336 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6337 expression->base.type = type_char_ptr;
6338 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6340 eat(T___PRETTY_FUNCTION__);
6345 static expression_t *parse_funcsig_keyword(void)
6347 if (current_function == NULL) {
6348 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6351 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6352 expression->base.type = type_char_ptr;
6353 expression->funcname.kind = FUNCNAME_FUNCSIG;
6360 static expression_t *parse_funcdname_keyword(void)
6362 if (current_function == NULL) {
6363 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6366 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6367 expression->base.type = type_char_ptr;
6368 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6370 eat(T___FUNCDNAME__);
6375 static designator_t *parse_designator(void)
6377 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6378 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6379 if (!result->symbol)
6382 designator_t *last_designator = result;
6385 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6386 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6387 if (!designator->symbol)
6390 last_designator->next = designator;
6391 last_designator = designator;
6395 add_anchor_token(']');
6396 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6397 designator->source_position = *HERE;
6398 designator->array_index = parse_expression();
6399 rem_anchor_token(']');
6401 if (designator->array_index == NULL) {
6405 last_designator->next = designator;
6406 last_designator = designator;
6416 * Parse the __builtin_offsetof() expression.
6418 static expression_t *parse_offsetof(void)
6420 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6421 expression->base.type = type_size_t;
6423 eat(T___builtin_offsetof);
6426 add_anchor_token(')');
6427 add_anchor_token(',');
6428 type_t *type = parse_typename();
6429 rem_anchor_token(',');
6431 designator_t *designator = parse_designator();
6432 rem_anchor_token(')');
6435 expression->offsetofe.type = type;
6436 expression->offsetofe.designator = designator;
6439 memset(&path, 0, sizeof(path));
6440 path.top_type = type;
6441 path.path = NEW_ARR_F(type_path_entry_t, 0);
6443 descend_into_subtype(&path);
6445 if (!walk_designator(&path, designator, true)) {
6446 return create_error_expression();
6449 DEL_ARR_F(path.path);
6455 * Parses a _builtin_va_start() expression.
6457 static expression_t *parse_va_start(void)
6459 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6461 eat(T___builtin_va_start);
6464 add_anchor_token(')');
6465 add_anchor_token(',');
6466 expression->va_starte.ap = parse_assignment_expression();
6467 rem_anchor_token(',');
6469 expression_t *const expr = parse_assignment_expression();
6470 if (expr->kind == EXPR_REFERENCE) {
6471 entity_t *const entity = expr->reference.entity;
6472 if (!current_function->base.type->function.variadic) {
6473 errorf(&expr->base.source_position,
6474 "'va_start' used in non-variadic function");
6475 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6476 entity->base.next != NULL ||
6477 entity->kind != ENTITY_PARAMETER) {
6478 errorf(&expr->base.source_position,
6479 "second argument of 'va_start' must be last parameter of the current function");
6481 expression->va_starte.parameter = &entity->variable;
6484 expression = create_error_expression();
6486 rem_anchor_token(')');
6492 * Parses a __builtin_va_arg() expression.
6494 static expression_t *parse_va_arg(void)
6496 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6498 eat(T___builtin_va_arg);
6501 add_anchor_token(')');
6502 add_anchor_token(',');
6504 ap.expression = parse_assignment_expression();
6505 expression->va_arge.ap = ap.expression;
6506 check_call_argument(type_valist, &ap, 1);
6508 rem_anchor_token(',');
6510 expression->base.type = parse_typename();
6511 rem_anchor_token(')');
6518 * Parses a __builtin_va_copy() expression.
6520 static expression_t *parse_va_copy(void)
6522 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6524 eat(T___builtin_va_copy);
6527 add_anchor_token(')');
6528 add_anchor_token(',');
6529 expression_t *dst = parse_assignment_expression();
6530 assign_error_t error = semantic_assign(type_valist, dst);
6531 report_assign_error(error, type_valist, dst, "call argument 1",
6532 &dst->base.source_position);
6533 expression->va_copye.dst = dst;
6535 rem_anchor_token(',');
6538 call_argument_t src;
6539 src.expression = parse_assignment_expression();
6540 check_call_argument(type_valist, &src, 2);
6541 expression->va_copye.src = src.expression;
6542 rem_anchor_token(')');
6549 * Parses a __builtin_constant_p() expression.
6551 static expression_t *parse_builtin_constant(void)
6553 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6555 eat(T___builtin_constant_p);
6558 add_anchor_token(')');
6559 expression->builtin_constant.value = parse_assignment_expression();
6560 rem_anchor_token(')');
6562 expression->base.type = type_int;
6568 * Parses a __builtin_types_compatible_p() expression.
6570 static expression_t *parse_builtin_types_compatible(void)
6572 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6574 eat(T___builtin_types_compatible_p);
6577 add_anchor_token(')');
6578 add_anchor_token(',');
6579 expression->builtin_types_compatible.left = parse_typename();
6580 rem_anchor_token(',');
6582 expression->builtin_types_compatible.right = parse_typename();
6583 rem_anchor_token(')');
6585 expression->base.type = type_int;
6591 * Parses a __builtin_is_*() compare expression.
6593 static expression_t *parse_compare_builtin(void)
6595 expression_t *expression;
6597 switch (token.kind) {
6598 case T___builtin_isgreater:
6599 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6601 case T___builtin_isgreaterequal:
6602 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6604 case T___builtin_isless:
6605 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6607 case T___builtin_islessequal:
6608 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6610 case T___builtin_islessgreater:
6611 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6613 case T___builtin_isunordered:
6614 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6617 internal_errorf(HERE, "invalid compare builtin found");
6619 expression->base.source_position = *HERE;
6623 add_anchor_token(')');
6624 add_anchor_token(',');
6625 expression->binary.left = parse_assignment_expression();
6626 rem_anchor_token(',');
6628 expression->binary.right = parse_assignment_expression();
6629 rem_anchor_token(')');
6632 type_t *const orig_type_left = expression->binary.left->base.type;
6633 type_t *const orig_type_right = expression->binary.right->base.type;
6635 type_t *const type_left = skip_typeref(orig_type_left);
6636 type_t *const type_right = skip_typeref(orig_type_right);
6637 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6638 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6639 type_error_incompatible("invalid operands in comparison",
6640 &expression->base.source_position, orig_type_left, orig_type_right);
6643 semantic_comparison(&expression->binary);
6650 * Parses a MS assume() expression.
6652 static expression_t *parse_assume(void)
6654 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6659 add_anchor_token(')');
6660 expression->unary.value = parse_assignment_expression();
6661 rem_anchor_token(')');
6664 expression->base.type = type_void;
6669 * Return the label for the current symbol or create a new one.
6671 static label_t *get_label(void)
6673 assert(token.kind == T_IDENTIFIER);
6674 assert(current_function != NULL);
6676 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6677 /* If we find a local label, we already created the declaration. */
6678 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6679 if (label->base.parent_scope != current_scope) {
6680 assert(label->base.parent_scope->depth < current_scope->depth);
6681 current_function->goto_to_outer = true;
6683 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6684 /* There is no matching label in the same function, so create a new one. */
6685 source_position_t const nowhere = { NULL, 0, 0, false };
6686 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6691 return &label->label;
6695 * Parses a GNU && label address expression.
6697 static expression_t *parse_label_address(void)
6699 source_position_t source_position = token.base.source_position;
6701 if (token.kind != T_IDENTIFIER) {
6702 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6703 return create_error_expression();
6706 label_t *const label = get_label();
6708 label->address_taken = true;
6710 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6711 expression->base.source_position = source_position;
6713 /* label address is treated as a void pointer */
6714 expression->base.type = type_void_ptr;
6715 expression->label_address.label = label;
6720 * Parse a microsoft __noop expression.
6722 static expression_t *parse_noop_expression(void)
6724 /* the result is a (int)0 */
6725 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6726 literal->base.type = type_int;
6727 literal->literal.value.begin = "__noop";
6728 literal->literal.value.size = 6;
6732 if (token.kind == '(') {
6733 /* parse arguments */
6735 add_anchor_token(')');
6736 add_anchor_token(',');
6738 if (token.kind != ')') do {
6739 (void)parse_assignment_expression();
6740 } while (next_if(','));
6742 rem_anchor_token(',');
6743 rem_anchor_token(')');
6751 * Parses a primary expression.
6753 static expression_t *parse_primary_expression(void)
6755 switch (token.kind) {
6756 case T_false: return parse_boolean_literal(false);
6757 case T_true: return parse_boolean_literal(true);
6759 case T_FLOATINGPOINT: return parse_number_literal();
6760 case T_CHARACTER_CONSTANT: return parse_character_constant();
6761 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6762 case T_STRING_LITERAL:
6763 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6764 case T___FUNCTION__:
6765 case T___func__: return parse_function_keyword();
6766 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6767 case T___FUNCSIG__: return parse_funcsig_keyword();
6768 case T___FUNCDNAME__: return parse_funcdname_keyword();
6769 case T___builtin_offsetof: return parse_offsetof();
6770 case T___builtin_va_start: return parse_va_start();
6771 case T___builtin_va_arg: return parse_va_arg();
6772 case T___builtin_va_copy: return parse_va_copy();
6773 case T___builtin_isgreater:
6774 case T___builtin_isgreaterequal:
6775 case T___builtin_isless:
6776 case T___builtin_islessequal:
6777 case T___builtin_islessgreater:
6778 case T___builtin_isunordered: return parse_compare_builtin();
6779 case T___builtin_constant_p: return parse_builtin_constant();
6780 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6781 case T__assume: return parse_assume();
6784 return parse_label_address();
6787 case '(': return parse_parenthesized_expression();
6788 case T___noop: return parse_noop_expression();
6790 /* Gracefully handle type names while parsing expressions. */
6792 return parse_reference();
6794 if (!is_typedef_symbol(token.identifier.symbol)) {
6795 return parse_reference();
6799 source_position_t const pos = *HERE;
6800 declaration_specifiers_t specifiers;
6801 parse_declaration_specifiers(&specifiers);
6802 type_t const *const type = parse_abstract_declarator(specifiers.type);
6803 errorf(&pos, "encountered type '%T' while parsing expression", type);
6804 return create_error_expression();
6808 errorf(HERE, "unexpected token %K, expected an expression", &token);
6810 return create_error_expression();
6813 static expression_t *parse_array_expression(expression_t *left)
6815 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6816 array_access_expression_t *const arr = &expr->array_access;
6819 add_anchor_token(']');
6821 expression_t *const inside = parse_expression();
6823 type_t *const orig_type_left = left->base.type;
6824 type_t *const orig_type_inside = inside->base.type;
6826 type_t *const type_left = skip_typeref(orig_type_left);
6827 type_t *const type_inside = skip_typeref(orig_type_inside);
6833 if (is_type_pointer(type_left)) {
6836 idx_type = type_inside;
6837 res_type = type_left->pointer.points_to;
6839 } else if (is_type_pointer(type_inside)) {
6840 arr->flipped = true;
6843 idx_type = type_left;
6844 res_type = type_inside->pointer.points_to;
6846 res_type = automatic_type_conversion(res_type);
6847 if (!is_type_integer(idx_type)) {
6848 errorf(&idx->base.source_position, "array subscript must have integer type");
6849 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6850 source_position_t const *const pos = &idx->base.source_position;
6851 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6854 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6855 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6857 res_type = type_error_type;
6862 arr->array_ref = ref;
6864 arr->base.type = res_type;
6866 rem_anchor_token(']');
6871 static bool is_bitfield(const expression_t *expression)
6873 return expression->kind == EXPR_SELECT
6874 && expression->select.compound_entry->compound_member.bitfield;
6877 static expression_t *parse_typeprop(expression_kind_t const kind)
6879 expression_t *tp_expression = allocate_expression_zero(kind);
6880 tp_expression->base.type = type_size_t;
6882 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6885 expression_t *expression;
6886 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6887 source_position_t const pos = *HERE;
6889 add_anchor_token(')');
6890 orig_type = parse_typename();
6891 rem_anchor_token(')');
6894 if (token.kind == '{') {
6895 /* It was not sizeof(type) after all. It is sizeof of an expression
6896 * starting with a compound literal */
6897 expression = parse_compound_literal(&pos, orig_type);
6898 goto typeprop_expression;
6901 expression = parse_subexpression(PREC_UNARY);
6903 typeprop_expression:
6904 if (is_bitfield(expression)) {
6905 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6906 errorf(&tp_expression->base.source_position,
6907 "operand of %s expression must not be a bitfield", what);
6910 tp_expression->typeprop.tp_expression = expression;
6912 orig_type = revert_automatic_type_conversion(expression);
6913 expression->base.type = orig_type;
6916 tp_expression->typeprop.type = orig_type;
6917 type_t const* const type = skip_typeref(orig_type);
6918 char const* wrong_type = NULL;
6919 if (is_type_incomplete(type)) {
6920 if (!is_type_void(type) || !GNU_MODE)
6921 wrong_type = "incomplete";
6922 } else if (type->kind == TYPE_FUNCTION) {
6924 /* function types are allowed (and return 1) */
6925 source_position_t const *const pos = &tp_expression->base.source_position;
6926 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6927 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6929 wrong_type = "function";
6933 if (wrong_type != NULL) {
6934 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6935 errorf(&tp_expression->base.source_position,
6936 "operand of %s expression must not be of %s type '%T'",
6937 what, wrong_type, orig_type);
6940 return tp_expression;
6943 static expression_t *parse_sizeof(void)
6945 return parse_typeprop(EXPR_SIZEOF);
6948 static expression_t *parse_alignof(void)
6950 return parse_typeprop(EXPR_ALIGNOF);
6953 static expression_t *parse_select_expression(expression_t *addr)
6955 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6956 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6957 source_position_t const pos = *HERE;
6960 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6962 return create_error_expression();
6964 type_t *const orig_type = addr->base.type;
6965 type_t *const type = skip_typeref(orig_type);
6968 bool saw_error = false;
6969 if (is_type_pointer(type)) {
6970 if (!select_left_arrow) {
6972 "request for member '%Y' in something not a struct or union, but '%T'",
6976 type_left = skip_typeref(type->pointer.points_to);
6978 if (select_left_arrow && is_type_valid(type)) {
6979 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6985 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6986 type_left->kind != TYPE_COMPOUND_UNION) {
6988 if (is_type_valid(type_left) && !saw_error) {
6990 "request for member '%Y' in something not a struct or union, but '%T'",
6993 return create_error_expression();
6996 compound_t *compound = type_left->compound.compound;
6997 if (!compound->complete) {
6998 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7000 return create_error_expression();
7003 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7004 expression_t *result =
7005 find_create_select(&pos, addr, qualifiers, compound, symbol);
7007 if (result == NULL) {
7008 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7009 return create_error_expression();
7015 static void check_call_argument(type_t *expected_type,
7016 call_argument_t *argument, unsigned pos)
7018 type_t *expected_type_skip = skip_typeref(expected_type);
7019 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7020 expression_t *arg_expr = argument->expression;
7021 type_t *arg_type = skip_typeref(arg_expr->base.type);
7023 /* handle transparent union gnu extension */
7024 if (is_type_union(expected_type_skip)
7025 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7026 compound_t *union_decl = expected_type_skip->compound.compound;
7027 type_t *best_type = NULL;
7028 entity_t *entry = union_decl->members.entities;
7029 for ( ; entry != NULL; entry = entry->base.next) {
7030 assert(is_declaration(entry));
7031 type_t *decl_type = entry->declaration.type;
7032 error = semantic_assign(decl_type, arg_expr);
7033 if (error == ASSIGN_ERROR_INCOMPATIBLE
7034 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7037 if (error == ASSIGN_SUCCESS) {
7038 best_type = decl_type;
7039 } else if (best_type == NULL) {
7040 best_type = decl_type;
7044 if (best_type != NULL) {
7045 expected_type = best_type;
7049 error = semantic_assign(expected_type, arg_expr);
7050 argument->expression = create_implicit_cast(arg_expr, expected_type);
7052 if (error != ASSIGN_SUCCESS) {
7053 /* report exact scope in error messages (like "in argument 3") */
7055 snprintf(buf, sizeof(buf), "call argument %u", pos);
7056 report_assign_error(error, expected_type, arg_expr, buf,
7057 &arg_expr->base.source_position);
7059 type_t *const promoted_type = get_default_promoted_type(arg_type);
7060 if (!types_compatible(expected_type_skip, promoted_type) &&
7061 !types_compatible(expected_type_skip, type_void_ptr) &&
7062 !types_compatible(type_void_ptr, promoted_type)) {
7063 /* Deliberately show the skipped types in this warning */
7064 source_position_t const *const apos = &arg_expr->base.source_position;
7065 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7071 * Handle the semantic restrictions of builtin calls
7073 static void handle_builtin_argument_restrictions(call_expression_t *call)
7075 entity_t *entity = call->function->reference.entity;
7076 switch (entity->function.btk) {
7078 switch (entity->function.b.firm_builtin_kind) {
7079 case ir_bk_return_address:
7080 case ir_bk_frame_address: {
7081 /* argument must be constant */
7082 call_argument_t *argument = call->arguments;
7084 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7085 errorf(&call->base.source_position,
7086 "argument of '%Y' must be a constant expression",
7087 call->function->reference.entity->base.symbol);
7091 case ir_bk_prefetch:
7092 /* second and third argument must be constant if existent */
7093 if (call->arguments == NULL)
7095 call_argument_t *rw = call->arguments->next;
7096 call_argument_t *locality = NULL;
7099 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7100 errorf(&call->base.source_position,
7101 "second argument of '%Y' must be a constant expression",
7102 call->function->reference.entity->base.symbol);
7104 locality = rw->next;
7106 if (locality != NULL) {
7107 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7108 errorf(&call->base.source_position,
7109 "third argument of '%Y' must be a constant expression",
7110 call->function->reference.entity->base.symbol);
7112 locality = rw->next;
7119 case BUILTIN_OBJECT_SIZE:
7120 if (call->arguments == NULL)
7123 call_argument_t *arg = call->arguments->next;
7124 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7125 errorf(&call->base.source_position,
7126 "second argument of '%Y' must be a constant expression",
7127 call->function->reference.entity->base.symbol);
7136 * Parse a call expression, ie. expression '( ... )'.
7138 * @param expression the function address
7140 static expression_t *parse_call_expression(expression_t *expression)
7142 expression_t *result = allocate_expression_zero(EXPR_CALL);
7143 call_expression_t *call = &result->call;
7144 call->function = expression;
7146 type_t *const orig_type = expression->base.type;
7147 type_t *const type = skip_typeref(orig_type);
7149 function_type_t *function_type = NULL;
7150 if (is_type_pointer(type)) {
7151 type_t *const to_type = skip_typeref(type->pointer.points_to);
7153 if (is_type_function(to_type)) {
7154 function_type = &to_type->function;
7155 call->base.type = function_type->return_type;
7159 if (function_type == NULL && is_type_valid(type)) {
7161 "called object '%E' (type '%T') is not a pointer to a function",
7162 expression, orig_type);
7165 /* parse arguments */
7167 add_anchor_token(')');
7168 add_anchor_token(',');
7170 if (token.kind != ')') {
7171 call_argument_t **anchor = &call->arguments;
7173 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7174 argument->expression = parse_assignment_expression();
7177 anchor = &argument->next;
7178 } while (next_if(','));
7180 rem_anchor_token(',');
7181 rem_anchor_token(')');
7184 if (function_type == NULL)
7187 /* check type and count of call arguments */
7188 function_parameter_t *parameter = function_type->parameters;
7189 call_argument_t *argument = call->arguments;
7190 if (!function_type->unspecified_parameters) {
7191 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7192 parameter = parameter->next, argument = argument->next) {
7193 check_call_argument(parameter->type, argument, ++pos);
7196 if (parameter != NULL) {
7197 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7198 } else if (argument != NULL && !function_type->variadic) {
7199 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7203 /* do default promotion for other arguments */
7204 for (; argument != NULL; argument = argument->next) {
7205 type_t *argument_type = argument->expression->base.type;
7206 if (!is_type_object(skip_typeref(argument_type))) {
7207 errorf(&argument->expression->base.source_position,
7208 "call argument '%E' must not be void", argument->expression);
7211 argument_type = get_default_promoted_type(argument_type);
7213 argument->expression
7214 = create_implicit_cast(argument->expression, argument_type);
7219 if (is_type_compound(skip_typeref(function_type->return_type))) {
7220 source_position_t const *const pos = &expression->base.source_position;
7221 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7224 if (expression->kind == EXPR_REFERENCE) {
7225 reference_expression_t *reference = &expression->reference;
7226 if (reference->entity->kind == ENTITY_FUNCTION &&
7227 reference->entity->function.btk != BUILTIN_NONE)
7228 handle_builtin_argument_restrictions(call);
7234 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7236 static bool same_compound_type(const type_t *type1, const type_t *type2)
7239 is_type_compound(type1) &&
7240 type1->kind == type2->kind &&
7241 type1->compound.compound == type2->compound.compound;
7244 static expression_t const *get_reference_address(expression_t const *expr)
7246 bool regular_take_address = true;
7248 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7249 expr = expr->unary.value;
7251 regular_take_address = false;
7254 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7257 expr = expr->unary.value;
7260 if (expr->kind != EXPR_REFERENCE)
7263 /* special case for functions which are automatically converted to a
7264 * pointer to function without an extra TAKE_ADDRESS operation */
7265 if (!regular_take_address &&
7266 expr->reference.entity->kind != ENTITY_FUNCTION) {
7273 static void warn_reference_address_as_bool(expression_t const* expr)
7275 expr = get_reference_address(expr);
7277 source_position_t const *const pos = &expr->base.source_position;
7278 entity_t const *const ent = expr->reference.entity;
7279 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7283 static void warn_assignment_in_condition(const expression_t *const expr)
7285 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7287 if (expr->base.parenthesized)
7289 source_position_t const *const pos = &expr->base.source_position;
7290 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7293 static void semantic_condition(expression_t const *const expr,
7294 char const *const context)
7296 type_t *const type = skip_typeref(expr->base.type);
7297 if (is_type_scalar(type)) {
7298 warn_reference_address_as_bool(expr);
7299 warn_assignment_in_condition(expr);
7300 } else if (is_type_valid(type)) {
7301 errorf(&expr->base.source_position,
7302 "%s must have scalar type", context);
7307 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7309 * @param expression the conditional expression
7311 static expression_t *parse_conditional_expression(expression_t *expression)
7313 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7315 conditional_expression_t *conditional = &result->conditional;
7316 conditional->condition = expression;
7319 add_anchor_token(':');
7321 /* §6.5.15:2 The first operand shall have scalar type. */
7322 semantic_condition(expression, "condition of conditional operator");
7324 expression_t *true_expression = expression;
7325 bool gnu_cond = false;
7326 if (GNU_MODE && token.kind == ':') {
7329 true_expression = parse_expression();
7331 rem_anchor_token(':');
7333 expression_t *false_expression =
7334 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7336 type_t *const orig_true_type = true_expression->base.type;
7337 type_t *const orig_false_type = false_expression->base.type;
7338 type_t *const true_type = skip_typeref(orig_true_type);
7339 type_t *const false_type = skip_typeref(orig_false_type);
7342 source_position_t const *const pos = &conditional->base.source_position;
7343 type_t *result_type;
7344 if (is_type_void(true_type) || is_type_void(false_type)) {
7345 /* ISO/IEC 14882:1998(E) §5.16:2 */
7346 if (true_expression->kind == EXPR_UNARY_THROW) {
7347 result_type = false_type;
7348 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7349 result_type = true_type;
7351 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7352 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7354 result_type = type_void;
7356 } else if (is_type_arithmetic(true_type)
7357 && is_type_arithmetic(false_type)) {
7358 result_type = semantic_arithmetic(true_type, false_type);
7359 } else if (same_compound_type(true_type, false_type)) {
7360 /* just take 1 of the 2 types */
7361 result_type = true_type;
7362 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7363 type_t *pointer_type;
7365 expression_t *other_expression;
7366 if (is_type_pointer(true_type) &&
7367 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7368 pointer_type = true_type;
7369 other_type = false_type;
7370 other_expression = false_expression;
7372 pointer_type = false_type;
7373 other_type = true_type;
7374 other_expression = true_expression;
7377 if (is_null_pointer_constant(other_expression)) {
7378 result_type = pointer_type;
7379 } else if (is_type_pointer(other_type)) {
7380 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7381 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7384 if (is_type_void(to1) || is_type_void(to2)) {
7386 } else if (types_compatible(get_unqualified_type(to1),
7387 get_unqualified_type(to2))) {
7390 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7394 type_t *const type =
7395 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7396 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7397 } else if (is_type_integer(other_type)) {
7398 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7399 result_type = pointer_type;
7401 goto types_incompatible;
7405 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7406 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7408 result_type = type_error_type;
7411 conditional->true_expression
7412 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7413 conditional->false_expression
7414 = create_implicit_cast(false_expression, result_type);
7415 conditional->base.type = result_type;
7420 * Parse an extension expression.
7422 static expression_t *parse_extension(void)
7425 expression_t *expression = parse_subexpression(PREC_UNARY);
7431 * Parse a __builtin_classify_type() expression.
7433 static expression_t *parse_builtin_classify_type(void)
7435 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7436 result->base.type = type_int;
7438 eat(T___builtin_classify_type);
7441 add_anchor_token(')');
7442 expression_t *expression = parse_expression();
7443 rem_anchor_token(')');
7445 result->classify_type.type_expression = expression;
7451 * Parse a delete expression
7452 * ISO/IEC 14882:1998(E) §5.3.5
7454 static expression_t *parse_delete(void)
7456 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7457 result->base.type = type_void;
7462 result->kind = EXPR_UNARY_DELETE_ARRAY;
7466 expression_t *const value = parse_subexpression(PREC_CAST);
7467 result->unary.value = value;
7469 type_t *const type = skip_typeref(value->base.type);
7470 if (!is_type_pointer(type)) {
7471 if (is_type_valid(type)) {
7472 errorf(&value->base.source_position,
7473 "operand of delete must have pointer type");
7475 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7476 source_position_t const *const pos = &value->base.source_position;
7477 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7484 * Parse a throw expression
7485 * ISO/IEC 14882:1998(E) §15:1
7487 static expression_t *parse_throw(void)
7489 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7490 result->base.type = type_void;
7494 expression_t *value = NULL;
7495 switch (token.kind) {
7497 value = parse_assignment_expression();
7498 /* ISO/IEC 14882:1998(E) §15.1:3 */
7499 type_t *const orig_type = value->base.type;
7500 type_t *const type = skip_typeref(orig_type);
7501 if (is_type_incomplete(type)) {
7502 errorf(&value->base.source_position,
7503 "cannot throw object of incomplete type '%T'", orig_type);
7504 } else if (is_type_pointer(type)) {
7505 type_t *const points_to = skip_typeref(type->pointer.points_to);
7506 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7507 errorf(&value->base.source_position,
7508 "cannot throw pointer to incomplete type '%T'", orig_type);
7516 result->unary.value = value;
7521 static bool check_pointer_arithmetic(const source_position_t *source_position,
7522 type_t *pointer_type,
7523 type_t *orig_pointer_type)
7525 type_t *points_to = pointer_type->pointer.points_to;
7526 points_to = skip_typeref(points_to);
7528 if (is_type_incomplete(points_to)) {
7529 if (!GNU_MODE || !is_type_void(points_to)) {
7530 errorf(source_position,
7531 "arithmetic with pointer to incomplete type '%T' not allowed",
7535 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7537 } else if (is_type_function(points_to)) {
7539 errorf(source_position,
7540 "arithmetic with pointer to function type '%T' not allowed",
7544 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7550 static bool is_lvalue(const expression_t *expression)
7552 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7553 switch (expression->kind) {
7554 case EXPR_ARRAY_ACCESS:
7555 case EXPR_COMPOUND_LITERAL:
7556 case EXPR_REFERENCE:
7558 case EXPR_UNARY_DEREFERENCE:
7562 type_t *type = skip_typeref(expression->base.type);
7564 /* ISO/IEC 14882:1998(E) §3.10:3 */
7565 is_type_reference(type) ||
7566 /* Claim it is an lvalue, if the type is invalid. There was a parse
7567 * error before, which maybe prevented properly recognizing it as
7569 !is_type_valid(type);
7574 static void semantic_incdec(unary_expression_t *expression)
7576 type_t *const orig_type = expression->value->base.type;
7577 type_t *const type = skip_typeref(orig_type);
7578 if (is_type_pointer(type)) {
7579 if (!check_pointer_arithmetic(&expression->base.source_position,
7583 } else if (!is_type_real(type) && is_type_valid(type)) {
7584 /* TODO: improve error message */
7585 errorf(&expression->base.source_position,
7586 "operation needs an arithmetic or pointer type");
7589 if (!is_lvalue(expression->value)) {
7590 /* TODO: improve error message */
7591 errorf(&expression->base.source_position, "lvalue required as operand");
7593 expression->base.type = orig_type;
7596 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7598 type_t *const res_type = promote_integer(type);
7599 expr->base.type = res_type;
7600 expr->value = create_implicit_cast(expr->value, res_type);
7603 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7605 type_t *const orig_type = expression->value->base.type;
7606 type_t *const type = skip_typeref(orig_type);
7607 if (!is_type_arithmetic(type)) {
7608 if (is_type_valid(type)) {
7609 /* TODO: improve error message */
7610 errorf(&expression->base.source_position,
7611 "operation needs an arithmetic type");
7614 } else if (is_type_integer(type)) {
7615 promote_unary_int_expr(expression, type);
7617 expression->base.type = orig_type;
7621 static void semantic_unexpr_plus(unary_expression_t *expression)
7623 semantic_unexpr_arithmetic(expression);
7624 source_position_t const *const pos = &expression->base.source_position;
7625 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7628 static void semantic_not(unary_expression_t *expression)
7630 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7631 semantic_condition(expression->value, "operand of !");
7632 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7635 static void semantic_unexpr_integer(unary_expression_t *expression)
7637 type_t *const orig_type = expression->value->base.type;
7638 type_t *const type = skip_typeref(orig_type);
7639 if (!is_type_integer(type)) {
7640 if (is_type_valid(type)) {
7641 errorf(&expression->base.source_position,
7642 "operand of ~ must be of integer type");
7647 promote_unary_int_expr(expression, type);
7650 static void semantic_dereference(unary_expression_t *expression)
7652 type_t *const orig_type = expression->value->base.type;
7653 type_t *const type = skip_typeref(orig_type);
7654 if (!is_type_pointer(type)) {
7655 if (is_type_valid(type)) {
7656 errorf(&expression->base.source_position,
7657 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7662 type_t *result_type = type->pointer.points_to;
7663 result_type = automatic_type_conversion(result_type);
7664 expression->base.type = result_type;
7668 * Record that an address is taken (expression represents an lvalue).
7670 * @param expression the expression
7671 * @param may_be_register if true, the expression might be an register
7673 static void set_address_taken(expression_t *expression, bool may_be_register)
7675 if (expression->kind != EXPR_REFERENCE)
7678 entity_t *const entity = expression->reference.entity;
7680 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7683 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7684 && !may_be_register) {
7685 source_position_t const *const pos = &expression->base.source_position;
7686 errorf(pos, "address of register '%N' requested", entity);
7689 if (entity->kind == ENTITY_VARIABLE) {
7690 entity->variable.address_taken = true;
7692 assert(entity->kind == ENTITY_PARAMETER);
7693 entity->parameter.address_taken = true;
7698 * Check the semantic of the address taken expression.
7700 static void semantic_take_addr(unary_expression_t *expression)
7702 expression_t *value = expression->value;
7703 value->base.type = revert_automatic_type_conversion(value);
7705 type_t *orig_type = value->base.type;
7706 type_t *type = skip_typeref(orig_type);
7707 if (!is_type_valid(type))
7711 if (!is_lvalue(value)) {
7712 errorf(&expression->base.source_position, "'&' requires an lvalue");
7714 if (is_bitfield(value)) {
7715 errorf(&expression->base.source_position,
7716 "'&' not allowed on bitfield");
7719 set_address_taken(value, false);
7721 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7724 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7725 static expression_t *parse_##unexpression_type(void) \
7727 expression_t *unary_expression \
7728 = allocate_expression_zero(unexpression_type); \
7730 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7732 sfunc(&unary_expression->unary); \
7734 return unary_expression; \
7737 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7738 semantic_unexpr_arithmetic)
7739 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7740 semantic_unexpr_plus)
7741 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7743 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7744 semantic_dereference)
7745 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7747 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7748 semantic_unexpr_integer)
7749 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7751 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7754 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7756 static expression_t *parse_##unexpression_type(expression_t *left) \
7758 expression_t *unary_expression \
7759 = allocate_expression_zero(unexpression_type); \
7761 unary_expression->unary.value = left; \
7763 sfunc(&unary_expression->unary); \
7765 return unary_expression; \
7768 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7769 EXPR_UNARY_POSTFIX_INCREMENT,
7771 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7772 EXPR_UNARY_POSTFIX_DECREMENT,
7775 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7777 /* TODO: handle complex + imaginary types */
7779 type_left = get_unqualified_type(type_left);
7780 type_right = get_unqualified_type(type_right);
7782 /* §6.3.1.8 Usual arithmetic conversions */
7783 if (type_left == type_long_double || type_right == type_long_double) {
7784 return type_long_double;
7785 } else if (type_left == type_double || type_right == type_double) {
7787 } else if (type_left == type_float || type_right == type_float) {
7791 type_left = promote_integer(type_left);
7792 type_right = promote_integer(type_right);
7794 if (type_left == type_right)
7797 bool const signed_left = is_type_signed(type_left);
7798 bool const signed_right = is_type_signed(type_right);
7799 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7800 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7802 if (signed_left == signed_right)
7803 return rank_left >= rank_right ? type_left : type_right;
7807 atomic_type_kind_t s_akind;
7808 atomic_type_kind_t u_akind;
7813 u_type = type_right;
7815 s_type = type_right;
7818 s_akind = get_akind(s_type);
7819 u_akind = get_akind(u_type);
7820 s_rank = get_akind_rank(s_akind);
7821 u_rank = get_akind_rank(u_akind);
7823 if (u_rank >= s_rank)
7826 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7830 case ATOMIC_TYPE_INT: return type_unsigned_int;
7831 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7832 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7834 default: panic("invalid atomic type");
7839 * Check the semantic restrictions for a binary expression.
7841 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7843 expression_t *const left = expression->left;
7844 expression_t *const right = expression->right;
7845 type_t *const orig_type_left = left->base.type;
7846 type_t *const orig_type_right = right->base.type;
7847 type_t *const type_left = skip_typeref(orig_type_left);
7848 type_t *const type_right = skip_typeref(orig_type_right);
7850 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7851 /* TODO: improve error message */
7852 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7853 errorf(&expression->base.source_position,
7854 "operation needs arithmetic types");
7859 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7860 expression->left = create_implicit_cast(left, arithmetic_type);
7861 expression->right = create_implicit_cast(right, arithmetic_type);
7862 expression->base.type = arithmetic_type;
7865 static void semantic_binexpr_integer(binary_expression_t *const expression)
7867 expression_t *const left = expression->left;
7868 expression_t *const right = expression->right;
7869 type_t *const orig_type_left = left->base.type;
7870 type_t *const orig_type_right = right->base.type;
7871 type_t *const type_left = skip_typeref(orig_type_left);
7872 type_t *const type_right = skip_typeref(orig_type_right);
7874 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7875 /* TODO: improve error message */
7876 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7877 errorf(&expression->base.source_position,
7878 "operation needs integer types");
7883 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7884 expression->left = create_implicit_cast(left, result_type);
7885 expression->right = create_implicit_cast(right, result_type);
7886 expression->base.type = result_type;
7889 static void warn_div_by_zero(binary_expression_t const *const expression)
7891 if (!is_type_integer(expression->base.type))
7894 expression_t const *const right = expression->right;
7895 /* The type of the right operand can be different for /= */
7896 if (is_type_integer(right->base.type) &&
7897 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7898 !fold_constant_to_bool(right)) {
7899 source_position_t const *const pos = &expression->base.source_position;
7900 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7905 * Check the semantic restrictions for a div/mod expression.
7907 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7909 semantic_binexpr_arithmetic(expression);
7910 warn_div_by_zero(expression);
7913 static void warn_addsub_in_shift(const expression_t *const expr)
7915 if (expr->base.parenthesized)
7919 switch (expr->kind) {
7920 case EXPR_BINARY_ADD: op = '+'; break;
7921 case EXPR_BINARY_SUB: op = '-'; break;
7925 source_position_t const *const pos = &expr->base.source_position;
7926 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7929 static bool semantic_shift(binary_expression_t *expression)
7931 expression_t *const left = expression->left;
7932 expression_t *const right = expression->right;
7933 type_t *const orig_type_left = left->base.type;
7934 type_t *const orig_type_right = right->base.type;
7935 type_t * type_left = skip_typeref(orig_type_left);
7936 type_t * type_right = skip_typeref(orig_type_right);
7938 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7939 /* TODO: improve error message */
7940 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7941 errorf(&expression->base.source_position,
7942 "operands of shift operation must have integer types");
7947 type_left = promote_integer(type_left);
7949 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7950 source_position_t const *const pos = &right->base.source_position;
7951 long const count = fold_constant_to_int(right);
7953 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7954 } else if ((unsigned long)count >=
7955 get_atomic_type_size(type_left->atomic.akind) * 8) {
7956 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7960 type_right = promote_integer(type_right);
7961 expression->right = create_implicit_cast(right, type_right);
7966 static void semantic_shift_op(binary_expression_t *expression)
7968 expression_t *const left = expression->left;
7969 expression_t *const right = expression->right;
7971 if (!semantic_shift(expression))
7974 warn_addsub_in_shift(left);
7975 warn_addsub_in_shift(right);
7977 type_t *const orig_type_left = left->base.type;
7978 type_t * type_left = skip_typeref(orig_type_left);
7980 type_left = promote_integer(type_left);
7981 expression->left = create_implicit_cast(left, type_left);
7982 expression->base.type = type_left;
7985 static void semantic_add(binary_expression_t *expression)
7987 expression_t *const left = expression->left;
7988 expression_t *const right = expression->right;
7989 type_t *const orig_type_left = left->base.type;
7990 type_t *const orig_type_right = right->base.type;
7991 type_t *const type_left = skip_typeref(orig_type_left);
7992 type_t *const type_right = skip_typeref(orig_type_right);
7995 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7996 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7997 expression->left = create_implicit_cast(left, arithmetic_type);
7998 expression->right = create_implicit_cast(right, arithmetic_type);
7999 expression->base.type = arithmetic_type;
8000 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8001 check_pointer_arithmetic(&expression->base.source_position,
8002 type_left, orig_type_left);
8003 expression->base.type = type_left;
8004 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8005 check_pointer_arithmetic(&expression->base.source_position,
8006 type_right, orig_type_right);
8007 expression->base.type = type_right;
8008 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8009 errorf(&expression->base.source_position,
8010 "invalid operands to binary + ('%T', '%T')",
8011 orig_type_left, orig_type_right);
8015 static void semantic_sub(binary_expression_t *expression)
8017 expression_t *const left = expression->left;
8018 expression_t *const right = expression->right;
8019 type_t *const orig_type_left = left->base.type;
8020 type_t *const orig_type_right = right->base.type;
8021 type_t *const type_left = skip_typeref(orig_type_left);
8022 type_t *const type_right = skip_typeref(orig_type_right);
8023 source_position_t const *const pos = &expression->base.source_position;
8026 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8027 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8028 expression->left = create_implicit_cast(left, arithmetic_type);
8029 expression->right = create_implicit_cast(right, arithmetic_type);
8030 expression->base.type = arithmetic_type;
8031 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8032 check_pointer_arithmetic(&expression->base.source_position,
8033 type_left, orig_type_left);
8034 expression->base.type = type_left;
8035 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8036 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8037 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8038 if (!types_compatible(unqual_left, unqual_right)) {
8040 "subtracting pointers to incompatible types '%T' and '%T'",
8041 orig_type_left, orig_type_right);
8042 } else if (!is_type_object(unqual_left)) {
8043 if (!is_type_void(unqual_left)) {
8044 errorf(pos, "subtracting pointers to non-object types '%T'",
8047 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8050 expression->base.type = type_ptrdiff_t;
8051 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8052 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8053 orig_type_left, orig_type_right);
8057 static void warn_string_literal_address(expression_t const* expr)
8059 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8060 expr = expr->unary.value;
8061 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8063 expr = expr->unary.value;
8066 if (expr->kind == EXPR_STRING_LITERAL
8067 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8068 source_position_t const *const pos = &expr->base.source_position;
8069 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8073 static bool maybe_negative(expression_t const *const expr)
8075 switch (is_constant_expression(expr)) {
8076 case EXPR_CLASS_ERROR: return false;
8077 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8078 default: return true;
8082 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8084 warn_string_literal_address(expr);
8086 expression_t const* const ref = get_reference_address(expr);
8087 if (ref != NULL && is_null_pointer_constant(other)) {
8088 entity_t const *const ent = ref->reference.entity;
8089 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8092 if (!expr->base.parenthesized) {
8093 switch (expr->base.kind) {
8094 case EXPR_BINARY_LESS:
8095 case EXPR_BINARY_GREATER:
8096 case EXPR_BINARY_LESSEQUAL:
8097 case EXPR_BINARY_GREATEREQUAL:
8098 case EXPR_BINARY_NOTEQUAL:
8099 case EXPR_BINARY_EQUAL:
8100 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8109 * Check the semantics of comparison expressions.
8111 * @param expression The expression to check.
8113 static void semantic_comparison(binary_expression_t *expression)
8115 source_position_t const *const pos = &expression->base.source_position;
8116 expression_t *const left = expression->left;
8117 expression_t *const right = expression->right;
8119 warn_comparison(pos, left, right);
8120 warn_comparison(pos, right, left);
8122 type_t *orig_type_left = left->base.type;
8123 type_t *orig_type_right = right->base.type;
8124 type_t *type_left = skip_typeref(orig_type_left);
8125 type_t *type_right = skip_typeref(orig_type_right);
8127 /* TODO non-arithmetic types */
8128 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8129 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8131 /* test for signed vs unsigned compares */
8132 if (is_type_integer(arithmetic_type)) {
8133 bool const signed_left = is_type_signed(type_left);
8134 bool const signed_right = is_type_signed(type_right);
8135 if (signed_left != signed_right) {
8136 /* FIXME long long needs better const folding magic */
8137 /* TODO check whether constant value can be represented by other type */
8138 if ((signed_left && maybe_negative(left)) ||
8139 (signed_right && maybe_negative(right))) {
8140 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8145 expression->left = create_implicit_cast(left, arithmetic_type);
8146 expression->right = create_implicit_cast(right, arithmetic_type);
8147 expression->base.type = arithmetic_type;
8148 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8149 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8150 is_type_float(arithmetic_type)) {
8151 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8153 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8154 /* TODO check compatibility */
8155 } else if (is_type_pointer(type_left)) {
8156 expression->right = create_implicit_cast(right, type_left);
8157 } else if (is_type_pointer(type_right)) {
8158 expression->left = create_implicit_cast(left, type_right);
8159 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8160 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8162 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8166 * Checks if a compound type has constant fields.
8168 static bool has_const_fields(const compound_type_t *type)
8170 compound_t *compound = type->compound;
8171 entity_t *entry = compound->members.entities;
8173 for (; entry != NULL; entry = entry->base.next) {
8174 if (!is_declaration(entry))
8177 const type_t *decl_type = skip_typeref(entry->declaration.type);
8178 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8185 static bool is_valid_assignment_lhs(expression_t const* const left)
8187 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8188 type_t *const type_left = skip_typeref(orig_type_left);
8190 if (!is_lvalue(left)) {
8191 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8196 if (left->kind == EXPR_REFERENCE
8197 && left->reference.entity->kind == ENTITY_FUNCTION) {
8198 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8202 if (is_type_array(type_left)) {
8203 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8206 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8207 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8211 if (is_type_incomplete(type_left)) {
8212 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8213 left, orig_type_left);
8216 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8217 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8218 left, orig_type_left);
8225 static void semantic_arithmetic_assign(binary_expression_t *expression)
8227 expression_t *left = expression->left;
8228 expression_t *right = expression->right;
8229 type_t *orig_type_left = left->base.type;
8230 type_t *orig_type_right = right->base.type;
8232 if (!is_valid_assignment_lhs(left))
8235 type_t *type_left = skip_typeref(orig_type_left);
8236 type_t *type_right = skip_typeref(orig_type_right);
8238 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8239 /* TODO: improve error message */
8240 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8241 errorf(&expression->base.source_position,
8242 "operation needs arithmetic types");
8247 /* combined instructions are tricky. We can't create an implicit cast on
8248 * the left side, because we need the uncasted form for the store.
8249 * The ast2firm pass has to know that left_type must be right_type
8250 * for the arithmetic operation and create a cast by itself */
8251 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8252 expression->right = create_implicit_cast(right, arithmetic_type);
8253 expression->base.type = type_left;
8256 static void semantic_divmod_assign(binary_expression_t *expression)
8258 semantic_arithmetic_assign(expression);
8259 warn_div_by_zero(expression);
8262 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8264 expression_t *const left = expression->left;
8265 expression_t *const right = expression->right;
8266 type_t *const orig_type_left = left->base.type;
8267 type_t *const orig_type_right = right->base.type;
8268 type_t *const type_left = skip_typeref(orig_type_left);
8269 type_t *const type_right = skip_typeref(orig_type_right);
8271 if (!is_valid_assignment_lhs(left))
8274 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8275 /* combined instructions are tricky. We can't create an implicit cast on
8276 * the left side, because we need the uncasted form for the store.
8277 * The ast2firm pass has to know that left_type must be right_type
8278 * for the arithmetic operation and create a cast by itself */
8279 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8280 expression->right = create_implicit_cast(right, arithmetic_type);
8281 expression->base.type = type_left;
8282 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8283 check_pointer_arithmetic(&expression->base.source_position,
8284 type_left, orig_type_left);
8285 expression->base.type = type_left;
8286 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8287 errorf(&expression->base.source_position,
8288 "incompatible types '%T' and '%T' in assignment",
8289 orig_type_left, orig_type_right);
8293 static void semantic_integer_assign(binary_expression_t *expression)
8295 expression_t *left = expression->left;
8296 expression_t *right = expression->right;
8297 type_t *orig_type_left = left->base.type;
8298 type_t *orig_type_right = right->base.type;
8300 if (!is_valid_assignment_lhs(left))
8303 type_t *type_left = skip_typeref(orig_type_left);
8304 type_t *type_right = skip_typeref(orig_type_right);
8306 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8307 /* TODO: improve error message */
8308 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8309 errorf(&expression->base.source_position,
8310 "operation needs integer types");
8315 /* combined instructions are tricky. We can't create an implicit cast on
8316 * the left side, because we need the uncasted form for the store.
8317 * The ast2firm pass has to know that left_type must be right_type
8318 * for the arithmetic operation and create a cast by itself */
8319 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8320 expression->right = create_implicit_cast(right, arithmetic_type);
8321 expression->base.type = type_left;
8324 static void semantic_shift_assign(binary_expression_t *expression)
8326 expression_t *left = expression->left;
8328 if (!is_valid_assignment_lhs(left))
8331 if (!semantic_shift(expression))
8334 expression->base.type = skip_typeref(left->base.type);
8337 static void warn_logical_and_within_or(const expression_t *const expr)
8339 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8341 if (expr->base.parenthesized)
8343 source_position_t const *const pos = &expr->base.source_position;
8344 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8348 * Check the semantic restrictions of a logical expression.
8350 static void semantic_logical_op(binary_expression_t *expression)
8352 /* §6.5.13:2 Each of the operands shall have scalar type.
8353 * §6.5.14:2 Each of the operands shall have scalar type. */
8354 semantic_condition(expression->left, "left operand of logical operator");
8355 semantic_condition(expression->right, "right operand of logical operator");
8356 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8357 warn_logical_and_within_or(expression->left);
8358 warn_logical_and_within_or(expression->right);
8360 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8364 * Check the semantic restrictions of a binary assign expression.
8366 static void semantic_binexpr_assign(binary_expression_t *expression)
8368 expression_t *left = expression->left;
8369 type_t *orig_type_left = left->base.type;
8371 if (!is_valid_assignment_lhs(left))
8374 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8375 report_assign_error(error, orig_type_left, expression->right,
8376 "assignment", &left->base.source_position);
8377 expression->right = create_implicit_cast(expression->right, orig_type_left);
8378 expression->base.type = orig_type_left;
8382 * Determine if the outermost operation (or parts thereof) of the given
8383 * expression has no effect in order to generate a warning about this fact.
8384 * Therefore in some cases this only examines some of the operands of the
8385 * expression (see comments in the function and examples below).
8387 * f() + 23; // warning, because + has no effect
8388 * x || f(); // no warning, because x controls execution of f()
8389 * x ? y : f(); // warning, because y has no effect
8390 * (void)x; // no warning to be able to suppress the warning
8391 * This function can NOT be used for an "expression has definitely no effect"-
8393 static bool expression_has_effect(const expression_t *const expr)
8395 switch (expr->kind) {
8396 case EXPR_ERROR: return true; /* do NOT warn */
8397 case EXPR_REFERENCE: return false;
8398 case EXPR_ENUM_CONSTANT: return false;
8399 case EXPR_LABEL_ADDRESS: return false;
8401 /* suppress the warning for microsoft __noop operations */
8402 case EXPR_LITERAL_MS_NOOP: return true;
8403 case EXPR_LITERAL_BOOLEAN:
8404 case EXPR_LITERAL_CHARACTER:
8405 case EXPR_LITERAL_WIDE_CHARACTER:
8406 case EXPR_LITERAL_INTEGER:
8407 case EXPR_LITERAL_FLOATINGPOINT:
8408 case EXPR_STRING_LITERAL: return false;
8409 case EXPR_WIDE_STRING_LITERAL: return false;
8412 const call_expression_t *const call = &expr->call;
8413 if (call->function->kind != EXPR_REFERENCE)
8416 switch (call->function->reference.entity->function.btk) {
8417 /* FIXME: which builtins have no effect? */
8418 default: return true;
8422 /* Generate the warning if either the left or right hand side of a
8423 * conditional expression has no effect */
8424 case EXPR_CONDITIONAL: {
8425 conditional_expression_t const *const cond = &expr->conditional;
8426 expression_t const *const t = cond->true_expression;
8428 (t == NULL || expression_has_effect(t)) &&
8429 expression_has_effect(cond->false_expression);
8432 case EXPR_SELECT: return false;
8433 case EXPR_ARRAY_ACCESS: return false;
8434 case EXPR_SIZEOF: return false;
8435 case EXPR_CLASSIFY_TYPE: return false;
8436 case EXPR_ALIGNOF: return false;
8438 case EXPR_FUNCNAME: return false;
8439 case EXPR_BUILTIN_CONSTANT_P: return false;
8440 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8441 case EXPR_OFFSETOF: return false;
8442 case EXPR_VA_START: return true;
8443 case EXPR_VA_ARG: return true;
8444 case EXPR_VA_COPY: return true;
8445 case EXPR_STATEMENT: return true; // TODO
8446 case EXPR_COMPOUND_LITERAL: return false;
8448 case EXPR_UNARY_NEGATE: return false;
8449 case EXPR_UNARY_PLUS: return false;
8450 case EXPR_UNARY_BITWISE_NEGATE: return false;
8451 case EXPR_UNARY_NOT: return false;
8452 case EXPR_UNARY_DEREFERENCE: return false;
8453 case EXPR_UNARY_TAKE_ADDRESS: return false;
8454 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8455 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8456 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8457 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8459 /* Treat void casts as if they have an effect in order to being able to
8460 * suppress the warning */
8461 case EXPR_UNARY_CAST: {
8462 type_t *const type = skip_typeref(expr->base.type);
8463 return is_type_void(type);
8466 case EXPR_UNARY_ASSUME: return true;
8467 case EXPR_UNARY_DELETE: return true;
8468 case EXPR_UNARY_DELETE_ARRAY: return true;
8469 case EXPR_UNARY_THROW: return true;
8471 case EXPR_BINARY_ADD: return false;
8472 case EXPR_BINARY_SUB: return false;
8473 case EXPR_BINARY_MUL: return false;
8474 case EXPR_BINARY_DIV: return false;
8475 case EXPR_BINARY_MOD: return false;
8476 case EXPR_BINARY_EQUAL: return false;
8477 case EXPR_BINARY_NOTEQUAL: return false;
8478 case EXPR_BINARY_LESS: return false;
8479 case EXPR_BINARY_LESSEQUAL: return false;
8480 case EXPR_BINARY_GREATER: return false;
8481 case EXPR_BINARY_GREATEREQUAL: return false;
8482 case EXPR_BINARY_BITWISE_AND: return false;
8483 case EXPR_BINARY_BITWISE_OR: return false;
8484 case EXPR_BINARY_BITWISE_XOR: return false;
8485 case EXPR_BINARY_SHIFTLEFT: return false;
8486 case EXPR_BINARY_SHIFTRIGHT: return false;
8487 case EXPR_BINARY_ASSIGN: return true;
8488 case EXPR_BINARY_MUL_ASSIGN: return true;
8489 case EXPR_BINARY_DIV_ASSIGN: return true;
8490 case EXPR_BINARY_MOD_ASSIGN: return true;
8491 case EXPR_BINARY_ADD_ASSIGN: return true;
8492 case EXPR_BINARY_SUB_ASSIGN: return true;
8493 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8494 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8495 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8496 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8497 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8499 /* Only examine the right hand side of && and ||, because the left hand
8500 * side already has the effect of controlling the execution of the right
8502 case EXPR_BINARY_LOGICAL_AND:
8503 case EXPR_BINARY_LOGICAL_OR:
8504 /* Only examine the right hand side of a comma expression, because the left
8505 * hand side has a separate warning */
8506 case EXPR_BINARY_COMMA:
8507 return expression_has_effect(expr->binary.right);
8509 case EXPR_BINARY_ISGREATER: return false;
8510 case EXPR_BINARY_ISGREATEREQUAL: return false;
8511 case EXPR_BINARY_ISLESS: return false;
8512 case EXPR_BINARY_ISLESSEQUAL: return false;
8513 case EXPR_BINARY_ISLESSGREATER: return false;
8514 case EXPR_BINARY_ISUNORDERED: return false;
8517 internal_errorf(HERE, "unexpected expression");
8520 static void semantic_comma(binary_expression_t *expression)
8522 const expression_t *const left = expression->left;
8523 if (!expression_has_effect(left)) {
8524 source_position_t const *const pos = &left->base.source_position;
8525 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8527 expression->base.type = expression->right->base.type;
8531 * @param prec_r precedence of the right operand
8533 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8534 static expression_t *parse_##binexpression_type(expression_t *left) \
8536 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8537 binexpr->binary.left = left; \
8540 expression_t *right = parse_subexpression(prec_r); \
8542 binexpr->binary.right = right; \
8543 sfunc(&binexpr->binary); \
8548 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8549 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8550 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8551 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8552 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8553 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8554 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8555 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8556 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8557 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8558 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8559 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8560 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8561 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8562 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8563 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8564 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8565 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8566 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8567 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8568 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8569 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8570 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8571 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8572 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8573 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8574 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8575 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8576 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8577 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8580 static expression_t *parse_subexpression(precedence_t precedence)
8582 expression_parser_function_t *parser
8583 = &expression_parsers[token.kind];
8586 if (parser->parser != NULL) {
8587 left = parser->parser();
8589 left = parse_primary_expression();
8591 assert(left != NULL);
8594 parser = &expression_parsers[token.kind];
8595 if (parser->infix_parser == NULL)
8597 if (parser->infix_precedence < precedence)
8600 left = parser->infix_parser(left);
8602 assert(left != NULL);
8609 * Parse an expression.
8611 static expression_t *parse_expression(void)
8613 return parse_subexpression(PREC_EXPRESSION);
8617 * Register a parser for a prefix-like operator.
8619 * @param parser the parser function
8620 * @param token_kind the token type of the prefix token
8622 static void register_expression_parser(parse_expression_function parser,
8625 expression_parser_function_t *entry = &expression_parsers[token_kind];
8627 if (entry->parser != NULL) {
8628 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8629 panic("trying to register multiple expression parsers for a token");
8631 entry->parser = parser;
8635 * Register a parser for an infix operator with given precedence.
8637 * @param parser the parser function
8638 * @param token_kind the token type of the infix operator
8639 * @param precedence the precedence of the operator
8641 static void register_infix_parser(parse_expression_infix_function parser,
8642 int token_kind, precedence_t precedence)
8644 expression_parser_function_t *entry = &expression_parsers[token_kind];
8646 if (entry->infix_parser != NULL) {
8647 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8648 panic("trying to register multiple infix expression parsers for a "
8651 entry->infix_parser = parser;
8652 entry->infix_precedence = precedence;
8656 * Initialize the expression parsers.
8658 static void init_expression_parsers(void)
8660 memset(&expression_parsers, 0, sizeof(expression_parsers));
8662 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8663 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8664 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8665 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8666 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8667 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8668 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8669 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8670 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8671 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8672 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8673 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8674 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8675 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8676 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8677 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8678 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8679 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8680 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8681 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8682 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8683 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8684 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8685 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8686 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8687 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8688 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8689 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8690 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8691 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8692 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8693 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8694 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8695 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8696 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8697 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8698 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8700 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8701 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8702 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8703 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8704 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8705 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8706 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8707 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8708 register_expression_parser(parse_sizeof, T_sizeof);
8709 register_expression_parser(parse_alignof, T___alignof__);
8710 register_expression_parser(parse_extension, T___extension__);
8711 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8712 register_expression_parser(parse_delete, T_delete);
8713 register_expression_parser(parse_throw, T_throw);
8717 * Parse a asm statement arguments specification.
8719 static asm_argument_t *parse_asm_arguments(bool is_out)
8721 asm_argument_t *result = NULL;
8722 asm_argument_t **anchor = &result;
8724 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8725 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8728 add_anchor_token(']');
8729 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8730 rem_anchor_token(']');
8732 if (!argument->symbol)
8736 argument->constraints = parse_string_literals();
8738 add_anchor_token(')');
8739 expression_t *expression = parse_expression();
8740 rem_anchor_token(')');
8742 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8743 * change size or type representation (e.g. int -> long is ok, but
8744 * int -> float is not) */
8745 if (expression->kind == EXPR_UNARY_CAST) {
8746 type_t *const type = expression->base.type;
8747 type_kind_t const kind = type->kind;
8748 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8751 if (kind == TYPE_ATOMIC) {
8752 atomic_type_kind_t const akind = type->atomic.akind;
8753 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8754 size = get_atomic_type_size(akind);
8756 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8757 size = get_type_size(type_void_ptr);
8761 expression_t *const value = expression->unary.value;
8762 type_t *const value_type = value->base.type;
8763 type_kind_t const value_kind = value_type->kind;
8765 unsigned value_flags;
8766 unsigned value_size;
8767 if (value_kind == TYPE_ATOMIC) {
8768 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8769 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8770 value_size = get_atomic_type_size(value_akind);
8771 } else if (value_kind == TYPE_POINTER) {
8772 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8773 value_size = get_type_size(type_void_ptr);
8778 if (value_flags != flags || value_size != size)
8782 } while (expression->kind == EXPR_UNARY_CAST);
8786 if (!is_lvalue(expression)) {
8787 errorf(&expression->base.source_position,
8788 "asm output argument is not an lvalue");
8791 if (argument->constraints.begin[0] == '=')
8792 determine_lhs_ent(expression, NULL);
8794 mark_vars_read(expression, NULL);
8796 mark_vars_read(expression, NULL);
8798 argument->expression = expression;
8801 set_address_taken(expression, true);
8804 anchor = &argument->next;
8814 * Parse a asm statement clobber specification.
8816 static asm_clobber_t *parse_asm_clobbers(void)
8818 asm_clobber_t *result = NULL;
8819 asm_clobber_t **anchor = &result;
8821 while (token.kind == T_STRING_LITERAL) {
8822 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8823 clobber->clobber = parse_string_literals();
8826 anchor = &clobber->next;
8836 * Parse an asm statement.
8838 static statement_t *parse_asm_statement(void)
8840 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8841 asm_statement_t *asm_statement = &statement->asms;
8845 if (next_if(T_volatile))
8846 asm_statement->is_volatile = true;
8849 add_anchor_token(')');
8850 if (token.kind != T_STRING_LITERAL) {
8851 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8854 asm_statement->asm_text = parse_string_literals();
8856 add_anchor_token(':');
8857 if (!next_if(':')) {
8858 rem_anchor_token(':');
8862 asm_statement->outputs = parse_asm_arguments(true);
8863 if (!next_if(':')) {
8864 rem_anchor_token(':');
8868 asm_statement->inputs = parse_asm_arguments(false);
8869 if (!next_if(':')) {
8870 rem_anchor_token(':');
8873 rem_anchor_token(':');
8875 asm_statement->clobbers = parse_asm_clobbers();
8878 rem_anchor_token(')');
8882 if (asm_statement->outputs == NULL) {
8883 /* GCC: An 'asm' instruction without any output operands will be treated
8884 * identically to a volatile 'asm' instruction. */
8885 asm_statement->is_volatile = true;
8891 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8893 statement_t *inner_stmt;
8894 switch (token.kind) {
8896 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8897 inner_stmt = create_error_statement();
8901 if (label->kind == STATEMENT_LABEL) {
8902 /* Eat an empty statement here, to avoid the warning about an empty
8903 * statement after a label. label:; is commonly used to have a label
8904 * before a closing brace. */
8905 inner_stmt = create_empty_statement();
8912 inner_stmt = parse_statement();
8913 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8914 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8915 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8916 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8924 * Parse a case statement.
8926 static statement_t *parse_case_statement(void)
8928 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8929 source_position_t *const pos = &statement->base.source_position;
8932 add_anchor_token(':');
8934 expression_t *expression = parse_expression();
8935 type_t *expression_type = expression->base.type;
8936 type_t *skipped = skip_typeref(expression_type);
8937 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8938 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8939 expression, expression_type);
8942 type_t *type = expression_type;
8943 if (current_switch != NULL) {
8944 type_t *switch_type = current_switch->expression->base.type;
8945 if (is_type_valid(switch_type)) {
8946 expression = create_implicit_cast(expression, switch_type);
8950 statement->case_label.expression = expression;
8951 expression_classification_t const expr_class = is_constant_expression(expression);
8952 if (expr_class != EXPR_CLASS_CONSTANT) {
8953 if (expr_class != EXPR_CLASS_ERROR) {
8954 errorf(pos, "case label does not reduce to an integer constant");
8956 statement->case_label.is_bad = true;
8958 long const val = fold_constant_to_int(expression);
8959 statement->case_label.first_case = val;
8960 statement->case_label.last_case = val;
8964 if (next_if(T_DOTDOTDOT)) {
8965 expression_t *end_range = parse_expression();
8966 expression_type = expression->base.type;
8967 skipped = skip_typeref(expression_type);
8968 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8969 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8970 expression, expression_type);
8973 end_range = create_implicit_cast(end_range, type);
8974 statement->case_label.end_range = end_range;
8975 expression_classification_t const end_class = is_constant_expression(end_range);
8976 if (end_class != EXPR_CLASS_CONSTANT) {
8977 if (end_class != EXPR_CLASS_ERROR) {
8978 errorf(pos, "case range does not reduce to an integer constant");
8980 statement->case_label.is_bad = true;
8982 long const val = fold_constant_to_int(end_range);
8983 statement->case_label.last_case = val;
8985 if (val < statement->case_label.first_case) {
8986 statement->case_label.is_empty_range = true;
8987 warningf(WARN_OTHER, pos, "empty range specified");
8993 PUSH_PARENT(statement);
8995 rem_anchor_token(':');
8998 if (current_switch != NULL) {
8999 if (! statement->case_label.is_bad) {
9000 /* Check for duplicate case values */
9001 case_label_statement_t *c = &statement->case_label;
9002 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9003 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9006 if (c->last_case < l->first_case || c->first_case > l->last_case)
9009 errorf(pos, "duplicate case value (previously used %P)",
9010 &l->base.source_position);
9014 /* link all cases into the switch statement */
9015 if (current_switch->last_case == NULL) {
9016 current_switch->first_case = &statement->case_label;
9018 current_switch->last_case->next = &statement->case_label;
9020 current_switch->last_case = &statement->case_label;
9022 errorf(pos, "case label not within a switch statement");
9025 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9032 * Parse a default statement.
9034 static statement_t *parse_default_statement(void)
9036 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9040 PUSH_PARENT(statement);
9044 if (current_switch != NULL) {
9045 const case_label_statement_t *def_label = current_switch->default_label;
9046 if (def_label != NULL) {
9047 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9049 current_switch->default_label = &statement->case_label;
9051 /* link all cases into the switch statement */
9052 if (current_switch->last_case == NULL) {
9053 current_switch->first_case = &statement->case_label;
9055 current_switch->last_case->next = &statement->case_label;
9057 current_switch->last_case = &statement->case_label;
9060 errorf(&statement->base.source_position,
9061 "'default' label not within a switch statement");
9064 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9071 * Parse a label statement.
9073 static statement_t *parse_label_statement(void)
9075 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9076 label_t *const label = get_label();
9077 statement->label.label = label;
9079 PUSH_PARENT(statement);
9081 /* if statement is already set then the label is defined twice,
9082 * otherwise it was just mentioned in a goto/local label declaration so far
9084 source_position_t const* const pos = &statement->base.source_position;
9085 if (label->statement != NULL) {
9086 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9088 label->base.source_position = *pos;
9089 label->statement = statement;
9094 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9095 parse_attributes(NULL); // TODO process attributes
9098 statement->label.statement = parse_label_inner_statement(statement, "label");
9100 /* remember the labels in a list for later checking */
9101 *label_anchor = &statement->label;
9102 label_anchor = &statement->label.next;
9108 static statement_t *parse_inner_statement(void)
9110 statement_t *const stmt = parse_statement();
9111 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9112 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9113 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9114 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9120 * Parse an expression in parentheses and mark its variables as read.
9122 static expression_t *parse_condition(void)
9125 add_anchor_token(')');
9126 expression_t *const expr = parse_expression();
9127 mark_vars_read(expr, NULL);
9128 rem_anchor_token(')');
9134 * Parse an if statement.
9136 static statement_t *parse_if(void)
9138 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9142 PUSH_PARENT(statement);
9143 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9145 add_anchor_token(T_else);
9147 expression_t *const expr = parse_condition();
9148 statement->ifs.condition = expr;
9149 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9151 semantic_condition(expr, "condition of 'if'-statment");
9153 statement_t *const true_stmt = parse_inner_statement();
9154 statement->ifs.true_statement = true_stmt;
9155 rem_anchor_token(T_else);
9157 if (true_stmt->kind == STATEMENT_EMPTY) {
9158 warningf(WARN_EMPTY_BODY, HERE,
9159 "suggest braces around empty body in an ‘if’ statement");
9162 if (next_if(T_else)) {
9163 statement->ifs.false_statement = parse_inner_statement();
9165 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9166 warningf(WARN_EMPTY_BODY, HERE,
9167 "suggest braces around empty body in an ‘if’ statement");
9169 } else if (true_stmt->kind == STATEMENT_IF &&
9170 true_stmt->ifs.false_statement != NULL) {
9171 source_position_t const *const pos = &true_stmt->base.source_position;
9172 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9181 * Check that all enums are handled in a switch.
9183 * @param statement the switch statement to check
9185 static void check_enum_cases(const switch_statement_t *statement)
9187 if (!is_warn_on(WARN_SWITCH_ENUM))
9189 const type_t *type = skip_typeref(statement->expression->base.type);
9190 if (! is_type_enum(type))
9192 const enum_type_t *enumt = &type->enumt;
9194 /* if we have a default, no warnings */
9195 if (statement->default_label != NULL)
9198 /* FIXME: calculation of value should be done while parsing */
9199 /* TODO: quadratic algorithm here. Change to an n log n one */
9200 long last_value = -1;
9201 const entity_t *entry = enumt->enume->base.next;
9202 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9203 entry = entry->base.next) {
9204 const expression_t *expression = entry->enum_value.value;
9205 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9207 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9208 if (l->expression == NULL)
9210 if (l->first_case <= value && value <= l->last_case) {
9216 source_position_t const *const pos = &statement->base.source_position;
9217 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9224 * Parse a switch statement.
9226 static statement_t *parse_switch(void)
9228 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9232 PUSH_PARENT(statement);
9233 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9235 expression_t *const expr = parse_condition();
9236 type_t * type = skip_typeref(expr->base.type);
9237 if (is_type_integer(type)) {
9238 type = promote_integer(type);
9239 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9240 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9242 } else if (is_type_valid(type)) {
9243 errorf(&expr->base.source_position,
9244 "switch quantity is not an integer, but '%T'", type);
9245 type = type_error_type;
9247 statement->switchs.expression = create_implicit_cast(expr, type);
9249 switch_statement_t *rem = current_switch;
9250 current_switch = &statement->switchs;
9251 statement->switchs.body = parse_inner_statement();
9252 current_switch = rem;
9254 if (statement->switchs.default_label == NULL) {
9255 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9257 check_enum_cases(&statement->switchs);
9264 static statement_t *parse_loop_body(statement_t *const loop)
9266 statement_t *const rem = current_loop;
9267 current_loop = loop;
9269 statement_t *const body = parse_inner_statement();
9276 * Parse a while statement.
9278 static statement_t *parse_while(void)
9280 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9284 PUSH_PARENT(statement);
9285 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9287 expression_t *const cond = parse_condition();
9288 statement->whiles.condition = cond;
9289 /* §6.8.5:2 The controlling expression of an iteration statement shall
9290 * have scalar type. */
9291 semantic_condition(cond, "condition of 'while'-statement");
9293 statement->whiles.body = parse_loop_body(statement);
9301 * Parse a do statement.
9303 static statement_t *parse_do(void)
9305 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9309 PUSH_PARENT(statement);
9310 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9312 add_anchor_token(T_while);
9313 statement->do_while.body = parse_loop_body(statement);
9314 rem_anchor_token(T_while);
9317 expression_t *const cond = parse_condition();
9318 statement->do_while.condition = cond;
9319 /* §6.8.5:2 The controlling expression of an iteration statement shall
9320 * have scalar type. */
9321 semantic_condition(cond, "condition of 'do-while'-statement");
9330 * Parse a for statement.
9332 static statement_t *parse_for(void)
9334 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9338 PUSH_PARENT(statement);
9339 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9342 add_anchor_token(')');
9347 } else if (is_declaration_specifier(&token)) {
9348 parse_declaration(record_entity, DECL_FLAGS_NONE);
9350 add_anchor_token(';');
9351 expression_t *const init = parse_expression();
9352 statement->fors.initialisation = init;
9353 mark_vars_read(init, ENT_ANY);
9354 if (!expression_has_effect(init)) {
9355 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9357 rem_anchor_token(';');
9363 if (token.kind != ';') {
9364 add_anchor_token(';');
9365 expression_t *const cond = parse_expression();
9366 statement->fors.condition = cond;
9367 /* §6.8.5:2 The controlling expression of an iteration statement
9368 * shall have scalar type. */
9369 semantic_condition(cond, "condition of 'for'-statement");
9370 mark_vars_read(cond, NULL);
9371 rem_anchor_token(';');
9374 if (token.kind != ')') {
9375 expression_t *const step = parse_expression();
9376 statement->fors.step = step;
9377 mark_vars_read(step, ENT_ANY);
9378 if (!expression_has_effect(step)) {
9379 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9382 rem_anchor_token(')');
9384 statement->fors.body = parse_loop_body(statement);
9392 * Parse a goto statement.
9394 static statement_t *parse_goto(void)
9396 statement_t *statement;
9397 if (GNU_MODE && look_ahead(1)->kind == '*') {
9398 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9402 expression_t *expression = parse_expression();
9403 mark_vars_read(expression, NULL);
9405 /* Argh: although documentation says the expression must be of type void*,
9406 * gcc accepts anything that can be casted into void* without error */
9407 type_t *type = expression->base.type;
9409 if (type != type_error_type) {
9410 if (!is_type_pointer(type) && !is_type_integer(type)) {
9411 errorf(&expression->base.source_position,
9412 "cannot convert to a pointer type");
9413 } else if (type != type_void_ptr) {
9414 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9416 expression = create_implicit_cast(expression, type_void_ptr);
9419 statement->computed_goto.expression = expression;
9421 statement = allocate_statement_zero(STATEMENT_GOTO);
9423 if (token.kind == T_IDENTIFIER) {
9424 label_t *const label = get_label();
9426 statement->gotos.label = label;
9428 /* remember the goto's in a list for later checking */
9429 *goto_anchor = &statement->gotos;
9430 goto_anchor = &statement->gotos.next;
9433 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9435 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9437 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9446 * Parse a continue statement.
9448 static statement_t *parse_continue(void)
9450 if (current_loop == NULL) {
9451 errorf(HERE, "continue statement not within loop");
9454 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9462 * Parse a break statement.
9464 static statement_t *parse_break(void)
9466 if (current_switch == NULL && current_loop == NULL) {
9467 errorf(HERE, "break statement not within loop or switch");
9470 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9478 * Parse a __leave statement.
9480 static statement_t *parse_leave_statement(void)
9482 if (current_try == NULL) {
9483 errorf(HERE, "__leave statement not within __try");
9486 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9494 * Check if a given entity represents a local variable.
9496 static bool is_local_variable(const entity_t *entity)
9498 if (entity->kind != ENTITY_VARIABLE)
9501 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9502 case STORAGE_CLASS_AUTO:
9503 case STORAGE_CLASS_REGISTER: {
9504 const type_t *type = skip_typeref(entity->declaration.type);
9505 if (is_type_function(type)) {
9517 * Check if a given expression represents a local variable.
9519 static bool expression_is_local_variable(const expression_t *expression)
9521 if (expression->base.kind != EXPR_REFERENCE) {
9524 const entity_t *entity = expression->reference.entity;
9525 return is_local_variable(entity);
9529 * Check if a given expression represents a local variable and
9530 * return its declaration then, else return NULL.
9532 entity_t *expression_is_variable(const expression_t *expression)
9534 if (expression->base.kind != EXPR_REFERENCE) {
9537 entity_t *entity = expression->reference.entity;
9538 if (entity->kind != ENTITY_VARIABLE)
9544 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9546 if (c_mode & _CXX || strict_mode) {
9549 warningf(WARN_OTHER, pos, msg);
9554 * Parse a return statement.
9556 static statement_t *parse_return(void)
9558 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9561 expression_t *return_value = NULL;
9562 if (token.kind != ';') {
9563 return_value = parse_expression();
9564 mark_vars_read(return_value, NULL);
9567 const type_t *const func_type = skip_typeref(current_function->base.type);
9568 assert(is_type_function(func_type));
9569 type_t *const return_type = skip_typeref(func_type->function.return_type);
9571 source_position_t const *const pos = &statement->base.source_position;
9572 if (return_value != NULL) {
9573 type_t *return_value_type = skip_typeref(return_value->base.type);
9575 if (is_type_void(return_type)) {
9576 if (!is_type_void(return_value_type)) {
9577 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9578 /* Only warn in C mode, because GCC does the same */
9579 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9580 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9581 /* Only warn in C mode, because GCC does the same */
9582 err_or_warn(pos, "'return' with expression in function returning 'void'");
9585 assign_error_t error = semantic_assign(return_type, return_value);
9586 report_assign_error(error, return_type, return_value, "'return'",
9589 return_value = create_implicit_cast(return_value, return_type);
9590 /* check for returning address of a local var */
9591 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9592 const expression_t *expression = return_value->unary.value;
9593 if (expression_is_local_variable(expression)) {
9594 warningf(WARN_OTHER, pos, "function returns address of local variable");
9597 } else if (!is_type_void(return_type)) {
9598 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9599 err_or_warn(pos, "'return' without value, in function returning non-void");
9601 statement->returns.value = return_value;
9608 * Parse a declaration statement.
9610 static statement_t *parse_declaration_statement(void)
9612 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9614 entity_t *before = current_scope->last_entity;
9616 parse_external_declaration();
9618 parse_declaration(record_entity, DECL_FLAGS_NONE);
9621 declaration_statement_t *const decl = &statement->declaration;
9622 entity_t *const begin =
9623 before != NULL ? before->base.next : current_scope->entities;
9624 decl->declarations_begin = begin;
9625 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9631 * Parse an expression statement, ie. expr ';'.
9633 static statement_t *parse_expression_statement(void)
9635 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9637 expression_t *const expr = parse_expression();
9638 statement->expression.expression = expr;
9639 mark_vars_read(expr, ENT_ANY);
9646 * Parse a microsoft __try { } __finally { } or
9647 * __try{ } __except() { }
9649 static statement_t *parse_ms_try_statment(void)
9651 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9654 PUSH_PARENT(statement);
9656 ms_try_statement_t *rem = current_try;
9657 current_try = &statement->ms_try;
9658 statement->ms_try.try_statement = parse_compound_statement(false);
9663 if (next_if(T___except)) {
9664 expression_t *const expr = parse_condition();
9665 type_t * type = skip_typeref(expr->base.type);
9666 if (is_type_integer(type)) {
9667 type = promote_integer(type);
9668 } else if (is_type_valid(type)) {
9669 errorf(&expr->base.source_position,
9670 "__expect expression is not an integer, but '%T'", type);
9671 type = type_error_type;
9673 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9674 } else if (!next_if(T__finally)) {
9675 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9677 statement->ms_try.final_statement = parse_compound_statement(false);
9681 static statement_t *parse_empty_statement(void)
9683 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9684 statement_t *const statement = create_empty_statement();
9689 static statement_t *parse_local_label_declaration(void)
9691 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9695 entity_t *begin = NULL;
9696 entity_t *end = NULL;
9697 entity_t **anchor = &begin;
9699 source_position_t pos;
9700 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9704 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9705 if (entity != NULL && entity->base.parent_scope == current_scope) {
9706 source_position_t const *const ppos = &entity->base.source_position;
9707 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9709 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9710 entity->base.parent_scope = current_scope;
9713 anchor = &entity->base.next;
9716 environment_push(entity);
9718 } while (next_if(','));
9721 statement->declaration.declarations_begin = begin;
9722 statement->declaration.declarations_end = end;
9726 static void parse_namespace_definition(void)
9730 entity_t *entity = NULL;
9731 symbol_t *symbol = NULL;
9733 if (token.kind == T_IDENTIFIER) {
9734 symbol = token.identifier.symbol;
9737 entity = get_entity(symbol, NAMESPACE_NORMAL);
9739 && entity->kind != ENTITY_NAMESPACE
9740 && entity->base.parent_scope == current_scope) {
9741 if (is_entity_valid(entity)) {
9742 error_redefined_as_different_kind(&token.base.source_position,
9743 entity, ENTITY_NAMESPACE);
9749 if (entity == NULL) {
9750 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9751 entity->base.parent_scope = current_scope;
9754 if (token.kind == '=') {
9755 /* TODO: parse namespace alias */
9756 panic("namespace alias definition not supported yet");
9759 environment_push(entity);
9760 append_entity(current_scope, entity);
9762 PUSH_SCOPE(&entity->namespacee.members);
9763 PUSH_CURRENT_ENTITY(entity);
9765 add_anchor_token('}');
9768 rem_anchor_token('}');
9771 POP_CURRENT_ENTITY();
9776 * Parse a statement.
9777 * There's also parse_statement() which additionally checks for
9778 * "statement has no effect" warnings
9780 static statement_t *intern_parse_statement(void)
9782 /* declaration or statement */
9783 statement_t *statement;
9784 switch (token.kind) {
9785 case T_IDENTIFIER: {
9786 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9787 if (la1_type == ':') {
9788 statement = parse_label_statement();
9789 } else if (is_typedef_symbol(token.identifier.symbol)) {
9790 statement = parse_declaration_statement();
9792 /* it's an identifier, the grammar says this must be an
9793 * expression statement. However it is common that users mistype
9794 * declaration types, so we guess a bit here to improve robustness
9795 * for incorrect programs */
9799 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9801 statement = parse_expression_statement();
9805 statement = parse_declaration_statement();
9813 case T___extension__: {
9814 /* This can be a prefix to a declaration or an expression statement.
9815 * We simply eat it now and parse the rest with tail recursion. */
9817 statement = intern_parse_statement();
9823 statement = parse_declaration_statement();
9827 statement = parse_local_label_declaration();
9830 case ';': statement = parse_empty_statement(); break;
9831 case '{': statement = parse_compound_statement(false); break;
9832 case T___leave: statement = parse_leave_statement(); break;
9833 case T___try: statement = parse_ms_try_statment(); break;
9834 case T_asm: statement = parse_asm_statement(); break;
9835 case T_break: statement = parse_break(); break;
9836 case T_case: statement = parse_case_statement(); break;
9837 case T_continue: statement = parse_continue(); break;
9838 case T_default: statement = parse_default_statement(); break;
9839 case T_do: statement = parse_do(); break;
9840 case T_for: statement = parse_for(); break;
9841 case T_goto: statement = parse_goto(); break;
9842 case T_if: statement = parse_if(); break;
9843 case T_return: statement = parse_return(); break;
9844 case T_switch: statement = parse_switch(); break;
9845 case T_while: statement = parse_while(); break;
9848 statement = parse_expression_statement();
9852 errorf(HERE, "unexpected token %K while parsing statement", &token);
9853 statement = create_error_statement();
9862 * parse a statement and emits "statement has no effect" warning if needed
9863 * (This is really a wrapper around intern_parse_statement with check for 1
9864 * single warning. It is needed, because for statement expressions we have
9865 * to avoid the warning on the last statement)
9867 static statement_t *parse_statement(void)
9869 statement_t *statement = intern_parse_statement();
9871 if (statement->kind == STATEMENT_EXPRESSION) {
9872 expression_t *expression = statement->expression.expression;
9873 if (!expression_has_effect(expression)) {
9874 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9882 * Parse a compound statement.
9884 static statement_t *parse_compound_statement(bool inside_expression_statement)
9886 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9888 PUSH_PARENT(statement);
9889 PUSH_SCOPE(&statement->compound.scope);
9892 add_anchor_token('}');
9893 /* tokens, which can start a statement */
9894 /* TODO MS, __builtin_FOO */
9895 add_anchor_token('!');
9896 add_anchor_token('&');
9897 add_anchor_token('(');
9898 add_anchor_token('*');
9899 add_anchor_token('+');
9900 add_anchor_token('-');
9901 add_anchor_token(';');
9902 add_anchor_token('{');
9903 add_anchor_token('~');
9904 add_anchor_token(T_CHARACTER_CONSTANT);
9905 add_anchor_token(T_COLONCOLON);
9906 add_anchor_token(T_FLOATINGPOINT);
9907 add_anchor_token(T_IDENTIFIER);
9908 add_anchor_token(T_INTEGER);
9909 add_anchor_token(T_MINUSMINUS);
9910 add_anchor_token(T_PLUSPLUS);
9911 add_anchor_token(T_STRING_LITERAL);
9912 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
9913 add_anchor_token(T_WIDE_STRING_LITERAL);
9914 add_anchor_token(T__Bool);
9915 add_anchor_token(T__Complex);
9916 add_anchor_token(T__Imaginary);
9917 add_anchor_token(T___FUNCTION__);
9918 add_anchor_token(T___PRETTY_FUNCTION__);
9919 add_anchor_token(T___alignof__);
9920 add_anchor_token(T___attribute__);
9921 add_anchor_token(T___builtin_va_start);
9922 add_anchor_token(T___extension__);
9923 add_anchor_token(T___func__);
9924 add_anchor_token(T___imag__);
9925 add_anchor_token(T___label__);
9926 add_anchor_token(T___real__);
9927 add_anchor_token(T___thread);
9928 add_anchor_token(T_asm);
9929 add_anchor_token(T_auto);
9930 add_anchor_token(T_bool);
9931 add_anchor_token(T_break);
9932 add_anchor_token(T_case);
9933 add_anchor_token(T_char);
9934 add_anchor_token(T_class);
9935 add_anchor_token(T_const);
9936 add_anchor_token(T_const_cast);
9937 add_anchor_token(T_continue);
9938 add_anchor_token(T_default);
9939 add_anchor_token(T_delete);
9940 add_anchor_token(T_double);
9941 add_anchor_token(T_do);
9942 add_anchor_token(T_dynamic_cast);
9943 add_anchor_token(T_enum);
9944 add_anchor_token(T_extern);
9945 add_anchor_token(T_false);
9946 add_anchor_token(T_float);
9947 add_anchor_token(T_for);
9948 add_anchor_token(T_goto);
9949 add_anchor_token(T_if);
9950 add_anchor_token(T_inline);
9951 add_anchor_token(T_int);
9952 add_anchor_token(T_long);
9953 add_anchor_token(T_new);
9954 add_anchor_token(T_operator);
9955 add_anchor_token(T_register);
9956 add_anchor_token(T_reinterpret_cast);
9957 add_anchor_token(T_restrict);
9958 add_anchor_token(T_return);
9959 add_anchor_token(T_short);
9960 add_anchor_token(T_signed);
9961 add_anchor_token(T_sizeof);
9962 add_anchor_token(T_static);
9963 add_anchor_token(T_static_cast);
9964 add_anchor_token(T_struct);
9965 add_anchor_token(T_switch);
9966 add_anchor_token(T_template);
9967 add_anchor_token(T_this);
9968 add_anchor_token(T_throw);
9969 add_anchor_token(T_true);
9970 add_anchor_token(T_try);
9971 add_anchor_token(T_typedef);
9972 add_anchor_token(T_typeid);
9973 add_anchor_token(T_typename);
9974 add_anchor_token(T_typeof);
9975 add_anchor_token(T_union);
9976 add_anchor_token(T_unsigned);
9977 add_anchor_token(T_using);
9978 add_anchor_token(T_void);
9979 add_anchor_token(T_volatile);
9980 add_anchor_token(T_wchar_t);
9981 add_anchor_token(T_while);
9983 statement_t **anchor = &statement->compound.statements;
9984 bool only_decls_so_far = true;
9985 while (token.kind != '}' && token.kind != T_EOF) {
9986 statement_t *sub_statement = intern_parse_statement();
9987 if (sub_statement->kind == STATEMENT_ERROR) {
9991 if (sub_statement->kind != STATEMENT_DECLARATION) {
9992 only_decls_so_far = false;
9993 } else if (!only_decls_so_far) {
9994 source_position_t const *const pos = &sub_statement->base.source_position;
9995 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9998 *anchor = sub_statement;
9999 anchor = &sub_statement->base.next;
10003 /* look over all statements again to produce no effect warnings */
10004 if (is_warn_on(WARN_UNUSED_VALUE)) {
10005 statement_t *sub_statement = statement->compound.statements;
10006 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10007 if (sub_statement->kind != STATEMENT_EXPRESSION)
10009 /* don't emit a warning for the last expression in an expression
10010 * statement as it has always an effect */
10011 if (inside_expression_statement && sub_statement->base.next == NULL)
10014 expression_t *expression = sub_statement->expression.expression;
10015 if (!expression_has_effect(expression)) {
10016 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10021 rem_anchor_token(T_while);
10022 rem_anchor_token(T_wchar_t);
10023 rem_anchor_token(T_volatile);
10024 rem_anchor_token(T_void);
10025 rem_anchor_token(T_using);
10026 rem_anchor_token(T_unsigned);
10027 rem_anchor_token(T_union);
10028 rem_anchor_token(T_typeof);
10029 rem_anchor_token(T_typename);
10030 rem_anchor_token(T_typeid);
10031 rem_anchor_token(T_typedef);
10032 rem_anchor_token(T_try);
10033 rem_anchor_token(T_true);
10034 rem_anchor_token(T_throw);
10035 rem_anchor_token(T_this);
10036 rem_anchor_token(T_template);
10037 rem_anchor_token(T_switch);
10038 rem_anchor_token(T_struct);
10039 rem_anchor_token(T_static_cast);
10040 rem_anchor_token(T_static);
10041 rem_anchor_token(T_sizeof);
10042 rem_anchor_token(T_signed);
10043 rem_anchor_token(T_short);
10044 rem_anchor_token(T_return);
10045 rem_anchor_token(T_restrict);
10046 rem_anchor_token(T_reinterpret_cast);
10047 rem_anchor_token(T_register);
10048 rem_anchor_token(T_operator);
10049 rem_anchor_token(T_new);
10050 rem_anchor_token(T_long);
10051 rem_anchor_token(T_int);
10052 rem_anchor_token(T_inline);
10053 rem_anchor_token(T_if);
10054 rem_anchor_token(T_goto);
10055 rem_anchor_token(T_for);
10056 rem_anchor_token(T_float);
10057 rem_anchor_token(T_false);
10058 rem_anchor_token(T_extern);
10059 rem_anchor_token(T_enum);
10060 rem_anchor_token(T_dynamic_cast);
10061 rem_anchor_token(T_do);
10062 rem_anchor_token(T_double);
10063 rem_anchor_token(T_delete);
10064 rem_anchor_token(T_default);
10065 rem_anchor_token(T_continue);
10066 rem_anchor_token(T_const_cast);
10067 rem_anchor_token(T_const);
10068 rem_anchor_token(T_class);
10069 rem_anchor_token(T_char);
10070 rem_anchor_token(T_case);
10071 rem_anchor_token(T_break);
10072 rem_anchor_token(T_bool);
10073 rem_anchor_token(T_auto);
10074 rem_anchor_token(T_asm);
10075 rem_anchor_token(T___thread);
10076 rem_anchor_token(T___real__);
10077 rem_anchor_token(T___label__);
10078 rem_anchor_token(T___imag__);
10079 rem_anchor_token(T___func__);
10080 rem_anchor_token(T___extension__);
10081 rem_anchor_token(T___builtin_va_start);
10082 rem_anchor_token(T___attribute__);
10083 rem_anchor_token(T___alignof__);
10084 rem_anchor_token(T___PRETTY_FUNCTION__);
10085 rem_anchor_token(T___FUNCTION__);
10086 rem_anchor_token(T__Imaginary);
10087 rem_anchor_token(T__Complex);
10088 rem_anchor_token(T__Bool);
10089 rem_anchor_token(T_WIDE_STRING_LITERAL);
10090 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10091 rem_anchor_token(T_STRING_LITERAL);
10092 rem_anchor_token(T_PLUSPLUS);
10093 rem_anchor_token(T_MINUSMINUS);
10094 rem_anchor_token(T_INTEGER);
10095 rem_anchor_token(T_IDENTIFIER);
10096 rem_anchor_token(T_FLOATINGPOINT);
10097 rem_anchor_token(T_COLONCOLON);
10098 rem_anchor_token(T_CHARACTER_CONSTANT);
10099 rem_anchor_token('~');
10100 rem_anchor_token('{');
10101 rem_anchor_token(';');
10102 rem_anchor_token('-');
10103 rem_anchor_token('+');
10104 rem_anchor_token('*');
10105 rem_anchor_token('(');
10106 rem_anchor_token('&');
10107 rem_anchor_token('!');
10108 rem_anchor_token('}');
10116 * Check for unused global static functions and variables
10118 static void check_unused_globals(void)
10120 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10123 for (const entity_t *entity = file_scope->entities; entity != NULL;
10124 entity = entity->base.next) {
10125 if (!is_declaration(entity))
10128 const declaration_t *declaration = &entity->declaration;
10129 if (declaration->used ||
10130 declaration->modifiers & DM_UNUSED ||
10131 declaration->modifiers & DM_USED ||
10132 declaration->storage_class != STORAGE_CLASS_STATIC)
10137 if (entity->kind == ENTITY_FUNCTION) {
10138 /* inhibit warning for static inline functions */
10139 if (entity->function.is_inline)
10142 why = WARN_UNUSED_FUNCTION;
10143 s = entity->function.statement != NULL ? "defined" : "declared";
10145 why = WARN_UNUSED_VARIABLE;
10149 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10153 static void parse_global_asm(void)
10155 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10158 add_anchor_token(';');
10159 add_anchor_token(')');
10160 add_anchor_token(T_STRING_LITERAL);
10163 rem_anchor_token(T_STRING_LITERAL);
10164 statement->asms.asm_text = parse_string_literals();
10165 statement->base.next = unit->global_asm;
10166 unit->global_asm = statement;
10168 rem_anchor_token(')');
10170 rem_anchor_token(';');
10174 static void parse_linkage_specification(void)
10178 source_position_t const pos = *HERE;
10179 char const *const linkage = parse_string_literals().begin;
10181 linkage_kind_t old_linkage = current_linkage;
10182 linkage_kind_t new_linkage;
10183 if (streq(linkage, "C")) {
10184 new_linkage = LINKAGE_C;
10185 } else if (streq(linkage, "C++")) {
10186 new_linkage = LINKAGE_CXX;
10188 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10189 new_linkage = LINKAGE_C;
10191 current_linkage = new_linkage;
10193 if (next_if('{')) {
10200 assert(current_linkage == new_linkage);
10201 current_linkage = old_linkage;
10204 static void parse_external(void)
10206 switch (token.kind) {
10208 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10209 parse_linkage_specification();
10211 DECLARATION_START_NO_EXTERN
10213 case T___extension__:
10214 /* tokens below are for implicit int */
10215 case '&': /* & x; -> int& x; (and error later, because C++ has no
10217 case '*': /* * x; -> int* x; */
10218 case '(': /* (x); -> int (x); */
10220 parse_external_declaration();
10226 parse_global_asm();
10230 parse_namespace_definition();
10234 if (!strict_mode) {
10235 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10242 errorf(HERE, "stray %K outside of function", &token);
10243 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10244 eat_until_matching_token(token.kind);
10250 static void parse_externals(void)
10252 add_anchor_token('}');
10253 add_anchor_token(T_EOF);
10256 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10257 unsigned short token_anchor_copy[T_LAST_TOKEN];
10258 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10261 while (token.kind != T_EOF && token.kind != '}') {
10263 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10264 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10266 /* the anchor set and its copy differs */
10267 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10270 if (in_gcc_extension) {
10271 /* an gcc extension scope was not closed */
10272 internal_errorf(HERE, "Leaked __extension__");
10279 rem_anchor_token(T_EOF);
10280 rem_anchor_token('}');
10284 * Parse a translation unit.
10286 static void parse_translation_unit(void)
10288 add_anchor_token(T_EOF);
10293 if (token.kind == T_EOF)
10296 errorf(HERE, "stray %K outside of function", &token);
10297 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10298 eat_until_matching_token(token.kind);
10303 void set_default_visibility(elf_visibility_tag_t visibility)
10305 default_visibility = visibility;
10311 * @return the translation unit or NULL if errors occurred.
10313 void start_parsing(void)
10315 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10316 label_stack = NEW_ARR_F(stack_entry_t, 0);
10317 diagnostic_count = 0;
10321 print_to_file(stderr);
10323 assert(unit == NULL);
10324 unit = allocate_ast_zero(sizeof(unit[0]));
10326 assert(file_scope == NULL);
10327 file_scope = &unit->scope;
10329 assert(current_scope == NULL);
10330 scope_push(&unit->scope);
10332 create_gnu_builtins();
10334 create_microsoft_intrinsics();
10337 translation_unit_t *finish_parsing(void)
10339 assert(current_scope == &unit->scope);
10342 assert(file_scope == &unit->scope);
10343 check_unused_globals();
10346 DEL_ARR_F(environment_stack);
10347 DEL_ARR_F(label_stack);
10349 translation_unit_t *result = unit;
10354 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10355 * are given length one. */
10356 static void complete_incomplete_arrays(void)
10358 size_t n = ARR_LEN(incomplete_arrays);
10359 for (size_t i = 0; i != n; ++i) {
10360 declaration_t *const decl = incomplete_arrays[i];
10361 type_t *const type = skip_typeref(decl->type);
10363 if (!is_type_incomplete(type))
10366 source_position_t const *const pos = &decl->base.source_position;
10367 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10369 type_t *const new_type = duplicate_type(type);
10370 new_type->array.size_constant = true;
10371 new_type->array.has_implicit_size = true;
10372 new_type->array.size = 1;
10374 type_t *const result = identify_new_type(new_type);
10376 decl->type = result;
10380 static void prepare_main_collect2(entity_t *const entity)
10382 PUSH_SCOPE(&entity->function.statement->compound.scope);
10384 // create call to __main
10385 symbol_t *symbol = symbol_table_insert("__main");
10386 entity_t *subsubmain_ent
10387 = create_implicit_function(symbol, &builtin_source_position);
10389 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10390 type_t *ftype = subsubmain_ent->declaration.type;
10391 ref->base.source_position = builtin_source_position;
10392 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10393 ref->reference.entity = subsubmain_ent;
10395 expression_t *call = allocate_expression_zero(EXPR_CALL);
10396 call->base.source_position = builtin_source_position;
10397 call->base.type = type_void;
10398 call->call.function = ref;
10400 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10401 expr_statement->base.source_position = builtin_source_position;
10402 expr_statement->expression.expression = call;
10404 statement_t *statement = entity->function.statement;
10405 assert(statement->kind == STATEMENT_COMPOUND);
10406 compound_statement_t *compounds = &statement->compound;
10408 expr_statement->base.next = compounds->statements;
10409 compounds->statements = expr_statement;
10416 lookahead_bufpos = 0;
10417 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10420 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10421 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10422 parse_translation_unit();
10423 complete_incomplete_arrays();
10424 DEL_ARR_F(incomplete_arrays);
10425 incomplete_arrays = NULL;
10429 * Initialize the parser.
10431 void init_parser(void)
10433 sym_anonymous = symbol_table_insert("<anonymous>");
10435 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10437 init_expression_parsers();
10438 obstack_init(&temp_obst);
10442 * Terminate the parser.
10444 void exit_parser(void)
10446 obstack_free(&temp_obst, NULL);