2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_CURRENT_ENTITY(entity) \
113 entity_t *const new_current_entity = (entity); \
114 entity_t *const old_current_entity = current_entity; \
115 ((void)(current_entity = new_current_entity))
116 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
118 #define PUSH_PARENT(stmt) \
119 statement_t *const new_parent = (stmt); \
120 statement_t *const old_parent = current_parent; \
121 ((void)(current_parent = new_parent))
122 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
124 #define PUSH_SCOPE(scope) \
125 size_t const top = environment_top(); \
126 scope_t *const new_scope = (scope); \
127 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
128 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
129 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
131 #define PUSH_EXTENSION() \
133 bool const old_gcc_extension = in_gcc_extension; \
134 while (next_if(T___extension__)) { \
135 in_gcc_extension = true; \
138 #define POP_EXTENSION() \
139 ((void)(in_gcc_extension = old_gcc_extension))
141 /** special symbol used for anonymous entities. */
142 static symbol_t *sym_anonymous = NULL;
144 /** The token anchor set */
145 static unsigned short token_anchor_set[T_LAST_TOKEN];
147 /** The current source position. */
148 #define HERE (&token.base.source_position)
150 /** true if we are in GCC mode. */
151 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
153 static statement_t *parse_compound_statement(bool inside_expression_statement);
154 static statement_t *parse_statement(void);
156 static expression_t *parse_subexpression(precedence_t);
157 static expression_t *parse_expression(void);
158 static type_t *parse_typename(void);
159 static void parse_externals(void);
160 static void parse_external(void);
162 static void parse_compound_type_entries(compound_t *compound_declaration);
164 static void check_call_argument(type_t *expected_type,
165 call_argument_t *argument, unsigned pos);
167 typedef enum declarator_flags_t {
169 DECL_MAY_BE_ABSTRACT = 1U << 0,
170 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
171 DECL_IS_PARAMETER = 1U << 2
172 } declarator_flags_t;
174 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
175 declarator_flags_t flags);
177 static void semantic_comparison(binary_expression_t *expression);
179 #define STORAGE_CLASSES \
180 STORAGE_CLASSES_NO_EXTERN \
183 #define STORAGE_CLASSES_NO_EXTERN \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #define COMPLEX_SPECIFIERS \
200 #define IMAGINARY_SPECIFIERS \
203 #define TYPE_SPECIFIERS \
205 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define DECLARATION_START_NO_EXTERN \
236 STORAGE_CLASSES_NO_EXTERN \
240 #define EXPRESSION_START \
249 case T_CHARACTER_CONSTANT: \
250 case T_FLOATINGPOINT: \
254 case T_STRING_LITERAL: \
255 case T_WIDE_CHARACTER_CONSTANT: \
256 case T_WIDE_STRING_LITERAL: \
257 case T___FUNCDNAME__: \
258 case T___FUNCSIG__: \
259 case T___FUNCTION__: \
260 case T___PRETTY_FUNCTION__: \
261 case T___alignof__: \
262 case T___builtin_classify_type: \
263 case T___builtin_constant_p: \
264 case T___builtin_isgreater: \
265 case T___builtin_isgreaterequal: \
266 case T___builtin_isless: \
267 case T___builtin_islessequal: \
268 case T___builtin_islessgreater: \
269 case T___builtin_isunordered: \
270 case T___builtin_offsetof: \
271 case T___builtin_va_arg: \
272 case T___builtin_va_copy: \
273 case T___builtin_va_start: \
284 * Returns the size of a statement node.
286 * @param kind the statement kind
288 static size_t get_statement_struct_size(statement_kind_t kind)
290 static const size_t sizes[] = {
291 [STATEMENT_ERROR] = sizeof(statement_base_t),
292 [STATEMENT_EMPTY] = sizeof(statement_base_t),
293 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
294 [STATEMENT_RETURN] = sizeof(return_statement_t),
295 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
296 [STATEMENT_IF] = sizeof(if_statement_t),
297 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
298 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
299 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
300 [STATEMENT_BREAK] = sizeof(statement_base_t),
301 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
302 [STATEMENT_GOTO] = sizeof(goto_statement_t),
303 [STATEMENT_LABEL] = sizeof(label_statement_t),
304 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
305 [STATEMENT_WHILE] = sizeof(while_statement_t),
306 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
307 [STATEMENT_FOR] = sizeof(for_statement_t),
308 [STATEMENT_ASM] = sizeof(asm_statement_t),
309 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
310 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
312 assert((size_t)kind < lengthof(sizes));
313 assert(sizes[kind] != 0);
318 * Returns the size of an expression node.
320 * @param kind the expression kind
322 static size_t get_expression_struct_size(expression_kind_t kind)
324 static const size_t sizes[] = {
325 [EXPR_ERROR] = sizeof(expression_base_t),
326 [EXPR_REFERENCE] = sizeof(reference_expression_t),
327 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
328 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
332 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
333 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
334 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
335 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
336 [EXPR_CALL] = sizeof(call_expression_t),
337 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
338 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
339 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
340 [EXPR_SELECT] = sizeof(select_expression_t),
341 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
342 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
343 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
344 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
345 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
346 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
347 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
348 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
349 [EXPR_VA_START] = sizeof(va_start_expression_t),
350 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
351 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
352 [EXPR_STATEMENT] = sizeof(statement_expression_t),
353 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
355 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
356 return sizes[EXPR_UNARY_FIRST];
358 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
359 return sizes[EXPR_BINARY_FIRST];
361 assert((size_t)kind < lengthof(sizes));
362 assert(sizes[kind] != 0);
367 * Allocate a statement node of given kind and initialize all
368 * fields with zero. Sets its source position to the position
369 * of the current token.
371 static statement_t *allocate_statement_zero(statement_kind_t kind)
373 size_t size = get_statement_struct_size(kind);
374 statement_t *res = allocate_ast_zero(size);
376 res->base.kind = kind;
377 res->base.parent = current_parent;
378 res->base.source_position = token.base.source_position;
383 * Allocate an expression node of given kind and initialize all
386 * @param kind the kind of the expression to allocate
388 static expression_t *allocate_expression_zero(expression_kind_t kind)
390 size_t size = get_expression_struct_size(kind);
391 expression_t *res = allocate_ast_zero(size);
393 res->base.kind = kind;
394 res->base.type = type_error_type;
395 res->base.source_position = token.base.source_position;
400 * Creates a new invalid expression at the source position
401 * of the current token.
403 static expression_t *create_error_expression(void)
405 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
406 expression->base.type = type_error_type;
411 * Creates a new invalid statement.
413 static statement_t *create_error_statement(void)
415 return allocate_statement_zero(STATEMENT_ERROR);
419 * Allocate a new empty statement.
421 static statement_t *create_empty_statement(void)
423 return allocate_statement_zero(STATEMENT_EMPTY);
427 * Returns the size of an initializer node.
429 * @param kind the initializer kind
431 static size_t get_initializer_size(initializer_kind_t kind)
433 static const size_t sizes[] = {
434 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
435 [INITIALIZER_STRING] = sizeof(initializer_string_t),
436 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
437 [INITIALIZER_LIST] = sizeof(initializer_list_t),
438 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
440 assert((size_t)kind < lengthof(sizes));
441 assert(sizes[kind] != 0);
446 * Allocate an initializer node of given kind and initialize all
449 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
451 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
458 * Returns the index of the top element of the environment stack.
460 static size_t environment_top(void)
462 return ARR_LEN(environment_stack);
466 * Returns the index of the top element of the global label stack.
468 static size_t label_top(void)
470 return ARR_LEN(label_stack);
474 * Return the next token.
476 static inline void next_token(void)
478 token = lookahead_buffer[lookahead_bufpos];
479 lookahead_buffer[lookahead_bufpos] = lexer_token;
482 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
485 print_token(stderr, &token);
486 fprintf(stderr, "\n");
490 static inline bool next_if(token_kind_t const type)
492 if (token.kind == type) {
501 * Return the next token with a given lookahead.
503 static inline const token_t *look_ahead(size_t num)
505 assert(0 < num && num <= MAX_LOOKAHEAD);
506 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
507 return &lookahead_buffer[pos];
511 * Adds a token type to the token type anchor set (a multi-set).
513 static void add_anchor_token(token_kind_t const token_kind)
515 assert(token_kind < T_LAST_TOKEN);
516 ++token_anchor_set[token_kind];
520 * Remove a token type from the token type anchor set (a multi-set).
522 static void rem_anchor_token(token_kind_t const token_kind)
524 assert(token_kind < T_LAST_TOKEN);
525 assert(token_anchor_set[token_kind] != 0);
526 --token_anchor_set[token_kind];
530 * Eat tokens until a matching token type is found.
532 static void eat_until_matching_token(token_kind_t const type)
534 token_kind_t end_token;
536 case '(': end_token = ')'; break;
537 case '{': end_token = '}'; break;
538 case '[': end_token = ']'; break;
539 default: end_token = type; break;
542 unsigned parenthesis_count = 0;
543 unsigned brace_count = 0;
544 unsigned bracket_count = 0;
545 while (token.kind != end_token ||
546 parenthesis_count != 0 ||
548 bracket_count != 0) {
549 switch (token.kind) {
551 case '(': ++parenthesis_count; break;
552 case '{': ++brace_count; break;
553 case '[': ++bracket_count; break;
556 if (parenthesis_count > 0)
566 if (bracket_count > 0)
569 if (token.kind == end_token &&
570 parenthesis_count == 0 &&
584 * Eat input tokens until an anchor is found.
586 static void eat_until_anchor(void)
588 while (token_anchor_set[token.kind] == 0) {
589 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
590 eat_until_matching_token(token.kind);
596 * Eat a whole block from input tokens.
598 static void eat_block(void)
600 eat_until_matching_token('{');
604 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
607 * Report a parse error because an expected token was not found.
610 #if defined __GNUC__ && __GNUC__ >= 4
611 __attribute__((sentinel))
613 void parse_error_expected(const char *message, ...)
615 if (message != NULL) {
616 errorf(HERE, "%s", message);
619 va_start(ap, message);
620 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
625 * Report an incompatible type.
627 static void type_error_incompatible(const char *msg,
628 const source_position_t *source_position, type_t *type1, type_t *type2)
630 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
635 * Expect the current token is the expected token.
636 * If not, generate an error and skip until the next anchor.
638 static void expect(token_kind_t const expected)
640 if (UNLIKELY(token.kind != expected)) {
641 parse_error_expected(NULL, expected, NULL);
642 add_anchor_token(expected);
644 rem_anchor_token(expected);
645 if (token.kind != expected)
651 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
653 if (token.kind != T_IDENTIFIER) {
654 parse_error_expected(context, T_IDENTIFIER, NULL);
655 add_anchor_token(T_IDENTIFIER);
657 rem_anchor_token(T_IDENTIFIER);
658 if (token.kind != T_IDENTIFIER)
661 symbol_t *const sym = token.base.symbol;
669 * Push a given scope on the scope stack and make it the
672 static scope_t *scope_push(scope_t *new_scope)
674 if (current_scope != NULL) {
675 new_scope->depth = current_scope->depth + 1;
678 scope_t *old_scope = current_scope;
679 current_scope = new_scope;
684 * Pop the current scope from the scope stack.
686 static void scope_pop(scope_t *old_scope)
688 current_scope = old_scope;
692 * Search an entity by its symbol in a given namespace.
694 static entity_t *get_entity(const symbol_t *const symbol,
695 namespace_tag_t namespc)
697 entity_t *entity = symbol->entity;
698 for (; entity != NULL; entity = entity->base.symbol_next) {
699 if ((namespace_tag_t)entity->base.namespc == namespc)
706 /* §6.2.3:1 24) There is only one name space for tags even though three are
708 static entity_t *get_tag(symbol_t const *const symbol,
709 entity_kind_tag_t const kind)
711 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
712 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
714 "'%Y' defined as wrong kind of tag (previous definition %P)",
715 symbol, &entity->base.source_position);
722 * pushs an entity on the environment stack and links the corresponding symbol
725 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
727 symbol_t *symbol = entity->base.symbol;
728 entity_namespace_t namespc = entity->base.namespc;
729 assert(namespc != 0);
731 /* replace/add entity into entity list of the symbol */
734 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
739 /* replace an entry? */
740 if (iter->base.namespc == namespc) {
741 entity->base.symbol_next = iter->base.symbol_next;
747 /* remember old declaration */
749 entry.symbol = symbol;
750 entry.old_entity = iter;
751 entry.namespc = namespc;
752 ARR_APP1(stack_entry_t, *stack_ptr, entry);
756 * Push an entity on the environment stack.
758 static void environment_push(entity_t *entity)
760 assert(entity->base.source_position.input_name != NULL);
761 assert(entity->base.parent_scope != NULL);
762 stack_push(&environment_stack, entity);
766 * Push a declaration on the global label stack.
768 * @param declaration the declaration
770 static void label_push(entity_t *label)
772 /* we abuse the parameters scope as parent for the labels */
773 label->base.parent_scope = ¤t_function->parameters;
774 stack_push(&label_stack, label);
778 * pops symbols from the environment stack until @p new_top is the top element
780 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
782 stack_entry_t *stack = *stack_ptr;
783 size_t top = ARR_LEN(stack);
786 assert(new_top <= top);
790 for (i = top; i > new_top; --i) {
791 stack_entry_t *entry = &stack[i - 1];
793 entity_t *old_entity = entry->old_entity;
794 symbol_t *symbol = entry->symbol;
795 entity_namespace_t namespc = entry->namespc;
797 /* replace with old_entity/remove */
800 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
802 assert(iter != NULL);
803 /* replace an entry? */
804 if (iter->base.namespc == namespc)
808 /* restore definition from outer scopes (if there was one) */
809 if (old_entity != NULL) {
810 old_entity->base.symbol_next = iter->base.symbol_next;
811 *anchor = old_entity;
813 /* remove entry from list */
814 *anchor = iter->base.symbol_next;
818 ARR_SHRINKLEN(*stack_ptr, new_top);
822 * Pop all entries from the environment stack until the new_top
825 * @param new_top the new stack top
827 static void environment_pop_to(size_t new_top)
829 stack_pop_to(&environment_stack, new_top);
833 * Pop all entries from the global label stack until the new_top
836 * @param new_top the new stack top
838 static void label_pop_to(size_t new_top)
840 stack_pop_to(&label_stack, new_top);
843 static atomic_type_kind_t get_akind(const type_t *type)
845 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
846 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
847 return type->atomic.akind;
851 * §6.3.1.1:2 Do integer promotion for a given type.
853 * @param type the type to promote
854 * @return the promoted type
856 static type_t *promote_integer(type_t *type)
858 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
865 * Check if a given expression represents a null pointer constant.
867 * @param expression the expression to check
869 static bool is_null_pointer_constant(const expression_t *expression)
871 /* skip void* cast */
872 if (expression->kind == EXPR_UNARY_CAST) {
873 type_t *const type = skip_typeref(expression->base.type);
874 if (types_compatible(type, type_void_ptr))
875 expression = expression->unary.value;
878 type_t *const type = skip_typeref(expression->base.type);
879 if (!is_type_integer(type))
881 switch (is_constant_expression(expression)) {
882 case EXPR_CLASS_ERROR: return true;
883 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
884 default: return false;
889 * Create an implicit cast expression.
891 * @param expression the expression to cast
892 * @param dest_type the destination type
894 static expression_t *create_implicit_cast(expression_t *expression,
897 type_t *const source_type = expression->base.type;
899 if (source_type == dest_type)
902 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
903 cast->unary.value = expression;
904 cast->base.type = dest_type;
905 cast->base.implicit = true;
910 typedef enum assign_error_t {
912 ASSIGN_ERROR_INCOMPATIBLE,
913 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
914 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
915 ASSIGN_WARNING_POINTER_FROM_INT,
916 ASSIGN_WARNING_INT_FROM_POINTER
919 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, source_position_t const *const pos)
921 type_t *const orig_type_right = right->base.type;
922 type_t *const type_left = skip_typeref(orig_type_left);
923 type_t *const type_right = skip_typeref(orig_type_right);
928 case ASSIGN_ERROR_INCOMPATIBLE:
929 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
932 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
933 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
934 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
936 /* the left type has all qualifiers from the right type */
937 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
938 warningf(WARN_OTHER, pos, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type", orig_type_left, context, orig_type_right, missing_qualifiers);
942 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
943 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
946 case ASSIGN_WARNING_POINTER_FROM_INT:
947 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
950 case ASSIGN_WARNING_INT_FROM_POINTER:
951 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
955 panic("invalid error value");
959 /** Implements the rules from §6.5.16.1 */
960 static assign_error_t semantic_assign(type_t *orig_type_left,
961 const expression_t *const right)
963 type_t *const orig_type_right = right->base.type;
964 type_t *const type_left = skip_typeref(orig_type_left);
965 type_t *const type_right = skip_typeref(orig_type_right);
967 if (is_type_pointer(type_left)) {
968 if (is_null_pointer_constant(right)) {
969 return ASSIGN_SUCCESS;
970 } else if (is_type_pointer(type_right)) {
971 type_t *points_to_left
972 = skip_typeref(type_left->pointer.points_to);
973 type_t *points_to_right
974 = skip_typeref(type_right->pointer.points_to);
975 assign_error_t res = ASSIGN_SUCCESS;
977 /* the left type has all qualifiers from the right type */
978 unsigned missing_qualifiers
979 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
980 if (missing_qualifiers != 0) {
981 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
984 points_to_left = get_unqualified_type(points_to_left);
985 points_to_right = get_unqualified_type(points_to_right);
987 if (is_type_void(points_to_left))
990 if (is_type_void(points_to_right)) {
991 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
992 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
995 if (!types_compatible(points_to_left, points_to_right)) {
996 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1000 } else if (is_type_integer(type_right)) {
1001 return ASSIGN_WARNING_POINTER_FROM_INT;
1003 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1004 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1005 && is_type_pointer(type_right))) {
1006 return ASSIGN_SUCCESS;
1007 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1008 type_t *const unqual_type_left = get_unqualified_type(type_left);
1009 type_t *const unqual_type_right = get_unqualified_type(type_right);
1010 if (types_compatible(unqual_type_left, unqual_type_right)) {
1011 return ASSIGN_SUCCESS;
1013 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1014 return ASSIGN_WARNING_INT_FROM_POINTER;
1017 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1018 return ASSIGN_SUCCESS;
1020 return ASSIGN_ERROR_INCOMPATIBLE;
1023 static expression_t *parse_constant_expression(void)
1025 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1027 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1028 errorf(&result->base.source_position,
1029 "expression '%E' is not constant", result);
1035 static expression_t *parse_assignment_expression(void)
1037 return parse_subexpression(PREC_ASSIGNMENT);
1040 static void warn_string_concat(const source_position_t *pos)
1042 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1045 static string_t parse_string_literals(void)
1047 assert(token.kind == T_STRING_LITERAL);
1048 string_t result = token.string.string;
1052 while (token.kind == T_STRING_LITERAL) {
1053 warn_string_concat(&token.base.source_position);
1054 result = concat_strings(&result, &token.string.string);
1061 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1063 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1064 attribute->kind = kind;
1065 attribute->source_position = *HERE;
1070 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1073 * __attribute__ ( ( attribute-list ) )
1077 * attribute_list , attrib
1082 * any-word ( identifier )
1083 * any-word ( identifier , nonempty-expr-list )
1084 * any-word ( expr-list )
1086 * where the "identifier" must not be declared as a type, and
1087 * "any-word" may be any identifier (including one declared as a
1088 * type), a reserved word storage class specifier, type specifier or
1089 * type qualifier. ??? This still leaves out most reserved keywords
1090 * (following the old parser), shouldn't we include them, and why not
1091 * allow identifiers declared as types to start the arguments?
1093 * Matze: this all looks confusing and little systematic, so we're even less
1094 * strict and parse any list of things which are identifiers or
1095 * (assignment-)expressions.
1097 static attribute_argument_t *parse_attribute_arguments(void)
1099 attribute_argument_t *first = NULL;
1100 attribute_argument_t **anchor = &first;
1101 if (token.kind != ')') do {
1102 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1104 /* is it an identifier */
1105 if (token.kind == T_IDENTIFIER
1106 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1107 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1108 argument->v.symbol = token.base.symbol;
1111 /* must be an expression */
1112 expression_t *expression = parse_assignment_expression();
1114 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1115 argument->v.expression = expression;
1118 /* append argument */
1120 anchor = &argument->next;
1121 } while (next_if(','));
1126 static attribute_t *parse_attribute_asm(void)
1128 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1131 attribute->a.arguments = parse_attribute_arguments();
1135 static attribute_t *parse_attribute_gnu_single(void)
1137 /* parse "any-word" */
1138 symbol_t *const symbol = token.base.symbol;
1139 if (symbol == NULL) {
1140 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1144 attribute_kind_t kind;
1145 char const *const name = symbol->string;
1146 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1147 if (kind > ATTRIBUTE_GNU_LAST) {
1148 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1149 /* TODO: we should still save the attribute in the list... */
1150 kind = ATTRIBUTE_UNKNOWN;
1154 const char *attribute_name = get_attribute_name(kind);
1155 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1159 attribute_t *attribute = allocate_attribute_zero(kind);
1162 /* parse arguments */
1164 attribute->a.arguments = parse_attribute_arguments();
1169 static attribute_t *parse_attribute_gnu(void)
1171 attribute_t *first = NULL;
1172 attribute_t **anchor = &first;
1174 eat(T___attribute__);
1178 add_anchor_token(')');
1179 add_anchor_token(',');
1180 if (token.kind != ')') do {
1181 attribute_t *attribute = parse_attribute_gnu_single();
1183 *anchor = attribute;
1184 anchor = &attribute->next;
1186 } while (next_if(','));
1187 rem_anchor_token(',');
1188 rem_anchor_token(')');
1195 /** Parse attributes. */
1196 static attribute_t *parse_attributes(attribute_t *first)
1198 attribute_t **anchor = &first;
1200 while (*anchor != NULL)
1201 anchor = &(*anchor)->next;
1203 attribute_t *attribute;
1204 switch (token.kind) {
1205 case T___attribute__:
1206 attribute = parse_attribute_gnu();
1207 if (attribute == NULL)
1212 attribute = parse_attribute_asm();
1216 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1221 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1225 case T__forceinline:
1226 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1227 eat(T__forceinline);
1231 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1236 /* TODO record modifier */
1237 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1238 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1246 *anchor = attribute;
1247 anchor = &attribute->next;
1251 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1253 static entity_t *determine_lhs_ent(expression_t *const expr,
1256 switch (expr->kind) {
1257 case EXPR_REFERENCE: {
1258 entity_t *const entity = expr->reference.entity;
1259 /* we should only find variables as lvalues... */
1260 if (entity->base.kind != ENTITY_VARIABLE
1261 && entity->base.kind != ENTITY_PARAMETER)
1267 case EXPR_ARRAY_ACCESS: {
1268 expression_t *const ref = expr->array_access.array_ref;
1269 entity_t * ent = NULL;
1270 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1271 ent = determine_lhs_ent(ref, lhs_ent);
1274 mark_vars_read(ref, lhs_ent);
1276 mark_vars_read(expr->array_access.index, lhs_ent);
1281 mark_vars_read(expr->select.compound, lhs_ent);
1282 if (is_type_compound(skip_typeref(expr->base.type)))
1283 return determine_lhs_ent(expr->select.compound, lhs_ent);
1287 case EXPR_UNARY_DEREFERENCE: {
1288 expression_t *const val = expr->unary.value;
1289 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1291 return determine_lhs_ent(val->unary.value, lhs_ent);
1293 mark_vars_read(val, NULL);
1299 mark_vars_read(expr, NULL);
1304 #define ENT_ANY ((entity_t*)-1)
1307 * Mark declarations, which are read. This is used to detect variables, which
1311 * x is not marked as "read", because it is only read to calculate its own new
1315 * x and y are not detected as "not read", because multiple variables are
1318 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1320 switch (expr->kind) {
1321 case EXPR_REFERENCE: {
1322 entity_t *const entity = expr->reference.entity;
1323 if (entity->kind != ENTITY_VARIABLE
1324 && entity->kind != ENTITY_PARAMETER)
1327 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1328 if (entity->kind == ENTITY_VARIABLE) {
1329 entity->variable.read = true;
1331 entity->parameter.read = true;
1338 // TODO respect pure/const
1339 mark_vars_read(expr->call.function, NULL);
1340 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1341 mark_vars_read(arg->expression, NULL);
1345 case EXPR_CONDITIONAL:
1346 // TODO lhs_decl should depend on whether true/false have an effect
1347 mark_vars_read(expr->conditional.condition, NULL);
1348 if (expr->conditional.true_expression != NULL)
1349 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1350 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1354 if (lhs_ent == ENT_ANY
1355 && !is_type_compound(skip_typeref(expr->base.type)))
1357 mark_vars_read(expr->select.compound, lhs_ent);
1360 case EXPR_ARRAY_ACCESS: {
1361 mark_vars_read(expr->array_access.index, lhs_ent);
1362 expression_t *const ref = expr->array_access.array_ref;
1363 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1364 if (lhs_ent == ENT_ANY)
1367 mark_vars_read(ref, lhs_ent);
1372 mark_vars_read(expr->va_arge.ap, lhs_ent);
1376 mark_vars_read(expr->va_copye.src, lhs_ent);
1379 case EXPR_UNARY_CAST:
1380 /* Special case: Use void cast to mark a variable as "read" */
1381 if (is_type_void(skip_typeref(expr->base.type)))
1386 case EXPR_UNARY_THROW:
1387 if (expr->unary.value == NULL)
1390 case EXPR_UNARY_DEREFERENCE:
1391 case EXPR_UNARY_DELETE:
1392 case EXPR_UNARY_DELETE_ARRAY:
1393 if (lhs_ent == ENT_ANY)
1397 case EXPR_UNARY_NEGATE:
1398 case EXPR_UNARY_PLUS:
1399 case EXPR_UNARY_BITWISE_NEGATE:
1400 case EXPR_UNARY_NOT:
1401 case EXPR_UNARY_TAKE_ADDRESS:
1402 case EXPR_UNARY_POSTFIX_INCREMENT:
1403 case EXPR_UNARY_POSTFIX_DECREMENT:
1404 case EXPR_UNARY_PREFIX_INCREMENT:
1405 case EXPR_UNARY_PREFIX_DECREMENT:
1406 case EXPR_UNARY_ASSUME:
1408 mark_vars_read(expr->unary.value, lhs_ent);
1411 case EXPR_BINARY_ADD:
1412 case EXPR_BINARY_SUB:
1413 case EXPR_BINARY_MUL:
1414 case EXPR_BINARY_DIV:
1415 case EXPR_BINARY_MOD:
1416 case EXPR_BINARY_EQUAL:
1417 case EXPR_BINARY_NOTEQUAL:
1418 case EXPR_BINARY_LESS:
1419 case EXPR_BINARY_LESSEQUAL:
1420 case EXPR_BINARY_GREATER:
1421 case EXPR_BINARY_GREATEREQUAL:
1422 case EXPR_BINARY_BITWISE_AND:
1423 case EXPR_BINARY_BITWISE_OR:
1424 case EXPR_BINARY_BITWISE_XOR:
1425 case EXPR_BINARY_LOGICAL_AND:
1426 case EXPR_BINARY_LOGICAL_OR:
1427 case EXPR_BINARY_SHIFTLEFT:
1428 case EXPR_BINARY_SHIFTRIGHT:
1429 case EXPR_BINARY_COMMA:
1430 case EXPR_BINARY_ISGREATER:
1431 case EXPR_BINARY_ISGREATEREQUAL:
1432 case EXPR_BINARY_ISLESS:
1433 case EXPR_BINARY_ISLESSEQUAL:
1434 case EXPR_BINARY_ISLESSGREATER:
1435 case EXPR_BINARY_ISUNORDERED:
1436 mark_vars_read(expr->binary.left, lhs_ent);
1437 mark_vars_read(expr->binary.right, lhs_ent);
1440 case EXPR_BINARY_ASSIGN:
1441 case EXPR_BINARY_MUL_ASSIGN:
1442 case EXPR_BINARY_DIV_ASSIGN:
1443 case EXPR_BINARY_MOD_ASSIGN:
1444 case EXPR_BINARY_ADD_ASSIGN:
1445 case EXPR_BINARY_SUB_ASSIGN:
1446 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1447 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1448 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1449 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1450 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1451 if (lhs_ent == ENT_ANY)
1453 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1454 mark_vars_read(expr->binary.right, lhs_ent);
1459 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1462 case EXPR_LITERAL_CASES:
1464 case EXPR_STRING_LITERAL:
1465 case EXPR_WIDE_STRING_LITERAL:
1466 case EXPR_COMPOUND_LITERAL: // TODO init?
1468 case EXPR_CLASSIFY_TYPE:
1471 case EXPR_BUILTIN_CONSTANT_P:
1472 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1474 case EXPR_STATEMENT: // TODO
1475 case EXPR_LABEL_ADDRESS:
1476 case EXPR_ENUM_CONSTANT:
1480 panic("unhandled expression");
1483 static designator_t *parse_designation(void)
1485 designator_t *result = NULL;
1486 designator_t **anchor = &result;
1489 designator_t *designator;
1490 switch (token.kind) {
1492 designator = allocate_ast_zero(sizeof(designator[0]));
1493 designator->source_position = token.base.source_position;
1495 add_anchor_token(']');
1496 designator->array_index = parse_constant_expression();
1497 rem_anchor_token(']');
1501 designator = allocate_ast_zero(sizeof(designator[0]));
1502 designator->source_position = token.base.source_position;
1504 designator->symbol = expect_identifier("while parsing designator", NULL);
1505 if (!designator->symbol)
1513 assert(designator != NULL);
1514 *anchor = designator;
1515 anchor = &designator->next;
1519 static initializer_t *initializer_from_string(array_type_t *const type,
1520 const string_t *const string)
1522 /* TODO: check len vs. size of array type */
1525 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1526 initializer->string.string = *string;
1531 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1532 const string_t *const string)
1534 /* TODO: check len vs. size of array type */
1537 initializer_t *const initializer =
1538 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1539 initializer->wide_string.string = *string;
1545 * Build an initializer from a given expression.
1547 static initializer_t *initializer_from_expression(type_t *orig_type,
1548 expression_t *expression)
1550 /* TODO check that expression is a constant expression */
1552 /* §6.7.8.14/15 char array may be initialized by string literals */
1553 type_t *type = skip_typeref(orig_type);
1554 type_t *expr_type_orig = expression->base.type;
1555 type_t *expr_type = skip_typeref(expr_type_orig);
1557 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1558 array_type_t *const array_type = &type->array;
1559 type_t *const element_type = skip_typeref(array_type->element_type);
1561 if (element_type->kind == TYPE_ATOMIC) {
1562 atomic_type_kind_t akind = element_type->atomic.akind;
1563 switch (expression->kind) {
1564 case EXPR_STRING_LITERAL:
1565 if (akind == ATOMIC_TYPE_CHAR
1566 || akind == ATOMIC_TYPE_SCHAR
1567 || akind == ATOMIC_TYPE_UCHAR) {
1568 return initializer_from_string(array_type,
1569 &expression->string_literal.value);
1573 case EXPR_WIDE_STRING_LITERAL: {
1574 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1575 if (get_unqualified_type(element_type) == bare_wchar_type) {
1576 return initializer_from_wide_string(array_type,
1577 &expression->string_literal.value);
1588 assign_error_t error = semantic_assign(type, expression);
1589 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1591 report_assign_error(error, type, expression, "initializer",
1592 &expression->base.source_position);
1594 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1595 result->value.value = create_implicit_cast(expression, type);
1601 * Parses an scalar initializer.
1603 * §6.7.8.11; eat {} without warning
1605 static initializer_t *parse_scalar_initializer(type_t *type,
1606 bool must_be_constant)
1608 /* there might be extra {} hierarchies */
1610 if (token.kind == '{') {
1611 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1615 } while (token.kind == '{');
1618 expression_t *expression = parse_assignment_expression();
1619 mark_vars_read(expression, NULL);
1620 if (must_be_constant && !is_linker_constant(expression)) {
1621 errorf(&expression->base.source_position,
1622 "initialisation expression '%E' is not constant",
1626 initializer_t *initializer = initializer_from_expression(type, expression);
1628 if (initializer == NULL) {
1629 errorf(&expression->base.source_position,
1630 "expression '%E' (type '%T') doesn't match expected type '%T'",
1631 expression, expression->base.type, type);
1636 bool additional_warning_displayed = false;
1637 while (braces > 0) {
1639 if (token.kind != '}') {
1640 if (!additional_warning_displayed) {
1641 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1642 additional_warning_displayed = true;
1653 * An entry in the type path.
1655 typedef struct type_path_entry_t type_path_entry_t;
1656 struct type_path_entry_t {
1657 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1659 size_t index; /**< For array types: the current index. */
1660 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1665 * A type path expression a position inside compound or array types.
1667 typedef struct type_path_t type_path_t;
1668 struct type_path_t {
1669 type_path_entry_t *path; /**< An flexible array containing the current path. */
1670 type_t *top_type; /**< type of the element the path points */
1671 size_t max_index; /**< largest index in outermost array */
1675 * Prints a type path for debugging.
1677 static __attribute__((unused)) void debug_print_type_path(
1678 const type_path_t *path)
1680 size_t len = ARR_LEN(path->path);
1682 for (size_t i = 0; i < len; ++i) {
1683 const type_path_entry_t *entry = & path->path[i];
1685 type_t *type = skip_typeref(entry->type);
1686 if (is_type_compound(type)) {
1687 /* in gcc mode structs can have no members */
1688 if (entry->v.compound_entry == NULL) {
1692 fprintf(stderr, ".%s",
1693 entry->v.compound_entry->base.symbol->string);
1694 } else if (is_type_array(type)) {
1695 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1697 fprintf(stderr, "-INVALID-");
1700 if (path->top_type != NULL) {
1701 fprintf(stderr, " (");
1702 print_type(path->top_type);
1703 fprintf(stderr, ")");
1708 * Return the top type path entry, ie. in a path
1709 * (type).a.b returns the b.
1711 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1713 size_t len = ARR_LEN(path->path);
1715 return &path->path[len-1];
1719 * Enlarge the type path by an (empty) element.
1721 static type_path_entry_t *append_to_type_path(type_path_t *path)
1723 size_t len = ARR_LEN(path->path);
1724 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1726 type_path_entry_t *result = & path->path[len];
1727 memset(result, 0, sizeof(result[0]));
1732 * Descending into a sub-type. Enter the scope of the current top_type.
1734 static void descend_into_subtype(type_path_t *path)
1736 type_t *orig_top_type = path->top_type;
1737 type_t *top_type = skip_typeref(orig_top_type);
1739 type_path_entry_t *top = append_to_type_path(path);
1740 top->type = top_type;
1742 if (is_type_compound(top_type)) {
1743 compound_t *const compound = top_type->compound.compound;
1744 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1746 if (entry != NULL) {
1747 top->v.compound_entry = &entry->declaration;
1748 path->top_type = entry->declaration.type;
1750 path->top_type = NULL;
1752 } else if (is_type_array(top_type)) {
1754 path->top_type = top_type->array.element_type;
1756 assert(!is_type_valid(top_type));
1761 * Pop an entry from the given type path, ie. returning from
1762 * (type).a.b to (type).a
1764 static void ascend_from_subtype(type_path_t *path)
1766 type_path_entry_t *top = get_type_path_top(path);
1768 path->top_type = top->type;
1770 size_t len = ARR_LEN(path->path);
1771 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1775 * Pop entries from the given type path until the given
1776 * path level is reached.
1778 static void ascend_to(type_path_t *path, size_t top_path_level)
1780 size_t len = ARR_LEN(path->path);
1782 while (len > top_path_level) {
1783 ascend_from_subtype(path);
1784 len = ARR_LEN(path->path);
1788 static bool walk_designator(type_path_t *path, const designator_t *designator,
1789 bool used_in_offsetof)
1791 for (; designator != NULL; designator = designator->next) {
1792 type_path_entry_t *top = get_type_path_top(path);
1793 type_t *orig_type = top->type;
1795 type_t *type = skip_typeref(orig_type);
1797 if (designator->symbol != NULL) {
1798 symbol_t *symbol = designator->symbol;
1799 if (!is_type_compound(type)) {
1800 if (is_type_valid(type)) {
1801 errorf(&designator->source_position,
1802 "'.%Y' designator used for non-compound type '%T'",
1806 top->type = type_error_type;
1807 top->v.compound_entry = NULL;
1808 orig_type = type_error_type;
1810 compound_t *compound = type->compound.compound;
1811 entity_t *iter = compound->members.entities;
1812 for (; iter != NULL; iter = iter->base.next) {
1813 if (iter->base.symbol == symbol) {
1818 errorf(&designator->source_position,
1819 "'%T' has no member named '%Y'", orig_type, symbol);
1822 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1823 if (used_in_offsetof && iter->compound_member.bitfield) {
1824 errorf(&designator->source_position,
1825 "offsetof designator '%Y' must not specify bitfield",
1830 top->type = orig_type;
1831 top->v.compound_entry = &iter->declaration;
1832 orig_type = iter->declaration.type;
1835 expression_t *array_index = designator->array_index;
1836 assert(designator->array_index != NULL);
1838 if (!is_type_array(type)) {
1839 if (is_type_valid(type)) {
1840 errorf(&designator->source_position,
1841 "[%E] designator used for non-array type '%T'",
1842 array_index, orig_type);
1847 long index = fold_constant_to_int(array_index);
1848 if (!used_in_offsetof) {
1850 errorf(&designator->source_position,
1851 "array index [%E] must be positive", array_index);
1852 } else if (type->array.size_constant) {
1853 long array_size = type->array.size;
1854 if (index >= array_size) {
1855 errorf(&designator->source_position,
1856 "designator [%E] (%d) exceeds array size %d",
1857 array_index, index, array_size);
1862 top->type = orig_type;
1863 top->v.index = (size_t) index;
1864 orig_type = type->array.element_type;
1866 path->top_type = orig_type;
1868 if (designator->next != NULL) {
1869 descend_into_subtype(path);
1875 static void advance_current_object(type_path_t *path, size_t top_path_level)
1877 type_path_entry_t *top = get_type_path_top(path);
1879 type_t *type = skip_typeref(top->type);
1880 if (is_type_union(type)) {
1881 /* in unions only the first element is initialized */
1882 top->v.compound_entry = NULL;
1883 } else if (is_type_struct(type)) {
1884 declaration_t *entry = top->v.compound_entry;
1886 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1887 if (next_entity != NULL) {
1888 assert(is_declaration(next_entity));
1889 entry = &next_entity->declaration;
1894 top->v.compound_entry = entry;
1895 if (entry != NULL) {
1896 path->top_type = entry->type;
1899 } else if (is_type_array(type)) {
1900 assert(is_type_array(type));
1904 if (!type->array.size_constant || top->v.index < type->array.size) {
1908 assert(!is_type_valid(type));
1912 /* we're past the last member of the current sub-aggregate, try if we
1913 * can ascend in the type hierarchy and continue with another subobject */
1914 size_t len = ARR_LEN(path->path);
1916 if (len > top_path_level) {
1917 ascend_from_subtype(path);
1918 advance_current_object(path, top_path_level);
1920 path->top_type = NULL;
1925 * skip any {...} blocks until a closing bracket is reached.
1927 static void skip_initializers(void)
1931 while (token.kind != '}') {
1932 if (token.kind == T_EOF)
1934 if (token.kind == '{') {
1942 static initializer_t *create_empty_initializer(void)
1944 static initializer_t empty_initializer
1945 = { .list = { { INITIALIZER_LIST }, 0 } };
1946 return &empty_initializer;
1950 * Parse a part of an initialiser for a struct or union,
1952 static initializer_t *parse_sub_initializer(type_path_t *path,
1953 type_t *outer_type, size_t top_path_level,
1954 parse_initializer_env_t *env)
1956 if (token.kind == '}') {
1957 /* empty initializer */
1958 return create_empty_initializer();
1961 type_t *orig_type = path->top_type;
1962 type_t *type = NULL;
1964 if (orig_type == NULL) {
1965 /* We are initializing an empty compound. */
1967 type = skip_typeref(orig_type);
1970 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1973 designator_t *designator = NULL;
1974 if (token.kind == '.' || token.kind == '[') {
1975 designator = parse_designation();
1976 goto finish_designator;
1977 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1978 /* GNU-style designator ("identifier: value") */
1979 designator = allocate_ast_zero(sizeof(designator[0]));
1980 designator->source_position = token.base.source_position;
1981 designator->symbol = token.base.symbol;
1986 /* reset path to toplevel, evaluate designator from there */
1987 ascend_to(path, top_path_level);
1988 if (!walk_designator(path, designator, false)) {
1989 /* can't continue after designation error */
1993 initializer_t *designator_initializer
1994 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1995 designator_initializer->designator.designator = designator;
1996 ARR_APP1(initializer_t*, initializers, designator_initializer);
1998 orig_type = path->top_type;
1999 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2004 if (token.kind == '{') {
2005 if (type != NULL && is_type_scalar(type)) {
2006 sub = parse_scalar_initializer(type, env->must_be_constant);
2009 if (env->entity != NULL) {
2010 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2012 errorf(HERE, "extra brace group at end of initializer");
2017 descend_into_subtype(path);
2020 add_anchor_token('}');
2021 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2023 rem_anchor_token('}');
2028 goto error_parse_next;
2030 ascend_from_subtype(path);
2033 /* must be an expression */
2034 expression_t *expression = parse_assignment_expression();
2035 mark_vars_read(expression, NULL);
2037 if (env->must_be_constant && !is_linker_constant(expression)) {
2038 errorf(&expression->base.source_position,
2039 "Initialisation expression '%E' is not constant",
2044 /* we are already outside, ... */
2045 if (outer_type == NULL)
2046 goto error_parse_next;
2047 type_t *const outer_type_skip = skip_typeref(outer_type);
2048 if (is_type_compound(outer_type_skip) &&
2049 !outer_type_skip->compound.compound->complete) {
2050 goto error_parse_next;
2053 source_position_t const* const pos = &expression->base.source_position;
2054 if (env->entity != NULL) {
2055 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2057 warningf(WARN_OTHER, pos, "excess elements in initializer");
2059 goto error_parse_next;
2062 /* handle { "string" } special case */
2063 if ((expression->kind == EXPR_STRING_LITERAL
2064 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2065 && outer_type != NULL) {
2066 sub = initializer_from_expression(outer_type, expression);
2069 if (token.kind != '}') {
2070 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2072 /* TODO: eat , ... */
2077 /* descend into subtypes until expression matches type */
2079 orig_type = path->top_type;
2080 type = skip_typeref(orig_type);
2082 sub = initializer_from_expression(orig_type, expression);
2086 if (!is_type_valid(type)) {
2089 if (is_type_scalar(type)) {
2090 errorf(&expression->base.source_position,
2091 "expression '%E' doesn't match expected type '%T'",
2092 expression, orig_type);
2096 descend_into_subtype(path);
2100 /* update largest index of top array */
2101 const type_path_entry_t *first = &path->path[0];
2102 type_t *first_type = first->type;
2103 first_type = skip_typeref(first_type);
2104 if (is_type_array(first_type)) {
2105 size_t index = first->v.index;
2106 if (index > path->max_index)
2107 path->max_index = index;
2110 /* append to initializers list */
2111 ARR_APP1(initializer_t*, initializers, sub);
2114 if (token.kind == '}') {
2117 add_anchor_token('}');
2119 rem_anchor_token('}');
2120 if (token.kind == '}') {
2125 /* advance to the next declaration if we are not at the end */
2126 advance_current_object(path, top_path_level);
2127 orig_type = path->top_type;
2128 if (orig_type != NULL)
2129 type = skip_typeref(orig_type);
2135 size_t len = ARR_LEN(initializers);
2136 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2137 initializer_t *result = allocate_ast_zero(size);
2138 result->kind = INITIALIZER_LIST;
2139 result->list.len = len;
2140 memcpy(&result->list.initializers, initializers,
2141 len * sizeof(initializers[0]));
2143 DEL_ARR_F(initializers);
2144 ascend_to(path, top_path_level+1);
2149 skip_initializers();
2150 DEL_ARR_F(initializers);
2151 ascend_to(path, top_path_level+1);
2155 static expression_t *make_size_literal(size_t value)
2157 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2158 literal->base.type = type_size_t;
2161 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2162 literal->literal.value = make_string(buf);
2168 * Parses an initializer. Parsers either a compound literal
2169 * (env->declaration == NULL) or an initializer of a declaration.
2171 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2173 type_t *type = skip_typeref(env->type);
2174 size_t max_index = 0;
2175 initializer_t *result;
2177 if (is_type_scalar(type)) {
2178 result = parse_scalar_initializer(type, env->must_be_constant);
2179 } else if (token.kind == '{') {
2183 memset(&path, 0, sizeof(path));
2184 path.top_type = env->type;
2185 path.path = NEW_ARR_F(type_path_entry_t, 0);
2187 descend_into_subtype(&path);
2189 add_anchor_token('}');
2190 result = parse_sub_initializer(&path, env->type, 1, env);
2191 rem_anchor_token('}');
2193 max_index = path.max_index;
2194 DEL_ARR_F(path.path);
2198 /* parse_scalar_initializer() also works in this case: we simply
2199 * have an expression without {} around it */
2200 result = parse_scalar_initializer(type, env->must_be_constant);
2203 /* §6.7.8:22 array initializers for arrays with unknown size determine
2204 * the array type size */
2205 if (is_type_array(type) && type->array.size_expression == NULL
2206 && result != NULL) {
2208 switch (result->kind) {
2209 case INITIALIZER_LIST:
2210 assert(max_index != 0xdeadbeaf);
2211 size = max_index + 1;
2214 case INITIALIZER_STRING:
2215 size = result->string.string.size;
2218 case INITIALIZER_WIDE_STRING:
2219 size = result->wide_string.string.size;
2222 case INITIALIZER_DESIGNATOR:
2223 case INITIALIZER_VALUE:
2224 /* can happen for parse errors */
2229 internal_errorf(HERE, "invalid initializer type");
2232 type_t *new_type = duplicate_type(type);
2234 new_type->array.size_expression = make_size_literal(size);
2235 new_type->array.size_constant = true;
2236 new_type->array.has_implicit_size = true;
2237 new_type->array.size = size;
2238 env->type = new_type;
2244 static void append_entity(scope_t *scope, entity_t *entity)
2246 if (scope->last_entity != NULL) {
2247 scope->last_entity->base.next = entity;
2249 scope->entities = entity;
2251 entity->base.parent_entity = current_entity;
2252 scope->last_entity = entity;
2256 static compound_t *parse_compound_type_specifier(bool is_struct)
2258 source_position_t const pos = *HERE;
2259 eat(is_struct ? T_struct : T_union);
2261 symbol_t *symbol = NULL;
2262 entity_t *entity = NULL;
2263 attribute_t *attributes = NULL;
2265 if (token.kind == T___attribute__) {
2266 attributes = parse_attributes(NULL);
2269 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2270 if (token.kind == T_IDENTIFIER) {
2271 /* the compound has a name, check if we have seen it already */
2272 symbol = token.base.symbol;
2273 entity = get_tag(symbol, kind);
2276 if (entity != NULL) {
2277 if (entity->base.parent_scope != current_scope &&
2278 (token.kind == '{' || token.kind == ';')) {
2279 /* we're in an inner scope and have a definition. Shadow
2280 * existing definition in outer scope */
2282 } else if (entity->compound.complete && token.kind == '{') {
2283 source_position_t const *const ppos = &entity->base.source_position;
2284 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2285 /* clear members in the hope to avoid further errors */
2286 entity->compound.members.entities = NULL;
2289 } else if (token.kind != '{') {
2290 char const *const msg =
2291 is_struct ? "while parsing struct type specifier" :
2292 "while parsing union type specifier";
2293 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2298 if (entity == NULL) {
2299 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2300 entity->compound.alignment = 1;
2301 entity->base.parent_scope = current_scope;
2302 if (symbol != NULL) {
2303 environment_push(entity);
2305 append_entity(current_scope, entity);
2308 if (token.kind == '{') {
2309 parse_compound_type_entries(&entity->compound);
2311 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2312 if (symbol == NULL) {
2313 assert(anonymous_entity == NULL);
2314 anonymous_entity = entity;
2318 if (attributes != NULL) {
2319 handle_entity_attributes(attributes, entity);
2322 return &entity->compound;
2325 static void parse_enum_entries(type_t *const enum_type)
2329 if (token.kind == '}') {
2330 errorf(HERE, "empty enum not allowed");
2335 add_anchor_token('}');
2336 add_anchor_token(',');
2338 add_anchor_token('=');
2339 source_position_t pos;
2340 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2341 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2342 entity->enum_value.enum_type = enum_type;
2343 rem_anchor_token('=');
2346 expression_t *value = parse_constant_expression();
2348 value = create_implicit_cast(value, enum_type);
2349 entity->enum_value.value = value;
2354 record_entity(entity, false);
2355 } while (next_if(',') && token.kind != '}');
2356 rem_anchor_token(',');
2357 rem_anchor_token('}');
2362 static type_t *parse_enum_specifier(void)
2364 source_position_t const pos = *HERE;
2369 switch (token.kind) {
2371 symbol = token.base.symbol;
2372 entity = get_tag(symbol, ENTITY_ENUM);
2375 if (entity != NULL) {
2376 if (entity->base.parent_scope != current_scope &&
2377 (token.kind == '{' || token.kind == ';')) {
2378 /* we're in an inner scope and have a definition. Shadow
2379 * existing definition in outer scope */
2381 } else if (entity->enume.complete && token.kind == '{') {
2382 source_position_t const *const ppos = &entity->base.source_position;
2383 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2394 parse_error_expected("while parsing enum type specifier",
2395 T_IDENTIFIER, '{', NULL);
2399 if (entity == NULL) {
2400 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2401 entity->base.parent_scope = current_scope;
2404 type_t *const type = allocate_type_zero(TYPE_ENUM);
2405 type->enumt.enume = &entity->enume;
2406 type->enumt.base.akind = ATOMIC_TYPE_INT;
2408 if (token.kind == '{') {
2409 if (symbol != NULL) {
2410 environment_push(entity);
2412 append_entity(current_scope, entity);
2413 entity->enume.complete = true;
2415 parse_enum_entries(type);
2416 parse_attributes(NULL);
2418 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2419 if (symbol == NULL) {
2420 assert(anonymous_entity == NULL);
2421 anonymous_entity = entity;
2423 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2424 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2431 * if a symbol is a typedef to another type, return true
2433 static bool is_typedef_symbol(symbol_t *symbol)
2435 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2436 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2439 static type_t *parse_typeof(void)
2446 add_anchor_token(')');
2448 expression_t *expression = NULL;
2450 switch (token.kind) {
2452 if (is_typedef_symbol(token.base.symbol)) {
2454 type = parse_typename();
2457 expression = parse_expression();
2458 type = revert_automatic_type_conversion(expression);
2463 rem_anchor_token(')');
2466 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2467 typeof_type->typeoft.expression = expression;
2468 typeof_type->typeoft.typeof_type = type;
2473 typedef enum specifiers_t {
2474 SPECIFIER_SIGNED = 1 << 0,
2475 SPECIFIER_UNSIGNED = 1 << 1,
2476 SPECIFIER_LONG = 1 << 2,
2477 SPECIFIER_INT = 1 << 3,
2478 SPECIFIER_DOUBLE = 1 << 4,
2479 SPECIFIER_CHAR = 1 << 5,
2480 SPECIFIER_WCHAR_T = 1 << 6,
2481 SPECIFIER_SHORT = 1 << 7,
2482 SPECIFIER_LONG_LONG = 1 << 8,
2483 SPECIFIER_FLOAT = 1 << 9,
2484 SPECIFIER_BOOL = 1 << 10,
2485 SPECIFIER_VOID = 1 << 11,
2486 SPECIFIER_INT8 = 1 << 12,
2487 SPECIFIER_INT16 = 1 << 13,
2488 SPECIFIER_INT32 = 1 << 14,
2489 SPECIFIER_INT64 = 1 << 15,
2490 SPECIFIER_INT128 = 1 << 16,
2491 SPECIFIER_COMPLEX = 1 << 17,
2492 SPECIFIER_IMAGINARY = 1 << 18,
2495 static type_t *get_typedef_type(symbol_t *symbol)
2497 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2498 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2501 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2502 type->typedeft.typedefe = &entity->typedefe;
2507 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2509 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2513 add_anchor_token(')');
2514 add_anchor_token(',');
2516 add_anchor_token('=');
2517 source_position_t pos;
2518 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2519 rem_anchor_token('=');
2521 symbol_t **prop = NULL;
2523 if (streq(prop_sym->string, "put")) {
2524 prop = &property->put_symbol;
2525 } else if (streq(prop_sym->string, "get")) {
2526 prop = &property->get_symbol;
2528 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2532 add_anchor_token(T_IDENTIFIER);
2534 rem_anchor_token(T_IDENTIFIER);
2536 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2538 *prop = sym ? sym : sym_anonymous;
2539 } while (next_if(','));
2540 rem_anchor_token(',');
2541 rem_anchor_token(')');
2543 attribute->a.property = property;
2549 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2551 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2552 if (next_if(T_restrict)) {
2553 kind = ATTRIBUTE_MS_RESTRICT;
2554 } else if (token.kind == T_IDENTIFIER) {
2555 char const *const name = token.base.symbol->string;
2556 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2558 const char *attribute_name = get_attribute_name(k);
2559 if (attribute_name != NULL && streq(attribute_name, name)) {
2565 if (kind == ATTRIBUTE_UNKNOWN) {
2566 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2569 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2573 attribute_t *attribute = allocate_attribute_zero(kind);
2576 if (kind == ATTRIBUTE_MS_PROPERTY) {
2577 return parse_attribute_ms_property(attribute);
2580 /* parse arguments */
2582 attribute->a.arguments = parse_attribute_arguments();
2587 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2592 if (token.kind != ')') {
2593 add_anchor_token(')');
2595 attribute_t **anchor = &first;
2597 while (*anchor != NULL)
2598 anchor = &(*anchor)->next;
2600 attribute_t *attribute
2601 = parse_microsoft_extended_decl_modifier_single();
2602 if (attribute == NULL)
2605 *anchor = attribute;
2606 anchor = &attribute->next;
2607 } while (next_if(','));
2609 rem_anchor_token(')');
2615 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2617 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2618 if (is_declaration(entity)) {
2619 entity->declaration.type = type_error_type;
2620 entity->declaration.implicit = true;
2621 } else if (kind == ENTITY_TYPEDEF) {
2622 entity->typedefe.type = type_error_type;
2623 entity->typedefe.builtin = true;
2625 if (kind != ENTITY_COMPOUND_MEMBER)
2626 record_entity(entity, false);
2630 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2632 type_t *type = NULL;
2633 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2634 unsigned type_specifiers = 0;
2635 bool newtype = false;
2636 bool saw_error = false;
2638 memset(specifiers, 0, sizeof(*specifiers));
2639 specifiers->source_position = token.base.source_position;
2642 specifiers->attributes = parse_attributes(specifiers->attributes);
2644 switch (token.kind) {
2646 #define MATCH_STORAGE_CLASS(token, class) \
2648 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2649 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2651 specifiers->storage_class = class; \
2652 if (specifiers->thread_local) \
2653 goto check_thread_storage_class; \
2657 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2658 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2659 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2660 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2661 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2664 specifiers->attributes
2665 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2669 if (specifiers->thread_local) {
2670 errorf(HERE, "duplicate '__thread'");
2672 specifiers->thread_local = true;
2673 check_thread_storage_class:
2674 switch (specifiers->storage_class) {
2675 case STORAGE_CLASS_EXTERN:
2676 case STORAGE_CLASS_NONE:
2677 case STORAGE_CLASS_STATIC:
2681 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2682 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2683 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2684 wrong_thread_storage_class:
2685 errorf(HERE, "'__thread' used with '%s'", wrong);
2692 /* type qualifiers */
2693 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2695 qualifiers |= qualifier; \
2699 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2700 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2701 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2702 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2703 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2704 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2705 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2706 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2708 /* type specifiers */
2709 #define MATCH_SPECIFIER(token, specifier, name) \
2711 if (type_specifiers & specifier) { \
2712 errorf(HERE, "multiple " name " type specifiers given"); \
2714 type_specifiers |= specifier; \
2719 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2720 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2721 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2722 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2723 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2724 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2725 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2726 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2727 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2728 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2729 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2730 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2731 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2732 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2733 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2734 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2735 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2736 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2740 specifiers->is_inline = true;
2744 case T__forceinline:
2746 specifiers->modifiers |= DM_FORCEINLINE;
2751 if (type_specifiers & SPECIFIER_LONG_LONG) {
2752 errorf(HERE, "too many long type specifiers given");
2753 } else if (type_specifiers & SPECIFIER_LONG) {
2754 type_specifiers |= SPECIFIER_LONG_LONG;
2756 type_specifiers |= SPECIFIER_LONG;
2761 #define CHECK_DOUBLE_TYPE() \
2762 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2765 CHECK_DOUBLE_TYPE();
2766 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2768 type->compound.compound = parse_compound_type_specifier(true);
2771 CHECK_DOUBLE_TYPE();
2772 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2773 type->compound.compound = parse_compound_type_specifier(false);
2776 CHECK_DOUBLE_TYPE();
2777 type = parse_enum_specifier();
2780 CHECK_DOUBLE_TYPE();
2781 type = parse_typeof();
2783 case T___builtin_va_list:
2784 CHECK_DOUBLE_TYPE();
2785 type = duplicate_type(type_valist);
2789 case T_IDENTIFIER: {
2790 /* only parse identifier if we haven't found a type yet */
2791 if (type != NULL || type_specifiers != 0) {
2792 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2793 * declaration, so it doesn't generate errors about expecting '(' or
2795 switch (look_ahead(1)->kind) {
2802 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2806 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2811 goto finish_specifiers;
2815 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2816 if (typedef_type == NULL) {
2817 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2818 * declaration, so it doesn't generate 'implicit int' followed by more
2819 * errors later on. */
2820 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2826 errorf(HERE, "%K does not name a type", &token);
2828 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2830 type = allocate_type_zero(TYPE_TYPEDEF);
2831 type->typedeft.typedefe = &entity->typedefe;
2839 goto finish_specifiers;
2844 type = typedef_type;
2848 /* function specifier */
2850 goto finish_specifiers;
2855 specifiers->attributes = parse_attributes(specifiers->attributes);
2857 if (type == NULL || (saw_error && type_specifiers != 0)) {
2858 atomic_type_kind_t atomic_type;
2860 /* match valid basic types */
2861 switch (type_specifiers) {
2862 case SPECIFIER_VOID:
2863 atomic_type = ATOMIC_TYPE_VOID;
2865 case SPECIFIER_WCHAR_T:
2866 atomic_type = ATOMIC_TYPE_WCHAR_T;
2868 case SPECIFIER_CHAR:
2869 atomic_type = ATOMIC_TYPE_CHAR;
2871 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2872 atomic_type = ATOMIC_TYPE_SCHAR;
2874 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2875 atomic_type = ATOMIC_TYPE_UCHAR;
2877 case SPECIFIER_SHORT:
2878 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2879 case SPECIFIER_SHORT | SPECIFIER_INT:
2880 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2881 atomic_type = ATOMIC_TYPE_SHORT;
2883 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2884 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2885 atomic_type = ATOMIC_TYPE_USHORT;
2888 case SPECIFIER_SIGNED:
2889 case SPECIFIER_SIGNED | SPECIFIER_INT:
2890 atomic_type = ATOMIC_TYPE_INT;
2892 case SPECIFIER_UNSIGNED:
2893 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2894 atomic_type = ATOMIC_TYPE_UINT;
2896 case SPECIFIER_LONG:
2897 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2898 case SPECIFIER_LONG | SPECIFIER_INT:
2899 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2900 atomic_type = ATOMIC_TYPE_LONG;
2902 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2903 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2904 atomic_type = ATOMIC_TYPE_ULONG;
2907 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2908 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2909 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2910 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2912 atomic_type = ATOMIC_TYPE_LONGLONG;
2913 goto warn_about_long_long;
2915 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2916 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2918 atomic_type = ATOMIC_TYPE_ULONGLONG;
2919 warn_about_long_long:
2920 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2923 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2924 atomic_type = unsigned_int8_type_kind;
2927 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2928 atomic_type = unsigned_int16_type_kind;
2931 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2932 atomic_type = unsigned_int32_type_kind;
2935 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2936 atomic_type = unsigned_int64_type_kind;
2939 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2940 atomic_type = unsigned_int128_type_kind;
2943 case SPECIFIER_INT8:
2944 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2945 atomic_type = int8_type_kind;
2948 case SPECIFIER_INT16:
2949 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2950 atomic_type = int16_type_kind;
2953 case SPECIFIER_INT32:
2954 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2955 atomic_type = int32_type_kind;
2958 case SPECIFIER_INT64:
2959 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2960 atomic_type = int64_type_kind;
2963 case SPECIFIER_INT128:
2964 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2965 atomic_type = int128_type_kind;
2968 case SPECIFIER_FLOAT:
2969 atomic_type = ATOMIC_TYPE_FLOAT;
2971 case SPECIFIER_DOUBLE:
2972 atomic_type = ATOMIC_TYPE_DOUBLE;
2974 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2975 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2977 case SPECIFIER_BOOL:
2978 atomic_type = ATOMIC_TYPE_BOOL;
2980 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2981 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2982 atomic_type = ATOMIC_TYPE_FLOAT;
2984 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2985 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2986 atomic_type = ATOMIC_TYPE_DOUBLE;
2988 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2989 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2990 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2993 /* invalid specifier combination, give an error message */
2994 source_position_t const* const pos = &specifiers->source_position;
2995 if (type_specifiers == 0) {
2997 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
2998 if (!(c_mode & _CXX) && !strict_mode) {
2999 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3000 atomic_type = ATOMIC_TYPE_INT;
3003 errorf(pos, "no type specifiers given in declaration");
3006 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3007 (type_specifiers & SPECIFIER_UNSIGNED)) {
3008 errorf(pos, "signed and unsigned specifiers given");
3009 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3010 errorf(pos, "only integer types can be signed or unsigned");
3012 errorf(pos, "multiple datatypes in declaration");
3018 if (type_specifiers & SPECIFIER_COMPLEX) {
3019 type = allocate_type_zero(TYPE_COMPLEX);
3020 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3021 type = allocate_type_zero(TYPE_IMAGINARY);
3023 type = allocate_type_zero(TYPE_ATOMIC);
3025 type->atomic.akind = atomic_type;
3027 } else if (type_specifiers != 0) {
3028 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3031 /* FIXME: check type qualifiers here */
3032 type->base.qualifiers = qualifiers;
3035 type = identify_new_type(type);
3037 type = typehash_insert(type);
3040 if (specifiers->attributes != NULL)
3041 type = handle_type_attributes(specifiers->attributes, type);
3042 specifiers->type = type;
3046 specifiers->type = type_error_type;
3049 static type_qualifiers_t parse_type_qualifiers(void)
3051 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3054 switch (token.kind) {
3055 /* type qualifiers */
3056 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3057 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3058 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3059 /* microsoft extended type modifiers */
3060 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3061 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3062 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3063 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3064 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3073 * Parses an K&R identifier list
3075 static void parse_identifier_list(scope_t *scope)
3077 assert(token.kind == T_IDENTIFIER);
3079 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3080 /* a K&R parameter has no type, yet */
3084 append_entity(scope, entity);
3085 } while (next_if(',') && token.kind == T_IDENTIFIER);
3088 static entity_t *parse_parameter(void)
3090 declaration_specifiers_t specifiers;
3091 parse_declaration_specifiers(&specifiers);
3093 entity_t *entity = parse_declarator(&specifiers,
3094 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3095 anonymous_entity = NULL;
3099 static void semantic_parameter_incomplete(const entity_t *entity)
3101 assert(entity->kind == ENTITY_PARAMETER);
3103 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3104 * list in a function declarator that is part of a
3105 * definition of that function shall not have
3106 * incomplete type. */
3107 type_t *type = skip_typeref(entity->declaration.type);
3108 if (is_type_incomplete(type)) {
3109 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3113 static bool has_parameters(void)
3115 /* func(void) is not a parameter */
3116 if (look_ahead(1)->kind != ')')
3118 if (token.kind == T_IDENTIFIER) {
3119 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3122 if (entity->kind != ENTITY_TYPEDEF)
3124 type_t const *const type = skip_typeref(entity->typedefe.type);
3125 if (!is_type_void(type))
3127 if (c_mode & _CXX) {
3128 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3129 * is not allowed. */
3130 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3131 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3132 /* §6.7.5.3:10 Qualification is not allowed here. */
3133 errorf(HERE, "'void' as parameter must not have type qualifiers");
3135 } else if (token.kind != T_void) {
3143 * Parses function type parameters (and optionally creates variable_t entities
3144 * for them in a scope)
3146 static void parse_parameters(function_type_t *type, scope_t *scope)
3149 add_anchor_token(')');
3151 if (token.kind == T_IDENTIFIER &&
3152 !is_typedef_symbol(token.base.symbol) &&
3153 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3154 type->kr_style_parameters = true;
3155 parse_identifier_list(scope);
3156 } else if (token.kind == ')') {
3157 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3158 if (!(c_mode & _CXX))
3159 type->unspecified_parameters = true;
3160 } else if (has_parameters()) {
3161 function_parameter_t **anchor = &type->parameters;
3162 add_anchor_token(',');
3164 switch (token.kind) {
3167 type->variadic = true;
3168 goto parameters_finished;
3173 entity_t *entity = parse_parameter();
3174 if (entity->kind == ENTITY_TYPEDEF) {
3175 errorf(&entity->base.source_position,
3176 "typedef not allowed as function parameter");
3179 assert(is_declaration(entity));
3181 semantic_parameter_incomplete(entity);
3183 function_parameter_t *const parameter =
3184 allocate_parameter(entity->declaration.type);
3186 if (scope != NULL) {
3187 append_entity(scope, entity);
3190 *anchor = parameter;
3191 anchor = ¶meter->next;
3196 goto parameters_finished;
3198 } while (next_if(','));
3199 parameters_finished:
3200 rem_anchor_token(',');
3203 rem_anchor_token(')');
3207 typedef enum construct_type_kind_t {
3208 CONSTRUCT_POINTER = 1,
3209 CONSTRUCT_REFERENCE,
3212 } construct_type_kind_t;
3214 typedef union construct_type_t construct_type_t;
3216 typedef struct construct_type_base_t {
3217 construct_type_kind_t kind;
3218 source_position_t pos;
3219 construct_type_t *next;
3220 } construct_type_base_t;
3222 typedef struct parsed_pointer_t {
3223 construct_type_base_t base;
3224 type_qualifiers_t type_qualifiers;
3225 variable_t *base_variable; /**< MS __based extension. */
3228 typedef struct parsed_reference_t {
3229 construct_type_base_t base;
3230 } parsed_reference_t;
3232 typedef struct construct_function_type_t {
3233 construct_type_base_t base;
3234 type_t *function_type;
3235 } construct_function_type_t;
3237 typedef struct parsed_array_t {
3238 construct_type_base_t base;
3239 type_qualifiers_t type_qualifiers;
3245 union construct_type_t {
3246 construct_type_kind_t kind;
3247 construct_type_base_t base;
3248 parsed_pointer_t pointer;
3249 parsed_reference_t reference;
3250 construct_function_type_t function;
3251 parsed_array_t array;
3254 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3256 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3257 memset(cons, 0, size);
3259 cons->base.pos = *HERE;
3264 static construct_type_t *parse_pointer_declarator(void)
3266 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3268 cons->pointer.type_qualifiers = parse_type_qualifiers();
3269 //cons->pointer.base_variable = base_variable;
3274 /* ISO/IEC 14882:1998(E) §8.3.2 */
3275 static construct_type_t *parse_reference_declarator(void)
3277 if (!(c_mode & _CXX))
3278 errorf(HERE, "references are only available for C++");
3280 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3287 static construct_type_t *parse_array_declarator(void)
3289 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3290 parsed_array_t *const array = &cons->array;
3293 add_anchor_token(']');
3295 bool is_static = next_if(T_static);
3297 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3300 is_static = next_if(T_static);
3302 array->type_qualifiers = type_qualifiers;
3303 array->is_static = is_static;
3305 expression_t *size = NULL;
3306 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3307 array->is_variable = true;
3309 } else if (token.kind != ']') {
3310 size = parse_assignment_expression();
3312 /* §6.7.5.2:1 Array size must have integer type */
3313 type_t *const orig_type = size->base.type;
3314 type_t *const type = skip_typeref(orig_type);
3315 if (!is_type_integer(type) && is_type_valid(type)) {
3316 errorf(&size->base.source_position,
3317 "array size '%E' must have integer type but has type '%T'",
3322 mark_vars_read(size, NULL);
3325 if (is_static && size == NULL)
3326 errorf(&array->base.pos, "static array parameters require a size");
3328 rem_anchor_token(']');
3334 static construct_type_t *parse_function_declarator(scope_t *scope)
3336 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3338 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3339 function_type_t *ftype = &type->function;
3341 ftype->linkage = current_linkage;
3342 ftype->calling_convention = CC_DEFAULT;
3344 parse_parameters(ftype, scope);
3346 cons->function.function_type = type;
3351 typedef struct parse_declarator_env_t {
3352 bool may_be_abstract : 1;
3353 bool must_be_abstract : 1;
3354 decl_modifiers_t modifiers;
3356 source_position_t source_position;
3358 attribute_t *attributes;
3359 } parse_declarator_env_t;
3362 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3364 /* construct a single linked list of construct_type_t's which describe
3365 * how to construct the final declarator type */
3366 construct_type_t *first = NULL;
3367 construct_type_t **anchor = &first;
3369 env->attributes = parse_attributes(env->attributes);
3372 construct_type_t *type;
3373 //variable_t *based = NULL; /* MS __based extension */
3374 switch (token.kind) {
3376 type = parse_reference_declarator();
3380 panic("based not supported anymore");
3385 type = parse_pointer_declarator();
3389 goto ptr_operator_end;
3393 anchor = &type->base.next;
3395 /* TODO: find out if this is correct */
3396 env->attributes = parse_attributes(env->attributes);
3400 construct_type_t *inner_types = NULL;
3402 switch (token.kind) {
3404 if (env->must_be_abstract) {
3405 errorf(HERE, "no identifier expected in typename");
3407 env->symbol = token.base.symbol;
3408 env->source_position = token.base.source_position;
3414 /* Parenthesized declarator or function declarator? */
3415 token_t const *const la1 = look_ahead(1);
3416 switch (la1->kind) {
3418 if (is_typedef_symbol(la1->base.symbol)) {
3420 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3421 * interpreted as ``function with no parameter specification'', rather
3422 * than redundant parentheses around the omitted identifier. */
3424 /* Function declarator. */
3425 if (!env->may_be_abstract) {
3426 errorf(HERE, "function declarator must have a name");
3433 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3434 /* Paranthesized declarator. */
3436 add_anchor_token(')');
3437 inner_types = parse_inner_declarator(env);
3438 if (inner_types != NULL) {
3439 /* All later declarators only modify the return type */
3440 env->must_be_abstract = true;
3442 rem_anchor_token(')');
3451 if (env->may_be_abstract)
3453 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3458 construct_type_t **const p = anchor;
3461 construct_type_t *type;
3462 switch (token.kind) {
3464 scope_t *scope = NULL;
3465 if (!env->must_be_abstract) {
3466 scope = &env->parameters;
3469 type = parse_function_declarator(scope);
3473 type = parse_array_declarator();
3476 goto declarator_finished;
3479 /* insert in the middle of the list (at p) */
3480 type->base.next = *p;
3483 anchor = &type->base.next;
3486 declarator_finished:
3487 /* append inner_types at the end of the list, we don't to set anchor anymore
3488 * as it's not needed anymore */
3489 *anchor = inner_types;
3494 static type_t *construct_declarator_type(construct_type_t *construct_list,
3497 construct_type_t *iter = construct_list;
3498 for (; iter != NULL; iter = iter->base.next) {
3499 source_position_t const* const pos = &iter->base.pos;
3500 switch (iter->kind) {
3501 case CONSTRUCT_FUNCTION: {
3502 construct_function_type_t *function = &iter->function;
3503 type_t *function_type = function->function_type;
3505 function_type->function.return_type = type;
3507 type_t *skipped_return_type = skip_typeref(type);
3509 if (is_type_function(skipped_return_type)) {
3510 errorf(pos, "function returning function is not allowed");
3511 } else if (is_type_array(skipped_return_type)) {
3512 errorf(pos, "function returning array is not allowed");
3514 if (skipped_return_type->base.qualifiers != 0) {
3515 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3519 /* The function type was constructed earlier. Freeing it here will
3520 * destroy other types. */
3521 type = typehash_insert(function_type);
3525 case CONSTRUCT_POINTER: {
3526 if (is_type_reference(skip_typeref(type)))
3527 errorf(pos, "cannot declare a pointer to reference");
3529 parsed_pointer_t *pointer = &iter->pointer;
3530 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3534 case CONSTRUCT_REFERENCE:
3535 if (is_type_reference(skip_typeref(type)))
3536 errorf(pos, "cannot declare a reference to reference");
3538 type = make_reference_type(type);
3541 case CONSTRUCT_ARRAY: {
3542 if (is_type_reference(skip_typeref(type)))
3543 errorf(pos, "cannot declare an array of references");
3545 parsed_array_t *array = &iter->array;
3546 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3548 expression_t *size_expression = array->size;
3549 if (size_expression != NULL) {
3551 = create_implicit_cast(size_expression, type_size_t);
3554 array_type->base.qualifiers = array->type_qualifiers;
3555 array_type->array.element_type = type;
3556 array_type->array.is_static = array->is_static;
3557 array_type->array.is_variable = array->is_variable;
3558 array_type->array.size_expression = size_expression;
3560 if (size_expression != NULL) {
3561 switch (is_constant_expression(size_expression)) {
3562 case EXPR_CLASS_CONSTANT: {
3563 long const size = fold_constant_to_int(size_expression);
3564 array_type->array.size = size;
3565 array_type->array.size_constant = true;
3566 /* §6.7.5.2:1 If the expression is a constant expression,
3567 * it shall have a value greater than zero. */
3569 errorf(&size_expression->base.source_position,
3570 "size of array must be greater than zero");
3571 } else if (size == 0 && !GNU_MODE) {
3572 errorf(&size_expression->base.source_position,
3573 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3578 case EXPR_CLASS_VARIABLE:
3579 array_type->array.is_vla = true;
3582 case EXPR_CLASS_ERROR:
3587 type_t *skipped_type = skip_typeref(type);
3589 if (is_type_incomplete(skipped_type)) {
3590 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3591 } else if (is_type_function(skipped_type)) {
3592 errorf(pos, "array of functions is not allowed");
3594 type = identify_new_type(array_type);
3598 internal_errorf(pos, "invalid type construction found");
3604 static type_t *automatic_type_conversion(type_t *orig_type);
3606 static type_t *semantic_parameter(const source_position_t *pos,
3608 const declaration_specifiers_t *specifiers,
3609 entity_t const *const param)
3611 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3612 * shall be adjusted to ``qualified pointer to type'',
3614 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3615 * type'' shall be adjusted to ``pointer to function
3616 * returning type'', as in 6.3.2.1. */
3617 type = automatic_type_conversion(type);
3619 if (specifiers->is_inline && is_type_valid(type)) {
3620 errorf(pos, "'%N' declared 'inline'", param);
3623 /* §6.9.1:6 The declarations in the declaration list shall contain
3624 * no storage-class specifier other than register and no
3625 * initializations. */
3626 if (specifiers->thread_local || (
3627 specifiers->storage_class != STORAGE_CLASS_NONE &&
3628 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3630 errorf(pos, "invalid storage class for '%N'", param);
3633 /* delay test for incomplete type, because we might have (void)
3634 * which is legal but incomplete... */
3639 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3640 declarator_flags_t flags)
3642 parse_declarator_env_t env;
3643 memset(&env, 0, sizeof(env));
3644 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3646 construct_type_t *construct_type = parse_inner_declarator(&env);
3648 construct_declarator_type(construct_type, specifiers->type);
3649 type_t *type = skip_typeref(orig_type);
3651 if (construct_type != NULL) {
3652 obstack_free(&temp_obst, construct_type);
3655 attribute_t *attributes = parse_attributes(env.attributes);
3656 /* append (shared) specifier attribute behind attributes of this
3658 attribute_t **anchor = &attributes;
3659 while (*anchor != NULL)
3660 anchor = &(*anchor)->next;
3661 *anchor = specifiers->attributes;
3664 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3665 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3666 entity->typedefe.type = orig_type;
3668 if (anonymous_entity != NULL) {
3669 if (is_type_compound(type)) {
3670 assert(anonymous_entity->compound.alias == NULL);
3671 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3672 anonymous_entity->kind == ENTITY_UNION);
3673 anonymous_entity->compound.alias = entity;
3674 anonymous_entity = NULL;
3675 } else if (is_type_enum(type)) {
3676 assert(anonymous_entity->enume.alias == NULL);
3677 assert(anonymous_entity->kind == ENTITY_ENUM);
3678 anonymous_entity->enume.alias = entity;
3679 anonymous_entity = NULL;
3683 /* create a declaration type entity */
3684 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3685 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3686 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3688 if (env.symbol != NULL) {
3689 if (specifiers->is_inline && is_type_valid(type)) {
3690 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3693 if (specifiers->thread_local ||
3694 specifiers->storage_class != STORAGE_CLASS_NONE) {
3695 errorf(&env.source_position, "'%N' must have no storage class", entity);
3698 } else if (flags & DECL_IS_PARAMETER) {
3699 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3700 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3701 } else if (is_type_function(type)) {
3702 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3703 entity->function.is_inline = specifiers->is_inline;
3704 entity->function.elf_visibility = default_visibility;
3705 entity->function.parameters = env.parameters;
3707 if (env.symbol != NULL) {
3708 /* this needs fixes for C++ */
3709 bool in_function_scope = current_function != NULL;
3711 if (specifiers->thread_local || (
3712 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3713 specifiers->storage_class != STORAGE_CLASS_NONE &&
3714 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3716 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3720 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3721 entity->variable.elf_visibility = default_visibility;
3722 entity->variable.thread_local = specifiers->thread_local;
3724 if (env.symbol != NULL) {
3725 if (specifiers->is_inline && is_type_valid(type)) {
3726 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3729 bool invalid_storage_class = false;
3730 if (current_scope == file_scope) {
3731 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3732 specifiers->storage_class != STORAGE_CLASS_NONE &&
3733 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3734 invalid_storage_class = true;
3737 if (specifiers->thread_local &&
3738 specifiers->storage_class == STORAGE_CLASS_NONE) {
3739 invalid_storage_class = true;
3742 if (invalid_storage_class) {
3743 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3748 entity->declaration.type = orig_type;
3749 entity->declaration.alignment = get_type_alignment(orig_type);
3750 entity->declaration.modifiers = env.modifiers;
3751 entity->declaration.attributes = attributes;
3753 storage_class_t storage_class = specifiers->storage_class;
3754 entity->declaration.declared_storage_class = storage_class;
3756 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3757 storage_class = STORAGE_CLASS_AUTO;
3758 entity->declaration.storage_class = storage_class;
3761 if (attributes != NULL) {
3762 handle_entity_attributes(attributes, entity);
3765 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3766 adapt_special_functions(&entity->function);
3772 static type_t *parse_abstract_declarator(type_t *base_type)
3774 parse_declarator_env_t env;
3775 memset(&env, 0, sizeof(env));
3776 env.may_be_abstract = true;
3777 env.must_be_abstract = true;
3779 construct_type_t *construct_type = parse_inner_declarator(&env);
3781 type_t *result = construct_declarator_type(construct_type, base_type);
3782 if (construct_type != NULL) {
3783 obstack_free(&temp_obst, construct_type);
3785 result = handle_type_attributes(env.attributes, result);
3791 * Check if the declaration of main is suspicious. main should be a
3792 * function with external linkage, returning int, taking either zero
3793 * arguments, two, or three arguments of appropriate types, ie.
3795 * int main([ int argc, char **argv [, char **env ] ]).
3797 * @param decl the declaration to check
3798 * @param type the function type of the declaration
3800 static void check_main(const entity_t *entity)
3802 const source_position_t *pos = &entity->base.source_position;
3803 if (entity->kind != ENTITY_FUNCTION) {
3804 warningf(WARN_MAIN, pos, "'main' is not a function");
3808 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3809 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3812 type_t *type = skip_typeref(entity->declaration.type);
3813 assert(is_type_function(type));
3815 function_type_t const *const func_type = &type->function;
3816 type_t *const ret_type = func_type->return_type;
3817 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3818 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3820 const function_parameter_t *parm = func_type->parameters;
3822 type_t *const first_type = skip_typeref(parm->type);
3823 type_t *const first_type_unqual = get_unqualified_type(first_type);
3824 if (!types_compatible(first_type_unqual, type_int)) {
3825 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3829 type_t *const second_type = skip_typeref(parm->type);
3830 type_t *const second_type_unqual
3831 = get_unqualified_type(second_type);
3832 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3833 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3837 type_t *const third_type = skip_typeref(parm->type);
3838 type_t *const third_type_unqual
3839 = get_unqualified_type(third_type);
3840 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3841 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3845 goto warn_arg_count;
3849 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3854 static void error_redefined_as_different_kind(const source_position_t *pos,
3855 const entity_t *old, entity_kind_t new_kind)
3857 char const *const what = get_entity_kind_name(new_kind);
3858 source_position_t const *const ppos = &old->base.source_position;
3859 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3862 static bool is_entity_valid(entity_t *const ent)
3864 if (is_declaration(ent)) {
3865 return is_type_valid(skip_typeref(ent->declaration.type));
3866 } else if (ent->kind == ENTITY_TYPEDEF) {
3867 return is_type_valid(skip_typeref(ent->typedefe.type));
3872 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3874 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3875 if (attributes_equal(tattr, attr))
3882 * test wether new_list contains any attributes not included in old_list
3884 static bool has_new_attributes(const attribute_t *old_list,
3885 const attribute_t *new_list)
3887 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3888 if (!contains_attribute(old_list, attr))
3895 * Merge in attributes from an attribute list (probably from a previous
3896 * declaration with the same name). Warning: destroys the old structure
3897 * of the attribute list - don't reuse attributes after this call.
3899 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3902 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3904 if (contains_attribute(decl->attributes, attr))
3907 /* move attribute to new declarations attributes list */
3908 attr->next = decl->attributes;
3909 decl->attributes = attr;
3913 static bool is_main(entity_t*);
3916 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3917 * for various problems that occur for multiple definitions
3919 entity_t *record_entity(entity_t *entity, const bool is_definition)
3921 const symbol_t *const symbol = entity->base.symbol;
3922 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3923 const source_position_t *pos = &entity->base.source_position;
3925 /* can happen in error cases */
3929 assert(!entity->base.parent_scope);
3930 assert(current_scope);
3931 entity->base.parent_scope = current_scope;
3933 entity_t *const previous_entity = get_entity(symbol, namespc);
3934 /* pushing the same entity twice will break the stack structure */
3935 assert(previous_entity != entity);
3937 if (entity->kind == ENTITY_FUNCTION) {
3938 type_t *const orig_type = entity->declaration.type;
3939 type_t *const type = skip_typeref(orig_type);
3941 assert(is_type_function(type));
3942 if (type->function.unspecified_parameters &&
3943 previous_entity == NULL &&
3944 !entity->declaration.implicit) {
3945 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3948 if (is_main(entity)) {
3953 if (is_declaration(entity) &&
3954 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3955 current_scope != file_scope &&
3956 !entity->declaration.implicit) {
3957 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3960 if (previous_entity != NULL) {
3961 source_position_t const *const ppos = &previous_entity->base.source_position;
3963 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3964 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3965 assert(previous_entity->kind == ENTITY_PARAMETER);
3966 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3970 if (previous_entity->base.parent_scope == current_scope) {
3971 if (previous_entity->kind != entity->kind) {
3972 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3973 error_redefined_as_different_kind(pos, previous_entity,
3978 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3979 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3982 if (previous_entity->kind == ENTITY_TYPEDEF) {
3983 type_t *const type = skip_typeref(entity->typedefe.type);
3984 type_t *const prev_type
3985 = skip_typeref(previous_entity->typedefe.type);
3986 if (c_mode & _CXX) {
3987 /* C++ allows double typedef if they are identical
3988 * (after skipping typedefs) */
3989 if (type == prev_type)
3992 /* GCC extension: redef in system headers is allowed */
3993 if ((pos->is_system_header || ppos->is_system_header) &&
3994 types_compatible(type, prev_type))
3997 errorf(pos, "redefinition of '%N' (declared %P)",
4002 /* at this point we should have only VARIABLES or FUNCTIONS */
4003 assert(is_declaration(previous_entity) && is_declaration(entity));
4005 declaration_t *const prev_decl = &previous_entity->declaration;
4006 declaration_t *const decl = &entity->declaration;
4008 /* can happen for K&R style declarations */
4009 if (prev_decl->type == NULL &&
4010 previous_entity->kind == ENTITY_PARAMETER &&
4011 entity->kind == ENTITY_PARAMETER) {
4012 prev_decl->type = decl->type;
4013 prev_decl->storage_class = decl->storage_class;
4014 prev_decl->declared_storage_class = decl->declared_storage_class;
4015 prev_decl->modifiers = decl->modifiers;
4016 return previous_entity;
4019 type_t *const type = skip_typeref(decl->type);
4020 type_t *const prev_type = skip_typeref(prev_decl->type);
4022 if (!types_compatible(type, prev_type)) {
4023 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4025 unsigned old_storage_class = prev_decl->storage_class;
4027 if (is_definition &&
4029 !(prev_decl->modifiers & DM_USED) &&
4030 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4031 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4034 storage_class_t new_storage_class = decl->storage_class;
4036 /* pretend no storage class means extern for function
4037 * declarations (except if the previous declaration is neither
4038 * none nor extern) */
4039 if (entity->kind == ENTITY_FUNCTION) {
4040 /* the previous declaration could have unspecified parameters or
4041 * be a typedef, so use the new type */
4042 if (prev_type->function.unspecified_parameters || is_definition)
4043 prev_decl->type = type;
4045 switch (old_storage_class) {
4046 case STORAGE_CLASS_NONE:
4047 old_storage_class = STORAGE_CLASS_EXTERN;
4050 case STORAGE_CLASS_EXTERN:
4051 if (is_definition) {
4052 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4053 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4055 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4056 new_storage_class = STORAGE_CLASS_EXTERN;
4063 } else if (is_type_incomplete(prev_type)) {
4064 prev_decl->type = type;
4067 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4068 new_storage_class == STORAGE_CLASS_EXTERN) {
4070 warn_redundant_declaration: ;
4072 = has_new_attributes(prev_decl->attributes,
4074 if (has_new_attrs) {
4075 merge_in_attributes(decl, prev_decl->attributes);
4076 } else if (!is_definition &&
4077 is_type_valid(prev_type) &&
4078 !pos->is_system_header) {
4079 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4081 } else if (current_function == NULL) {
4082 if (old_storage_class != STORAGE_CLASS_STATIC &&
4083 new_storage_class == STORAGE_CLASS_STATIC) {
4084 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4085 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4086 prev_decl->storage_class = STORAGE_CLASS_NONE;
4087 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4089 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4091 goto error_redeclaration;
4092 goto warn_redundant_declaration;
4094 } else if (is_type_valid(prev_type)) {
4095 if (old_storage_class == new_storage_class) {
4096 error_redeclaration:
4097 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4099 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4104 prev_decl->modifiers |= decl->modifiers;
4105 if (entity->kind == ENTITY_FUNCTION) {
4106 previous_entity->function.is_inline |= entity->function.is_inline;
4108 return previous_entity;
4112 if (is_warn_on(why = WARN_SHADOW) ||
4113 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4114 char const *const what = get_entity_kind_name(previous_entity->kind);
4115 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4119 if (entity->kind == ENTITY_FUNCTION) {
4120 if (is_definition &&
4121 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4123 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4124 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4126 goto warn_missing_declaration;
4129 } else if (entity->kind == ENTITY_VARIABLE) {
4130 if (current_scope == file_scope &&
4131 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4132 !entity->declaration.implicit) {
4133 warn_missing_declaration:
4134 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4139 environment_push(entity);
4140 append_entity(current_scope, entity);
4145 static void parser_error_multiple_definition(entity_t *entity,
4146 const source_position_t *source_position)
4148 errorf(source_position, "redefinition of '%N' (declared %P)", entity, &entity->base.source_position);
4151 static bool is_declaration_specifier(const token_t *token)
4153 switch (token->kind) {
4157 return is_typedef_symbol(token->base.symbol);
4164 static void parse_init_declarator_rest(entity_t *entity)
4166 type_t *orig_type = type_error_type;
4168 if (entity->base.kind == ENTITY_TYPEDEF) {
4169 source_position_t const *const pos = &entity->base.source_position;
4170 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4172 assert(is_declaration(entity));
4173 orig_type = entity->declaration.type;
4176 type_t *type = skip_typeref(orig_type);
4178 if (entity->kind == ENTITY_VARIABLE
4179 && entity->variable.initializer != NULL) {
4180 parser_error_multiple_definition(entity, HERE);
4184 declaration_t *const declaration = &entity->declaration;
4185 bool must_be_constant = false;
4186 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4187 entity->base.parent_scope == file_scope) {
4188 must_be_constant = true;
4191 if (is_type_function(type)) {
4192 source_position_t const *const pos = &entity->base.source_position;
4193 errorf(pos, "'%N' is initialized like a variable", entity);
4194 orig_type = type_error_type;
4197 parse_initializer_env_t env;
4198 env.type = orig_type;
4199 env.must_be_constant = must_be_constant;
4200 env.entity = entity;
4202 initializer_t *initializer = parse_initializer(&env);
4204 if (entity->kind == ENTITY_VARIABLE) {
4205 /* §6.7.5:22 array initializers for arrays with unknown size
4206 * determine the array type size */
4207 declaration->type = env.type;
4208 entity->variable.initializer = initializer;
4212 /* parse rest of a declaration without any declarator */
4213 static void parse_anonymous_declaration_rest(
4214 const declaration_specifiers_t *specifiers)
4217 anonymous_entity = NULL;
4219 source_position_t const *const pos = &specifiers->source_position;
4220 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4221 specifiers->thread_local) {
4222 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4225 type_t *type = specifiers->type;
4226 switch (type->kind) {
4227 case TYPE_COMPOUND_STRUCT:
4228 case TYPE_COMPOUND_UNION: {
4229 if (type->compound.compound->base.symbol == NULL) {
4230 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4239 warningf(WARN_OTHER, pos, "empty declaration");
4244 static void check_variable_type_complete(entity_t *ent)
4246 if (ent->kind != ENTITY_VARIABLE)
4249 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4250 * type for the object shall be complete [...] */
4251 declaration_t *decl = &ent->declaration;
4252 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4253 decl->storage_class == STORAGE_CLASS_STATIC)
4256 type_t *const type = skip_typeref(decl->type);
4257 if (!is_type_incomplete(type))
4260 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4261 * are given length one. */
4262 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4263 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4267 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4271 static void parse_declaration_rest(entity_t *ndeclaration,
4272 const declaration_specifiers_t *specifiers,
4273 parsed_declaration_func finished_declaration,
4274 declarator_flags_t flags)
4276 add_anchor_token(';');
4277 add_anchor_token(',');
4279 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4281 if (token.kind == '=') {
4282 parse_init_declarator_rest(entity);
4283 } else if (entity->kind == ENTITY_VARIABLE) {
4284 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4285 * [...] where the extern specifier is explicitly used. */
4286 declaration_t *decl = &entity->declaration;
4287 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4288 is_type_reference(skip_typeref(decl->type))) {
4289 source_position_t const *const pos = &entity->base.source_position;
4290 errorf(pos, "reference '%#N' must be initialized", entity);
4294 check_variable_type_complete(entity);
4299 add_anchor_token('=');
4300 ndeclaration = parse_declarator(specifiers, flags);
4301 rem_anchor_token('=');
4303 rem_anchor_token(',');
4304 rem_anchor_token(';');
4307 anonymous_entity = NULL;
4310 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4312 symbol_t *symbol = entity->base.symbol;
4316 assert(entity->base.namespc == NAMESPACE_NORMAL);
4317 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4318 if (previous_entity == NULL
4319 || previous_entity->base.parent_scope != current_scope) {
4320 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4325 if (is_definition) {
4326 errorf(HERE, "'%N' is initialised", entity);
4329 return record_entity(entity, false);
4332 static void parse_declaration(parsed_declaration_func finished_declaration,
4333 declarator_flags_t flags)
4335 add_anchor_token(';');
4336 declaration_specifiers_t specifiers;
4337 parse_declaration_specifiers(&specifiers);
4338 rem_anchor_token(';');
4340 if (token.kind == ';') {
4341 parse_anonymous_declaration_rest(&specifiers);
4343 entity_t *entity = parse_declarator(&specifiers, flags);
4344 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4349 static type_t *get_default_promoted_type(type_t *orig_type)
4351 type_t *result = orig_type;
4353 type_t *type = skip_typeref(orig_type);
4354 if (is_type_integer(type)) {
4355 result = promote_integer(type);
4356 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4357 result = type_double;
4363 static void parse_kr_declaration_list(entity_t *entity)
4365 if (entity->kind != ENTITY_FUNCTION)
4368 type_t *type = skip_typeref(entity->declaration.type);
4369 assert(is_type_function(type));
4370 if (!type->function.kr_style_parameters)
4373 add_anchor_token('{');
4375 PUSH_SCOPE(&entity->function.parameters);
4377 entity_t *parameter = entity->function.parameters.entities;
4378 for ( ; parameter != NULL; parameter = parameter->base.next) {
4379 assert(parameter->base.parent_scope == NULL);
4380 parameter->base.parent_scope = current_scope;
4381 environment_push(parameter);
4384 /* parse declaration list */
4386 switch (token.kind) {
4388 /* This covers symbols, which are no type, too, and results in
4389 * better error messages. The typical cases are misspelled type
4390 * names and missing includes. */
4392 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4402 /* update function type */
4403 type_t *new_type = duplicate_type(type);
4405 function_parameter_t *parameters = NULL;
4406 function_parameter_t **anchor = ¶meters;
4408 /* did we have an earlier prototype? */
4409 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4410 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4413 function_parameter_t *proto_parameter = NULL;
4414 if (proto_type != NULL) {
4415 type_t *proto_type_type = proto_type->declaration.type;
4416 proto_parameter = proto_type_type->function.parameters;
4417 /* If a K&R function definition has a variadic prototype earlier, then
4418 * make the function definition variadic, too. This should conform to
4419 * §6.7.5.3:15 and §6.9.1:8. */
4420 new_type->function.variadic = proto_type_type->function.variadic;
4422 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4424 new_type->function.unspecified_parameters = true;
4427 bool need_incompatible_warning = false;
4428 parameter = entity->function.parameters.entities;
4429 for (; parameter != NULL; parameter = parameter->base.next,
4431 proto_parameter == NULL ? NULL : proto_parameter->next) {
4432 if (parameter->kind != ENTITY_PARAMETER)
4435 type_t *parameter_type = parameter->declaration.type;
4436 if (parameter_type == NULL) {
4437 source_position_t const* const pos = ¶meter->base.source_position;
4439 errorf(pos, "no type specified for function '%N'", parameter);
4440 parameter_type = type_error_type;
4442 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4443 parameter_type = type_int;
4445 parameter->declaration.type = parameter_type;
4448 semantic_parameter_incomplete(parameter);
4450 /* we need the default promoted types for the function type */
4451 type_t *not_promoted = parameter_type;
4452 parameter_type = get_default_promoted_type(parameter_type);
4454 /* gcc special: if the type of the prototype matches the unpromoted
4455 * type don't promote */
4456 if (!strict_mode && proto_parameter != NULL) {
4457 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4458 type_t *promo_skip = skip_typeref(parameter_type);
4459 type_t *param_skip = skip_typeref(not_promoted);
4460 if (!types_compatible(proto_p_type, promo_skip)
4461 && types_compatible(proto_p_type, param_skip)) {
4463 need_incompatible_warning = true;
4464 parameter_type = not_promoted;
4467 function_parameter_t *const function_parameter
4468 = allocate_parameter(parameter_type);
4470 *anchor = function_parameter;
4471 anchor = &function_parameter->next;
4474 new_type->function.parameters = parameters;
4475 new_type = identify_new_type(new_type);
4477 if (need_incompatible_warning) {
4478 symbol_t const *const sym = entity->base.symbol;
4479 source_position_t const *const pos = &entity->base.source_position;
4480 source_position_t const *const ppos = &proto_type->base.source_position;
4481 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4483 entity->declaration.type = new_type;
4485 rem_anchor_token('{');
4488 static bool first_err = true;
4491 * When called with first_err set, prints the name of the current function,
4494 static void print_in_function(void)
4498 char const *const file = current_function->base.base.source_position.input_name;
4499 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4504 * Check if all labels are defined in the current function.
4505 * Check if all labels are used in the current function.
4507 static void check_labels(void)
4509 for (const goto_statement_t *goto_statement = goto_first;
4510 goto_statement != NULL;
4511 goto_statement = goto_statement->next) {
4512 label_t *label = goto_statement->label;
4513 if (label->base.source_position.input_name == NULL) {
4514 print_in_function();
4515 source_position_t const *const pos = &goto_statement->base.source_position;
4516 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4520 if (is_warn_on(WARN_UNUSED_LABEL)) {
4521 for (const label_statement_t *label_statement = label_first;
4522 label_statement != NULL;
4523 label_statement = label_statement->next) {
4524 label_t *label = label_statement->label;
4526 if (! label->used) {
4527 print_in_function();
4528 source_position_t const *const pos = &label_statement->base.source_position;
4529 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4535 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4537 entity_t const *const end = last != NULL ? last->base.next : NULL;
4538 for (; entity != end; entity = entity->base.next) {
4539 if (!is_declaration(entity))
4542 declaration_t *declaration = &entity->declaration;
4543 if (declaration->implicit)
4546 if (!declaration->used) {
4547 print_in_function();
4548 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4549 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4550 print_in_function();
4551 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4556 static void check_unused_variables(statement_t *const stmt, void *const env)
4560 switch (stmt->kind) {
4561 case STATEMENT_DECLARATION: {
4562 declaration_statement_t const *const decls = &stmt->declaration;
4563 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4568 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4577 * Check declarations of current_function for unused entities.
4579 static void check_declarations(void)
4581 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4582 const scope_t *scope = ¤t_function->parameters;
4583 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4585 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4586 walk_statements(current_function->statement, check_unused_variables,
4591 static int determine_truth(expression_t const* const cond)
4594 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4595 fold_constant_to_bool(cond) ? 1 :
4599 static void check_reachable(statement_t *);
4600 static bool reaches_end;
4602 static bool expression_returns(expression_t const *const expr)
4604 switch (expr->kind) {
4606 expression_t const *const func = expr->call.function;
4607 type_t const *const type = skip_typeref(func->base.type);
4608 if (type->kind == TYPE_POINTER) {
4609 type_t const *const points_to
4610 = skip_typeref(type->pointer.points_to);
4611 if (points_to->kind == TYPE_FUNCTION
4612 && points_to->function.modifiers & DM_NORETURN)
4616 if (!expression_returns(func))
4619 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4620 if (!expression_returns(arg->expression))
4627 case EXPR_REFERENCE:
4628 case EXPR_ENUM_CONSTANT:
4629 case EXPR_LITERAL_CASES:
4630 case EXPR_STRING_LITERAL:
4631 case EXPR_WIDE_STRING_LITERAL:
4632 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4633 case EXPR_LABEL_ADDRESS:
4634 case EXPR_CLASSIFY_TYPE:
4635 case EXPR_SIZEOF: // TODO handle obscure VLA case
4638 case EXPR_BUILTIN_CONSTANT_P:
4639 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4644 case EXPR_STATEMENT: {
4645 bool old_reaches_end = reaches_end;
4646 reaches_end = false;
4647 check_reachable(expr->statement.statement);
4648 bool returns = reaches_end;
4649 reaches_end = old_reaches_end;
4653 case EXPR_CONDITIONAL:
4654 // TODO handle constant expression
4656 if (!expression_returns(expr->conditional.condition))
4659 if (expr->conditional.true_expression != NULL
4660 && expression_returns(expr->conditional.true_expression))
4663 return expression_returns(expr->conditional.false_expression);
4666 return expression_returns(expr->select.compound);
4668 case EXPR_ARRAY_ACCESS:
4670 expression_returns(expr->array_access.array_ref) &&
4671 expression_returns(expr->array_access.index);
4674 return expression_returns(expr->va_starte.ap);
4677 return expression_returns(expr->va_arge.ap);
4680 return expression_returns(expr->va_copye.src);
4682 case EXPR_UNARY_CASES_MANDATORY:
4683 return expression_returns(expr->unary.value);
4685 case EXPR_UNARY_THROW:
4688 case EXPR_BINARY_CASES:
4689 // TODO handle constant lhs of && and ||
4691 expression_returns(expr->binary.left) &&
4692 expression_returns(expr->binary.right);
4695 panic("unhandled expression");
4698 static bool initializer_returns(initializer_t const *const init)
4700 switch (init->kind) {
4701 case INITIALIZER_VALUE:
4702 return expression_returns(init->value.value);
4704 case INITIALIZER_LIST: {
4705 initializer_t * const* i = init->list.initializers;
4706 initializer_t * const* const end = i + init->list.len;
4707 bool returns = true;
4708 for (; i != end; ++i) {
4709 if (!initializer_returns(*i))
4715 case INITIALIZER_STRING:
4716 case INITIALIZER_WIDE_STRING:
4717 case INITIALIZER_DESIGNATOR: // designators have no payload
4720 panic("unhandled initializer");
4723 static bool noreturn_candidate;
4725 static void check_reachable(statement_t *const stmt)
4727 if (stmt->base.reachable)
4729 if (stmt->kind != STATEMENT_DO_WHILE)
4730 stmt->base.reachable = true;
4732 statement_t *last = stmt;
4734 switch (stmt->kind) {
4735 case STATEMENT_ERROR:
4736 case STATEMENT_EMPTY:
4738 next = stmt->base.next;
4741 case STATEMENT_DECLARATION: {
4742 declaration_statement_t const *const decl = &stmt->declaration;
4743 entity_t const * ent = decl->declarations_begin;
4744 entity_t const *const last_decl = decl->declarations_end;
4746 for (;; ent = ent->base.next) {
4747 if (ent->kind == ENTITY_VARIABLE &&
4748 ent->variable.initializer != NULL &&
4749 !initializer_returns(ent->variable.initializer)) {
4752 if (ent == last_decl)
4756 next = stmt->base.next;
4760 case STATEMENT_COMPOUND:
4761 next = stmt->compound.statements;
4763 next = stmt->base.next;
4766 case STATEMENT_RETURN: {
4767 expression_t const *const val = stmt->returns.value;
4768 if (val == NULL || expression_returns(val))
4769 noreturn_candidate = false;
4773 case STATEMENT_IF: {
4774 if_statement_t const *const ifs = &stmt->ifs;
4775 expression_t const *const cond = ifs->condition;
4777 if (!expression_returns(cond))
4780 int const val = determine_truth(cond);
4783 check_reachable(ifs->true_statement);
4788 if (ifs->false_statement != NULL) {
4789 check_reachable(ifs->false_statement);
4793 next = stmt->base.next;
4797 case STATEMENT_SWITCH: {
4798 switch_statement_t const *const switchs = &stmt->switchs;
4799 expression_t const *const expr = switchs->expression;
4801 if (!expression_returns(expr))
4804 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4805 long const val = fold_constant_to_int(expr);
4806 case_label_statement_t * defaults = NULL;
4807 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4808 if (i->expression == NULL) {
4813 if (i->first_case <= val && val <= i->last_case) {
4814 check_reachable((statement_t*)i);
4819 if (defaults != NULL) {
4820 check_reachable((statement_t*)defaults);
4824 bool has_default = false;
4825 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4826 if (i->expression == NULL)
4829 check_reachable((statement_t*)i);
4836 next = stmt->base.next;
4840 case STATEMENT_EXPRESSION: {
4841 /* Check for noreturn function call */
4842 expression_t const *const expr = stmt->expression.expression;
4843 if (!expression_returns(expr))
4846 next = stmt->base.next;
4850 case STATEMENT_CONTINUE:
4851 for (statement_t *parent = stmt;;) {
4852 parent = parent->base.parent;
4853 if (parent == NULL) /* continue not within loop */
4857 switch (parent->kind) {
4858 case STATEMENT_WHILE: goto continue_while;
4859 case STATEMENT_DO_WHILE: goto continue_do_while;
4860 case STATEMENT_FOR: goto continue_for;
4866 case STATEMENT_BREAK:
4867 for (statement_t *parent = stmt;;) {
4868 parent = parent->base.parent;
4869 if (parent == NULL) /* break not within loop/switch */
4872 switch (parent->kind) {
4873 case STATEMENT_SWITCH:
4874 case STATEMENT_WHILE:
4875 case STATEMENT_DO_WHILE:
4878 next = parent->base.next;
4879 goto found_break_parent;
4887 case STATEMENT_COMPUTED_GOTO: {
4888 if (!expression_returns(stmt->computed_goto.expression))
4891 statement_t *parent = stmt->base.parent;
4892 if (parent == NULL) /* top level goto */
4898 case STATEMENT_GOTO:
4899 next = stmt->gotos.label->statement;
4900 if (next == NULL) /* missing label */
4904 case STATEMENT_LABEL:
4905 next = stmt->label.statement;
4908 case STATEMENT_CASE_LABEL:
4909 next = stmt->case_label.statement;
4912 case STATEMENT_WHILE: {
4913 while_statement_t const *const whiles = &stmt->whiles;
4914 expression_t const *const cond = whiles->condition;
4916 if (!expression_returns(cond))
4919 int const val = determine_truth(cond);
4922 check_reachable(whiles->body);
4927 next = stmt->base.next;
4931 case STATEMENT_DO_WHILE:
4932 next = stmt->do_while.body;
4935 case STATEMENT_FOR: {
4936 for_statement_t *const fors = &stmt->fors;
4938 if (fors->condition_reachable)
4940 fors->condition_reachable = true;
4942 expression_t const *const cond = fors->condition;
4947 } else if (expression_returns(cond)) {
4948 val = determine_truth(cond);
4954 check_reachable(fors->body);
4959 next = stmt->base.next;
4963 case STATEMENT_MS_TRY: {
4964 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4965 check_reachable(ms_try->try_statement);
4966 next = ms_try->final_statement;
4970 case STATEMENT_LEAVE: {
4971 statement_t *parent = stmt;
4973 parent = parent->base.parent;
4974 if (parent == NULL) /* __leave not within __try */
4977 if (parent->kind == STATEMENT_MS_TRY) {
4979 next = parent->ms_try.final_statement;
4987 panic("invalid statement kind");
4990 while (next == NULL) {
4991 next = last->base.parent;
4993 noreturn_candidate = false;
4995 type_t *const type = skip_typeref(current_function->base.type);
4996 assert(is_type_function(type));
4997 type_t *const ret = skip_typeref(type->function.return_type);
4998 if (!is_type_void(ret) &&
4999 is_type_valid(ret) &&
5000 !is_main(current_entity)) {
5001 source_position_t const *const pos = &stmt->base.source_position;
5002 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5007 switch (next->kind) {
5008 case STATEMENT_ERROR:
5009 case STATEMENT_EMPTY:
5010 case STATEMENT_DECLARATION:
5011 case STATEMENT_EXPRESSION:
5013 case STATEMENT_RETURN:
5014 case STATEMENT_CONTINUE:
5015 case STATEMENT_BREAK:
5016 case STATEMENT_COMPUTED_GOTO:
5017 case STATEMENT_GOTO:
5018 case STATEMENT_LEAVE:
5019 panic("invalid control flow in function");
5021 case STATEMENT_COMPOUND:
5022 if (next->compound.stmt_expr) {
5028 case STATEMENT_SWITCH:
5029 case STATEMENT_LABEL:
5030 case STATEMENT_CASE_LABEL:
5032 next = next->base.next;
5035 case STATEMENT_WHILE: {
5037 if (next->base.reachable)
5039 next->base.reachable = true;
5041 while_statement_t const *const whiles = &next->whiles;
5042 expression_t const *const cond = whiles->condition;
5044 if (!expression_returns(cond))
5047 int const val = determine_truth(cond);
5050 check_reachable(whiles->body);
5056 next = next->base.next;
5060 case STATEMENT_DO_WHILE: {
5062 if (next->base.reachable)
5064 next->base.reachable = true;
5066 do_while_statement_t const *const dw = &next->do_while;
5067 expression_t const *const cond = dw->condition;
5069 if (!expression_returns(cond))
5072 int const val = determine_truth(cond);
5075 check_reachable(dw->body);
5081 next = next->base.next;
5085 case STATEMENT_FOR: {
5087 for_statement_t *const fors = &next->fors;
5089 fors->step_reachable = true;
5091 if (fors->condition_reachable)
5093 fors->condition_reachable = true;
5095 expression_t const *const cond = fors->condition;
5100 } else if (expression_returns(cond)) {
5101 val = determine_truth(cond);
5107 check_reachable(fors->body);
5113 next = next->base.next;
5117 case STATEMENT_MS_TRY:
5119 next = next->ms_try.final_statement;
5124 check_reachable(next);
5127 static void check_unreachable(statement_t* const stmt, void *const env)
5131 switch (stmt->kind) {
5132 case STATEMENT_DO_WHILE:
5133 if (!stmt->base.reachable) {
5134 expression_t const *const cond = stmt->do_while.condition;
5135 if (determine_truth(cond) >= 0) {
5136 source_position_t const *const pos = &cond->base.source_position;
5137 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5142 case STATEMENT_FOR: {
5143 for_statement_t const* const fors = &stmt->fors;
5145 // if init and step are unreachable, cond is unreachable, too
5146 if (!stmt->base.reachable && !fors->step_reachable) {
5147 goto warn_unreachable;
5149 if (!stmt->base.reachable && fors->initialisation != NULL) {
5150 source_position_t const *const pos = &fors->initialisation->base.source_position;
5151 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5154 if (!fors->condition_reachable && fors->condition != NULL) {
5155 source_position_t const *const pos = &fors->condition->base.source_position;
5156 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5159 if (!fors->step_reachable && fors->step != NULL) {
5160 source_position_t const *const pos = &fors->step->base.source_position;
5161 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5167 case STATEMENT_COMPOUND:
5168 if (stmt->compound.statements != NULL)
5170 goto warn_unreachable;
5172 case STATEMENT_DECLARATION: {
5173 /* Only warn if there is at least one declarator with an initializer.
5174 * This typically occurs in switch statements. */
5175 declaration_statement_t const *const decl = &stmt->declaration;
5176 entity_t const * ent = decl->declarations_begin;
5177 entity_t const *const last = decl->declarations_end;
5179 for (;; ent = ent->base.next) {
5180 if (ent->kind == ENTITY_VARIABLE &&
5181 ent->variable.initializer != NULL) {
5182 goto warn_unreachable;
5192 if (!stmt->base.reachable) {
5193 source_position_t const *const pos = &stmt->base.source_position;
5194 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5200 static bool is_main(entity_t *entity)
5202 static symbol_t *sym_main = NULL;
5203 if (sym_main == NULL) {
5204 sym_main = symbol_table_insert("main");
5207 if (entity->base.symbol != sym_main)
5209 /* must be in outermost scope */
5210 if (entity->base.parent_scope != file_scope)
5216 static void prepare_main_collect2(entity_t*);
5218 static void parse_external_declaration(void)
5220 /* function-definitions and declarations both start with declaration
5222 add_anchor_token(';');
5223 declaration_specifiers_t specifiers;
5224 parse_declaration_specifiers(&specifiers);
5225 rem_anchor_token(';');
5227 /* must be a declaration */
5228 if (token.kind == ';') {
5229 parse_anonymous_declaration_rest(&specifiers);
5233 add_anchor_token(',');
5234 add_anchor_token('=');
5235 add_anchor_token(';');
5236 add_anchor_token('{');
5238 /* declarator is common to both function-definitions and declarations */
5239 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5241 rem_anchor_token('{');
5242 rem_anchor_token(';');
5243 rem_anchor_token('=');
5244 rem_anchor_token(',');
5246 /* must be a declaration */
5247 switch (token.kind) {
5251 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5256 /* must be a function definition */
5257 parse_kr_declaration_list(ndeclaration);
5259 if (token.kind != '{') {
5260 parse_error_expected("while parsing function definition", '{', NULL);
5261 eat_until_matching_token(';');
5265 assert(is_declaration(ndeclaration));
5266 type_t *const orig_type = ndeclaration->declaration.type;
5267 type_t * type = skip_typeref(orig_type);
5269 if (!is_type_function(type)) {
5270 if (is_type_valid(type)) {
5271 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5277 source_position_t const *const pos = &ndeclaration->base.source_position;
5278 if (is_typeref(orig_type)) {
5280 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5283 if (is_type_compound(skip_typeref(type->function.return_type))) {
5284 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5286 if (type->function.unspecified_parameters) {
5287 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5289 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5292 /* §6.7.5.3:14 a function definition with () means no
5293 * parameters (and not unspecified parameters) */
5294 if (type->function.unspecified_parameters &&
5295 type->function.parameters == NULL) {
5296 type_t *copy = duplicate_type(type);
5297 copy->function.unspecified_parameters = false;
5298 type = identify_new_type(copy);
5300 ndeclaration->declaration.type = type;
5303 entity_t *const entity = record_entity(ndeclaration, true);
5304 assert(entity->kind == ENTITY_FUNCTION);
5305 assert(ndeclaration->kind == ENTITY_FUNCTION);
5307 function_t *const function = &entity->function;
5308 if (ndeclaration != entity) {
5309 function->parameters = ndeclaration->function.parameters;
5312 PUSH_SCOPE(&function->parameters);
5314 entity_t *parameter = function->parameters.entities;
5315 for (; parameter != NULL; parameter = parameter->base.next) {
5316 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5317 parameter->base.parent_scope = current_scope;
5319 assert(parameter->base.parent_scope == NULL
5320 || parameter->base.parent_scope == current_scope);
5321 parameter->base.parent_scope = current_scope;
5322 if (parameter->base.symbol == NULL) {
5323 errorf(¶meter->base.source_position, "parameter name omitted");
5326 environment_push(parameter);
5329 if (function->statement != NULL) {
5330 parser_error_multiple_definition(entity, HERE);
5333 /* parse function body */
5334 int label_stack_top = label_top();
5335 function_t *old_current_function = current_function;
5336 current_function = function;
5337 PUSH_CURRENT_ENTITY(entity);
5341 goto_anchor = &goto_first;
5343 label_anchor = &label_first;
5345 statement_t *const body = parse_compound_statement(false);
5346 function->statement = body;
5349 check_declarations();
5350 if (is_warn_on(WARN_RETURN_TYPE) ||
5351 is_warn_on(WARN_UNREACHABLE_CODE) ||
5352 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5353 noreturn_candidate = true;
5354 check_reachable(body);
5355 if (is_warn_on(WARN_UNREACHABLE_CODE))
5356 walk_statements(body, check_unreachable, NULL);
5357 if (noreturn_candidate &&
5358 !(function->base.modifiers & DM_NORETURN)) {
5359 source_position_t const *const pos = &body->base.source_position;
5360 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5364 if (is_main(entity)) {
5365 /* Force main to C linkage. */
5366 type_t *const type = entity->declaration.type;
5367 assert(is_type_function(type));
5368 if (type->function.linkage != LINKAGE_C) {
5369 type_t *new_type = duplicate_type(type);
5370 new_type->function.linkage = LINKAGE_C;
5371 entity->declaration.type = identify_new_type(new_type);
5374 if (enable_main_collect2_hack)
5375 prepare_main_collect2(entity);
5378 POP_CURRENT_ENTITY();
5380 assert(current_function == function);
5381 current_function = old_current_function;
5382 label_pop_to(label_stack_top);
5388 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5390 entity_t *iter = compound->members.entities;
5391 for (; iter != NULL; iter = iter->base.next) {
5392 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5395 if (iter->base.symbol == symbol) {
5397 } else if (iter->base.symbol == NULL) {
5398 /* search in anonymous structs and unions */
5399 type_t *type = skip_typeref(iter->declaration.type);
5400 if (is_type_compound(type)) {
5401 if (find_compound_entry(type->compound.compound, symbol)
5412 static void check_deprecated(const source_position_t *source_position,
5413 const entity_t *entity)
5415 if (!is_declaration(entity))
5417 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5420 source_position_t const *const epos = &entity->base.source_position;
5421 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5423 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5425 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5430 static expression_t *create_select(const source_position_t *pos,
5432 type_qualifiers_t qualifiers,
5435 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5437 check_deprecated(pos, entry);
5439 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5440 select->select.compound = addr;
5441 select->select.compound_entry = entry;
5443 type_t *entry_type = entry->declaration.type;
5444 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5446 /* bitfields need special treatment */
5447 if (entry->compound_member.bitfield) {
5448 unsigned bit_size = entry->compound_member.bit_size;
5449 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5450 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5451 res_type = type_int;
5455 /* we always do the auto-type conversions; the & and sizeof parser contains
5456 * code to revert this! */
5457 select->base.type = automatic_type_conversion(res_type);
5464 * Find entry with symbol in compound. Search anonymous structs and unions and
5465 * creates implicit select expressions for them.
5466 * Returns the adress for the innermost compound.
5468 static expression_t *find_create_select(const source_position_t *pos,
5470 type_qualifiers_t qualifiers,
5471 compound_t *compound, symbol_t *symbol)
5473 entity_t *iter = compound->members.entities;
5474 for (; iter != NULL; iter = iter->base.next) {
5475 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5478 symbol_t *iter_symbol = iter->base.symbol;
5479 if (iter_symbol == NULL) {
5480 type_t *type = iter->declaration.type;
5481 if (type->kind != TYPE_COMPOUND_STRUCT
5482 && type->kind != TYPE_COMPOUND_UNION)
5485 compound_t *sub_compound = type->compound.compound;
5487 if (find_compound_entry(sub_compound, symbol) == NULL)
5490 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5491 sub_addr->base.source_position = *pos;
5492 sub_addr->base.implicit = true;
5493 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5497 if (iter_symbol == symbol) {
5498 return create_select(pos, addr, qualifiers, iter);
5505 static void parse_bitfield_member(entity_t *entity)
5509 expression_t *size = parse_constant_expression();
5512 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5513 type_t *type = entity->declaration.type;
5514 if (!is_type_integer(skip_typeref(type))) {
5515 errorf(HERE, "bitfield base type '%T' is not an integer type",
5519 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5520 /* error already reported by parse_constant_expression */
5521 size_long = get_type_size(type) * 8;
5523 size_long = fold_constant_to_int(size);
5525 const symbol_t *symbol = entity->base.symbol;
5526 const symbol_t *user_symbol
5527 = symbol == NULL ? sym_anonymous : symbol;
5528 unsigned bit_size = get_type_size(type) * 8;
5529 if (size_long < 0) {
5530 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5531 } else if (size_long == 0 && symbol != NULL) {
5532 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5533 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5534 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5537 /* hope that people don't invent crazy types with more bits
5538 * than our struct can hold */
5540 (1 << sizeof(entity->compound_member.bit_size)*8));
5544 entity->compound_member.bitfield = true;
5545 entity->compound_member.bit_size = (unsigned char)size_long;
5548 static void parse_compound_declarators(compound_t *compound,
5549 const declaration_specifiers_t *specifiers)
5551 add_anchor_token(';');
5552 add_anchor_token(',');
5556 if (token.kind == ':') {
5557 /* anonymous bitfield */
5558 type_t *type = specifiers->type;
5559 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5560 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5561 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5562 entity->declaration.type = type;
5564 parse_bitfield_member(entity);
5566 attribute_t *attributes = parse_attributes(NULL);
5567 attribute_t **anchor = &attributes;
5568 while (*anchor != NULL)
5569 anchor = &(*anchor)->next;
5570 *anchor = specifiers->attributes;
5571 if (attributes != NULL) {
5572 handle_entity_attributes(attributes, entity);
5574 entity->declaration.attributes = attributes;
5576 append_entity(&compound->members, entity);
5578 entity = parse_declarator(specifiers,
5579 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5580 source_position_t const *const pos = &entity->base.source_position;
5581 if (entity->kind == ENTITY_TYPEDEF) {
5582 errorf(pos, "typedef not allowed as compound member");
5584 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5586 /* make sure we don't define a symbol multiple times */
5587 symbol_t *symbol = entity->base.symbol;
5588 if (symbol != NULL) {
5589 entity_t *prev = find_compound_entry(compound, symbol);
5591 source_position_t const *const ppos = &prev->base.source_position;
5592 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5596 if (token.kind == ':') {
5597 parse_bitfield_member(entity);
5599 attribute_t *attributes = parse_attributes(NULL);
5600 handle_entity_attributes(attributes, entity);
5602 type_t *orig_type = entity->declaration.type;
5603 type_t *type = skip_typeref(orig_type);
5604 if (is_type_function(type)) {
5605 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5606 } else if (is_type_incomplete(type)) {
5607 /* §6.7.2.1:16 flexible array member */
5608 if (!is_type_array(type) ||
5609 token.kind != ';' ||
5610 look_ahead(1)->kind != '}') {
5611 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5612 } else if (compound->members.entities == NULL) {
5613 errorf(pos, "flexible array member in otherwise empty struct");
5618 append_entity(&compound->members, entity);
5621 } while (next_if(','));
5622 rem_anchor_token(',');
5623 rem_anchor_token(';');
5626 anonymous_entity = NULL;
5629 static void parse_compound_type_entries(compound_t *compound)
5632 add_anchor_token('}');
5635 switch (token.kind) {
5637 case T___extension__:
5638 case T_IDENTIFIER: {
5640 declaration_specifiers_t specifiers;
5641 parse_declaration_specifiers(&specifiers);
5642 parse_compound_declarators(compound, &specifiers);
5648 rem_anchor_token('}');
5651 compound->complete = true;
5657 static type_t *parse_typename(void)
5659 declaration_specifiers_t specifiers;
5660 parse_declaration_specifiers(&specifiers);
5661 if (specifiers.storage_class != STORAGE_CLASS_NONE
5662 || specifiers.thread_local) {
5663 /* TODO: improve error message, user does probably not know what a
5664 * storage class is...
5666 errorf(&specifiers.source_position, "typename must not have a storage class");
5669 type_t *result = parse_abstract_declarator(specifiers.type);
5677 typedef expression_t* (*parse_expression_function)(void);
5678 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5680 typedef struct expression_parser_function_t expression_parser_function_t;
5681 struct expression_parser_function_t {
5682 parse_expression_function parser;
5683 precedence_t infix_precedence;
5684 parse_expression_infix_function infix_parser;
5687 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5689 static type_t *get_string_type(void)
5691 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5694 static type_t *get_wide_string_type(void)
5696 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5700 * Parse a string constant.
5702 static expression_t *parse_string_literal(void)
5704 source_position_t begin = token.base.source_position;
5705 string_t res = token.string.string;
5706 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5709 while (token.kind == T_STRING_LITERAL
5710 || token.kind == T_WIDE_STRING_LITERAL) {
5711 warn_string_concat(&token.base.source_position);
5712 res = concat_strings(&res, &token.string.string);
5714 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5717 expression_t *literal;
5719 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5720 literal->base.type = get_wide_string_type();
5722 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5723 literal->base.type = get_string_type();
5725 literal->base.source_position = begin;
5726 literal->literal.value = res;
5732 * Parse a boolean constant.
5734 static expression_t *parse_boolean_literal(bool value)
5736 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5737 literal->base.type = type_bool;
5738 literal->literal.value.begin = value ? "true" : "false";
5739 literal->literal.value.size = value ? 4 : 5;
5745 static void warn_traditional_suffix(void)
5747 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5748 &token.number.suffix);
5751 static void check_integer_suffix(void)
5753 const string_t *suffix = &token.number.suffix;
5754 if (suffix->size == 0)
5757 bool not_traditional = false;
5758 const char *c = suffix->begin;
5759 if (*c == 'l' || *c == 'L') {
5762 not_traditional = true;
5764 if (*c == 'u' || *c == 'U') {
5767 } else if (*c == 'u' || *c == 'U') {
5768 not_traditional = true;
5771 } else if (*c == 'u' || *c == 'U') {
5772 not_traditional = true;
5774 if (*c == 'l' || *c == 'L') {
5782 errorf(&token.base.source_position,
5783 "invalid suffix '%S' on integer constant", suffix);
5784 } else if (not_traditional) {
5785 warn_traditional_suffix();
5789 static type_t *check_floatingpoint_suffix(void)
5791 const string_t *suffix = &token.number.suffix;
5792 type_t *type = type_double;
5793 if (suffix->size == 0)
5796 bool not_traditional = false;
5797 const char *c = suffix->begin;
5798 if (*c == 'f' || *c == 'F') {
5801 } else if (*c == 'l' || *c == 'L') {
5803 type = type_long_double;
5806 errorf(&token.base.source_position,
5807 "invalid suffix '%S' on floatingpoint constant", suffix);
5808 } else if (not_traditional) {
5809 warn_traditional_suffix();
5816 * Parse an integer constant.
5818 static expression_t *parse_number_literal(void)
5820 expression_kind_t kind;
5823 switch (token.kind) {
5825 kind = EXPR_LITERAL_INTEGER;
5826 check_integer_suffix();
5830 case T_FLOATINGPOINT:
5831 kind = EXPR_LITERAL_FLOATINGPOINT;
5832 type = check_floatingpoint_suffix();
5836 panic("unexpected token type in parse_number_literal");
5839 expression_t *literal = allocate_expression_zero(kind);
5840 literal->base.type = type;
5841 literal->literal.value = token.number.number;
5842 literal->literal.suffix = token.number.suffix;
5845 /* integer type depends on the size of the number and the size
5846 * representable by the types. The backend/codegeneration has to determine
5849 determine_literal_type(&literal->literal);
5854 * Parse a character constant.
5856 static expression_t *parse_character_constant(void)
5858 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5859 literal->base.type = c_mode & _CXX ? type_char : type_int;
5860 literal->literal.value = token.string.string;
5862 size_t len = literal->literal.value.size;
5864 if (!GNU_MODE && !(c_mode & _C99)) {
5865 errorf(HERE, "more than 1 character in character constant");
5867 literal->base.type = type_int;
5868 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5877 * Parse a wide character constant.
5879 static expression_t *parse_wide_character_constant(void)
5881 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5882 literal->base.type = type_int;
5883 literal->literal.value = token.string.string;
5885 size_t len = wstrlen(&literal->literal.value);
5887 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5894 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5896 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5897 ntype->function.return_type = type_int;
5898 ntype->function.unspecified_parameters = true;
5899 ntype->function.linkage = LINKAGE_C;
5900 type_t *type = identify_new_type(ntype);
5902 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5903 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5904 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5905 entity->declaration.type = type;
5906 entity->declaration.implicit = true;
5908 if (current_scope != NULL)
5909 record_entity(entity, false);
5915 * Performs automatic type cast as described in §6.3.2.1.
5917 * @param orig_type the original type
5919 static type_t *automatic_type_conversion(type_t *orig_type)
5921 type_t *type = skip_typeref(orig_type);
5922 if (is_type_array(type)) {
5923 array_type_t *array_type = &type->array;
5924 type_t *element_type = array_type->element_type;
5925 unsigned qualifiers = array_type->base.qualifiers;
5927 return make_pointer_type(element_type, qualifiers);
5930 if (is_type_function(type)) {
5931 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5938 * reverts the automatic casts of array to pointer types and function
5939 * to function-pointer types as defined §6.3.2.1
5941 type_t *revert_automatic_type_conversion(const expression_t *expression)
5943 switch (expression->kind) {
5944 case EXPR_REFERENCE: {
5945 entity_t *entity = expression->reference.entity;
5946 if (is_declaration(entity)) {
5947 return entity->declaration.type;
5948 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5949 return entity->enum_value.enum_type;
5951 panic("no declaration or enum in reference");
5956 entity_t *entity = expression->select.compound_entry;
5957 assert(is_declaration(entity));
5958 type_t *type = entity->declaration.type;
5959 return get_qualified_type(type, expression->base.type->base.qualifiers);
5962 case EXPR_UNARY_DEREFERENCE: {
5963 const expression_t *const value = expression->unary.value;
5964 type_t *const type = skip_typeref(value->base.type);
5965 if (!is_type_pointer(type))
5966 return type_error_type;
5967 return type->pointer.points_to;
5970 case EXPR_ARRAY_ACCESS: {
5971 const expression_t *array_ref = expression->array_access.array_ref;
5972 type_t *type_left = skip_typeref(array_ref->base.type);
5973 if (!is_type_pointer(type_left))
5974 return type_error_type;
5975 return type_left->pointer.points_to;
5978 case EXPR_STRING_LITERAL: {
5979 size_t size = expression->string_literal.value.size;
5980 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5983 case EXPR_WIDE_STRING_LITERAL: {
5984 size_t size = wstrlen(&expression->string_literal.value);
5985 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5988 case EXPR_COMPOUND_LITERAL:
5989 return expression->compound_literal.type;
5994 return expression->base.type;
5998 * Find an entity matching a symbol in a scope.
5999 * Uses current scope if scope is NULL
6001 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6002 namespace_tag_t namespc)
6004 if (scope == NULL) {
6005 return get_entity(symbol, namespc);
6008 /* we should optimize here, if scope grows above a certain size we should
6009 construct a hashmap here... */
6010 entity_t *entity = scope->entities;
6011 for ( ; entity != NULL; entity = entity->base.next) {
6012 if (entity->base.symbol == symbol
6013 && (namespace_tag_t)entity->base.namespc == namespc)
6020 static entity_t *parse_qualified_identifier(void)
6022 /* namespace containing the symbol */
6024 source_position_t pos;
6025 const scope_t *lookup_scope = NULL;
6027 if (next_if(T_COLONCOLON))
6028 lookup_scope = &unit->scope;
6032 symbol = expect_identifier("while parsing identifier", &pos);
6034 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6037 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6039 if (!next_if(T_COLONCOLON))
6042 switch (entity->kind) {
6043 case ENTITY_NAMESPACE:
6044 lookup_scope = &entity->namespacee.members;
6049 lookup_scope = &entity->compound.members;
6052 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6053 symbol, get_entity_kind_name(entity->kind));
6055 /* skip further qualifications */
6056 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6058 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6062 if (entity == NULL) {
6063 if (!strict_mode && token.kind == '(') {
6064 /* an implicitly declared function */
6065 entity = create_implicit_function(symbol, &pos);
6066 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6068 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6069 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6076 static expression_t *parse_reference(void)
6078 source_position_t const pos = token.base.source_position;
6079 entity_t *const entity = parse_qualified_identifier();
6082 if (is_declaration(entity)) {
6083 orig_type = entity->declaration.type;
6084 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6085 orig_type = entity->enum_value.enum_type;
6087 panic("expected declaration or enum value in reference");
6090 /* we always do the auto-type conversions; the & and sizeof parser contains
6091 * code to revert this! */
6092 type_t *type = automatic_type_conversion(orig_type);
6094 expression_kind_t kind = EXPR_REFERENCE;
6095 if (entity->kind == ENTITY_ENUM_VALUE)
6096 kind = EXPR_ENUM_CONSTANT;
6098 expression_t *expression = allocate_expression_zero(kind);
6099 expression->base.source_position = pos;
6100 expression->base.type = type;
6101 expression->reference.entity = entity;
6103 /* this declaration is used */
6104 if (is_declaration(entity)) {
6105 entity->declaration.used = true;
6108 if (entity->base.parent_scope != file_scope
6109 && (current_function != NULL
6110 && entity->base.parent_scope->depth < current_function->parameters.depth)
6111 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6112 if (entity->kind == ENTITY_VARIABLE) {
6113 /* access of a variable from an outer function */
6114 entity->variable.address_taken = true;
6115 } else if (entity->kind == ENTITY_PARAMETER) {
6116 entity->parameter.address_taken = true;
6118 current_function->need_closure = true;
6121 check_deprecated(&pos, entity);
6126 static bool semantic_cast(expression_t *cast)
6128 expression_t *expression = cast->unary.value;
6129 type_t *orig_dest_type = cast->base.type;
6130 type_t *orig_type_right = expression->base.type;
6131 type_t const *dst_type = skip_typeref(orig_dest_type);
6132 type_t const *src_type = skip_typeref(orig_type_right);
6133 source_position_t const *pos = &cast->base.source_position;
6135 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6136 if (is_type_void(dst_type))
6139 /* only integer and pointer can be casted to pointer */
6140 if (is_type_pointer(dst_type) &&
6141 !is_type_pointer(src_type) &&
6142 !is_type_integer(src_type) &&
6143 is_type_valid(src_type)) {
6144 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6148 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6149 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6153 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6154 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6158 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6159 type_t *src = skip_typeref(src_type->pointer.points_to);
6160 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6161 unsigned missing_qualifiers =
6162 src->base.qualifiers & ~dst->base.qualifiers;
6163 if (missing_qualifiers != 0) {
6164 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6170 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6172 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6173 expression->base.source_position = *pos;
6175 parse_initializer_env_t env;
6178 env.must_be_constant = false;
6179 initializer_t *initializer = parse_initializer(&env);
6182 expression->compound_literal.initializer = initializer;
6183 expression->compound_literal.type = type;
6184 expression->base.type = automatic_type_conversion(type);
6190 * Parse a cast expression.
6192 static expression_t *parse_cast(void)
6194 source_position_t const pos = *HERE;
6197 add_anchor_token(')');
6199 type_t *type = parse_typename();
6201 rem_anchor_token(')');
6204 if (token.kind == '{') {
6205 return parse_compound_literal(&pos, type);
6208 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6209 cast->base.source_position = pos;
6211 expression_t *value = parse_subexpression(PREC_CAST);
6212 cast->base.type = type;
6213 cast->unary.value = value;
6215 if (! semantic_cast(cast)) {
6216 /* TODO: record the error in the AST. else it is impossible to detect it */
6223 * Parse a statement expression.
6225 static expression_t *parse_statement_expression(void)
6227 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6230 add_anchor_token(')');
6232 statement_t *statement = parse_compound_statement(true);
6233 statement->compound.stmt_expr = true;
6234 expression->statement.statement = statement;
6236 /* find last statement and use its type */
6237 type_t *type = type_void;
6238 const statement_t *stmt = statement->compound.statements;
6240 while (stmt->base.next != NULL)
6241 stmt = stmt->base.next;
6243 if (stmt->kind == STATEMENT_EXPRESSION) {
6244 type = stmt->expression.expression->base.type;
6247 source_position_t const *const pos = &expression->base.source_position;
6248 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6250 expression->base.type = type;
6252 rem_anchor_token(')');
6258 * Parse a parenthesized expression.
6260 static expression_t *parse_parenthesized_expression(void)
6262 token_t const* const la1 = look_ahead(1);
6263 switch (la1->kind) {
6265 /* gcc extension: a statement expression */
6266 return parse_statement_expression();
6269 if (is_typedef_symbol(la1->base.symbol)) {
6271 return parse_cast();
6276 add_anchor_token(')');
6277 expression_t *result = parse_expression();
6278 result->base.parenthesized = true;
6279 rem_anchor_token(')');
6285 static expression_t *parse_function_keyword(void)
6289 if (current_function == NULL) {
6290 errorf(HERE, "'__func__' used outside of a function");
6293 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6294 expression->base.type = type_char_ptr;
6295 expression->funcname.kind = FUNCNAME_FUNCTION;
6302 static expression_t *parse_pretty_function_keyword(void)
6304 if (current_function == NULL) {
6305 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6308 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6309 expression->base.type = type_char_ptr;
6310 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6312 eat(T___PRETTY_FUNCTION__);
6317 static expression_t *parse_funcsig_keyword(void)
6319 if (current_function == NULL) {
6320 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6323 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6324 expression->base.type = type_char_ptr;
6325 expression->funcname.kind = FUNCNAME_FUNCSIG;
6332 static expression_t *parse_funcdname_keyword(void)
6334 if (current_function == NULL) {
6335 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6338 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6339 expression->base.type = type_char_ptr;
6340 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6342 eat(T___FUNCDNAME__);
6347 static designator_t *parse_designator(void)
6349 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6350 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6351 if (!result->symbol)
6354 designator_t *last_designator = result;
6357 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6358 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6359 if (!designator->symbol)
6362 last_designator->next = designator;
6363 last_designator = designator;
6367 add_anchor_token(']');
6368 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6369 designator->source_position = *HERE;
6370 designator->array_index = parse_expression();
6371 rem_anchor_token(']');
6373 if (designator->array_index == NULL) {
6377 last_designator->next = designator;
6378 last_designator = designator;
6388 * Parse the __builtin_offsetof() expression.
6390 static expression_t *parse_offsetof(void)
6392 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6393 expression->base.type = type_size_t;
6395 eat(T___builtin_offsetof);
6398 add_anchor_token(')');
6399 add_anchor_token(',');
6400 type_t *type = parse_typename();
6401 rem_anchor_token(',');
6403 designator_t *designator = parse_designator();
6404 rem_anchor_token(')');
6407 expression->offsetofe.type = type;
6408 expression->offsetofe.designator = designator;
6411 memset(&path, 0, sizeof(path));
6412 path.top_type = type;
6413 path.path = NEW_ARR_F(type_path_entry_t, 0);
6415 descend_into_subtype(&path);
6417 if (!walk_designator(&path, designator, true)) {
6418 return create_error_expression();
6421 DEL_ARR_F(path.path);
6427 * Parses a _builtin_va_start() expression.
6429 static expression_t *parse_va_start(void)
6431 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6433 eat(T___builtin_va_start);
6436 add_anchor_token(')');
6437 add_anchor_token(',');
6438 expression->va_starte.ap = parse_assignment_expression();
6439 rem_anchor_token(',');
6441 expression_t *const expr = parse_assignment_expression();
6442 if (expr->kind == EXPR_REFERENCE) {
6443 entity_t *const entity = expr->reference.entity;
6444 if (!current_function->base.type->function.variadic) {
6445 errorf(&expr->base.source_position,
6446 "'va_start' used in non-variadic function");
6447 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6448 entity->base.next != NULL ||
6449 entity->kind != ENTITY_PARAMETER) {
6450 errorf(&expr->base.source_position,
6451 "second argument of 'va_start' must be last parameter of the current function");
6453 expression->va_starte.parameter = &entity->variable;
6456 expression = create_error_expression();
6458 rem_anchor_token(')');
6464 * Parses a __builtin_va_arg() expression.
6466 static expression_t *parse_va_arg(void)
6468 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6470 eat(T___builtin_va_arg);
6473 add_anchor_token(')');
6474 add_anchor_token(',');
6476 ap.expression = parse_assignment_expression();
6477 expression->va_arge.ap = ap.expression;
6478 check_call_argument(type_valist, &ap, 1);
6480 rem_anchor_token(',');
6482 expression->base.type = parse_typename();
6483 rem_anchor_token(')');
6490 * Parses a __builtin_va_copy() expression.
6492 static expression_t *parse_va_copy(void)
6494 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6496 eat(T___builtin_va_copy);
6499 add_anchor_token(')');
6500 add_anchor_token(',');
6501 expression_t *dst = parse_assignment_expression();
6502 assign_error_t error = semantic_assign(type_valist, dst);
6503 report_assign_error(error, type_valist, dst, "call argument 1",
6504 &dst->base.source_position);
6505 expression->va_copye.dst = dst;
6507 rem_anchor_token(',');
6510 call_argument_t src;
6511 src.expression = parse_assignment_expression();
6512 check_call_argument(type_valist, &src, 2);
6513 expression->va_copye.src = src.expression;
6514 rem_anchor_token(')');
6521 * Parses a __builtin_constant_p() expression.
6523 static expression_t *parse_builtin_constant(void)
6525 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6527 eat(T___builtin_constant_p);
6530 add_anchor_token(')');
6531 expression->builtin_constant.value = parse_assignment_expression();
6532 rem_anchor_token(')');
6534 expression->base.type = type_int;
6540 * Parses a __builtin_types_compatible_p() expression.
6542 static expression_t *parse_builtin_types_compatible(void)
6544 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6546 eat(T___builtin_types_compatible_p);
6549 add_anchor_token(')');
6550 add_anchor_token(',');
6551 expression->builtin_types_compatible.left = parse_typename();
6552 rem_anchor_token(',');
6554 expression->builtin_types_compatible.right = parse_typename();
6555 rem_anchor_token(')');
6557 expression->base.type = type_int;
6563 * Parses a __builtin_is_*() compare expression.
6565 static expression_t *parse_compare_builtin(void)
6567 expression_t *expression;
6569 switch (token.kind) {
6570 case T___builtin_isgreater:
6571 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6573 case T___builtin_isgreaterequal:
6574 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6576 case T___builtin_isless:
6577 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6579 case T___builtin_islessequal:
6580 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6582 case T___builtin_islessgreater:
6583 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6585 case T___builtin_isunordered:
6586 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6589 internal_errorf(HERE, "invalid compare builtin found");
6591 expression->base.source_position = *HERE;
6595 add_anchor_token(')');
6596 add_anchor_token(',');
6597 expression->binary.left = parse_assignment_expression();
6598 rem_anchor_token(',');
6600 expression->binary.right = parse_assignment_expression();
6601 rem_anchor_token(')');
6604 type_t *const orig_type_left = expression->binary.left->base.type;
6605 type_t *const orig_type_right = expression->binary.right->base.type;
6607 type_t *const type_left = skip_typeref(orig_type_left);
6608 type_t *const type_right = skip_typeref(orig_type_right);
6609 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6610 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6611 type_error_incompatible("invalid operands in comparison",
6612 &expression->base.source_position, orig_type_left, orig_type_right);
6615 semantic_comparison(&expression->binary);
6622 * Parses a MS assume() expression.
6624 static expression_t *parse_assume(void)
6626 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6631 add_anchor_token(')');
6632 expression->unary.value = parse_assignment_expression();
6633 rem_anchor_token(')');
6636 expression->base.type = type_void;
6641 * Return the label for the current symbol or create a new one.
6643 static label_t *get_label(void)
6645 assert(token.kind == T_IDENTIFIER);
6646 assert(current_function != NULL);
6648 entity_t *label = get_entity(token.base.symbol, NAMESPACE_LABEL);
6649 /* If we find a local label, we already created the declaration. */
6650 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6651 if (label->base.parent_scope != current_scope) {
6652 assert(label->base.parent_scope->depth < current_scope->depth);
6653 current_function->goto_to_outer = true;
6655 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6656 /* There is no matching label in the same function, so create a new one. */
6657 source_position_t const nowhere = { NULL, 0, 0, false };
6658 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.base.symbol, &nowhere);
6663 return &label->label;
6667 * Parses a GNU && label address expression.
6669 static expression_t *parse_label_address(void)
6671 source_position_t source_position = token.base.source_position;
6673 if (token.kind != T_IDENTIFIER) {
6674 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6675 return create_error_expression();
6678 label_t *const label = get_label();
6680 label->address_taken = true;
6682 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6683 expression->base.source_position = source_position;
6685 /* label address is treated as a void pointer */
6686 expression->base.type = type_void_ptr;
6687 expression->label_address.label = label;
6692 * Parse a microsoft __noop expression.
6694 static expression_t *parse_noop_expression(void)
6696 /* the result is a (int)0 */
6697 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6698 literal->base.type = type_int;
6699 literal->literal.value.begin = "__noop";
6700 literal->literal.value.size = 6;
6704 if (token.kind == '(') {
6705 /* parse arguments */
6707 add_anchor_token(')');
6708 add_anchor_token(',');
6710 if (token.kind != ')') do {
6711 (void)parse_assignment_expression();
6712 } while (next_if(','));
6714 rem_anchor_token(',');
6715 rem_anchor_token(')');
6723 * Parses a primary expression.
6725 static expression_t *parse_primary_expression(void)
6727 switch (token.kind) {
6728 case T_false: return parse_boolean_literal(false);
6729 case T_true: return parse_boolean_literal(true);
6731 case T_FLOATINGPOINT: return parse_number_literal();
6732 case T_CHARACTER_CONSTANT: return parse_character_constant();
6733 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6734 case T_STRING_LITERAL:
6735 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6736 case T___FUNCTION__:
6737 case T___func__: return parse_function_keyword();
6738 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6739 case T___FUNCSIG__: return parse_funcsig_keyword();
6740 case T___FUNCDNAME__: return parse_funcdname_keyword();
6741 case T___builtin_offsetof: return parse_offsetof();
6742 case T___builtin_va_start: return parse_va_start();
6743 case T___builtin_va_arg: return parse_va_arg();
6744 case T___builtin_va_copy: return parse_va_copy();
6745 case T___builtin_isgreater:
6746 case T___builtin_isgreaterequal:
6747 case T___builtin_isless:
6748 case T___builtin_islessequal:
6749 case T___builtin_islessgreater:
6750 case T___builtin_isunordered: return parse_compare_builtin();
6751 case T___builtin_constant_p: return parse_builtin_constant();
6752 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6753 case T__assume: return parse_assume();
6756 return parse_label_address();
6759 case '(': return parse_parenthesized_expression();
6760 case T___noop: return parse_noop_expression();
6762 /* Gracefully handle type names while parsing expressions. */
6764 return parse_reference();
6766 if (!is_typedef_symbol(token.base.symbol)) {
6767 return parse_reference();
6771 source_position_t const pos = *HERE;
6772 declaration_specifiers_t specifiers;
6773 parse_declaration_specifiers(&specifiers);
6774 type_t const *const type = parse_abstract_declarator(specifiers.type);
6775 errorf(&pos, "encountered type '%T' while parsing expression", type);
6776 return create_error_expression();
6780 errorf(HERE, "unexpected token %K, expected an expression", &token);
6782 return create_error_expression();
6785 static expression_t *parse_array_expression(expression_t *left)
6787 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6788 array_access_expression_t *const arr = &expr->array_access;
6791 add_anchor_token(']');
6793 expression_t *const inside = parse_expression();
6795 type_t *const orig_type_left = left->base.type;
6796 type_t *const orig_type_inside = inside->base.type;
6798 type_t *const type_left = skip_typeref(orig_type_left);
6799 type_t *const type_inside = skip_typeref(orig_type_inside);
6805 if (is_type_pointer(type_left)) {
6808 idx_type = type_inside;
6809 res_type = type_left->pointer.points_to;
6811 } else if (is_type_pointer(type_inside)) {
6812 arr->flipped = true;
6815 idx_type = type_left;
6816 res_type = type_inside->pointer.points_to;
6818 res_type = automatic_type_conversion(res_type);
6819 if (!is_type_integer(idx_type)) {
6820 errorf(&idx->base.source_position, "array subscript must have integer type");
6821 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6822 source_position_t const *const pos = &idx->base.source_position;
6823 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6826 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6827 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6829 res_type = type_error_type;
6834 arr->array_ref = ref;
6836 arr->base.type = res_type;
6838 rem_anchor_token(']');
6843 static bool is_bitfield(const expression_t *expression)
6845 return expression->kind == EXPR_SELECT
6846 && expression->select.compound_entry->compound_member.bitfield;
6849 static expression_t *parse_typeprop(expression_kind_t const kind)
6851 expression_t *tp_expression = allocate_expression_zero(kind);
6852 tp_expression->base.type = type_size_t;
6854 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6857 expression_t *expression;
6858 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6859 source_position_t const pos = *HERE;
6861 add_anchor_token(')');
6862 orig_type = parse_typename();
6863 rem_anchor_token(')');
6866 if (token.kind == '{') {
6867 /* It was not sizeof(type) after all. It is sizeof of an expression
6868 * starting with a compound literal */
6869 expression = parse_compound_literal(&pos, orig_type);
6870 goto typeprop_expression;
6873 expression = parse_subexpression(PREC_UNARY);
6875 typeprop_expression:
6876 if (is_bitfield(expression)) {
6877 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6878 errorf(&tp_expression->base.source_position,
6879 "operand of %s expression must not be a bitfield", what);
6882 tp_expression->typeprop.tp_expression = expression;
6884 orig_type = revert_automatic_type_conversion(expression);
6885 expression->base.type = orig_type;
6888 tp_expression->typeprop.type = orig_type;
6889 type_t const* const type = skip_typeref(orig_type);
6890 char const* wrong_type = NULL;
6891 if (is_type_incomplete(type)) {
6892 if (!is_type_void(type) || !GNU_MODE)
6893 wrong_type = "incomplete";
6894 } else if (type->kind == TYPE_FUNCTION) {
6896 /* function types are allowed (and return 1) */
6897 source_position_t const *const pos = &tp_expression->base.source_position;
6898 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6899 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6901 wrong_type = "function";
6905 if (wrong_type != NULL) {
6906 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6907 errorf(&tp_expression->base.source_position,
6908 "operand of %s expression must not be of %s type '%T'",
6909 what, wrong_type, orig_type);
6912 return tp_expression;
6915 static expression_t *parse_sizeof(void)
6917 return parse_typeprop(EXPR_SIZEOF);
6920 static expression_t *parse_alignof(void)
6922 return parse_typeprop(EXPR_ALIGNOF);
6925 static expression_t *parse_select_expression(expression_t *addr)
6927 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6928 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6929 source_position_t const pos = *HERE;
6932 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6934 return create_error_expression();
6936 type_t *const orig_type = addr->base.type;
6937 type_t *const type = skip_typeref(orig_type);
6940 bool saw_error = false;
6941 if (is_type_pointer(type)) {
6942 if (!select_left_arrow) {
6944 "request for member '%Y' in something not a struct or union, but '%T'",
6948 type_left = skip_typeref(type->pointer.points_to);
6950 if (select_left_arrow && is_type_valid(type)) {
6951 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6957 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6958 type_left->kind != TYPE_COMPOUND_UNION) {
6960 if (is_type_valid(type_left) && !saw_error) {
6962 "request for member '%Y' in something not a struct or union, but '%T'",
6965 return create_error_expression();
6968 compound_t *compound = type_left->compound.compound;
6969 if (!compound->complete) {
6970 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6972 return create_error_expression();
6975 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6976 expression_t *result =
6977 find_create_select(&pos, addr, qualifiers, compound, symbol);
6979 if (result == NULL) {
6980 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6981 return create_error_expression();
6987 static void check_call_argument(type_t *expected_type,
6988 call_argument_t *argument, unsigned pos)
6990 type_t *expected_type_skip = skip_typeref(expected_type);
6991 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6992 expression_t *arg_expr = argument->expression;
6993 type_t *arg_type = skip_typeref(arg_expr->base.type);
6995 /* handle transparent union gnu extension */
6996 if (is_type_union(expected_type_skip)
6997 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6998 compound_t *union_decl = expected_type_skip->compound.compound;
6999 type_t *best_type = NULL;
7000 entity_t *entry = union_decl->members.entities;
7001 for ( ; entry != NULL; entry = entry->base.next) {
7002 assert(is_declaration(entry));
7003 type_t *decl_type = entry->declaration.type;
7004 error = semantic_assign(decl_type, arg_expr);
7005 if (error == ASSIGN_ERROR_INCOMPATIBLE
7006 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7009 if (error == ASSIGN_SUCCESS) {
7010 best_type = decl_type;
7011 } else if (best_type == NULL) {
7012 best_type = decl_type;
7016 if (best_type != NULL) {
7017 expected_type = best_type;
7021 error = semantic_assign(expected_type, arg_expr);
7022 argument->expression = create_implicit_cast(arg_expr, expected_type);
7024 if (error != ASSIGN_SUCCESS) {
7025 /* report exact scope in error messages (like "in argument 3") */
7027 snprintf(buf, sizeof(buf), "call argument %u", pos);
7028 report_assign_error(error, expected_type, arg_expr, buf,
7029 &arg_expr->base.source_position);
7031 type_t *const promoted_type = get_default_promoted_type(arg_type);
7032 if (!types_compatible(expected_type_skip, promoted_type) &&
7033 !types_compatible(expected_type_skip, type_void_ptr) &&
7034 !types_compatible(type_void_ptr, promoted_type)) {
7035 /* Deliberately show the skipped types in this warning */
7036 source_position_t const *const apos = &arg_expr->base.source_position;
7037 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7043 * Handle the semantic restrictions of builtin calls
7045 static void handle_builtin_argument_restrictions(call_expression_t *call)
7047 entity_t *entity = call->function->reference.entity;
7048 switch (entity->function.btk) {
7050 switch (entity->function.b.firm_builtin_kind) {
7051 case ir_bk_return_address:
7052 case ir_bk_frame_address: {
7053 /* argument must be constant */
7054 call_argument_t *argument = call->arguments;
7056 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7057 errorf(&call->base.source_position,
7058 "argument of '%Y' must be a constant expression",
7059 call->function->reference.entity->base.symbol);
7063 case ir_bk_prefetch:
7064 /* second and third argument must be constant if existent */
7065 if (call->arguments == NULL)
7067 call_argument_t *rw = call->arguments->next;
7068 call_argument_t *locality = NULL;
7071 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7072 errorf(&call->base.source_position,
7073 "second argument of '%Y' must be a constant expression",
7074 call->function->reference.entity->base.symbol);
7076 locality = rw->next;
7078 if (locality != NULL) {
7079 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7080 errorf(&call->base.source_position,
7081 "third argument of '%Y' must be a constant expression",
7082 call->function->reference.entity->base.symbol);
7084 locality = rw->next;
7091 case BUILTIN_OBJECT_SIZE:
7092 if (call->arguments == NULL)
7095 call_argument_t *arg = call->arguments->next;
7096 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7097 errorf(&call->base.source_position,
7098 "second argument of '%Y' must be a constant expression",
7099 call->function->reference.entity->base.symbol);
7108 * Parse a call expression, ie. expression '( ... )'.
7110 * @param expression the function address
7112 static expression_t *parse_call_expression(expression_t *expression)
7114 expression_t *result = allocate_expression_zero(EXPR_CALL);
7115 call_expression_t *call = &result->call;
7116 call->function = expression;
7118 type_t *const orig_type = expression->base.type;
7119 type_t *const type = skip_typeref(orig_type);
7121 function_type_t *function_type = NULL;
7122 if (is_type_pointer(type)) {
7123 type_t *const to_type = skip_typeref(type->pointer.points_to);
7125 if (is_type_function(to_type)) {
7126 function_type = &to_type->function;
7127 call->base.type = function_type->return_type;
7131 if (function_type == NULL && is_type_valid(type)) {
7133 "called object '%E' (type '%T') is not a pointer to a function",
7134 expression, orig_type);
7137 /* parse arguments */
7139 add_anchor_token(')');
7140 add_anchor_token(',');
7142 if (token.kind != ')') {
7143 call_argument_t **anchor = &call->arguments;
7145 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7146 argument->expression = parse_assignment_expression();
7149 anchor = &argument->next;
7150 } while (next_if(','));
7152 rem_anchor_token(',');
7153 rem_anchor_token(')');
7156 if (function_type == NULL)
7159 /* check type and count of call arguments */
7160 function_parameter_t *parameter = function_type->parameters;
7161 call_argument_t *argument = call->arguments;
7162 if (!function_type->unspecified_parameters) {
7163 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7164 parameter = parameter->next, argument = argument->next) {
7165 check_call_argument(parameter->type, argument, ++pos);
7168 if (parameter != NULL) {
7169 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7170 } else if (argument != NULL && !function_type->variadic) {
7171 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7175 /* do default promotion for other arguments */
7176 for (; argument != NULL; argument = argument->next) {
7177 type_t *argument_type = argument->expression->base.type;
7178 if (!is_type_object(skip_typeref(argument_type))) {
7179 errorf(&argument->expression->base.source_position,
7180 "call argument '%E' must not be void", argument->expression);
7183 argument_type = get_default_promoted_type(argument_type);
7185 argument->expression
7186 = create_implicit_cast(argument->expression, argument_type);
7191 if (is_type_compound(skip_typeref(function_type->return_type))) {
7192 source_position_t const *const pos = &expression->base.source_position;
7193 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7196 if (expression->kind == EXPR_REFERENCE) {
7197 reference_expression_t *reference = &expression->reference;
7198 if (reference->entity->kind == ENTITY_FUNCTION &&
7199 reference->entity->function.btk != BUILTIN_NONE)
7200 handle_builtin_argument_restrictions(call);
7206 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7208 static bool same_compound_type(const type_t *type1, const type_t *type2)
7211 is_type_compound(type1) &&
7212 type1->kind == type2->kind &&
7213 type1->compound.compound == type2->compound.compound;
7216 static expression_t const *get_reference_address(expression_t const *expr)
7218 bool regular_take_address = true;
7220 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7221 expr = expr->unary.value;
7223 regular_take_address = false;
7226 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7229 expr = expr->unary.value;
7232 if (expr->kind != EXPR_REFERENCE)
7235 /* special case for functions which are automatically converted to a
7236 * pointer to function without an extra TAKE_ADDRESS operation */
7237 if (!regular_take_address &&
7238 expr->reference.entity->kind != ENTITY_FUNCTION) {
7245 static void warn_reference_address_as_bool(expression_t const* expr)
7247 expr = get_reference_address(expr);
7249 source_position_t const *const pos = &expr->base.source_position;
7250 entity_t const *const ent = expr->reference.entity;
7251 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7255 static void warn_assignment_in_condition(const expression_t *const expr)
7257 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7259 if (expr->base.parenthesized)
7261 source_position_t const *const pos = &expr->base.source_position;
7262 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7265 static void semantic_condition(expression_t const *const expr,
7266 char const *const context)
7268 type_t *const type = skip_typeref(expr->base.type);
7269 if (is_type_scalar(type)) {
7270 warn_reference_address_as_bool(expr);
7271 warn_assignment_in_condition(expr);
7272 } else if (is_type_valid(type)) {
7273 errorf(&expr->base.source_position,
7274 "%s must have scalar type", context);
7279 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7281 * @param expression the conditional expression
7283 static expression_t *parse_conditional_expression(expression_t *expression)
7285 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7287 conditional_expression_t *conditional = &result->conditional;
7288 conditional->condition = expression;
7291 add_anchor_token(':');
7293 /* §6.5.15:2 The first operand shall have scalar type. */
7294 semantic_condition(expression, "condition of conditional operator");
7296 expression_t *true_expression = expression;
7297 bool gnu_cond = false;
7298 if (GNU_MODE && token.kind == ':') {
7301 true_expression = parse_expression();
7303 rem_anchor_token(':');
7305 expression_t *false_expression =
7306 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7308 type_t *const orig_true_type = true_expression->base.type;
7309 type_t *const orig_false_type = false_expression->base.type;
7310 type_t *const true_type = skip_typeref(orig_true_type);
7311 type_t *const false_type = skip_typeref(orig_false_type);
7314 source_position_t const *const pos = &conditional->base.source_position;
7315 type_t *result_type;
7316 if (is_type_void(true_type) || is_type_void(false_type)) {
7317 /* ISO/IEC 14882:1998(E) §5.16:2 */
7318 if (true_expression->kind == EXPR_UNARY_THROW) {
7319 result_type = false_type;
7320 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7321 result_type = true_type;
7323 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7324 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7326 result_type = type_void;
7328 } else if (is_type_arithmetic(true_type)
7329 && is_type_arithmetic(false_type)) {
7330 result_type = semantic_arithmetic(true_type, false_type);
7331 } else if (same_compound_type(true_type, false_type)) {
7332 /* just take 1 of the 2 types */
7333 result_type = true_type;
7334 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7335 type_t *pointer_type;
7337 expression_t *other_expression;
7338 if (is_type_pointer(true_type) &&
7339 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7340 pointer_type = true_type;
7341 other_type = false_type;
7342 other_expression = false_expression;
7344 pointer_type = false_type;
7345 other_type = true_type;
7346 other_expression = true_expression;
7349 if (is_null_pointer_constant(other_expression)) {
7350 result_type = pointer_type;
7351 } else if (is_type_pointer(other_type)) {
7352 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7353 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7356 if (is_type_void(to1) || is_type_void(to2)) {
7358 } else if (types_compatible(get_unqualified_type(to1),
7359 get_unqualified_type(to2))) {
7362 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7366 type_t *const type =
7367 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7368 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7369 } else if (is_type_integer(other_type)) {
7370 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7371 result_type = pointer_type;
7373 goto types_incompatible;
7377 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7378 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7380 result_type = type_error_type;
7383 conditional->true_expression
7384 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7385 conditional->false_expression
7386 = create_implicit_cast(false_expression, result_type);
7387 conditional->base.type = result_type;
7392 * Parse an extension expression.
7394 static expression_t *parse_extension(void)
7397 expression_t *expression = parse_subexpression(PREC_UNARY);
7403 * Parse a __builtin_classify_type() expression.
7405 static expression_t *parse_builtin_classify_type(void)
7407 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7408 result->base.type = type_int;
7410 eat(T___builtin_classify_type);
7413 add_anchor_token(')');
7414 expression_t *expression = parse_expression();
7415 rem_anchor_token(')');
7417 result->classify_type.type_expression = expression;
7423 * Parse a delete expression
7424 * ISO/IEC 14882:1998(E) §5.3.5
7426 static expression_t *parse_delete(void)
7428 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7429 result->base.type = type_void;
7434 result->kind = EXPR_UNARY_DELETE_ARRAY;
7438 expression_t *const value = parse_subexpression(PREC_CAST);
7439 result->unary.value = value;
7441 type_t *const type = skip_typeref(value->base.type);
7442 if (!is_type_pointer(type)) {
7443 if (is_type_valid(type)) {
7444 errorf(&value->base.source_position,
7445 "operand of delete must have pointer type");
7447 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7448 source_position_t const *const pos = &value->base.source_position;
7449 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7456 * Parse a throw expression
7457 * ISO/IEC 14882:1998(E) §15:1
7459 static expression_t *parse_throw(void)
7461 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7462 result->base.type = type_void;
7466 expression_t *value = NULL;
7467 switch (token.kind) {
7469 value = parse_assignment_expression();
7470 /* ISO/IEC 14882:1998(E) §15.1:3 */
7471 type_t *const orig_type = value->base.type;
7472 type_t *const type = skip_typeref(orig_type);
7473 if (is_type_incomplete(type)) {
7474 errorf(&value->base.source_position,
7475 "cannot throw object of incomplete type '%T'", orig_type);
7476 } else if (is_type_pointer(type)) {
7477 type_t *const points_to = skip_typeref(type->pointer.points_to);
7478 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7479 errorf(&value->base.source_position,
7480 "cannot throw pointer to incomplete type '%T'", orig_type);
7488 result->unary.value = value;
7493 static bool check_pointer_arithmetic(const source_position_t *source_position,
7494 type_t *pointer_type,
7495 type_t *orig_pointer_type)
7497 type_t *points_to = pointer_type->pointer.points_to;
7498 points_to = skip_typeref(points_to);
7500 if (is_type_incomplete(points_to)) {
7501 if (!GNU_MODE || !is_type_void(points_to)) {
7502 errorf(source_position,
7503 "arithmetic with pointer to incomplete type '%T' not allowed",
7507 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7509 } else if (is_type_function(points_to)) {
7511 errorf(source_position,
7512 "arithmetic with pointer to function type '%T' not allowed",
7516 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7522 static bool is_lvalue(const expression_t *expression)
7524 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7525 switch (expression->kind) {
7526 case EXPR_ARRAY_ACCESS:
7527 case EXPR_COMPOUND_LITERAL:
7528 case EXPR_REFERENCE:
7530 case EXPR_UNARY_DEREFERENCE:
7534 type_t *type = skip_typeref(expression->base.type);
7536 /* ISO/IEC 14882:1998(E) §3.10:3 */
7537 is_type_reference(type) ||
7538 /* Claim it is an lvalue, if the type is invalid. There was a parse
7539 * error before, which maybe prevented properly recognizing it as
7541 !is_type_valid(type);
7546 static void semantic_incdec(unary_expression_t *expression)
7548 type_t *const orig_type = expression->value->base.type;
7549 type_t *const type = skip_typeref(orig_type);
7550 if (is_type_pointer(type)) {
7551 if (!check_pointer_arithmetic(&expression->base.source_position,
7555 } else if (!is_type_real(type) && is_type_valid(type)) {
7556 /* TODO: improve error message */
7557 errorf(&expression->base.source_position,
7558 "operation needs an arithmetic or pointer type");
7561 if (!is_lvalue(expression->value)) {
7562 /* TODO: improve error message */
7563 errorf(&expression->base.source_position, "lvalue required as operand");
7565 expression->base.type = orig_type;
7568 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7570 type_t *const res_type = promote_integer(type);
7571 expr->base.type = res_type;
7572 expr->value = create_implicit_cast(expr->value, res_type);
7575 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7577 type_t *const orig_type = expression->value->base.type;
7578 type_t *const type = skip_typeref(orig_type);
7579 if (!is_type_arithmetic(type)) {
7580 if (is_type_valid(type)) {
7581 /* TODO: improve error message */
7582 errorf(&expression->base.source_position,
7583 "operation needs an arithmetic type");
7586 } else if (is_type_integer(type)) {
7587 promote_unary_int_expr(expression, type);
7589 expression->base.type = orig_type;
7593 static void semantic_unexpr_plus(unary_expression_t *expression)
7595 semantic_unexpr_arithmetic(expression);
7596 source_position_t const *const pos = &expression->base.source_position;
7597 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7600 static void semantic_not(unary_expression_t *expression)
7602 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7603 semantic_condition(expression->value, "operand of !");
7604 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7607 static void semantic_unexpr_integer(unary_expression_t *expression)
7609 type_t *const orig_type = expression->value->base.type;
7610 type_t *const type = skip_typeref(orig_type);
7611 if (!is_type_integer(type)) {
7612 if (is_type_valid(type)) {
7613 errorf(&expression->base.source_position,
7614 "operand of ~ must be of integer type");
7619 promote_unary_int_expr(expression, type);
7622 static void semantic_dereference(unary_expression_t *expression)
7624 type_t *const orig_type = expression->value->base.type;
7625 type_t *const type = skip_typeref(orig_type);
7626 if (!is_type_pointer(type)) {
7627 if (is_type_valid(type)) {
7628 errorf(&expression->base.source_position,
7629 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7634 type_t *result_type = type->pointer.points_to;
7635 result_type = automatic_type_conversion(result_type);
7636 expression->base.type = result_type;
7640 * Record that an address is taken (expression represents an lvalue).
7642 * @param expression the expression
7643 * @param may_be_register if true, the expression might be an register
7645 static void set_address_taken(expression_t *expression, bool may_be_register)
7647 if (expression->kind != EXPR_REFERENCE)
7650 entity_t *const entity = expression->reference.entity;
7652 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7655 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7656 && !may_be_register) {
7657 source_position_t const *const pos = &expression->base.source_position;
7658 errorf(pos, "address of register '%N' requested", entity);
7661 if (entity->kind == ENTITY_VARIABLE) {
7662 entity->variable.address_taken = true;
7664 assert(entity->kind == ENTITY_PARAMETER);
7665 entity->parameter.address_taken = true;
7670 * Check the semantic of the address taken expression.
7672 static void semantic_take_addr(unary_expression_t *expression)
7674 expression_t *value = expression->value;
7675 value->base.type = revert_automatic_type_conversion(value);
7677 type_t *orig_type = value->base.type;
7678 type_t *type = skip_typeref(orig_type);
7679 if (!is_type_valid(type))
7683 if (!is_lvalue(value)) {
7684 errorf(&expression->base.source_position, "'&' requires an lvalue");
7686 if (is_bitfield(value)) {
7687 errorf(&expression->base.source_position,
7688 "'&' not allowed on bitfield");
7691 set_address_taken(value, false);
7693 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7696 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7697 static expression_t *parse_##unexpression_type(void) \
7699 expression_t *unary_expression \
7700 = allocate_expression_zero(unexpression_type); \
7702 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7704 sfunc(&unary_expression->unary); \
7706 return unary_expression; \
7709 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7710 semantic_unexpr_arithmetic)
7711 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7712 semantic_unexpr_plus)
7713 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7715 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7716 semantic_dereference)
7717 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7719 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7720 semantic_unexpr_integer)
7721 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7723 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7726 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7728 static expression_t *parse_##unexpression_type(expression_t *left) \
7730 expression_t *unary_expression \
7731 = allocate_expression_zero(unexpression_type); \
7733 unary_expression->unary.value = left; \
7735 sfunc(&unary_expression->unary); \
7737 return unary_expression; \
7740 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7741 EXPR_UNARY_POSTFIX_INCREMENT,
7743 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7744 EXPR_UNARY_POSTFIX_DECREMENT,
7747 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7749 /* TODO: handle complex + imaginary types */
7751 type_left = get_unqualified_type(type_left);
7752 type_right = get_unqualified_type(type_right);
7754 /* §6.3.1.8 Usual arithmetic conversions */
7755 if (type_left == type_long_double || type_right == type_long_double) {
7756 return type_long_double;
7757 } else if (type_left == type_double || type_right == type_double) {
7759 } else if (type_left == type_float || type_right == type_float) {
7763 type_left = promote_integer(type_left);
7764 type_right = promote_integer(type_right);
7766 if (type_left == type_right)
7769 bool const signed_left = is_type_signed(type_left);
7770 bool const signed_right = is_type_signed(type_right);
7771 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7772 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7774 if (signed_left == signed_right)
7775 return rank_left >= rank_right ? type_left : type_right;
7779 atomic_type_kind_t s_akind;
7780 atomic_type_kind_t u_akind;
7785 u_type = type_right;
7787 s_type = type_right;
7790 s_akind = get_akind(s_type);
7791 u_akind = get_akind(u_type);
7792 s_rank = get_akind_rank(s_akind);
7793 u_rank = get_akind_rank(u_akind);
7795 if (u_rank >= s_rank)
7798 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7802 case ATOMIC_TYPE_INT: return type_unsigned_int;
7803 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7804 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7806 default: panic("invalid atomic type");
7811 * Check the semantic restrictions for a binary expression.
7813 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7815 expression_t *const left = expression->left;
7816 expression_t *const right = expression->right;
7817 type_t *const orig_type_left = left->base.type;
7818 type_t *const orig_type_right = right->base.type;
7819 type_t *const type_left = skip_typeref(orig_type_left);
7820 type_t *const type_right = skip_typeref(orig_type_right);
7822 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7823 /* TODO: improve error message */
7824 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7825 errorf(&expression->base.source_position,
7826 "operation needs arithmetic types");
7831 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7832 expression->left = create_implicit_cast(left, arithmetic_type);
7833 expression->right = create_implicit_cast(right, arithmetic_type);
7834 expression->base.type = arithmetic_type;
7837 static void semantic_binexpr_integer(binary_expression_t *const expression)
7839 expression_t *const left = expression->left;
7840 expression_t *const right = expression->right;
7841 type_t *const orig_type_left = left->base.type;
7842 type_t *const orig_type_right = right->base.type;
7843 type_t *const type_left = skip_typeref(orig_type_left);
7844 type_t *const type_right = skip_typeref(orig_type_right);
7846 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7847 /* TODO: improve error message */
7848 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7849 errorf(&expression->base.source_position,
7850 "operation needs integer types");
7855 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7856 expression->left = create_implicit_cast(left, result_type);
7857 expression->right = create_implicit_cast(right, result_type);
7858 expression->base.type = result_type;
7861 static void warn_div_by_zero(binary_expression_t const *const expression)
7863 if (!is_type_integer(expression->base.type))
7866 expression_t const *const right = expression->right;
7867 /* The type of the right operand can be different for /= */
7868 if (is_type_integer(right->base.type) &&
7869 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7870 !fold_constant_to_bool(right)) {
7871 source_position_t const *const pos = &expression->base.source_position;
7872 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7877 * Check the semantic restrictions for a div/mod expression.
7879 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7881 semantic_binexpr_arithmetic(expression);
7882 warn_div_by_zero(expression);
7885 static void warn_addsub_in_shift(const expression_t *const expr)
7887 if (expr->base.parenthesized)
7891 switch (expr->kind) {
7892 case EXPR_BINARY_ADD: op = '+'; break;
7893 case EXPR_BINARY_SUB: op = '-'; break;
7897 source_position_t const *const pos = &expr->base.source_position;
7898 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7901 static bool semantic_shift(binary_expression_t *expression)
7903 expression_t *const left = expression->left;
7904 expression_t *const right = expression->right;
7905 type_t *const orig_type_left = left->base.type;
7906 type_t *const orig_type_right = right->base.type;
7907 type_t * type_left = skip_typeref(orig_type_left);
7908 type_t * type_right = skip_typeref(orig_type_right);
7910 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7911 /* TODO: improve error message */
7912 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7913 errorf(&expression->base.source_position,
7914 "operands of shift operation must have integer types");
7919 type_left = promote_integer(type_left);
7921 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7922 source_position_t const *const pos = &right->base.source_position;
7923 long const count = fold_constant_to_int(right);
7925 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7926 } else if ((unsigned long)count >=
7927 get_atomic_type_size(type_left->atomic.akind) * 8) {
7928 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7932 type_right = promote_integer(type_right);
7933 expression->right = create_implicit_cast(right, type_right);
7938 static void semantic_shift_op(binary_expression_t *expression)
7940 expression_t *const left = expression->left;
7941 expression_t *const right = expression->right;
7943 if (!semantic_shift(expression))
7946 warn_addsub_in_shift(left);
7947 warn_addsub_in_shift(right);
7949 type_t *const orig_type_left = left->base.type;
7950 type_t * type_left = skip_typeref(orig_type_left);
7952 type_left = promote_integer(type_left);
7953 expression->left = create_implicit_cast(left, type_left);
7954 expression->base.type = type_left;
7957 static void semantic_add(binary_expression_t *expression)
7959 expression_t *const left = expression->left;
7960 expression_t *const right = expression->right;
7961 type_t *const orig_type_left = left->base.type;
7962 type_t *const orig_type_right = right->base.type;
7963 type_t *const type_left = skip_typeref(orig_type_left);
7964 type_t *const type_right = skip_typeref(orig_type_right);
7967 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7968 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7969 expression->left = create_implicit_cast(left, arithmetic_type);
7970 expression->right = create_implicit_cast(right, arithmetic_type);
7971 expression->base.type = arithmetic_type;
7972 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7973 check_pointer_arithmetic(&expression->base.source_position,
7974 type_left, orig_type_left);
7975 expression->base.type = type_left;
7976 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7977 check_pointer_arithmetic(&expression->base.source_position,
7978 type_right, orig_type_right);
7979 expression->base.type = type_right;
7980 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7981 errorf(&expression->base.source_position,
7982 "invalid operands to binary + ('%T', '%T')",
7983 orig_type_left, orig_type_right);
7987 static void semantic_sub(binary_expression_t *expression)
7989 expression_t *const left = expression->left;
7990 expression_t *const right = expression->right;
7991 type_t *const orig_type_left = left->base.type;
7992 type_t *const orig_type_right = right->base.type;
7993 type_t *const type_left = skip_typeref(orig_type_left);
7994 type_t *const type_right = skip_typeref(orig_type_right);
7995 source_position_t const *const pos = &expression->base.source_position;
7998 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7999 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8000 expression->left = create_implicit_cast(left, arithmetic_type);
8001 expression->right = create_implicit_cast(right, arithmetic_type);
8002 expression->base.type = arithmetic_type;
8003 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8004 check_pointer_arithmetic(&expression->base.source_position,
8005 type_left, orig_type_left);
8006 expression->base.type = type_left;
8007 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8008 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8009 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8010 if (!types_compatible(unqual_left, unqual_right)) {
8012 "subtracting pointers to incompatible types '%T' and '%T'",
8013 orig_type_left, orig_type_right);
8014 } else if (!is_type_object(unqual_left)) {
8015 if (!is_type_void(unqual_left)) {
8016 errorf(pos, "subtracting pointers to non-object types '%T'",
8019 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8022 expression->base.type = type_ptrdiff_t;
8023 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8024 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8025 orig_type_left, orig_type_right);
8029 static void warn_string_literal_address(expression_t const* expr)
8031 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8032 expr = expr->unary.value;
8033 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8035 expr = expr->unary.value;
8038 if (expr->kind == EXPR_STRING_LITERAL
8039 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8040 source_position_t const *const pos = &expr->base.source_position;
8041 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8045 static bool maybe_negative(expression_t const *const expr)
8047 switch (is_constant_expression(expr)) {
8048 case EXPR_CLASS_ERROR: return false;
8049 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8050 default: return true;
8054 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8056 warn_string_literal_address(expr);
8058 expression_t const* const ref = get_reference_address(expr);
8059 if (ref != NULL && is_null_pointer_constant(other)) {
8060 entity_t const *const ent = ref->reference.entity;
8061 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8064 if (!expr->base.parenthesized) {
8065 switch (expr->base.kind) {
8066 case EXPR_BINARY_LESS:
8067 case EXPR_BINARY_GREATER:
8068 case EXPR_BINARY_LESSEQUAL:
8069 case EXPR_BINARY_GREATEREQUAL:
8070 case EXPR_BINARY_NOTEQUAL:
8071 case EXPR_BINARY_EQUAL:
8072 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8081 * Check the semantics of comparison expressions.
8083 * @param expression The expression to check.
8085 static void semantic_comparison(binary_expression_t *expression)
8087 source_position_t const *const pos = &expression->base.source_position;
8088 expression_t *const left = expression->left;
8089 expression_t *const right = expression->right;
8091 warn_comparison(pos, left, right);
8092 warn_comparison(pos, right, left);
8094 type_t *orig_type_left = left->base.type;
8095 type_t *orig_type_right = right->base.type;
8096 type_t *type_left = skip_typeref(orig_type_left);
8097 type_t *type_right = skip_typeref(orig_type_right);
8099 /* TODO non-arithmetic types */
8100 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8101 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8103 /* test for signed vs unsigned compares */
8104 if (is_type_integer(arithmetic_type)) {
8105 bool const signed_left = is_type_signed(type_left);
8106 bool const signed_right = is_type_signed(type_right);
8107 if (signed_left != signed_right) {
8108 /* FIXME long long needs better const folding magic */
8109 /* TODO check whether constant value can be represented by other type */
8110 if ((signed_left && maybe_negative(left)) ||
8111 (signed_right && maybe_negative(right))) {
8112 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8117 expression->left = create_implicit_cast(left, arithmetic_type);
8118 expression->right = create_implicit_cast(right, arithmetic_type);
8119 expression->base.type = arithmetic_type;
8120 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8121 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8122 is_type_float(arithmetic_type)) {
8123 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8125 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8126 /* TODO check compatibility */
8127 } else if (is_type_pointer(type_left)) {
8128 expression->right = create_implicit_cast(right, type_left);
8129 } else if (is_type_pointer(type_right)) {
8130 expression->left = create_implicit_cast(left, type_right);
8131 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8132 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8134 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8138 * Checks if a compound type has constant fields.
8140 static bool has_const_fields(const compound_type_t *type)
8142 compound_t *compound = type->compound;
8143 entity_t *entry = compound->members.entities;
8145 for (; entry != NULL; entry = entry->base.next) {
8146 if (!is_declaration(entry))
8149 const type_t *decl_type = skip_typeref(entry->declaration.type);
8150 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8157 static bool is_valid_assignment_lhs(expression_t const* const left)
8159 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8160 type_t *const type_left = skip_typeref(orig_type_left);
8162 if (!is_lvalue(left)) {
8163 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8168 if (left->kind == EXPR_REFERENCE
8169 && left->reference.entity->kind == ENTITY_FUNCTION) {
8170 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8174 if (is_type_array(type_left)) {
8175 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8178 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8179 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8183 if (is_type_incomplete(type_left)) {
8184 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8185 left, orig_type_left);
8188 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8189 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8190 left, orig_type_left);
8197 static void semantic_arithmetic_assign(binary_expression_t *expression)
8199 expression_t *left = expression->left;
8200 expression_t *right = expression->right;
8201 type_t *orig_type_left = left->base.type;
8202 type_t *orig_type_right = right->base.type;
8204 if (!is_valid_assignment_lhs(left))
8207 type_t *type_left = skip_typeref(orig_type_left);
8208 type_t *type_right = skip_typeref(orig_type_right);
8210 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8211 /* TODO: improve error message */
8212 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8213 errorf(&expression->base.source_position,
8214 "operation needs arithmetic types");
8219 /* combined instructions are tricky. We can't create an implicit cast on
8220 * the left side, because we need the uncasted form for the store.
8221 * The ast2firm pass has to know that left_type must be right_type
8222 * for the arithmetic operation and create a cast by itself */
8223 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8224 expression->right = create_implicit_cast(right, arithmetic_type);
8225 expression->base.type = type_left;
8228 static void semantic_divmod_assign(binary_expression_t *expression)
8230 semantic_arithmetic_assign(expression);
8231 warn_div_by_zero(expression);
8234 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8236 expression_t *const left = expression->left;
8237 expression_t *const right = expression->right;
8238 type_t *const orig_type_left = left->base.type;
8239 type_t *const orig_type_right = right->base.type;
8240 type_t *const type_left = skip_typeref(orig_type_left);
8241 type_t *const type_right = skip_typeref(orig_type_right);
8243 if (!is_valid_assignment_lhs(left))
8246 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
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 *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8252 expression->right = create_implicit_cast(right, arithmetic_type);
8253 expression->base.type = type_left;
8254 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8255 check_pointer_arithmetic(&expression->base.source_position,
8256 type_left, orig_type_left);
8257 expression->base.type = type_left;
8258 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8259 errorf(&expression->base.source_position,
8260 "incompatible types '%T' and '%T' in assignment",
8261 orig_type_left, orig_type_right);
8265 static void semantic_integer_assign(binary_expression_t *expression)
8267 expression_t *left = expression->left;
8268 expression_t *right = expression->right;
8269 type_t *orig_type_left = left->base.type;
8270 type_t *orig_type_right = right->base.type;
8272 if (!is_valid_assignment_lhs(left))
8275 type_t *type_left = skip_typeref(orig_type_left);
8276 type_t *type_right = skip_typeref(orig_type_right);
8278 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8279 /* TODO: improve error message */
8280 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8281 errorf(&expression->base.source_position,
8282 "operation needs integer types");
8287 /* combined instructions are tricky. We can't create an implicit cast on
8288 * the left side, because we need the uncasted form for the store.
8289 * The ast2firm pass has to know that left_type must be right_type
8290 * for the arithmetic operation and create a cast by itself */
8291 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8292 expression->right = create_implicit_cast(right, arithmetic_type);
8293 expression->base.type = type_left;
8296 static void semantic_shift_assign(binary_expression_t *expression)
8298 expression_t *left = expression->left;
8300 if (!is_valid_assignment_lhs(left))
8303 if (!semantic_shift(expression))
8306 expression->base.type = skip_typeref(left->base.type);
8309 static void warn_logical_and_within_or(const expression_t *const expr)
8311 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8313 if (expr->base.parenthesized)
8315 source_position_t const *const pos = &expr->base.source_position;
8316 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8320 * Check the semantic restrictions of a logical expression.
8322 static void semantic_logical_op(binary_expression_t *expression)
8324 /* §6.5.13:2 Each of the operands shall have scalar type.
8325 * §6.5.14:2 Each of the operands shall have scalar type. */
8326 semantic_condition(expression->left, "left operand of logical operator");
8327 semantic_condition(expression->right, "right operand of logical operator");
8328 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8329 warn_logical_and_within_or(expression->left);
8330 warn_logical_and_within_or(expression->right);
8332 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8336 * Check the semantic restrictions of a binary assign expression.
8338 static void semantic_binexpr_assign(binary_expression_t *expression)
8340 expression_t *left = expression->left;
8341 type_t *orig_type_left = left->base.type;
8343 if (!is_valid_assignment_lhs(left))
8346 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8347 report_assign_error(error, orig_type_left, expression->right,
8348 "assignment", &left->base.source_position);
8349 expression->right = create_implicit_cast(expression->right, orig_type_left);
8350 expression->base.type = orig_type_left;
8354 * Determine if the outermost operation (or parts thereof) of the given
8355 * expression has no effect in order to generate a warning about this fact.
8356 * Therefore in some cases this only examines some of the operands of the
8357 * expression (see comments in the function and examples below).
8359 * f() + 23; // warning, because + has no effect
8360 * x || f(); // no warning, because x controls execution of f()
8361 * x ? y : f(); // warning, because y has no effect
8362 * (void)x; // no warning to be able to suppress the warning
8363 * This function can NOT be used for an "expression has definitely no effect"-
8365 static bool expression_has_effect(const expression_t *const expr)
8367 switch (expr->kind) {
8368 case EXPR_ERROR: return true; /* do NOT warn */
8369 case EXPR_REFERENCE: return false;
8370 case EXPR_ENUM_CONSTANT: return false;
8371 case EXPR_LABEL_ADDRESS: return false;
8373 /* suppress the warning for microsoft __noop operations */
8374 case EXPR_LITERAL_MS_NOOP: return true;
8375 case EXPR_LITERAL_BOOLEAN:
8376 case EXPR_LITERAL_CHARACTER:
8377 case EXPR_LITERAL_WIDE_CHARACTER:
8378 case EXPR_LITERAL_INTEGER:
8379 case EXPR_LITERAL_FLOATINGPOINT:
8380 case EXPR_STRING_LITERAL: return false;
8381 case EXPR_WIDE_STRING_LITERAL: return false;
8384 const call_expression_t *const call = &expr->call;
8385 if (call->function->kind != EXPR_REFERENCE)
8388 switch (call->function->reference.entity->function.btk) {
8389 /* FIXME: which builtins have no effect? */
8390 default: return true;
8394 /* Generate the warning if either the left or right hand side of a
8395 * conditional expression has no effect */
8396 case EXPR_CONDITIONAL: {
8397 conditional_expression_t const *const cond = &expr->conditional;
8398 expression_t const *const t = cond->true_expression;
8400 (t == NULL || expression_has_effect(t)) &&
8401 expression_has_effect(cond->false_expression);
8404 case EXPR_SELECT: return false;
8405 case EXPR_ARRAY_ACCESS: return false;
8406 case EXPR_SIZEOF: return false;
8407 case EXPR_CLASSIFY_TYPE: return false;
8408 case EXPR_ALIGNOF: return false;
8410 case EXPR_FUNCNAME: return false;
8411 case EXPR_BUILTIN_CONSTANT_P: return false;
8412 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8413 case EXPR_OFFSETOF: return false;
8414 case EXPR_VA_START: return true;
8415 case EXPR_VA_ARG: return true;
8416 case EXPR_VA_COPY: return true;
8417 case EXPR_STATEMENT: return true; // TODO
8418 case EXPR_COMPOUND_LITERAL: return false;
8420 case EXPR_UNARY_NEGATE: return false;
8421 case EXPR_UNARY_PLUS: return false;
8422 case EXPR_UNARY_BITWISE_NEGATE: return false;
8423 case EXPR_UNARY_NOT: return false;
8424 case EXPR_UNARY_DEREFERENCE: return false;
8425 case EXPR_UNARY_TAKE_ADDRESS: return false;
8426 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8427 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8428 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8429 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8431 /* Treat void casts as if they have an effect in order to being able to
8432 * suppress the warning */
8433 case EXPR_UNARY_CAST: {
8434 type_t *const type = skip_typeref(expr->base.type);
8435 return is_type_void(type);
8438 case EXPR_UNARY_ASSUME: return true;
8439 case EXPR_UNARY_DELETE: return true;
8440 case EXPR_UNARY_DELETE_ARRAY: return true;
8441 case EXPR_UNARY_THROW: return true;
8443 case EXPR_BINARY_ADD: return false;
8444 case EXPR_BINARY_SUB: return false;
8445 case EXPR_BINARY_MUL: return false;
8446 case EXPR_BINARY_DIV: return false;
8447 case EXPR_BINARY_MOD: return false;
8448 case EXPR_BINARY_EQUAL: return false;
8449 case EXPR_BINARY_NOTEQUAL: return false;
8450 case EXPR_BINARY_LESS: return false;
8451 case EXPR_BINARY_LESSEQUAL: return false;
8452 case EXPR_BINARY_GREATER: return false;
8453 case EXPR_BINARY_GREATEREQUAL: return false;
8454 case EXPR_BINARY_BITWISE_AND: return false;
8455 case EXPR_BINARY_BITWISE_OR: return false;
8456 case EXPR_BINARY_BITWISE_XOR: return false;
8457 case EXPR_BINARY_SHIFTLEFT: return false;
8458 case EXPR_BINARY_SHIFTRIGHT: return false;
8459 case EXPR_BINARY_ASSIGN: return true;
8460 case EXPR_BINARY_MUL_ASSIGN: return true;
8461 case EXPR_BINARY_DIV_ASSIGN: return true;
8462 case EXPR_BINARY_MOD_ASSIGN: return true;
8463 case EXPR_BINARY_ADD_ASSIGN: return true;
8464 case EXPR_BINARY_SUB_ASSIGN: return true;
8465 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8466 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8467 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8468 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8469 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8471 /* Only examine the right hand side of && and ||, because the left hand
8472 * side already has the effect of controlling the execution of the right
8474 case EXPR_BINARY_LOGICAL_AND:
8475 case EXPR_BINARY_LOGICAL_OR:
8476 /* Only examine the right hand side of a comma expression, because the left
8477 * hand side has a separate warning */
8478 case EXPR_BINARY_COMMA:
8479 return expression_has_effect(expr->binary.right);
8481 case EXPR_BINARY_ISGREATER: return false;
8482 case EXPR_BINARY_ISGREATEREQUAL: return false;
8483 case EXPR_BINARY_ISLESS: return false;
8484 case EXPR_BINARY_ISLESSEQUAL: return false;
8485 case EXPR_BINARY_ISLESSGREATER: return false;
8486 case EXPR_BINARY_ISUNORDERED: return false;
8489 internal_errorf(HERE, "unexpected expression");
8492 static void semantic_comma(binary_expression_t *expression)
8494 const expression_t *const left = expression->left;
8495 if (!expression_has_effect(left)) {
8496 source_position_t const *const pos = &left->base.source_position;
8497 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8499 expression->base.type = expression->right->base.type;
8503 * @param prec_r precedence of the right operand
8505 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8506 static expression_t *parse_##binexpression_type(expression_t *left) \
8508 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8509 binexpr->binary.left = left; \
8512 expression_t *right = parse_subexpression(prec_r); \
8514 binexpr->binary.right = right; \
8515 sfunc(&binexpr->binary); \
8520 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8521 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8522 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8523 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8524 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8525 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8526 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8527 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8528 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8529 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8530 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8531 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8532 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8533 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8534 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8535 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8536 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8537 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8538 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8539 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8540 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8541 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8542 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8543 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8544 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8545 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8546 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8547 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8548 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8549 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8552 static expression_t *parse_subexpression(precedence_t precedence)
8554 expression_parser_function_t *parser
8555 = &expression_parsers[token.kind];
8558 if (parser->parser != NULL) {
8559 left = parser->parser();
8561 left = parse_primary_expression();
8563 assert(left != NULL);
8566 parser = &expression_parsers[token.kind];
8567 if (parser->infix_parser == NULL)
8569 if (parser->infix_precedence < precedence)
8572 left = parser->infix_parser(left);
8574 assert(left != NULL);
8581 * Parse an expression.
8583 static expression_t *parse_expression(void)
8585 return parse_subexpression(PREC_EXPRESSION);
8589 * Register a parser for a prefix-like operator.
8591 * @param parser the parser function
8592 * @param token_kind the token type of the prefix token
8594 static void register_expression_parser(parse_expression_function parser,
8597 expression_parser_function_t *entry = &expression_parsers[token_kind];
8599 if (entry->parser != NULL) {
8600 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8601 panic("trying to register multiple expression parsers for a token");
8603 entry->parser = parser;
8607 * Register a parser for an infix operator with given precedence.
8609 * @param parser the parser function
8610 * @param token_kind the token type of the infix operator
8611 * @param precedence the precedence of the operator
8613 static void register_infix_parser(parse_expression_infix_function parser,
8614 int token_kind, precedence_t precedence)
8616 expression_parser_function_t *entry = &expression_parsers[token_kind];
8618 if (entry->infix_parser != NULL) {
8619 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8620 panic("trying to register multiple infix expression parsers for a "
8623 entry->infix_parser = parser;
8624 entry->infix_precedence = precedence;
8628 * Initialize the expression parsers.
8630 static void init_expression_parsers(void)
8632 memset(&expression_parsers, 0, sizeof(expression_parsers));
8634 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8635 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8636 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8637 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8638 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8639 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8640 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8641 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8642 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8643 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8644 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8645 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8646 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8647 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8648 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8649 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8650 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8651 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8652 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8653 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8654 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8655 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8656 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8657 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8658 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8659 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8660 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8661 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8662 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8663 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8664 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8665 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8666 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8667 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8668 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8669 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8670 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8672 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8673 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8674 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8675 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8676 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8677 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8678 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8679 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8680 register_expression_parser(parse_sizeof, T_sizeof);
8681 register_expression_parser(parse_alignof, T___alignof__);
8682 register_expression_parser(parse_extension, T___extension__);
8683 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8684 register_expression_parser(parse_delete, T_delete);
8685 register_expression_parser(parse_throw, T_throw);
8689 * Parse a asm statement arguments specification.
8691 static asm_argument_t *parse_asm_arguments(bool is_out)
8693 asm_argument_t *result = NULL;
8694 asm_argument_t **anchor = &result;
8696 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8697 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8700 add_anchor_token(']');
8701 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8702 rem_anchor_token(']');
8704 if (!argument->symbol)
8708 argument->constraints = parse_string_literals();
8710 add_anchor_token(')');
8711 expression_t *expression = parse_expression();
8712 rem_anchor_token(')');
8714 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8715 * change size or type representation (e.g. int -> long is ok, but
8716 * int -> float is not) */
8717 if (expression->kind == EXPR_UNARY_CAST) {
8718 type_t *const type = expression->base.type;
8719 type_kind_t const kind = type->kind;
8720 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8723 if (kind == TYPE_ATOMIC) {
8724 atomic_type_kind_t const akind = type->atomic.akind;
8725 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8726 size = get_atomic_type_size(akind);
8728 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8729 size = get_type_size(type_void_ptr);
8733 expression_t *const value = expression->unary.value;
8734 type_t *const value_type = value->base.type;
8735 type_kind_t const value_kind = value_type->kind;
8737 unsigned value_flags;
8738 unsigned value_size;
8739 if (value_kind == TYPE_ATOMIC) {
8740 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8741 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8742 value_size = get_atomic_type_size(value_akind);
8743 } else if (value_kind == TYPE_POINTER) {
8744 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8745 value_size = get_type_size(type_void_ptr);
8750 if (value_flags != flags || value_size != size)
8754 } while (expression->kind == EXPR_UNARY_CAST);
8758 if (!is_lvalue(expression)) {
8759 errorf(&expression->base.source_position,
8760 "asm output argument is not an lvalue");
8763 if (argument->constraints.begin[0] == '=')
8764 determine_lhs_ent(expression, NULL);
8766 mark_vars_read(expression, NULL);
8768 mark_vars_read(expression, NULL);
8770 argument->expression = expression;
8773 set_address_taken(expression, true);
8776 anchor = &argument->next;
8786 * Parse a asm statement clobber specification.
8788 static asm_clobber_t *parse_asm_clobbers(void)
8790 asm_clobber_t *result = NULL;
8791 asm_clobber_t **anchor = &result;
8793 while (token.kind == T_STRING_LITERAL) {
8794 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8795 clobber->clobber = parse_string_literals();
8798 anchor = &clobber->next;
8808 * Parse an asm statement.
8810 static statement_t *parse_asm_statement(void)
8812 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8813 asm_statement_t *asm_statement = &statement->asms;
8817 if (next_if(T_volatile))
8818 asm_statement->is_volatile = true;
8821 add_anchor_token(')');
8822 if (token.kind != T_STRING_LITERAL) {
8823 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8826 asm_statement->asm_text = parse_string_literals();
8828 add_anchor_token(':');
8829 if (!next_if(':')) {
8830 rem_anchor_token(':');
8834 asm_statement->outputs = parse_asm_arguments(true);
8835 if (!next_if(':')) {
8836 rem_anchor_token(':');
8840 asm_statement->inputs = parse_asm_arguments(false);
8841 if (!next_if(':')) {
8842 rem_anchor_token(':');
8845 rem_anchor_token(':');
8847 asm_statement->clobbers = parse_asm_clobbers();
8850 rem_anchor_token(')');
8854 if (asm_statement->outputs == NULL) {
8855 /* GCC: An 'asm' instruction without any output operands will be treated
8856 * identically to a volatile 'asm' instruction. */
8857 asm_statement->is_volatile = true;
8863 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8865 statement_t *inner_stmt;
8866 switch (token.kind) {
8868 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8869 inner_stmt = create_error_statement();
8873 if (label->kind == STATEMENT_LABEL) {
8874 /* Eat an empty statement here, to avoid the warning about an empty
8875 * statement after a label. label:; is commonly used to have a label
8876 * before a closing brace. */
8877 inner_stmt = create_empty_statement();
8884 inner_stmt = parse_statement();
8885 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8886 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8887 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8888 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8896 * Parse a case statement.
8898 static statement_t *parse_case_statement(void)
8900 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8901 source_position_t *const pos = &statement->base.source_position;
8904 add_anchor_token(':');
8906 expression_t *expression = parse_expression();
8907 type_t *expression_type = expression->base.type;
8908 type_t *skipped = skip_typeref(expression_type);
8909 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8910 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8911 expression, expression_type);
8914 type_t *type = expression_type;
8915 if (current_switch != NULL) {
8916 type_t *switch_type = current_switch->expression->base.type;
8917 if (is_type_valid(switch_type)) {
8918 expression = create_implicit_cast(expression, switch_type);
8922 statement->case_label.expression = expression;
8923 expression_classification_t const expr_class = is_constant_expression(expression);
8924 if (expr_class != EXPR_CLASS_CONSTANT) {
8925 if (expr_class != EXPR_CLASS_ERROR) {
8926 errorf(pos, "case label does not reduce to an integer constant");
8928 statement->case_label.is_bad = true;
8930 long const val = fold_constant_to_int(expression);
8931 statement->case_label.first_case = val;
8932 statement->case_label.last_case = val;
8936 if (next_if(T_DOTDOTDOT)) {
8937 expression_t *end_range = parse_expression();
8938 expression_type = expression->base.type;
8939 skipped = skip_typeref(expression_type);
8940 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8941 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8942 expression, expression_type);
8945 end_range = create_implicit_cast(end_range, type);
8946 statement->case_label.end_range = end_range;
8947 expression_classification_t const end_class = is_constant_expression(end_range);
8948 if (end_class != EXPR_CLASS_CONSTANT) {
8949 if (end_class != EXPR_CLASS_ERROR) {
8950 errorf(pos, "case range does not reduce to an integer constant");
8952 statement->case_label.is_bad = true;
8954 long const val = fold_constant_to_int(end_range);
8955 statement->case_label.last_case = val;
8957 if (val < statement->case_label.first_case) {
8958 statement->case_label.is_empty_range = true;
8959 warningf(WARN_OTHER, pos, "empty range specified");
8965 PUSH_PARENT(statement);
8967 rem_anchor_token(':');
8970 if (current_switch != NULL) {
8971 if (! statement->case_label.is_bad) {
8972 /* Check for duplicate case values */
8973 case_label_statement_t *c = &statement->case_label;
8974 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8975 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8978 if (c->last_case < l->first_case || c->first_case > l->last_case)
8981 errorf(pos, "duplicate case value (previously used %P)",
8982 &l->base.source_position);
8986 /* link all cases into the switch statement */
8987 if (current_switch->last_case == NULL) {
8988 current_switch->first_case = &statement->case_label;
8990 current_switch->last_case->next = &statement->case_label;
8992 current_switch->last_case = &statement->case_label;
8994 errorf(pos, "case label not within a switch statement");
8997 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9004 * Parse a default statement.
9006 static statement_t *parse_default_statement(void)
9008 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9012 PUSH_PARENT(statement);
9016 if (current_switch != NULL) {
9017 const case_label_statement_t *def_label = current_switch->default_label;
9018 if (def_label != NULL) {
9019 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9021 current_switch->default_label = &statement->case_label;
9023 /* link all cases into the switch statement */
9024 if (current_switch->last_case == NULL) {
9025 current_switch->first_case = &statement->case_label;
9027 current_switch->last_case->next = &statement->case_label;
9029 current_switch->last_case = &statement->case_label;
9032 errorf(&statement->base.source_position,
9033 "'default' label not within a switch statement");
9036 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9043 * Parse a label statement.
9045 static statement_t *parse_label_statement(void)
9047 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9048 label_t *const label = get_label();
9049 statement->label.label = label;
9051 PUSH_PARENT(statement);
9053 /* if statement is already set then the label is defined twice,
9054 * otherwise it was just mentioned in a goto/local label declaration so far
9056 source_position_t const* const pos = &statement->base.source_position;
9057 if (label->statement != NULL) {
9058 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9060 label->base.source_position = *pos;
9061 label->statement = statement;
9066 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9067 parse_attributes(NULL); // TODO process attributes
9070 statement->label.statement = parse_label_inner_statement(statement, "label");
9072 /* remember the labels in a list for later checking */
9073 *label_anchor = &statement->label;
9074 label_anchor = &statement->label.next;
9080 static statement_t *parse_inner_statement(void)
9082 statement_t *const stmt = parse_statement();
9083 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9084 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9085 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9086 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9092 * Parse an expression in parentheses and mark its variables as read.
9094 static expression_t *parse_condition(void)
9097 add_anchor_token(')');
9098 expression_t *const expr = parse_expression();
9099 mark_vars_read(expr, NULL);
9100 rem_anchor_token(')');
9106 * Parse an if statement.
9108 static statement_t *parse_if(void)
9110 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9114 PUSH_PARENT(statement);
9115 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9117 add_anchor_token(T_else);
9119 expression_t *const expr = parse_condition();
9120 statement->ifs.condition = expr;
9121 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9123 semantic_condition(expr, "condition of 'if'-statment");
9125 statement_t *const true_stmt = parse_inner_statement();
9126 statement->ifs.true_statement = true_stmt;
9127 rem_anchor_token(T_else);
9129 if (true_stmt->kind == STATEMENT_EMPTY) {
9130 warningf(WARN_EMPTY_BODY, HERE,
9131 "suggest braces around empty body in an ‘if’ statement");
9134 if (next_if(T_else)) {
9135 statement->ifs.false_statement = parse_inner_statement();
9137 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9138 warningf(WARN_EMPTY_BODY, HERE,
9139 "suggest braces around empty body in an ‘if’ statement");
9141 } else if (true_stmt->kind == STATEMENT_IF &&
9142 true_stmt->ifs.false_statement != NULL) {
9143 source_position_t const *const pos = &true_stmt->base.source_position;
9144 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9153 * Check that all enums are handled in a switch.
9155 * @param statement the switch statement to check
9157 static void check_enum_cases(const switch_statement_t *statement)
9159 if (!is_warn_on(WARN_SWITCH_ENUM))
9161 const type_t *type = skip_typeref(statement->expression->base.type);
9162 if (! is_type_enum(type))
9164 const enum_type_t *enumt = &type->enumt;
9166 /* if we have a default, no warnings */
9167 if (statement->default_label != NULL)
9170 /* FIXME: calculation of value should be done while parsing */
9171 /* TODO: quadratic algorithm here. Change to an n log n one */
9172 long last_value = -1;
9173 const entity_t *entry = enumt->enume->base.next;
9174 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9175 entry = entry->base.next) {
9176 const expression_t *expression = entry->enum_value.value;
9177 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9179 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9180 if (l->expression == NULL)
9182 if (l->first_case <= value && value <= l->last_case) {
9188 source_position_t const *const pos = &statement->base.source_position;
9189 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9196 * Parse a switch statement.
9198 static statement_t *parse_switch(void)
9200 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9204 PUSH_PARENT(statement);
9205 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9207 expression_t *const expr = parse_condition();
9208 type_t * type = skip_typeref(expr->base.type);
9209 if (is_type_integer(type)) {
9210 type = promote_integer(type);
9211 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9212 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9214 } else if (is_type_valid(type)) {
9215 errorf(&expr->base.source_position,
9216 "switch quantity is not an integer, but '%T'", type);
9217 type = type_error_type;
9219 statement->switchs.expression = create_implicit_cast(expr, type);
9221 switch_statement_t *rem = current_switch;
9222 current_switch = &statement->switchs;
9223 statement->switchs.body = parse_inner_statement();
9224 current_switch = rem;
9226 if (statement->switchs.default_label == NULL) {
9227 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9229 check_enum_cases(&statement->switchs);
9236 static statement_t *parse_loop_body(statement_t *const loop)
9238 statement_t *const rem = current_loop;
9239 current_loop = loop;
9241 statement_t *const body = parse_inner_statement();
9248 * Parse a while statement.
9250 static statement_t *parse_while(void)
9252 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9256 PUSH_PARENT(statement);
9257 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9259 expression_t *const cond = parse_condition();
9260 statement->whiles.condition = cond;
9261 /* §6.8.5:2 The controlling expression of an iteration statement shall
9262 * have scalar type. */
9263 semantic_condition(cond, "condition of 'while'-statement");
9265 statement->whiles.body = parse_loop_body(statement);
9273 * Parse a do statement.
9275 static statement_t *parse_do(void)
9277 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9281 PUSH_PARENT(statement);
9282 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9284 add_anchor_token(T_while);
9285 statement->do_while.body = parse_loop_body(statement);
9286 rem_anchor_token(T_while);
9289 expression_t *const cond = parse_condition();
9290 statement->do_while.condition = cond;
9291 /* §6.8.5:2 The controlling expression of an iteration statement shall
9292 * have scalar type. */
9293 semantic_condition(cond, "condition of 'do-while'-statement");
9302 * Parse a for statement.
9304 static statement_t *parse_for(void)
9306 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9310 PUSH_PARENT(statement);
9311 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9314 add_anchor_token(')');
9319 } else if (is_declaration_specifier(&token)) {
9320 parse_declaration(record_entity, DECL_FLAGS_NONE);
9322 add_anchor_token(';');
9323 expression_t *const init = parse_expression();
9324 statement->fors.initialisation = init;
9325 mark_vars_read(init, ENT_ANY);
9326 if (!expression_has_effect(init)) {
9327 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9329 rem_anchor_token(';');
9335 if (token.kind != ';') {
9336 add_anchor_token(';');
9337 expression_t *const cond = parse_expression();
9338 statement->fors.condition = cond;
9339 /* §6.8.5:2 The controlling expression of an iteration statement
9340 * shall have scalar type. */
9341 semantic_condition(cond, "condition of 'for'-statement");
9342 mark_vars_read(cond, NULL);
9343 rem_anchor_token(';');
9346 if (token.kind != ')') {
9347 expression_t *const step = parse_expression();
9348 statement->fors.step = step;
9349 mark_vars_read(step, ENT_ANY);
9350 if (!expression_has_effect(step)) {
9351 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9354 rem_anchor_token(')');
9356 statement->fors.body = parse_loop_body(statement);
9364 * Parse a goto statement.
9366 static statement_t *parse_goto(void)
9368 statement_t *statement;
9369 if (GNU_MODE && look_ahead(1)->kind == '*') {
9370 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9374 expression_t *expression = parse_expression();
9375 mark_vars_read(expression, NULL);
9377 /* Argh: although documentation says the expression must be of type void*,
9378 * gcc accepts anything that can be casted into void* without error */
9379 type_t *type = expression->base.type;
9381 if (type != type_error_type) {
9382 if (!is_type_pointer(type) && !is_type_integer(type)) {
9383 errorf(&expression->base.source_position,
9384 "cannot convert to a pointer type");
9385 } else if (type != type_void_ptr) {
9386 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9388 expression = create_implicit_cast(expression, type_void_ptr);
9391 statement->computed_goto.expression = expression;
9393 statement = allocate_statement_zero(STATEMENT_GOTO);
9395 if (token.kind == T_IDENTIFIER) {
9396 label_t *const label = get_label();
9398 statement->gotos.label = label;
9400 /* remember the goto's in a list for later checking */
9401 *goto_anchor = &statement->gotos;
9402 goto_anchor = &statement->gotos.next;
9405 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9407 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9409 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9418 * Parse a continue statement.
9420 static statement_t *parse_continue(void)
9422 if (current_loop == NULL) {
9423 errorf(HERE, "continue statement not within loop");
9426 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9434 * Parse a break statement.
9436 static statement_t *parse_break(void)
9438 if (current_switch == NULL && current_loop == NULL) {
9439 errorf(HERE, "break statement not within loop or switch");
9442 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9450 * Parse a __leave statement.
9452 static statement_t *parse_leave_statement(void)
9454 if (current_try == NULL) {
9455 errorf(HERE, "__leave statement not within __try");
9458 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9466 * Check if a given entity represents a local variable.
9468 static bool is_local_variable(const entity_t *entity)
9470 if (entity->kind != ENTITY_VARIABLE)
9473 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9474 case STORAGE_CLASS_AUTO:
9475 case STORAGE_CLASS_REGISTER: {
9476 const type_t *type = skip_typeref(entity->declaration.type);
9477 if (is_type_function(type)) {
9489 * Check if a given expression represents a local variable.
9491 static bool expression_is_local_variable(const expression_t *expression)
9493 if (expression->base.kind != EXPR_REFERENCE) {
9496 const entity_t *entity = expression->reference.entity;
9497 return is_local_variable(entity);
9501 * Check if a given expression represents a local variable and
9502 * return its declaration then, else return NULL.
9504 entity_t *expression_is_variable(const expression_t *expression)
9506 if (expression->base.kind != EXPR_REFERENCE) {
9509 entity_t *entity = expression->reference.entity;
9510 if (entity->kind != ENTITY_VARIABLE)
9516 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9518 if (c_mode & _CXX || strict_mode) {
9521 warningf(WARN_OTHER, pos, msg);
9526 * Parse a return statement.
9528 static statement_t *parse_return(void)
9530 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9533 expression_t *return_value = NULL;
9534 if (token.kind != ';') {
9535 return_value = parse_expression();
9536 mark_vars_read(return_value, NULL);
9539 const type_t *const func_type = skip_typeref(current_function->base.type);
9540 assert(is_type_function(func_type));
9541 type_t *const return_type = skip_typeref(func_type->function.return_type);
9543 source_position_t const *const pos = &statement->base.source_position;
9544 if (return_value != NULL) {
9545 type_t *return_value_type = skip_typeref(return_value->base.type);
9547 if (is_type_void(return_type)) {
9548 if (!is_type_void(return_value_type)) {
9549 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9550 /* Only warn in C mode, because GCC does the same */
9551 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9552 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9553 /* Only warn in C mode, because GCC does the same */
9554 err_or_warn(pos, "'return' with expression in function returning 'void'");
9557 assign_error_t error = semantic_assign(return_type, return_value);
9558 report_assign_error(error, return_type, return_value, "'return'",
9561 return_value = create_implicit_cast(return_value, return_type);
9562 /* check for returning address of a local var */
9563 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9564 const expression_t *expression = return_value->unary.value;
9565 if (expression_is_local_variable(expression)) {
9566 warningf(WARN_OTHER, pos, "function returns address of local variable");
9569 } else if (!is_type_void(return_type)) {
9570 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9571 err_or_warn(pos, "'return' without value, in function returning non-void");
9573 statement->returns.value = return_value;
9580 * Parse a declaration statement.
9582 static statement_t *parse_declaration_statement(void)
9584 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9586 entity_t *before = current_scope->last_entity;
9588 parse_external_declaration();
9590 parse_declaration(record_entity, DECL_FLAGS_NONE);
9593 declaration_statement_t *const decl = &statement->declaration;
9594 entity_t *const begin =
9595 before != NULL ? before->base.next : current_scope->entities;
9596 decl->declarations_begin = begin;
9597 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9603 * Parse an expression statement, ie. expr ';'.
9605 static statement_t *parse_expression_statement(void)
9607 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9609 expression_t *const expr = parse_expression();
9610 statement->expression.expression = expr;
9611 mark_vars_read(expr, ENT_ANY);
9618 * Parse a microsoft __try { } __finally { } or
9619 * __try{ } __except() { }
9621 static statement_t *parse_ms_try_statment(void)
9623 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9626 PUSH_PARENT(statement);
9628 ms_try_statement_t *rem = current_try;
9629 current_try = &statement->ms_try;
9630 statement->ms_try.try_statement = parse_compound_statement(false);
9635 if (next_if(T___except)) {
9636 expression_t *const expr = parse_condition();
9637 type_t * type = skip_typeref(expr->base.type);
9638 if (is_type_integer(type)) {
9639 type = promote_integer(type);
9640 } else if (is_type_valid(type)) {
9641 errorf(&expr->base.source_position,
9642 "__expect expression is not an integer, but '%T'", type);
9643 type = type_error_type;
9645 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9646 } else if (!next_if(T__finally)) {
9647 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9649 statement->ms_try.final_statement = parse_compound_statement(false);
9653 static statement_t *parse_empty_statement(void)
9655 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9656 statement_t *const statement = create_empty_statement();
9661 static statement_t *parse_local_label_declaration(void)
9663 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9667 entity_t *begin = NULL;
9668 entity_t *end = NULL;
9669 entity_t **anchor = &begin;
9671 source_position_t pos;
9672 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9676 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9677 if (entity != NULL && entity->base.parent_scope == current_scope) {
9678 source_position_t const *const ppos = &entity->base.source_position;
9679 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9681 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9682 entity->base.parent_scope = current_scope;
9685 anchor = &entity->base.next;
9688 environment_push(entity);
9690 } while (next_if(','));
9693 statement->declaration.declarations_begin = begin;
9694 statement->declaration.declarations_end = end;
9698 static void parse_namespace_definition(void)
9702 entity_t *entity = NULL;
9703 symbol_t *symbol = NULL;
9705 if (token.kind == T_IDENTIFIER) {
9706 symbol = token.base.symbol;
9709 entity = get_entity(symbol, NAMESPACE_NORMAL);
9711 && entity->kind != ENTITY_NAMESPACE
9712 && entity->base.parent_scope == current_scope) {
9713 if (is_entity_valid(entity)) {
9714 error_redefined_as_different_kind(&token.base.source_position,
9715 entity, ENTITY_NAMESPACE);
9721 if (entity == NULL) {
9722 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9723 entity->base.parent_scope = current_scope;
9726 if (token.kind == '=') {
9727 /* TODO: parse namespace alias */
9728 panic("namespace alias definition not supported yet");
9731 environment_push(entity);
9732 append_entity(current_scope, entity);
9734 PUSH_SCOPE(&entity->namespacee.members);
9735 PUSH_CURRENT_ENTITY(entity);
9737 add_anchor_token('}');
9740 rem_anchor_token('}');
9743 POP_CURRENT_ENTITY();
9748 * Parse a statement.
9749 * There's also parse_statement() which additionally checks for
9750 * "statement has no effect" warnings
9752 static statement_t *intern_parse_statement(void)
9754 /* declaration or statement */
9755 statement_t *statement;
9756 switch (token.kind) {
9757 case T_IDENTIFIER: {
9758 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9759 if (la1_type == ':') {
9760 statement = parse_label_statement();
9761 } else if (is_typedef_symbol(token.base.symbol)) {
9762 statement = parse_declaration_statement();
9764 /* it's an identifier, the grammar says this must be an
9765 * expression statement. However it is common that users mistype
9766 * declaration types, so we guess a bit here to improve robustness
9767 * for incorrect programs */
9771 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9773 statement = parse_expression_statement();
9777 statement = parse_declaration_statement();
9785 case T___extension__: {
9786 /* This can be a prefix to a declaration or an expression statement.
9787 * We simply eat it now and parse the rest with tail recursion. */
9789 statement = intern_parse_statement();
9795 statement = parse_declaration_statement();
9799 statement = parse_local_label_declaration();
9802 case ';': statement = parse_empty_statement(); break;
9803 case '{': statement = parse_compound_statement(false); break;
9804 case T___leave: statement = parse_leave_statement(); break;
9805 case T___try: statement = parse_ms_try_statment(); break;
9806 case T_asm: statement = parse_asm_statement(); break;
9807 case T_break: statement = parse_break(); break;
9808 case T_case: statement = parse_case_statement(); break;
9809 case T_continue: statement = parse_continue(); break;
9810 case T_default: statement = parse_default_statement(); break;
9811 case T_do: statement = parse_do(); break;
9812 case T_for: statement = parse_for(); break;
9813 case T_goto: statement = parse_goto(); break;
9814 case T_if: statement = parse_if(); break;
9815 case T_return: statement = parse_return(); break;
9816 case T_switch: statement = parse_switch(); break;
9817 case T_while: statement = parse_while(); break;
9820 statement = parse_expression_statement();
9824 errorf(HERE, "unexpected token %K while parsing statement", &token);
9825 statement = create_error_statement();
9834 * parse a statement and emits "statement has no effect" warning if needed
9835 * (This is really a wrapper around intern_parse_statement with check for 1
9836 * single warning. It is needed, because for statement expressions we have
9837 * to avoid the warning on the last statement)
9839 static statement_t *parse_statement(void)
9841 statement_t *statement = intern_parse_statement();
9843 if (statement->kind == STATEMENT_EXPRESSION) {
9844 expression_t *expression = statement->expression.expression;
9845 if (!expression_has_effect(expression)) {
9846 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9854 * Parse a compound statement.
9856 static statement_t *parse_compound_statement(bool inside_expression_statement)
9858 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9860 PUSH_PARENT(statement);
9861 PUSH_SCOPE(&statement->compound.scope);
9864 add_anchor_token('}');
9865 /* tokens, which can start a statement */
9866 /* TODO MS, __builtin_FOO */
9867 add_anchor_token('!');
9868 add_anchor_token('&');
9869 add_anchor_token('(');
9870 add_anchor_token('*');
9871 add_anchor_token('+');
9872 add_anchor_token('-');
9873 add_anchor_token(';');
9874 add_anchor_token('{');
9875 add_anchor_token('~');
9876 add_anchor_token(T_CHARACTER_CONSTANT);
9877 add_anchor_token(T_COLONCOLON);
9878 add_anchor_token(T_FLOATINGPOINT);
9879 add_anchor_token(T_IDENTIFIER);
9880 add_anchor_token(T_INTEGER);
9881 add_anchor_token(T_MINUSMINUS);
9882 add_anchor_token(T_PLUSPLUS);
9883 add_anchor_token(T_STRING_LITERAL);
9884 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
9885 add_anchor_token(T_WIDE_STRING_LITERAL);
9886 add_anchor_token(T__Bool);
9887 add_anchor_token(T__Complex);
9888 add_anchor_token(T__Imaginary);
9889 add_anchor_token(T___FUNCTION__);
9890 add_anchor_token(T___PRETTY_FUNCTION__);
9891 add_anchor_token(T___alignof__);
9892 add_anchor_token(T___attribute__);
9893 add_anchor_token(T___builtin_va_start);
9894 add_anchor_token(T___extension__);
9895 add_anchor_token(T___func__);
9896 add_anchor_token(T___imag__);
9897 add_anchor_token(T___label__);
9898 add_anchor_token(T___real__);
9899 add_anchor_token(T___thread);
9900 add_anchor_token(T_asm);
9901 add_anchor_token(T_auto);
9902 add_anchor_token(T_bool);
9903 add_anchor_token(T_break);
9904 add_anchor_token(T_case);
9905 add_anchor_token(T_char);
9906 add_anchor_token(T_class);
9907 add_anchor_token(T_const);
9908 add_anchor_token(T_const_cast);
9909 add_anchor_token(T_continue);
9910 add_anchor_token(T_default);
9911 add_anchor_token(T_delete);
9912 add_anchor_token(T_double);
9913 add_anchor_token(T_do);
9914 add_anchor_token(T_dynamic_cast);
9915 add_anchor_token(T_enum);
9916 add_anchor_token(T_extern);
9917 add_anchor_token(T_false);
9918 add_anchor_token(T_float);
9919 add_anchor_token(T_for);
9920 add_anchor_token(T_goto);
9921 add_anchor_token(T_if);
9922 add_anchor_token(T_inline);
9923 add_anchor_token(T_int);
9924 add_anchor_token(T_long);
9925 add_anchor_token(T_new);
9926 add_anchor_token(T_operator);
9927 add_anchor_token(T_register);
9928 add_anchor_token(T_reinterpret_cast);
9929 add_anchor_token(T_restrict);
9930 add_anchor_token(T_return);
9931 add_anchor_token(T_short);
9932 add_anchor_token(T_signed);
9933 add_anchor_token(T_sizeof);
9934 add_anchor_token(T_static);
9935 add_anchor_token(T_static_cast);
9936 add_anchor_token(T_struct);
9937 add_anchor_token(T_switch);
9938 add_anchor_token(T_template);
9939 add_anchor_token(T_this);
9940 add_anchor_token(T_throw);
9941 add_anchor_token(T_true);
9942 add_anchor_token(T_try);
9943 add_anchor_token(T_typedef);
9944 add_anchor_token(T_typeid);
9945 add_anchor_token(T_typename);
9946 add_anchor_token(T_typeof);
9947 add_anchor_token(T_union);
9948 add_anchor_token(T_unsigned);
9949 add_anchor_token(T_using);
9950 add_anchor_token(T_void);
9951 add_anchor_token(T_volatile);
9952 add_anchor_token(T_wchar_t);
9953 add_anchor_token(T_while);
9955 statement_t **anchor = &statement->compound.statements;
9956 bool only_decls_so_far = true;
9957 while (token.kind != '}' && token.kind != T_EOF) {
9958 statement_t *sub_statement = intern_parse_statement();
9959 if (sub_statement->kind == STATEMENT_ERROR) {
9963 if (sub_statement->kind != STATEMENT_DECLARATION) {
9964 only_decls_so_far = false;
9965 } else if (!only_decls_so_far) {
9966 source_position_t const *const pos = &sub_statement->base.source_position;
9967 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9970 *anchor = sub_statement;
9971 anchor = &sub_statement->base.next;
9975 /* look over all statements again to produce no effect warnings */
9976 if (is_warn_on(WARN_UNUSED_VALUE)) {
9977 statement_t *sub_statement = statement->compound.statements;
9978 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9979 if (sub_statement->kind != STATEMENT_EXPRESSION)
9981 /* don't emit a warning for the last expression in an expression
9982 * statement as it has always an effect */
9983 if (inside_expression_statement && sub_statement->base.next == NULL)
9986 expression_t *expression = sub_statement->expression.expression;
9987 if (!expression_has_effect(expression)) {
9988 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9993 rem_anchor_token(T_while);
9994 rem_anchor_token(T_wchar_t);
9995 rem_anchor_token(T_volatile);
9996 rem_anchor_token(T_void);
9997 rem_anchor_token(T_using);
9998 rem_anchor_token(T_unsigned);
9999 rem_anchor_token(T_union);
10000 rem_anchor_token(T_typeof);
10001 rem_anchor_token(T_typename);
10002 rem_anchor_token(T_typeid);
10003 rem_anchor_token(T_typedef);
10004 rem_anchor_token(T_try);
10005 rem_anchor_token(T_true);
10006 rem_anchor_token(T_throw);
10007 rem_anchor_token(T_this);
10008 rem_anchor_token(T_template);
10009 rem_anchor_token(T_switch);
10010 rem_anchor_token(T_struct);
10011 rem_anchor_token(T_static_cast);
10012 rem_anchor_token(T_static);
10013 rem_anchor_token(T_sizeof);
10014 rem_anchor_token(T_signed);
10015 rem_anchor_token(T_short);
10016 rem_anchor_token(T_return);
10017 rem_anchor_token(T_restrict);
10018 rem_anchor_token(T_reinterpret_cast);
10019 rem_anchor_token(T_register);
10020 rem_anchor_token(T_operator);
10021 rem_anchor_token(T_new);
10022 rem_anchor_token(T_long);
10023 rem_anchor_token(T_int);
10024 rem_anchor_token(T_inline);
10025 rem_anchor_token(T_if);
10026 rem_anchor_token(T_goto);
10027 rem_anchor_token(T_for);
10028 rem_anchor_token(T_float);
10029 rem_anchor_token(T_false);
10030 rem_anchor_token(T_extern);
10031 rem_anchor_token(T_enum);
10032 rem_anchor_token(T_dynamic_cast);
10033 rem_anchor_token(T_do);
10034 rem_anchor_token(T_double);
10035 rem_anchor_token(T_delete);
10036 rem_anchor_token(T_default);
10037 rem_anchor_token(T_continue);
10038 rem_anchor_token(T_const_cast);
10039 rem_anchor_token(T_const);
10040 rem_anchor_token(T_class);
10041 rem_anchor_token(T_char);
10042 rem_anchor_token(T_case);
10043 rem_anchor_token(T_break);
10044 rem_anchor_token(T_bool);
10045 rem_anchor_token(T_auto);
10046 rem_anchor_token(T_asm);
10047 rem_anchor_token(T___thread);
10048 rem_anchor_token(T___real__);
10049 rem_anchor_token(T___label__);
10050 rem_anchor_token(T___imag__);
10051 rem_anchor_token(T___func__);
10052 rem_anchor_token(T___extension__);
10053 rem_anchor_token(T___builtin_va_start);
10054 rem_anchor_token(T___attribute__);
10055 rem_anchor_token(T___alignof__);
10056 rem_anchor_token(T___PRETTY_FUNCTION__);
10057 rem_anchor_token(T___FUNCTION__);
10058 rem_anchor_token(T__Imaginary);
10059 rem_anchor_token(T__Complex);
10060 rem_anchor_token(T__Bool);
10061 rem_anchor_token(T_WIDE_STRING_LITERAL);
10062 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10063 rem_anchor_token(T_STRING_LITERAL);
10064 rem_anchor_token(T_PLUSPLUS);
10065 rem_anchor_token(T_MINUSMINUS);
10066 rem_anchor_token(T_INTEGER);
10067 rem_anchor_token(T_IDENTIFIER);
10068 rem_anchor_token(T_FLOATINGPOINT);
10069 rem_anchor_token(T_COLONCOLON);
10070 rem_anchor_token(T_CHARACTER_CONSTANT);
10071 rem_anchor_token('~');
10072 rem_anchor_token('{');
10073 rem_anchor_token(';');
10074 rem_anchor_token('-');
10075 rem_anchor_token('+');
10076 rem_anchor_token('*');
10077 rem_anchor_token('(');
10078 rem_anchor_token('&');
10079 rem_anchor_token('!');
10080 rem_anchor_token('}');
10088 * Check for unused global static functions and variables
10090 static void check_unused_globals(void)
10092 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10095 for (const entity_t *entity = file_scope->entities; entity != NULL;
10096 entity = entity->base.next) {
10097 if (!is_declaration(entity))
10100 const declaration_t *declaration = &entity->declaration;
10101 if (declaration->used ||
10102 declaration->modifiers & DM_UNUSED ||
10103 declaration->modifiers & DM_USED ||
10104 declaration->storage_class != STORAGE_CLASS_STATIC)
10109 if (entity->kind == ENTITY_FUNCTION) {
10110 /* inhibit warning for static inline functions */
10111 if (entity->function.is_inline)
10114 why = WARN_UNUSED_FUNCTION;
10115 s = entity->function.statement != NULL ? "defined" : "declared";
10117 why = WARN_UNUSED_VARIABLE;
10121 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10125 static void parse_global_asm(void)
10127 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10130 add_anchor_token(';');
10131 add_anchor_token(')');
10132 add_anchor_token(T_STRING_LITERAL);
10135 rem_anchor_token(T_STRING_LITERAL);
10136 statement->asms.asm_text = parse_string_literals();
10137 statement->base.next = unit->global_asm;
10138 unit->global_asm = statement;
10140 rem_anchor_token(')');
10142 rem_anchor_token(';');
10146 static void parse_linkage_specification(void)
10150 source_position_t const pos = *HERE;
10151 char const *const linkage = parse_string_literals().begin;
10153 linkage_kind_t old_linkage = current_linkage;
10154 linkage_kind_t new_linkage;
10155 if (streq(linkage, "C")) {
10156 new_linkage = LINKAGE_C;
10157 } else if (streq(linkage, "C++")) {
10158 new_linkage = LINKAGE_CXX;
10160 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10161 new_linkage = LINKAGE_C;
10163 current_linkage = new_linkage;
10165 if (next_if('{')) {
10172 assert(current_linkage == new_linkage);
10173 current_linkage = old_linkage;
10176 static void parse_external(void)
10178 switch (token.kind) {
10180 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10181 parse_linkage_specification();
10183 DECLARATION_START_NO_EXTERN
10185 case T___extension__:
10186 /* tokens below are for implicit int */
10187 case '&': /* & x; -> int& x; (and error later, because C++ has no
10189 case '*': /* * x; -> int* x; */
10190 case '(': /* (x); -> int (x); */
10192 parse_external_declaration();
10198 parse_global_asm();
10202 parse_namespace_definition();
10206 if (!strict_mode) {
10207 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10214 errorf(HERE, "stray %K outside of function", &token);
10215 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10216 eat_until_matching_token(token.kind);
10222 static void parse_externals(void)
10224 add_anchor_token('}');
10225 add_anchor_token(T_EOF);
10228 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10229 unsigned short token_anchor_copy[T_LAST_TOKEN];
10230 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10233 while (token.kind != T_EOF && token.kind != '}') {
10235 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10236 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10238 /* the anchor set and its copy differs */
10239 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10242 if (in_gcc_extension) {
10243 /* an gcc extension scope was not closed */
10244 internal_errorf(HERE, "Leaked __extension__");
10251 rem_anchor_token(T_EOF);
10252 rem_anchor_token('}');
10256 * Parse a translation unit.
10258 static void parse_translation_unit(void)
10260 add_anchor_token(T_EOF);
10265 if (token.kind == T_EOF)
10268 errorf(HERE, "stray %K outside of function", &token);
10269 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10270 eat_until_matching_token(token.kind);
10275 void set_default_visibility(elf_visibility_tag_t visibility)
10277 default_visibility = visibility;
10283 * @return the translation unit or NULL if errors occurred.
10285 void start_parsing(void)
10287 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10288 label_stack = NEW_ARR_F(stack_entry_t, 0);
10289 diagnostic_count = 0;
10293 print_to_file(stderr);
10295 assert(unit == NULL);
10296 unit = allocate_ast_zero(sizeof(unit[0]));
10298 assert(file_scope == NULL);
10299 file_scope = &unit->scope;
10301 assert(current_scope == NULL);
10302 scope_push(&unit->scope);
10304 create_gnu_builtins();
10306 create_microsoft_intrinsics();
10309 translation_unit_t *finish_parsing(void)
10311 assert(current_scope == &unit->scope);
10314 assert(file_scope == &unit->scope);
10315 check_unused_globals();
10318 DEL_ARR_F(environment_stack);
10319 DEL_ARR_F(label_stack);
10321 translation_unit_t *result = unit;
10326 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10327 * are given length one. */
10328 static void complete_incomplete_arrays(void)
10330 size_t n = ARR_LEN(incomplete_arrays);
10331 for (size_t i = 0; i != n; ++i) {
10332 declaration_t *const decl = incomplete_arrays[i];
10333 type_t *const type = skip_typeref(decl->type);
10335 if (!is_type_incomplete(type))
10338 source_position_t const *const pos = &decl->base.source_position;
10339 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10341 type_t *const new_type = duplicate_type(type);
10342 new_type->array.size_constant = true;
10343 new_type->array.has_implicit_size = true;
10344 new_type->array.size = 1;
10346 type_t *const result = identify_new_type(new_type);
10348 decl->type = result;
10352 static void prepare_main_collect2(entity_t *const entity)
10354 PUSH_SCOPE(&entity->function.statement->compound.scope);
10356 // create call to __main
10357 symbol_t *symbol = symbol_table_insert("__main");
10358 entity_t *subsubmain_ent
10359 = create_implicit_function(symbol, &builtin_source_position);
10361 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10362 type_t *ftype = subsubmain_ent->declaration.type;
10363 ref->base.source_position = builtin_source_position;
10364 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10365 ref->reference.entity = subsubmain_ent;
10367 expression_t *call = allocate_expression_zero(EXPR_CALL);
10368 call->base.source_position = builtin_source_position;
10369 call->base.type = type_void;
10370 call->call.function = ref;
10372 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10373 expr_statement->base.source_position = builtin_source_position;
10374 expr_statement->expression.expression = call;
10376 statement_t *statement = entity->function.statement;
10377 assert(statement->kind == STATEMENT_COMPOUND);
10378 compound_statement_t *compounds = &statement->compound;
10380 expr_statement->base.next = compounds->statements;
10381 compounds->statements = expr_statement;
10388 lookahead_bufpos = 0;
10389 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10392 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10393 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10394 parse_translation_unit();
10395 complete_incomplete_arrays();
10396 DEL_ARR_F(incomplete_arrays);
10397 incomplete_arrays = NULL;
10401 * Initialize the parser.
10403 void init_parser(void)
10405 sym_anonymous = symbol_table_insert("<anonymous>");
10407 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10409 init_expression_parsers();
10410 obstack_init(&temp_obst);
10414 * Terminate the parser.
10416 void exit_parser(void)
10418 obstack_free(&temp_obst, NULL);