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___FUNCDNAME__: \
256 case T___FUNCSIG__: \
257 case T___FUNCTION__: \
258 case T___PRETTY_FUNCTION__: \
259 case T___alignof__: \
260 case T___builtin_classify_type: \
261 case T___builtin_constant_p: \
262 case T___builtin_isgreater: \
263 case T___builtin_isgreaterequal: \
264 case T___builtin_isless: \
265 case T___builtin_islessequal: \
266 case T___builtin_islessgreater: \
267 case T___builtin_isunordered: \
268 case T___builtin_offsetof: \
269 case T___builtin_va_arg: \
270 case T___builtin_va_copy: \
271 case T___builtin_va_start: \
282 * Returns the size of a statement node.
284 * @param kind the statement kind
286 static size_t get_statement_struct_size(statement_kind_t kind)
288 static const size_t sizes[] = {
289 [STATEMENT_ERROR] = sizeof(statement_base_t),
290 [STATEMENT_EMPTY] = sizeof(statement_base_t),
291 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
292 [STATEMENT_RETURN] = sizeof(return_statement_t),
293 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
294 [STATEMENT_IF] = sizeof(if_statement_t),
295 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
296 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
297 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
298 [STATEMENT_BREAK] = sizeof(statement_base_t),
299 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
300 [STATEMENT_GOTO] = sizeof(goto_statement_t),
301 [STATEMENT_LABEL] = sizeof(label_statement_t),
302 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
303 [STATEMENT_WHILE] = sizeof(while_statement_t),
304 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
305 [STATEMENT_FOR] = sizeof(for_statement_t),
306 [STATEMENT_ASM] = sizeof(asm_statement_t),
307 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
308 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
310 assert((size_t)kind < lengthof(sizes));
311 assert(sizes[kind] != 0);
316 * Returns the size of an expression node.
318 * @param kind the expression kind
320 static size_t get_expression_struct_size(expression_kind_t kind)
322 static const size_t sizes[] = {
323 [EXPR_ERROR] = sizeof(expression_base_t),
324 [EXPR_REFERENCE] = sizeof(reference_expression_t),
325 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
326 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
331 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
332 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
333 [EXPR_CALL] = sizeof(call_expression_t),
334 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
335 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
336 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
337 [EXPR_SELECT] = sizeof(select_expression_t),
338 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
339 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
340 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
341 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
342 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
343 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
344 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
345 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
346 [EXPR_VA_START] = sizeof(va_start_expression_t),
347 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
348 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
349 [EXPR_STATEMENT] = sizeof(statement_expression_t),
350 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
352 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
353 return sizes[EXPR_UNARY_FIRST];
355 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
356 return sizes[EXPR_BINARY_FIRST];
358 assert((size_t)kind < lengthof(sizes));
359 assert(sizes[kind] != 0);
364 * Allocate a statement node of given kind and initialize all
365 * fields with zero. Sets its source position to the position
366 * of the current token.
368 static statement_t *allocate_statement_zero(statement_kind_t kind)
370 size_t size = get_statement_struct_size(kind);
371 statement_t *res = allocate_ast_zero(size);
373 res->base.kind = kind;
374 res->base.parent = current_parent;
375 res->base.source_position = *HERE;
380 * Allocate an expression node of given kind and initialize all
383 * @param kind the kind of the expression to allocate
385 static expression_t *allocate_expression_zero(expression_kind_t kind)
387 size_t size = get_expression_struct_size(kind);
388 expression_t *res = allocate_ast_zero(size);
390 res->base.kind = kind;
391 res->base.type = type_error_type;
392 res->base.source_position = *HERE;
397 * Creates a new invalid expression at the source position
398 * of the current token.
400 static expression_t *create_error_expression(void)
402 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
403 expression->base.type = type_error_type;
408 * Creates a new invalid statement.
410 static statement_t *create_error_statement(void)
412 return allocate_statement_zero(STATEMENT_ERROR);
416 * Allocate a new empty statement.
418 static statement_t *create_empty_statement(void)
420 return allocate_statement_zero(STATEMENT_EMPTY);
424 * Returns the size of an initializer node.
426 * @param kind the initializer kind
428 static size_t get_initializer_size(initializer_kind_t kind)
430 static const size_t sizes[] = {
431 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
432 [INITIALIZER_STRING] = sizeof(initializer_string_t),
433 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
434 [INITIALIZER_LIST] = sizeof(initializer_list_t),
435 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
437 assert((size_t)kind < lengthof(sizes));
438 assert(sizes[kind] != 0);
443 * Allocate an initializer node of given kind and initialize all
446 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
448 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
455 * Returns the index of the top element of the environment stack.
457 static size_t environment_top(void)
459 return ARR_LEN(environment_stack);
463 * Returns the index of the top element of the global label stack.
465 static size_t label_top(void)
467 return ARR_LEN(label_stack);
471 * Return the next token.
473 static inline void next_token(void)
475 token = lookahead_buffer[lookahead_bufpos];
476 lookahead_buffer[lookahead_bufpos] = lexer_token;
479 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
482 print_token(stderr, &token);
483 fprintf(stderr, "\n");
487 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
489 static inline bool next_if(token_kind_t const type)
491 if (token.kind == type) {
500 * Return the next token with a given lookahead.
502 static inline const token_t *look_ahead(size_t num)
504 assert(0 < num && num <= MAX_LOOKAHEAD);
505 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
506 return &lookahead_buffer[pos];
510 * Adds a token type to the token type anchor set (a multi-set).
512 static void add_anchor_token(token_kind_t const token_kind)
514 assert(token_kind < T_LAST_TOKEN);
515 ++token_anchor_set[token_kind];
519 * Remove a token type from the token type anchor set (a multi-set).
521 static void rem_anchor_token(token_kind_t const token_kind)
523 assert(token_kind < T_LAST_TOKEN);
524 assert(token_anchor_set[token_kind] != 0);
525 --token_anchor_set[token_kind];
529 * Eat tokens until a matching token type is found.
531 static void eat_until_matching_token(token_kind_t const type)
533 token_kind_t end_token;
535 case '(': end_token = ')'; break;
536 case '{': end_token = '}'; break;
537 case '[': end_token = ']'; break;
538 default: end_token = type; break;
541 unsigned parenthesis_count = 0;
542 unsigned brace_count = 0;
543 unsigned bracket_count = 0;
544 while (token.kind != end_token ||
545 parenthesis_count != 0 ||
547 bracket_count != 0) {
548 switch (token.kind) {
550 case '(': ++parenthesis_count; break;
551 case '{': ++brace_count; break;
552 case '[': ++bracket_count; break;
555 if (parenthesis_count > 0)
565 if (bracket_count > 0)
568 if (token.kind == end_token &&
569 parenthesis_count == 0 &&
583 * Eat input tokens until an anchor is found.
585 static void eat_until_anchor(void)
587 while (token_anchor_set[token.kind] == 0) {
588 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
589 eat_until_matching_token(token.kind);
595 * Eat a whole block from input tokens.
597 static void eat_block(void)
599 eat_until_matching_token('{');
604 * Report a parse error because an expected token was not found.
607 #if defined __GNUC__ && __GNUC__ >= 4
608 __attribute__((sentinel))
610 void parse_error_expected(const char *message, ...)
612 if (message != NULL) {
613 errorf(HERE, "%s", message);
616 va_start(ap, message);
617 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
622 * Report an incompatible type.
624 static void type_error_incompatible(const char *msg,
625 const source_position_t *source_position, type_t *type1, type_t *type2)
627 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
631 static bool skip_till(token_kind_t const expected, char const *const context)
633 if (UNLIKELY(token.kind != expected)) {
634 parse_error_expected(context, expected, NULL);
635 add_anchor_token(expected);
637 rem_anchor_token(expected);
638 if (token.kind != expected)
645 * Expect the current token is the expected token.
646 * If not, generate an error and skip until the next anchor.
648 static void expect(token_kind_t const expected)
650 if (skip_till(expected, NULL))
654 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
656 if (!skip_till(T_IDENTIFIER, context))
658 symbol_t *const sym = token.base.symbol;
666 * Push a given scope on the scope stack and make it the
669 static scope_t *scope_push(scope_t *new_scope)
671 if (current_scope != NULL) {
672 new_scope->depth = current_scope->depth + 1;
675 scope_t *old_scope = current_scope;
676 current_scope = new_scope;
681 * Pop the current scope from the scope stack.
683 static void scope_pop(scope_t *old_scope)
685 current_scope = old_scope;
689 * Search an entity by its symbol in a given namespace.
691 static entity_t *get_entity(const symbol_t *const symbol,
692 namespace_tag_t namespc)
694 entity_t *entity = symbol->entity;
695 for (; entity != NULL; entity = entity->base.symbol_next) {
696 if ((namespace_tag_t)entity->base.namespc == namespc)
703 /* §6.2.3:1 24) There is only one name space for tags even though three are
705 static entity_t *get_tag(symbol_t const *const symbol,
706 entity_kind_tag_t const kind)
708 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
709 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
711 "'%Y' defined as wrong kind of tag (previous definition %P)",
712 symbol, &entity->base.source_position);
719 * pushs an entity on the environment stack and links the corresponding symbol
722 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
724 symbol_t *symbol = entity->base.symbol;
725 entity_namespace_t namespc = entity->base.namespc;
726 assert(namespc != 0);
728 /* replace/add entity into entity list of the symbol */
731 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
736 /* replace an entry? */
737 if (iter->base.namespc == namespc) {
738 entity->base.symbol_next = iter->base.symbol_next;
744 /* remember old declaration */
746 entry.symbol = symbol;
747 entry.old_entity = iter;
748 entry.namespc = namespc;
749 ARR_APP1(stack_entry_t, *stack_ptr, entry);
753 * Push an entity on the environment stack.
755 static void environment_push(entity_t *entity)
757 assert(entity->base.source_position.input_name != NULL);
758 assert(entity->base.parent_scope != NULL);
759 stack_push(&environment_stack, entity);
763 * Push a declaration on the global label stack.
765 * @param declaration the declaration
767 static void label_push(entity_t *label)
769 /* we abuse the parameters scope as parent for the labels */
770 label->base.parent_scope = ¤t_function->parameters;
771 stack_push(&label_stack, label);
775 * pops symbols from the environment stack until @p new_top is the top element
777 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
779 stack_entry_t *stack = *stack_ptr;
780 size_t top = ARR_LEN(stack);
783 assert(new_top <= top);
787 for (i = top; i > new_top; --i) {
788 stack_entry_t *entry = &stack[i - 1];
790 entity_t *old_entity = entry->old_entity;
791 symbol_t *symbol = entry->symbol;
792 entity_namespace_t namespc = entry->namespc;
794 /* replace with old_entity/remove */
797 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
799 assert(iter != NULL);
800 /* replace an entry? */
801 if (iter->base.namespc == namespc)
805 /* restore definition from outer scopes (if there was one) */
806 if (old_entity != NULL) {
807 old_entity->base.symbol_next = iter->base.symbol_next;
808 *anchor = old_entity;
810 /* remove entry from list */
811 *anchor = iter->base.symbol_next;
815 ARR_SHRINKLEN(*stack_ptr, new_top);
819 * Pop all entries from the environment stack until the new_top
822 * @param new_top the new stack top
824 static void environment_pop_to(size_t new_top)
826 stack_pop_to(&environment_stack, new_top);
830 * Pop all entries from the global label stack until the new_top
833 * @param new_top the new stack top
835 static void label_pop_to(size_t new_top)
837 stack_pop_to(&label_stack, new_top);
840 static atomic_type_kind_t get_akind(const type_t *type)
842 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
843 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
844 return type->atomic.akind;
848 * §6.3.1.1:2 Do integer promotion for a given type.
850 * @param type the type to promote
851 * @return the promoted type
853 static type_t *promote_integer(type_t *type)
855 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
862 * Check if a given expression represents a null pointer constant.
864 * @param expression the expression to check
866 static bool is_null_pointer_constant(const expression_t *expression)
868 /* skip void* cast */
869 if (expression->kind == EXPR_UNARY_CAST) {
870 type_t *const type = skip_typeref(expression->base.type);
871 if (types_compatible(type, type_void_ptr))
872 expression = expression->unary.value;
875 type_t *const type = skip_typeref(expression->base.type);
876 if (!is_type_integer(type))
878 switch (is_constant_expression(expression)) {
879 case EXPR_CLASS_ERROR: return true;
880 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
881 default: return false;
886 * Create an implicit cast expression.
888 * @param expression the expression to cast
889 * @param dest_type the destination type
891 static expression_t *create_implicit_cast(expression_t *expression,
894 type_t *const source_type = expression->base.type;
896 if (source_type == dest_type)
899 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
900 cast->unary.value = expression;
901 cast->base.type = dest_type;
902 cast->base.implicit = true;
907 typedef enum assign_error_t {
909 ASSIGN_ERROR_INCOMPATIBLE,
910 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
911 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
912 ASSIGN_WARNING_POINTER_FROM_INT,
913 ASSIGN_WARNING_INT_FROM_POINTER
916 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, source_position_t const *const pos)
918 type_t *const orig_type_right = right->base.type;
919 type_t *const type_left = skip_typeref(orig_type_left);
920 type_t *const type_right = skip_typeref(orig_type_right);
925 case ASSIGN_ERROR_INCOMPATIBLE:
926 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
929 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
930 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
931 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
933 /* the left type has all qualifiers from the right type */
934 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
935 warningf(WARN_OTHER, pos, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type", orig_type_left, context, orig_type_right, missing_qualifiers);
939 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
940 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
943 case ASSIGN_WARNING_POINTER_FROM_INT:
944 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
947 case ASSIGN_WARNING_INT_FROM_POINTER:
948 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
952 panic("invalid error value");
956 /** Implements the rules from §6.5.16.1 */
957 static assign_error_t semantic_assign(type_t *orig_type_left,
958 const expression_t *const right)
960 type_t *const orig_type_right = right->base.type;
961 type_t *const type_left = skip_typeref(orig_type_left);
962 type_t *const type_right = skip_typeref(orig_type_right);
964 if (is_type_pointer(type_left)) {
965 if (is_null_pointer_constant(right)) {
966 return ASSIGN_SUCCESS;
967 } else if (is_type_pointer(type_right)) {
968 type_t *points_to_left
969 = skip_typeref(type_left->pointer.points_to);
970 type_t *points_to_right
971 = skip_typeref(type_right->pointer.points_to);
972 assign_error_t res = ASSIGN_SUCCESS;
974 /* the left type has all qualifiers from the right type */
975 unsigned missing_qualifiers
976 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
977 if (missing_qualifiers != 0) {
978 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
981 points_to_left = get_unqualified_type(points_to_left);
982 points_to_right = get_unqualified_type(points_to_right);
984 if (is_type_void(points_to_left))
987 if (is_type_void(points_to_right)) {
988 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
989 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
992 if (!types_compatible(points_to_left, points_to_right)) {
993 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
997 } else if (is_type_integer(type_right)) {
998 return ASSIGN_WARNING_POINTER_FROM_INT;
1000 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1001 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1002 && is_type_pointer(type_right))) {
1003 return ASSIGN_SUCCESS;
1004 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1005 type_t *const unqual_type_left = get_unqualified_type(type_left);
1006 type_t *const unqual_type_right = get_unqualified_type(type_right);
1007 if (types_compatible(unqual_type_left, unqual_type_right)) {
1008 return ASSIGN_SUCCESS;
1010 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1011 return ASSIGN_WARNING_INT_FROM_POINTER;
1014 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1015 return ASSIGN_SUCCESS;
1017 return ASSIGN_ERROR_INCOMPATIBLE;
1020 static expression_t *parse_constant_expression(void)
1022 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1024 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1025 errorf(&result->base.source_position,
1026 "expression '%E' is not constant", result);
1032 static expression_t *parse_assignment_expression(void)
1034 return parse_subexpression(PREC_ASSIGNMENT);
1037 static void append_string(string_t const *const s)
1039 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1040 * possible, because other tokens are grown there alongside. */
1041 obstack_grow(&ast_obstack, s->begin, s->size);
1044 static string_t finish_string(void)
1046 obstack_1grow(&ast_obstack, '\0');
1047 size_t const size = obstack_object_size(&ast_obstack) - 1;
1048 char const *const string = obstack_finish(&ast_obstack);
1049 return (string_t){ string, size };
1052 static string_t concat_string_literals(string_encoding_t *const out_enc)
1054 assert(token.kind == T_STRING_LITERAL);
1057 string_encoding_t enc = token.string.encoding;
1058 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1059 append_string(&token.string.string);
1060 eat(T_STRING_LITERAL);
1061 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1063 if (token.string.encoding != STRING_ENCODING_CHAR) {
1064 enc = token.string.encoding;
1066 append_string(&token.string.string);
1067 eat(T_STRING_LITERAL);
1068 } while (token.kind == T_STRING_LITERAL);
1069 result = finish_string();
1071 result = token.string.string;
1072 eat(T_STRING_LITERAL);
1079 static string_t parse_string_literals(void)
1081 string_encoding_t enc;
1082 source_position_t const pos = *HERE;
1083 string_t const res = concat_string_literals(&enc);
1085 if (enc != STRING_ENCODING_CHAR) {
1086 errorf(&pos, "expected plain string literal, got wide string literal");
1092 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1094 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1095 attribute->kind = kind;
1096 attribute->source_position = *HERE;
1101 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1104 * __attribute__ ( ( attribute-list ) )
1108 * attribute_list , attrib
1113 * any-word ( identifier )
1114 * any-word ( identifier , nonempty-expr-list )
1115 * any-word ( expr-list )
1117 * where the "identifier" must not be declared as a type, and
1118 * "any-word" may be any identifier (including one declared as a
1119 * type), a reserved word storage class specifier, type specifier or
1120 * type qualifier. ??? This still leaves out most reserved keywords
1121 * (following the old parser), shouldn't we include them, and why not
1122 * allow identifiers declared as types to start the arguments?
1124 * Matze: this all looks confusing and little systematic, so we're even less
1125 * strict and parse any list of things which are identifiers or
1126 * (assignment-)expressions.
1128 static attribute_argument_t *parse_attribute_arguments(void)
1130 attribute_argument_t *first = NULL;
1131 attribute_argument_t **anchor = &first;
1132 if (token.kind != ')') do {
1133 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1135 /* is it an identifier */
1136 if (token.kind == T_IDENTIFIER
1137 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1138 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1139 argument->v.symbol = token.base.symbol;
1142 /* must be an expression */
1143 expression_t *expression = parse_assignment_expression();
1145 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1146 argument->v.expression = expression;
1149 /* append argument */
1151 anchor = &argument->next;
1152 } while (next_if(','));
1157 static attribute_t *parse_attribute_asm(void)
1159 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1162 attribute->a.arguments = parse_attribute_arguments();
1166 static attribute_t *parse_attribute_gnu_single(void)
1168 /* parse "any-word" */
1169 symbol_t *const symbol = token.base.symbol;
1170 if (symbol == NULL) {
1171 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1175 attribute_kind_t kind;
1176 char const *const name = symbol->string;
1177 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1178 if (kind > ATTRIBUTE_GNU_LAST) {
1179 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1180 /* TODO: we should still save the attribute in the list... */
1181 kind = ATTRIBUTE_UNKNOWN;
1185 const char *attribute_name = get_attribute_name(kind);
1186 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1190 attribute_t *attribute = allocate_attribute_zero(kind);
1193 /* parse arguments */
1195 attribute->a.arguments = parse_attribute_arguments();
1200 static attribute_t *parse_attribute_gnu(void)
1202 attribute_t *first = NULL;
1203 attribute_t **anchor = &first;
1205 eat(T___attribute__);
1206 add_anchor_token(')');
1207 add_anchor_token(',');
1211 if (token.kind != ')') do {
1212 attribute_t *attribute = parse_attribute_gnu_single();
1214 *anchor = attribute;
1215 anchor = &attribute->next;
1217 } while (next_if(','));
1218 rem_anchor_token(',');
1219 rem_anchor_token(')');
1226 /** Parse attributes. */
1227 static attribute_t *parse_attributes(attribute_t *first)
1229 attribute_t **anchor = &first;
1231 while (*anchor != NULL)
1232 anchor = &(*anchor)->next;
1234 attribute_t *attribute;
1235 switch (token.kind) {
1236 case T___attribute__:
1237 attribute = parse_attribute_gnu();
1238 if (attribute == NULL)
1243 attribute = parse_attribute_asm();
1247 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1252 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1256 case T__forceinline:
1257 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1258 eat(T__forceinline);
1262 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1267 /* TODO record modifier */
1268 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1269 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1277 *anchor = attribute;
1278 anchor = &attribute->next;
1282 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1284 static entity_t *determine_lhs_ent(expression_t *const expr,
1287 switch (expr->kind) {
1288 case EXPR_REFERENCE: {
1289 entity_t *const entity = expr->reference.entity;
1290 /* we should only find variables as lvalues... */
1291 if (entity->base.kind != ENTITY_VARIABLE
1292 && entity->base.kind != ENTITY_PARAMETER)
1298 case EXPR_ARRAY_ACCESS: {
1299 expression_t *const ref = expr->array_access.array_ref;
1300 entity_t * ent = NULL;
1301 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1302 ent = determine_lhs_ent(ref, lhs_ent);
1305 mark_vars_read(ref, lhs_ent);
1307 mark_vars_read(expr->array_access.index, lhs_ent);
1312 mark_vars_read(expr->select.compound, lhs_ent);
1313 if (is_type_compound(skip_typeref(expr->base.type)))
1314 return determine_lhs_ent(expr->select.compound, lhs_ent);
1318 case EXPR_UNARY_DEREFERENCE: {
1319 expression_t *const val = expr->unary.value;
1320 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1322 return determine_lhs_ent(val->unary.value, lhs_ent);
1324 mark_vars_read(val, NULL);
1330 mark_vars_read(expr, NULL);
1335 #define ENT_ANY ((entity_t*)-1)
1338 * Mark declarations, which are read. This is used to detect variables, which
1342 * x is not marked as "read", because it is only read to calculate its own new
1346 * x and y are not detected as "not read", because multiple variables are
1349 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1351 switch (expr->kind) {
1352 case EXPR_REFERENCE: {
1353 entity_t *const entity = expr->reference.entity;
1354 if (entity->kind != ENTITY_VARIABLE
1355 && entity->kind != ENTITY_PARAMETER)
1358 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1359 entity->variable.read = true;
1365 // TODO respect pure/const
1366 mark_vars_read(expr->call.function, NULL);
1367 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1368 mark_vars_read(arg->expression, NULL);
1372 case EXPR_CONDITIONAL:
1373 // TODO lhs_decl should depend on whether true/false have an effect
1374 mark_vars_read(expr->conditional.condition, NULL);
1375 if (expr->conditional.true_expression != NULL)
1376 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1377 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1381 if (lhs_ent == ENT_ANY
1382 && !is_type_compound(skip_typeref(expr->base.type)))
1384 mark_vars_read(expr->select.compound, lhs_ent);
1387 case EXPR_ARRAY_ACCESS: {
1388 mark_vars_read(expr->array_access.index, lhs_ent);
1389 expression_t *const ref = expr->array_access.array_ref;
1390 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1391 if (lhs_ent == ENT_ANY)
1394 mark_vars_read(ref, lhs_ent);
1399 mark_vars_read(expr->va_arge.ap, lhs_ent);
1403 mark_vars_read(expr->va_copye.src, lhs_ent);
1406 case EXPR_UNARY_CAST:
1407 /* Special case: Use void cast to mark a variable as "read" */
1408 if (is_type_void(skip_typeref(expr->base.type)))
1413 case EXPR_UNARY_THROW:
1414 if (expr->unary.value == NULL)
1417 case EXPR_UNARY_DEREFERENCE:
1418 case EXPR_UNARY_DELETE:
1419 case EXPR_UNARY_DELETE_ARRAY:
1420 if (lhs_ent == ENT_ANY)
1424 case EXPR_UNARY_NEGATE:
1425 case EXPR_UNARY_PLUS:
1426 case EXPR_UNARY_BITWISE_NEGATE:
1427 case EXPR_UNARY_NOT:
1428 case EXPR_UNARY_TAKE_ADDRESS:
1429 case EXPR_UNARY_POSTFIX_INCREMENT:
1430 case EXPR_UNARY_POSTFIX_DECREMENT:
1431 case EXPR_UNARY_PREFIX_INCREMENT:
1432 case EXPR_UNARY_PREFIX_DECREMENT:
1433 case EXPR_UNARY_ASSUME:
1435 mark_vars_read(expr->unary.value, lhs_ent);
1438 case EXPR_BINARY_ADD:
1439 case EXPR_BINARY_SUB:
1440 case EXPR_BINARY_MUL:
1441 case EXPR_BINARY_DIV:
1442 case EXPR_BINARY_MOD:
1443 case EXPR_BINARY_EQUAL:
1444 case EXPR_BINARY_NOTEQUAL:
1445 case EXPR_BINARY_LESS:
1446 case EXPR_BINARY_LESSEQUAL:
1447 case EXPR_BINARY_GREATER:
1448 case EXPR_BINARY_GREATEREQUAL:
1449 case EXPR_BINARY_BITWISE_AND:
1450 case EXPR_BINARY_BITWISE_OR:
1451 case EXPR_BINARY_BITWISE_XOR:
1452 case EXPR_BINARY_LOGICAL_AND:
1453 case EXPR_BINARY_LOGICAL_OR:
1454 case EXPR_BINARY_SHIFTLEFT:
1455 case EXPR_BINARY_SHIFTRIGHT:
1456 case EXPR_BINARY_COMMA:
1457 case EXPR_BINARY_ISGREATER:
1458 case EXPR_BINARY_ISGREATEREQUAL:
1459 case EXPR_BINARY_ISLESS:
1460 case EXPR_BINARY_ISLESSEQUAL:
1461 case EXPR_BINARY_ISLESSGREATER:
1462 case EXPR_BINARY_ISUNORDERED:
1463 mark_vars_read(expr->binary.left, lhs_ent);
1464 mark_vars_read(expr->binary.right, lhs_ent);
1467 case EXPR_BINARY_ASSIGN:
1468 case EXPR_BINARY_MUL_ASSIGN:
1469 case EXPR_BINARY_DIV_ASSIGN:
1470 case EXPR_BINARY_MOD_ASSIGN:
1471 case EXPR_BINARY_ADD_ASSIGN:
1472 case EXPR_BINARY_SUB_ASSIGN:
1473 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1474 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1475 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1476 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1477 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1478 if (lhs_ent == ENT_ANY)
1480 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1481 mark_vars_read(expr->binary.right, lhs_ent);
1486 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1489 case EXPR_LITERAL_CASES:
1491 case EXPR_STRING_LITERAL:
1492 case EXPR_COMPOUND_LITERAL: // TODO init?
1494 case EXPR_CLASSIFY_TYPE:
1497 case EXPR_BUILTIN_CONSTANT_P:
1498 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1500 case EXPR_STATEMENT: // TODO
1501 case EXPR_LABEL_ADDRESS:
1502 case EXPR_ENUM_CONSTANT:
1506 panic("unhandled expression");
1509 static designator_t *parse_designation(void)
1511 designator_t *result = NULL;
1512 designator_t **anchor = &result;
1515 designator_t *designator;
1516 switch (token.kind) {
1518 designator = allocate_ast_zero(sizeof(designator[0]));
1519 designator->source_position = *HERE;
1521 add_anchor_token(']');
1522 designator->array_index = parse_constant_expression();
1523 rem_anchor_token(']');
1527 designator = allocate_ast_zero(sizeof(designator[0]));
1528 designator->source_position = *HERE;
1530 designator->symbol = expect_identifier("while parsing designator", NULL);
1531 if (!designator->symbol)
1539 assert(designator != NULL);
1540 *anchor = designator;
1541 anchor = &designator->next;
1545 static initializer_t *initializer_from_string(array_type_t *const type,
1546 const string_t *const string)
1548 /* TODO: check len vs. size of array type */
1551 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1552 initializer->string.string = *string;
1557 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1558 const string_t *const string)
1560 /* TODO: check len vs. size of array type */
1563 initializer_t *const initializer =
1564 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1565 initializer->wide_string.string = *string;
1571 * Build an initializer from a given expression.
1573 static initializer_t *initializer_from_expression(type_t *orig_type,
1574 expression_t *expression)
1576 /* TODO check that expression is a constant expression */
1578 /* §6.7.8.14/15 char array may be initialized by string literals */
1579 type_t *type = skip_typeref(orig_type);
1580 type_t *expr_type_orig = expression->base.type;
1581 type_t *expr_type = skip_typeref(expr_type_orig);
1583 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1584 array_type_t *const array_type = &type->array;
1585 type_t *const element_type = skip_typeref(array_type->element_type);
1587 if (element_type->kind == TYPE_ATOMIC && expression->kind == EXPR_STRING_LITERAL) {
1588 switch (expression->string_literal.encoding) {
1589 case STRING_ENCODING_CHAR: {
1590 atomic_type_kind_t const akind = element_type->atomic.akind;
1591 if (akind == ATOMIC_TYPE_CHAR
1592 || akind == ATOMIC_TYPE_SCHAR
1593 || akind == ATOMIC_TYPE_UCHAR) {
1594 return initializer_from_string(array_type,
1595 &expression->string_literal.value);
1600 case STRING_ENCODING_WIDE: {
1601 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1602 if (get_unqualified_type(element_type) == bare_wchar_type) {
1603 return initializer_from_wide_string(array_type,
1604 &expression->string_literal.value);
1612 assign_error_t error = semantic_assign(type, expression);
1613 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1615 report_assign_error(error, type, expression, "initializer",
1616 &expression->base.source_position);
1618 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1619 result->value.value = create_implicit_cast(expression, type);
1625 * Parses an scalar initializer.
1627 * §6.7.8.11; eat {} without warning
1629 static initializer_t *parse_scalar_initializer(type_t *type,
1630 bool must_be_constant)
1632 /* there might be extra {} hierarchies */
1634 if (token.kind == '{') {
1635 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1639 } while (token.kind == '{');
1642 expression_t *expression = parse_assignment_expression();
1643 mark_vars_read(expression, NULL);
1644 if (must_be_constant && !is_linker_constant(expression)) {
1645 errorf(&expression->base.source_position,
1646 "initialisation expression '%E' is not constant",
1650 initializer_t *initializer = initializer_from_expression(type, expression);
1652 if (initializer == NULL) {
1653 errorf(&expression->base.source_position,
1654 "expression '%E' (type '%T') doesn't match expected type '%T'",
1655 expression, expression->base.type, type);
1660 bool additional_warning_displayed = false;
1661 while (braces > 0) {
1663 if (token.kind != '}') {
1664 if (!additional_warning_displayed) {
1665 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1666 additional_warning_displayed = true;
1677 * An entry in the type path.
1679 typedef struct type_path_entry_t type_path_entry_t;
1680 struct type_path_entry_t {
1681 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1683 size_t index; /**< For array types: the current index. */
1684 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1689 * A type path expression a position inside compound or array types.
1691 typedef struct type_path_t type_path_t;
1692 struct type_path_t {
1693 type_path_entry_t *path; /**< An flexible array containing the current path. */
1694 type_t *top_type; /**< type of the element the path points */
1695 size_t max_index; /**< largest index in outermost array */
1699 * Prints a type path for debugging.
1701 static __attribute__((unused)) void debug_print_type_path(
1702 const type_path_t *path)
1704 size_t len = ARR_LEN(path->path);
1706 for (size_t i = 0; i < len; ++i) {
1707 const type_path_entry_t *entry = & path->path[i];
1709 type_t *type = skip_typeref(entry->type);
1710 if (is_type_compound(type)) {
1711 /* in gcc mode structs can have no members */
1712 if (entry->v.compound_entry == NULL) {
1716 fprintf(stderr, ".%s",
1717 entry->v.compound_entry->base.symbol->string);
1718 } else if (is_type_array(type)) {
1719 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1721 fprintf(stderr, "-INVALID-");
1724 if (path->top_type != NULL) {
1725 fprintf(stderr, " (");
1726 print_type(path->top_type);
1727 fprintf(stderr, ")");
1732 * Return the top type path entry, ie. in a path
1733 * (type).a.b returns the b.
1735 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1737 size_t len = ARR_LEN(path->path);
1739 return &path->path[len-1];
1743 * Enlarge the type path by an (empty) element.
1745 static type_path_entry_t *append_to_type_path(type_path_t *path)
1747 size_t len = ARR_LEN(path->path);
1748 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1750 type_path_entry_t *result = & path->path[len];
1751 memset(result, 0, sizeof(result[0]));
1756 * Descending into a sub-type. Enter the scope of the current top_type.
1758 static void descend_into_subtype(type_path_t *path)
1760 type_t *orig_top_type = path->top_type;
1761 type_t *top_type = skip_typeref(orig_top_type);
1763 type_path_entry_t *top = append_to_type_path(path);
1764 top->type = top_type;
1766 if (is_type_compound(top_type)) {
1767 compound_t *const compound = top_type->compound.compound;
1768 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1770 if (entry != NULL) {
1771 top->v.compound_entry = &entry->declaration;
1772 path->top_type = entry->declaration.type;
1774 path->top_type = NULL;
1776 } else if (is_type_array(top_type)) {
1778 path->top_type = top_type->array.element_type;
1780 assert(!is_type_valid(top_type));
1785 * Pop an entry from the given type path, ie. returning from
1786 * (type).a.b to (type).a
1788 static void ascend_from_subtype(type_path_t *path)
1790 type_path_entry_t *top = get_type_path_top(path);
1792 path->top_type = top->type;
1794 size_t len = ARR_LEN(path->path);
1795 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1799 * Pop entries from the given type path until the given
1800 * path level is reached.
1802 static void ascend_to(type_path_t *path, size_t top_path_level)
1804 size_t len = ARR_LEN(path->path);
1806 while (len > top_path_level) {
1807 ascend_from_subtype(path);
1808 len = ARR_LEN(path->path);
1812 static bool walk_designator(type_path_t *path, const designator_t *designator,
1813 bool used_in_offsetof)
1815 for (; designator != NULL; designator = designator->next) {
1816 type_path_entry_t *top = get_type_path_top(path);
1817 type_t *orig_type = top->type;
1819 type_t *type = skip_typeref(orig_type);
1821 if (designator->symbol != NULL) {
1822 symbol_t *symbol = designator->symbol;
1823 if (!is_type_compound(type)) {
1824 if (is_type_valid(type)) {
1825 errorf(&designator->source_position,
1826 "'.%Y' designator used for non-compound type '%T'",
1830 top->type = type_error_type;
1831 top->v.compound_entry = NULL;
1832 orig_type = type_error_type;
1834 compound_t *compound = type->compound.compound;
1835 entity_t *iter = compound->members.entities;
1836 for (; iter != NULL; iter = iter->base.next) {
1837 if (iter->base.symbol == symbol) {
1842 errorf(&designator->source_position,
1843 "'%T' has no member named '%Y'", orig_type, symbol);
1846 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1847 if (used_in_offsetof && iter->compound_member.bitfield) {
1848 errorf(&designator->source_position,
1849 "offsetof designator '%Y' must not specify bitfield",
1854 top->type = orig_type;
1855 top->v.compound_entry = &iter->declaration;
1856 orig_type = iter->declaration.type;
1859 expression_t *array_index = designator->array_index;
1860 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1863 if (!is_type_array(type)) {
1864 if (is_type_valid(type)) {
1865 errorf(&designator->source_position,
1866 "[%E] designator used for non-array type '%T'",
1867 array_index, orig_type);
1872 long index = fold_constant_to_int(array_index);
1873 if (!used_in_offsetof) {
1875 errorf(&designator->source_position,
1876 "array index [%E] must be positive", array_index);
1877 } else if (type->array.size_constant) {
1878 long array_size = type->array.size;
1879 if (index >= array_size) {
1880 errorf(&designator->source_position,
1881 "designator [%E] (%d) exceeds array size %d",
1882 array_index, index, array_size);
1887 top->type = orig_type;
1888 top->v.index = (size_t) index;
1889 orig_type = type->array.element_type;
1891 path->top_type = orig_type;
1893 if (designator->next != NULL) {
1894 descend_into_subtype(path);
1900 static void advance_current_object(type_path_t *path, size_t top_path_level)
1902 type_path_entry_t *top = get_type_path_top(path);
1904 type_t *type = skip_typeref(top->type);
1905 if (is_type_union(type)) {
1906 /* in unions only the first element is initialized */
1907 top->v.compound_entry = NULL;
1908 } else if (is_type_struct(type)) {
1909 declaration_t *entry = top->v.compound_entry;
1911 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1912 if (next_entity != NULL) {
1913 assert(is_declaration(next_entity));
1914 entry = &next_entity->declaration;
1919 top->v.compound_entry = entry;
1920 if (entry != NULL) {
1921 path->top_type = entry->type;
1924 } else if (is_type_array(type)) {
1925 assert(is_type_array(type));
1929 if (!type->array.size_constant || top->v.index < type->array.size) {
1933 assert(!is_type_valid(type));
1937 /* we're past the last member of the current sub-aggregate, try if we
1938 * can ascend in the type hierarchy and continue with another subobject */
1939 size_t len = ARR_LEN(path->path);
1941 if (len > top_path_level) {
1942 ascend_from_subtype(path);
1943 advance_current_object(path, top_path_level);
1945 path->top_type = NULL;
1950 * skip any {...} blocks until a closing bracket is reached.
1952 static void skip_initializers(void)
1956 while (token.kind != '}') {
1957 if (token.kind == T_EOF)
1959 if (token.kind == '{') {
1967 static initializer_t *create_empty_initializer(void)
1969 static initializer_t empty_initializer
1970 = { .list = { { INITIALIZER_LIST }, 0 } };
1971 return &empty_initializer;
1975 * Parse a part of an initialiser for a struct or union,
1977 static initializer_t *parse_sub_initializer(type_path_t *path,
1978 type_t *outer_type, size_t top_path_level,
1979 parse_initializer_env_t *env)
1981 if (token.kind == '}') {
1982 /* empty initializer */
1983 return create_empty_initializer();
1986 type_t *orig_type = path->top_type;
1987 type_t *type = NULL;
1989 if (orig_type == NULL) {
1990 /* We are initializing an empty compound. */
1992 type = skip_typeref(orig_type);
1995 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1998 designator_t *designator = NULL;
1999 if (token.kind == '.' || token.kind == '[') {
2000 designator = parse_designation();
2001 goto finish_designator;
2002 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2003 /* GNU-style designator ("identifier: value") */
2004 designator = allocate_ast_zero(sizeof(designator[0]));
2005 designator->source_position = *HERE;
2006 designator->symbol = token.base.symbol;
2011 /* reset path to toplevel, evaluate designator from there */
2012 ascend_to(path, top_path_level);
2013 if (!walk_designator(path, designator, false)) {
2014 /* can't continue after designation error */
2018 initializer_t *designator_initializer
2019 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2020 designator_initializer->designator.designator = designator;
2021 ARR_APP1(initializer_t*, initializers, designator_initializer);
2023 orig_type = path->top_type;
2024 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2029 if (token.kind == '{') {
2030 if (type != NULL && is_type_scalar(type)) {
2031 sub = parse_scalar_initializer(type, env->must_be_constant);
2034 if (env->entity != NULL) {
2035 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2037 errorf(HERE, "extra brace group at end of initializer");
2042 descend_into_subtype(path);
2045 add_anchor_token('}');
2046 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2048 rem_anchor_token('}');
2053 goto error_parse_next;
2055 ascend_from_subtype(path);
2058 /* must be an expression */
2059 expression_t *expression = parse_assignment_expression();
2060 mark_vars_read(expression, NULL);
2062 if (env->must_be_constant && !is_linker_constant(expression)) {
2063 errorf(&expression->base.source_position,
2064 "Initialisation expression '%E' is not constant",
2069 /* we are already outside, ... */
2070 if (outer_type == NULL)
2071 goto error_parse_next;
2072 type_t *const outer_type_skip = skip_typeref(outer_type);
2073 if (is_type_compound(outer_type_skip) &&
2074 !outer_type_skip->compound.compound->complete) {
2075 goto error_parse_next;
2078 source_position_t const* const pos = &expression->base.source_position;
2079 if (env->entity != NULL) {
2080 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2082 warningf(WARN_OTHER, pos, "excess elements in initializer");
2084 goto error_parse_next;
2087 /* handle { "string" } special case */
2088 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2089 sub = initializer_from_expression(outer_type, expression);
2092 if (token.kind != '}') {
2093 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2095 /* TODO: eat , ... */
2100 /* descend into subtypes until expression matches type */
2102 orig_type = path->top_type;
2103 type = skip_typeref(orig_type);
2105 sub = initializer_from_expression(orig_type, expression);
2109 if (!is_type_valid(type)) {
2112 if (is_type_scalar(type)) {
2113 errorf(&expression->base.source_position,
2114 "expression '%E' doesn't match expected type '%T'",
2115 expression, orig_type);
2119 descend_into_subtype(path);
2123 /* update largest index of top array */
2124 const type_path_entry_t *first = &path->path[0];
2125 type_t *first_type = first->type;
2126 first_type = skip_typeref(first_type);
2127 if (is_type_array(first_type)) {
2128 size_t index = first->v.index;
2129 if (index > path->max_index)
2130 path->max_index = index;
2133 /* append to initializers list */
2134 ARR_APP1(initializer_t*, initializers, sub);
2137 if (token.kind == '}') {
2140 add_anchor_token('}');
2142 rem_anchor_token('}');
2143 if (token.kind == '}') {
2148 /* advance to the next declaration if we are not at the end */
2149 advance_current_object(path, top_path_level);
2150 orig_type = path->top_type;
2151 if (orig_type != NULL)
2152 type = skip_typeref(orig_type);
2158 size_t len = ARR_LEN(initializers);
2159 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2160 initializer_t *result = allocate_ast_zero(size);
2161 result->kind = INITIALIZER_LIST;
2162 result->list.len = len;
2163 memcpy(&result->list.initializers, initializers,
2164 len * sizeof(initializers[0]));
2166 DEL_ARR_F(initializers);
2167 ascend_to(path, top_path_level+1);
2172 skip_initializers();
2173 DEL_ARR_F(initializers);
2174 ascend_to(path, top_path_level+1);
2178 static expression_t *make_size_literal(size_t value)
2180 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2181 literal->base.type = type_size_t;
2184 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2185 literal->literal.value = make_string(buf);
2191 * Parses an initializer. Parsers either a compound literal
2192 * (env->declaration == NULL) or an initializer of a declaration.
2194 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2196 type_t *type = skip_typeref(env->type);
2197 size_t max_index = 0;
2198 initializer_t *result;
2200 if (is_type_scalar(type)) {
2201 result = parse_scalar_initializer(type, env->must_be_constant);
2202 } else if (token.kind == '{') {
2206 memset(&path, 0, sizeof(path));
2207 path.top_type = env->type;
2208 path.path = NEW_ARR_F(type_path_entry_t, 0);
2210 descend_into_subtype(&path);
2212 add_anchor_token('}');
2213 result = parse_sub_initializer(&path, env->type, 1, env);
2214 rem_anchor_token('}');
2216 max_index = path.max_index;
2217 DEL_ARR_F(path.path);
2221 /* parse_scalar_initializer() also works in this case: we simply
2222 * have an expression without {} around it */
2223 result = parse_scalar_initializer(type, env->must_be_constant);
2226 /* §6.7.8:22 array initializers for arrays with unknown size determine
2227 * the array type size */
2228 if (is_type_array(type) && type->array.size_expression == NULL
2229 && result != NULL) {
2231 switch (result->kind) {
2232 case INITIALIZER_LIST:
2233 assert(max_index != 0xdeadbeaf);
2234 size = max_index + 1;
2237 case INITIALIZER_STRING:
2238 size = result->string.string.size + 1;
2241 case INITIALIZER_WIDE_STRING:
2242 size = result->wide_string.string.size;
2245 case INITIALIZER_DESIGNATOR:
2246 case INITIALIZER_VALUE:
2247 /* can happen for parse errors */
2252 internal_errorf(HERE, "invalid initializer type");
2255 type_t *new_type = duplicate_type(type);
2257 new_type->array.size_expression = make_size_literal(size);
2258 new_type->array.size_constant = true;
2259 new_type->array.has_implicit_size = true;
2260 new_type->array.size = size;
2261 env->type = new_type;
2267 static void append_entity(scope_t *scope, entity_t *entity)
2269 if (scope->last_entity != NULL) {
2270 scope->last_entity->base.next = entity;
2272 scope->entities = entity;
2274 entity->base.parent_entity = current_entity;
2275 scope->last_entity = entity;
2279 static compound_t *parse_compound_type_specifier(bool is_struct)
2281 source_position_t const pos = *HERE;
2282 eat(is_struct ? T_struct : T_union);
2284 symbol_t *symbol = NULL;
2285 entity_t *entity = NULL;
2286 attribute_t *attributes = NULL;
2288 if (token.kind == T___attribute__) {
2289 attributes = parse_attributes(NULL);
2292 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2293 if (token.kind == T_IDENTIFIER) {
2294 /* the compound has a name, check if we have seen it already */
2295 symbol = token.base.symbol;
2296 entity = get_tag(symbol, kind);
2299 if (entity != NULL) {
2300 if (entity->base.parent_scope != current_scope &&
2301 (token.kind == '{' || token.kind == ';')) {
2302 /* we're in an inner scope and have a definition. Shadow
2303 * existing definition in outer scope */
2305 } else if (entity->compound.complete && token.kind == '{') {
2306 source_position_t const *const ppos = &entity->base.source_position;
2307 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2308 /* clear members in the hope to avoid further errors */
2309 entity->compound.members.entities = NULL;
2312 } else if (token.kind != '{') {
2313 char const *const msg =
2314 is_struct ? "while parsing struct type specifier" :
2315 "while parsing union type specifier";
2316 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2321 if (entity == NULL) {
2322 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2323 entity->compound.alignment = 1;
2324 entity->base.parent_scope = current_scope;
2325 if (symbol != NULL) {
2326 environment_push(entity);
2328 append_entity(current_scope, entity);
2331 if (token.kind == '{') {
2332 parse_compound_type_entries(&entity->compound);
2334 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2335 if (symbol == NULL) {
2336 assert(anonymous_entity == NULL);
2337 anonymous_entity = entity;
2341 if (attributes != NULL) {
2342 handle_entity_attributes(attributes, entity);
2345 return &entity->compound;
2348 static void parse_enum_entries(type_t *const enum_type)
2352 if (token.kind == '}') {
2353 errorf(HERE, "empty enum not allowed");
2358 add_anchor_token('}');
2359 add_anchor_token(',');
2361 add_anchor_token('=');
2362 source_position_t pos;
2363 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2364 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2365 entity->enum_value.enum_type = enum_type;
2366 rem_anchor_token('=');
2369 expression_t *value = parse_constant_expression();
2371 value = create_implicit_cast(value, enum_type);
2372 entity->enum_value.value = value;
2377 record_entity(entity, false);
2378 } while (next_if(',') && token.kind != '}');
2379 rem_anchor_token(',');
2380 rem_anchor_token('}');
2385 static type_t *parse_enum_specifier(void)
2387 source_position_t const pos = *HERE;
2392 switch (token.kind) {
2394 symbol = token.base.symbol;
2395 entity = get_tag(symbol, ENTITY_ENUM);
2398 if (entity != NULL) {
2399 if (entity->base.parent_scope != current_scope &&
2400 (token.kind == '{' || token.kind == ';')) {
2401 /* we're in an inner scope and have a definition. Shadow
2402 * existing definition in outer scope */
2404 } else if (entity->enume.complete && token.kind == '{') {
2405 source_position_t const *const ppos = &entity->base.source_position;
2406 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2417 parse_error_expected("while parsing enum type specifier",
2418 T_IDENTIFIER, '{', NULL);
2422 if (entity == NULL) {
2423 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2424 entity->base.parent_scope = current_scope;
2427 type_t *const type = allocate_type_zero(TYPE_ENUM);
2428 type->enumt.enume = &entity->enume;
2429 type->enumt.base.akind = ATOMIC_TYPE_INT;
2431 if (token.kind == '{') {
2432 if (symbol != NULL) {
2433 environment_push(entity);
2435 append_entity(current_scope, entity);
2436 entity->enume.complete = true;
2438 parse_enum_entries(type);
2439 parse_attributes(NULL);
2441 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2442 if (symbol == NULL) {
2443 assert(anonymous_entity == NULL);
2444 anonymous_entity = entity;
2446 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2447 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2454 * if a symbol is a typedef to another type, return true
2456 static bool is_typedef_symbol(symbol_t *symbol)
2458 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2459 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2462 static type_t *parse_typeof(void)
2468 add_anchor_token(')');
2471 expression_t *expression = NULL;
2473 switch (token.kind) {
2475 if (is_typedef_symbol(token.base.symbol)) {
2477 type = parse_typename();
2480 expression = parse_expression();
2481 type = revert_automatic_type_conversion(expression);
2486 rem_anchor_token(')');
2489 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2490 typeof_type->typeoft.expression = expression;
2491 typeof_type->typeoft.typeof_type = type;
2496 typedef enum specifiers_t {
2497 SPECIFIER_SIGNED = 1 << 0,
2498 SPECIFIER_UNSIGNED = 1 << 1,
2499 SPECIFIER_LONG = 1 << 2,
2500 SPECIFIER_INT = 1 << 3,
2501 SPECIFIER_DOUBLE = 1 << 4,
2502 SPECIFIER_CHAR = 1 << 5,
2503 SPECIFIER_WCHAR_T = 1 << 6,
2504 SPECIFIER_SHORT = 1 << 7,
2505 SPECIFIER_LONG_LONG = 1 << 8,
2506 SPECIFIER_FLOAT = 1 << 9,
2507 SPECIFIER_BOOL = 1 << 10,
2508 SPECIFIER_VOID = 1 << 11,
2509 SPECIFIER_INT8 = 1 << 12,
2510 SPECIFIER_INT16 = 1 << 13,
2511 SPECIFIER_INT32 = 1 << 14,
2512 SPECIFIER_INT64 = 1 << 15,
2513 SPECIFIER_INT128 = 1 << 16,
2514 SPECIFIER_COMPLEX = 1 << 17,
2515 SPECIFIER_IMAGINARY = 1 << 18,
2518 static type_t *get_typedef_type(symbol_t *symbol)
2520 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2521 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2524 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2525 type->typedeft.typedefe = &entity->typedefe;
2530 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2532 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2534 add_anchor_token(')');
2535 add_anchor_token(',');
2539 add_anchor_token('=');
2540 source_position_t pos;
2541 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2542 rem_anchor_token('=');
2544 symbol_t **prop = NULL;
2546 if (streq(prop_sym->string, "put")) {
2547 prop = &property->put_symbol;
2548 } else if (streq(prop_sym->string, "get")) {
2549 prop = &property->get_symbol;
2551 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2555 add_anchor_token(T_IDENTIFIER);
2557 rem_anchor_token(T_IDENTIFIER);
2559 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2561 *prop = sym ? sym : sym_anonymous;
2562 } while (next_if(','));
2563 rem_anchor_token(',');
2564 rem_anchor_token(')');
2566 attribute->a.property = property;
2572 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2574 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2575 if (next_if(T_restrict)) {
2576 kind = ATTRIBUTE_MS_RESTRICT;
2577 } else if (token.kind == T_IDENTIFIER) {
2578 char const *const name = token.base.symbol->string;
2579 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2581 const char *attribute_name = get_attribute_name(k);
2582 if (attribute_name != NULL && streq(attribute_name, name)) {
2588 if (kind == ATTRIBUTE_UNKNOWN) {
2589 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2592 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2596 attribute_t *attribute = allocate_attribute_zero(kind);
2599 if (kind == ATTRIBUTE_MS_PROPERTY) {
2600 return parse_attribute_ms_property(attribute);
2603 /* parse arguments */
2605 attribute->a.arguments = parse_attribute_arguments();
2610 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2614 add_anchor_token(')');
2616 if (token.kind != ')') {
2617 attribute_t **anchor = &first;
2619 while (*anchor != NULL)
2620 anchor = &(*anchor)->next;
2622 attribute_t *attribute
2623 = parse_microsoft_extended_decl_modifier_single();
2624 if (attribute == NULL)
2627 *anchor = attribute;
2628 anchor = &attribute->next;
2629 } while (next_if(','));
2631 rem_anchor_token(')');
2636 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2638 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2639 if (is_declaration(entity)) {
2640 entity->declaration.type = type_error_type;
2641 entity->declaration.implicit = true;
2642 } else if (kind == ENTITY_TYPEDEF) {
2643 entity->typedefe.type = type_error_type;
2644 entity->typedefe.builtin = true;
2646 if (kind != ENTITY_COMPOUND_MEMBER)
2647 record_entity(entity, false);
2651 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2653 type_t *type = NULL;
2654 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2655 unsigned type_specifiers = 0;
2656 bool newtype = false;
2657 bool saw_error = false;
2659 memset(specifiers, 0, sizeof(*specifiers));
2660 specifiers->source_position = *HERE;
2663 specifiers->attributes = parse_attributes(specifiers->attributes);
2665 switch (token.kind) {
2667 #define MATCH_STORAGE_CLASS(token, class) \
2669 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2670 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2672 specifiers->storage_class = class; \
2673 if (specifiers->thread_local) \
2674 goto check_thread_storage_class; \
2678 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2679 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2680 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2681 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2682 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2685 specifiers->attributes
2686 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2690 if (specifiers->thread_local) {
2691 errorf(HERE, "duplicate '__thread'");
2693 specifiers->thread_local = true;
2694 check_thread_storage_class:
2695 switch (specifiers->storage_class) {
2696 case STORAGE_CLASS_EXTERN:
2697 case STORAGE_CLASS_NONE:
2698 case STORAGE_CLASS_STATIC:
2702 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2703 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2704 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2705 wrong_thread_storage_class:
2706 errorf(HERE, "'__thread' used with '%s'", wrong);
2713 /* type qualifiers */
2714 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2716 qualifiers |= qualifier; \
2720 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2721 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2722 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2723 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2724 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2725 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2726 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2727 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2729 /* type specifiers */
2730 #define MATCH_SPECIFIER(token, specifier, name) \
2732 if (type_specifiers & specifier) { \
2733 errorf(HERE, "multiple " name " type specifiers given"); \
2735 type_specifiers |= specifier; \
2740 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2741 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2742 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2743 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2744 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2745 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2746 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2747 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2748 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2749 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2750 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2751 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2752 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2753 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2754 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2755 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2756 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2757 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2761 specifiers->is_inline = true;
2765 case T__forceinline:
2766 eat(T__forceinline);
2767 specifiers->modifiers |= DM_FORCEINLINE;
2772 if (type_specifiers & SPECIFIER_LONG_LONG) {
2773 errorf(HERE, "too many long type specifiers given");
2774 } else if (type_specifiers & SPECIFIER_LONG) {
2775 type_specifiers |= SPECIFIER_LONG_LONG;
2777 type_specifiers |= SPECIFIER_LONG;
2782 #define CHECK_DOUBLE_TYPE() \
2783 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2786 CHECK_DOUBLE_TYPE();
2787 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2789 type->compound.compound = parse_compound_type_specifier(true);
2792 CHECK_DOUBLE_TYPE();
2793 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2794 type->compound.compound = parse_compound_type_specifier(false);
2797 CHECK_DOUBLE_TYPE();
2798 type = parse_enum_specifier();
2801 CHECK_DOUBLE_TYPE();
2802 type = parse_typeof();
2804 case T___builtin_va_list:
2805 CHECK_DOUBLE_TYPE();
2806 type = duplicate_type(type_valist);
2807 eat(T___builtin_va_list);
2810 case T_IDENTIFIER: {
2811 /* only parse identifier if we haven't found a type yet */
2812 if (type != NULL || type_specifiers != 0) {
2813 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2814 * declaration, so it doesn't generate errors about expecting '(' or
2816 switch (look_ahead(1)->kind) {
2823 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2827 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2832 goto finish_specifiers;
2836 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2837 if (typedef_type == NULL) {
2838 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2839 * declaration, so it doesn't generate 'implicit int' followed by more
2840 * errors later on. */
2841 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2847 errorf(HERE, "%K does not name a type", &token);
2849 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2851 type = allocate_type_zero(TYPE_TYPEDEF);
2852 type->typedeft.typedefe = &entity->typedefe;
2860 goto finish_specifiers;
2865 type = typedef_type;
2869 /* function specifier */
2871 goto finish_specifiers;
2876 specifiers->attributes = parse_attributes(specifiers->attributes);
2878 if (type == NULL || (saw_error && type_specifiers != 0)) {
2879 atomic_type_kind_t atomic_type;
2881 /* match valid basic types */
2882 switch (type_specifiers) {
2883 case SPECIFIER_VOID:
2884 atomic_type = ATOMIC_TYPE_VOID;
2886 case SPECIFIER_WCHAR_T:
2887 atomic_type = ATOMIC_TYPE_WCHAR_T;
2889 case SPECIFIER_CHAR:
2890 atomic_type = ATOMIC_TYPE_CHAR;
2892 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2893 atomic_type = ATOMIC_TYPE_SCHAR;
2895 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2896 atomic_type = ATOMIC_TYPE_UCHAR;
2898 case SPECIFIER_SHORT:
2899 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2900 case SPECIFIER_SHORT | SPECIFIER_INT:
2901 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2902 atomic_type = ATOMIC_TYPE_SHORT;
2904 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2905 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2906 atomic_type = ATOMIC_TYPE_USHORT;
2909 case SPECIFIER_SIGNED:
2910 case SPECIFIER_SIGNED | SPECIFIER_INT:
2911 atomic_type = ATOMIC_TYPE_INT;
2913 case SPECIFIER_UNSIGNED:
2914 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2915 atomic_type = ATOMIC_TYPE_UINT;
2917 case SPECIFIER_LONG:
2918 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2919 case SPECIFIER_LONG | SPECIFIER_INT:
2920 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2921 atomic_type = ATOMIC_TYPE_LONG;
2923 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2924 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2925 atomic_type = ATOMIC_TYPE_ULONG;
2928 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2929 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2930 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2931 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2933 atomic_type = ATOMIC_TYPE_LONGLONG;
2934 goto warn_about_long_long;
2936 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2937 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2939 atomic_type = ATOMIC_TYPE_ULONGLONG;
2940 warn_about_long_long:
2941 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2944 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2945 atomic_type = unsigned_int8_type_kind;
2948 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2949 atomic_type = unsigned_int16_type_kind;
2952 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2953 atomic_type = unsigned_int32_type_kind;
2956 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2957 atomic_type = unsigned_int64_type_kind;
2960 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2961 atomic_type = unsigned_int128_type_kind;
2964 case SPECIFIER_INT8:
2965 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2966 atomic_type = int8_type_kind;
2969 case SPECIFIER_INT16:
2970 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2971 atomic_type = int16_type_kind;
2974 case SPECIFIER_INT32:
2975 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2976 atomic_type = int32_type_kind;
2979 case SPECIFIER_INT64:
2980 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2981 atomic_type = int64_type_kind;
2984 case SPECIFIER_INT128:
2985 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2986 atomic_type = int128_type_kind;
2989 case SPECIFIER_FLOAT:
2990 atomic_type = ATOMIC_TYPE_FLOAT;
2992 case SPECIFIER_DOUBLE:
2993 atomic_type = ATOMIC_TYPE_DOUBLE;
2995 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2996 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2998 case SPECIFIER_BOOL:
2999 atomic_type = ATOMIC_TYPE_BOOL;
3001 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3002 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3003 atomic_type = ATOMIC_TYPE_FLOAT;
3005 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3006 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3007 atomic_type = ATOMIC_TYPE_DOUBLE;
3009 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3010 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3011 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3014 /* invalid specifier combination, give an error message */
3015 source_position_t const* const pos = &specifiers->source_position;
3016 if (type_specifiers == 0) {
3018 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3019 if (!(c_mode & _CXX) && !strict_mode) {
3020 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3021 atomic_type = ATOMIC_TYPE_INT;
3024 errorf(pos, "no type specifiers given in declaration");
3027 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3028 (type_specifiers & SPECIFIER_UNSIGNED)) {
3029 errorf(pos, "signed and unsigned specifiers given");
3030 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3031 errorf(pos, "only integer types can be signed or unsigned");
3033 errorf(pos, "multiple datatypes in declaration");
3039 if (type_specifiers & SPECIFIER_COMPLEX) {
3040 type = allocate_type_zero(TYPE_COMPLEX);
3041 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3042 type = allocate_type_zero(TYPE_IMAGINARY);
3044 type = allocate_type_zero(TYPE_ATOMIC);
3046 type->atomic.akind = atomic_type;
3048 } else if (type_specifiers != 0) {
3049 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3052 /* FIXME: check type qualifiers here */
3053 type->base.qualifiers = qualifiers;
3056 type = identify_new_type(type);
3058 type = typehash_insert(type);
3061 if (specifiers->attributes != NULL)
3062 type = handle_type_attributes(specifiers->attributes, type);
3063 specifiers->type = type;
3067 specifiers->type = type_error_type;
3070 static type_qualifiers_t parse_type_qualifiers(void)
3072 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3075 switch (token.kind) {
3076 /* type qualifiers */
3077 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3078 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3079 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3080 /* microsoft extended type modifiers */
3081 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3082 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3083 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3084 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3085 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3094 * Parses an K&R identifier list
3096 static void parse_identifier_list(scope_t *scope)
3098 assert(token.kind == T_IDENTIFIER);
3100 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3101 /* a K&R parameter has no type, yet */
3105 append_entity(scope, entity);
3106 } while (next_if(',') && token.kind == T_IDENTIFIER);
3109 static entity_t *parse_parameter(void)
3111 declaration_specifiers_t specifiers;
3112 parse_declaration_specifiers(&specifiers);
3114 entity_t *entity = parse_declarator(&specifiers,
3115 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3116 anonymous_entity = NULL;
3120 static void semantic_parameter_incomplete(const entity_t *entity)
3122 assert(entity->kind == ENTITY_PARAMETER);
3124 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3125 * list in a function declarator that is part of a
3126 * definition of that function shall not have
3127 * incomplete type. */
3128 type_t *type = skip_typeref(entity->declaration.type);
3129 if (is_type_incomplete(type)) {
3130 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3134 static bool has_parameters(void)
3136 /* func(void) is not a parameter */
3137 if (look_ahead(1)->kind != ')')
3139 if (token.kind == T_IDENTIFIER) {
3140 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3143 if (entity->kind != ENTITY_TYPEDEF)
3145 type_t const *const type = skip_typeref(entity->typedefe.type);
3146 if (!is_type_void(type))
3148 if (c_mode & _CXX) {
3149 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3150 * is not allowed. */
3151 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3152 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3153 /* §6.7.5.3:10 Qualification is not allowed here. */
3154 errorf(HERE, "'void' as parameter must not have type qualifiers");
3156 } else if (token.kind != T_void) {
3164 * Parses function type parameters (and optionally creates variable_t entities
3165 * for them in a scope)
3167 static void parse_parameters(function_type_t *type, scope_t *scope)
3169 add_anchor_token(')');
3172 if (token.kind == T_IDENTIFIER &&
3173 !is_typedef_symbol(token.base.symbol) &&
3174 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3175 type->kr_style_parameters = true;
3176 parse_identifier_list(scope);
3177 } else if (token.kind == ')') {
3178 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3179 if (!(c_mode & _CXX))
3180 type->unspecified_parameters = true;
3181 } else if (has_parameters()) {
3182 function_parameter_t **anchor = &type->parameters;
3183 add_anchor_token(',');
3185 switch (token.kind) {
3188 type->variadic = true;
3189 goto parameters_finished;
3194 entity_t *entity = parse_parameter();
3195 if (entity->kind == ENTITY_TYPEDEF) {
3196 errorf(&entity->base.source_position,
3197 "typedef not allowed as function parameter");
3200 assert(is_declaration(entity));
3202 semantic_parameter_incomplete(entity);
3204 function_parameter_t *const parameter =
3205 allocate_parameter(entity->declaration.type);
3207 if (scope != NULL) {
3208 append_entity(scope, entity);
3211 *anchor = parameter;
3212 anchor = ¶meter->next;
3217 goto parameters_finished;
3219 } while (next_if(','));
3220 parameters_finished:
3221 rem_anchor_token(',');
3224 rem_anchor_token(')');
3228 typedef enum construct_type_kind_t {
3229 CONSTRUCT_POINTER = 1,
3230 CONSTRUCT_REFERENCE,
3233 } construct_type_kind_t;
3235 typedef union construct_type_t construct_type_t;
3237 typedef struct construct_type_base_t {
3238 construct_type_kind_t kind;
3239 source_position_t pos;
3240 construct_type_t *next;
3241 } construct_type_base_t;
3243 typedef struct parsed_pointer_t {
3244 construct_type_base_t base;
3245 type_qualifiers_t type_qualifiers;
3246 variable_t *base_variable; /**< MS __based extension. */
3249 typedef struct parsed_reference_t {
3250 construct_type_base_t base;
3251 } parsed_reference_t;
3253 typedef struct construct_function_type_t {
3254 construct_type_base_t base;
3255 type_t *function_type;
3256 } construct_function_type_t;
3258 typedef struct parsed_array_t {
3259 construct_type_base_t base;
3260 type_qualifiers_t type_qualifiers;
3266 union construct_type_t {
3267 construct_type_kind_t kind;
3268 construct_type_base_t base;
3269 parsed_pointer_t pointer;
3270 parsed_reference_t reference;
3271 construct_function_type_t function;
3272 parsed_array_t array;
3275 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3277 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3278 memset(cons, 0, size);
3280 cons->base.pos = *HERE;
3285 static construct_type_t *parse_pointer_declarator(void)
3287 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3289 cons->pointer.type_qualifiers = parse_type_qualifiers();
3290 //cons->pointer.base_variable = base_variable;
3295 /* ISO/IEC 14882:1998(E) §8.3.2 */
3296 static construct_type_t *parse_reference_declarator(void)
3298 if (!(c_mode & _CXX))
3299 errorf(HERE, "references are only available for C++");
3301 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3308 static construct_type_t *parse_array_declarator(void)
3310 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3311 parsed_array_t *const array = &cons->array;
3314 add_anchor_token(']');
3316 bool is_static = next_if(T_static);
3318 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3321 is_static = next_if(T_static);
3323 array->type_qualifiers = type_qualifiers;
3324 array->is_static = is_static;
3326 expression_t *size = NULL;
3327 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3328 array->is_variable = true;
3330 } else if (token.kind != ']') {
3331 size = parse_assignment_expression();
3333 /* §6.7.5.2:1 Array size must have integer type */
3334 type_t *const orig_type = size->base.type;
3335 type_t *const type = skip_typeref(orig_type);
3336 if (!is_type_integer(type) && is_type_valid(type)) {
3337 errorf(&size->base.source_position,
3338 "array size '%E' must have integer type but has type '%T'",
3343 mark_vars_read(size, NULL);
3346 if (is_static && size == NULL)
3347 errorf(&array->base.pos, "static array parameters require a size");
3349 rem_anchor_token(']');
3355 static construct_type_t *parse_function_declarator(scope_t *scope)
3357 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3359 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3360 function_type_t *ftype = &type->function;
3362 ftype->linkage = current_linkage;
3363 ftype->calling_convention = CC_DEFAULT;
3365 parse_parameters(ftype, scope);
3367 cons->function.function_type = type;
3372 typedef struct parse_declarator_env_t {
3373 bool may_be_abstract : 1;
3374 bool must_be_abstract : 1;
3375 decl_modifiers_t modifiers;
3377 source_position_t source_position;
3379 attribute_t *attributes;
3380 } parse_declarator_env_t;
3383 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3385 /* construct a single linked list of construct_type_t's which describe
3386 * how to construct the final declarator type */
3387 construct_type_t *first = NULL;
3388 construct_type_t **anchor = &first;
3390 env->attributes = parse_attributes(env->attributes);
3393 construct_type_t *type;
3394 //variable_t *based = NULL; /* MS __based extension */
3395 switch (token.kind) {
3397 type = parse_reference_declarator();
3401 panic("based not supported anymore");
3406 type = parse_pointer_declarator();
3410 goto ptr_operator_end;
3414 anchor = &type->base.next;
3416 /* TODO: find out if this is correct */
3417 env->attributes = parse_attributes(env->attributes);
3421 construct_type_t *inner_types = NULL;
3423 switch (token.kind) {
3425 if (env->must_be_abstract) {
3426 errorf(HERE, "no identifier expected in typename");
3428 env->symbol = token.base.symbol;
3429 env->source_position = *HERE;
3435 /* Parenthesized declarator or function declarator? */
3436 token_t const *const la1 = look_ahead(1);
3437 switch (la1->kind) {
3439 if (is_typedef_symbol(la1->base.symbol)) {
3441 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3442 * interpreted as ``function with no parameter specification'', rather
3443 * than redundant parentheses around the omitted identifier. */
3445 /* Function declarator. */
3446 if (!env->may_be_abstract) {
3447 errorf(HERE, "function declarator must have a name");
3454 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3455 /* Paranthesized declarator. */
3457 add_anchor_token(')');
3458 inner_types = parse_inner_declarator(env);
3459 if (inner_types != NULL) {
3460 /* All later declarators only modify the return type */
3461 env->must_be_abstract = true;
3463 rem_anchor_token(')');
3472 if (env->may_be_abstract)
3474 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3479 construct_type_t **const p = anchor;
3482 construct_type_t *type;
3483 switch (token.kind) {
3485 scope_t *scope = NULL;
3486 if (!env->must_be_abstract) {
3487 scope = &env->parameters;
3490 type = parse_function_declarator(scope);
3494 type = parse_array_declarator();
3497 goto declarator_finished;
3500 /* insert in the middle of the list (at p) */
3501 type->base.next = *p;
3504 anchor = &type->base.next;
3507 declarator_finished:
3508 /* append inner_types at the end of the list, we don't to set anchor anymore
3509 * as it's not needed anymore */
3510 *anchor = inner_types;
3515 static type_t *construct_declarator_type(construct_type_t *construct_list,
3518 construct_type_t *iter = construct_list;
3519 for (; iter != NULL; iter = iter->base.next) {
3520 source_position_t const* const pos = &iter->base.pos;
3521 switch (iter->kind) {
3522 case CONSTRUCT_FUNCTION: {
3523 construct_function_type_t *function = &iter->function;
3524 type_t *function_type = function->function_type;
3526 function_type->function.return_type = type;
3528 type_t *skipped_return_type = skip_typeref(type);
3530 if (is_type_function(skipped_return_type)) {
3531 errorf(pos, "function returning function is not allowed");
3532 } else if (is_type_array(skipped_return_type)) {
3533 errorf(pos, "function returning array is not allowed");
3535 if (skipped_return_type->base.qualifiers != 0) {
3536 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3540 /* The function type was constructed earlier. Freeing it here will
3541 * destroy other types. */
3542 type = typehash_insert(function_type);
3546 case CONSTRUCT_POINTER: {
3547 if (is_type_reference(skip_typeref(type)))
3548 errorf(pos, "cannot declare a pointer to reference");
3550 parsed_pointer_t *pointer = &iter->pointer;
3551 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3555 case CONSTRUCT_REFERENCE:
3556 if (is_type_reference(skip_typeref(type)))
3557 errorf(pos, "cannot declare a reference to reference");
3559 type = make_reference_type(type);
3562 case CONSTRUCT_ARRAY: {
3563 if (is_type_reference(skip_typeref(type)))
3564 errorf(pos, "cannot declare an array of references");
3566 parsed_array_t *array = &iter->array;
3567 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3569 expression_t *size_expression = array->size;
3570 if (size_expression != NULL) {
3572 = create_implicit_cast(size_expression, type_size_t);
3575 array_type->base.qualifiers = array->type_qualifiers;
3576 array_type->array.element_type = type;
3577 array_type->array.is_static = array->is_static;
3578 array_type->array.is_variable = array->is_variable;
3579 array_type->array.size_expression = size_expression;
3581 if (size_expression != NULL) {
3582 switch (is_constant_expression(size_expression)) {
3583 case EXPR_CLASS_CONSTANT: {
3584 long const size = fold_constant_to_int(size_expression);
3585 array_type->array.size = size;
3586 array_type->array.size_constant = true;
3587 /* §6.7.5.2:1 If the expression is a constant expression,
3588 * it shall have a value greater than zero. */
3590 errorf(&size_expression->base.source_position,
3591 "size of array must be greater than zero");
3592 } else if (size == 0 && !GNU_MODE) {
3593 errorf(&size_expression->base.source_position,
3594 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3599 case EXPR_CLASS_VARIABLE:
3600 array_type->array.is_vla = true;
3603 case EXPR_CLASS_ERROR:
3608 type_t *skipped_type = skip_typeref(type);
3610 if (is_type_incomplete(skipped_type)) {
3611 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3612 } else if (is_type_function(skipped_type)) {
3613 errorf(pos, "array of functions is not allowed");
3615 type = identify_new_type(array_type);
3619 internal_errorf(pos, "invalid type construction found");
3625 static type_t *automatic_type_conversion(type_t *orig_type);
3627 static type_t *semantic_parameter(const source_position_t *pos,
3629 const declaration_specifiers_t *specifiers,
3630 entity_t const *const param)
3632 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3633 * shall be adjusted to ``qualified pointer to type'',
3635 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3636 * type'' shall be adjusted to ``pointer to function
3637 * returning type'', as in 6.3.2.1. */
3638 type = automatic_type_conversion(type);
3640 if (specifiers->is_inline && is_type_valid(type)) {
3641 errorf(pos, "'%N' declared 'inline'", param);
3644 /* §6.9.1:6 The declarations in the declaration list shall contain
3645 * no storage-class specifier other than register and no
3646 * initializations. */
3647 if (specifiers->thread_local || (
3648 specifiers->storage_class != STORAGE_CLASS_NONE &&
3649 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3651 errorf(pos, "invalid storage class for '%N'", param);
3654 /* delay test for incomplete type, because we might have (void)
3655 * which is legal but incomplete... */
3660 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3661 declarator_flags_t flags)
3663 parse_declarator_env_t env;
3664 memset(&env, 0, sizeof(env));
3665 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3667 construct_type_t *construct_type = parse_inner_declarator(&env);
3669 construct_declarator_type(construct_type, specifiers->type);
3670 type_t *type = skip_typeref(orig_type);
3672 if (construct_type != NULL) {
3673 obstack_free(&temp_obst, construct_type);
3676 attribute_t *attributes = parse_attributes(env.attributes);
3677 /* append (shared) specifier attribute behind attributes of this
3679 attribute_t **anchor = &attributes;
3680 while (*anchor != NULL)
3681 anchor = &(*anchor)->next;
3682 *anchor = specifiers->attributes;
3685 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3686 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3687 entity->typedefe.type = orig_type;
3689 if (anonymous_entity != NULL) {
3690 if (is_type_compound(type)) {
3691 assert(anonymous_entity->compound.alias == NULL);
3692 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3693 anonymous_entity->kind == ENTITY_UNION);
3694 anonymous_entity->compound.alias = entity;
3695 anonymous_entity = NULL;
3696 } else if (is_type_enum(type)) {
3697 assert(anonymous_entity->enume.alias == NULL);
3698 assert(anonymous_entity->kind == ENTITY_ENUM);
3699 anonymous_entity->enume.alias = entity;
3700 anonymous_entity = NULL;
3704 /* create a declaration type entity */
3705 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3706 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3707 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3709 if (env.symbol != NULL) {
3710 if (specifiers->is_inline && is_type_valid(type)) {
3711 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3714 if (specifiers->thread_local ||
3715 specifiers->storage_class != STORAGE_CLASS_NONE) {
3716 errorf(&env.source_position, "'%N' must have no storage class", entity);
3719 } else if (flags & DECL_IS_PARAMETER) {
3720 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3721 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3722 } else if (is_type_function(type)) {
3723 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3724 entity->function.is_inline = specifiers->is_inline;
3725 entity->function.elf_visibility = default_visibility;
3726 entity->function.parameters = env.parameters;
3728 if (env.symbol != NULL) {
3729 /* this needs fixes for C++ */
3730 bool in_function_scope = current_function != NULL;
3732 if (specifiers->thread_local || (
3733 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3734 specifiers->storage_class != STORAGE_CLASS_NONE &&
3735 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3737 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3741 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3742 entity->variable.elf_visibility = default_visibility;
3743 entity->variable.thread_local = specifiers->thread_local;
3745 if (env.symbol != NULL) {
3746 if (specifiers->is_inline && is_type_valid(type)) {
3747 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3750 bool invalid_storage_class = false;
3751 if (current_scope == file_scope) {
3752 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3753 specifiers->storage_class != STORAGE_CLASS_NONE &&
3754 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3755 invalid_storage_class = true;
3758 if (specifiers->thread_local &&
3759 specifiers->storage_class == STORAGE_CLASS_NONE) {
3760 invalid_storage_class = true;
3763 if (invalid_storage_class) {
3764 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3769 entity->declaration.type = orig_type;
3770 entity->declaration.alignment = get_type_alignment(orig_type);
3771 entity->declaration.modifiers = env.modifiers;
3772 entity->declaration.attributes = attributes;
3774 storage_class_t storage_class = specifiers->storage_class;
3775 entity->declaration.declared_storage_class = storage_class;
3777 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3778 storage_class = STORAGE_CLASS_AUTO;
3779 entity->declaration.storage_class = storage_class;
3782 if (attributes != NULL) {
3783 handle_entity_attributes(attributes, entity);
3786 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3787 adapt_special_functions(&entity->function);
3793 static type_t *parse_abstract_declarator(type_t *base_type)
3795 parse_declarator_env_t env;
3796 memset(&env, 0, sizeof(env));
3797 env.may_be_abstract = true;
3798 env.must_be_abstract = true;
3800 construct_type_t *construct_type = parse_inner_declarator(&env);
3802 type_t *result = construct_declarator_type(construct_type, base_type);
3803 if (construct_type != NULL) {
3804 obstack_free(&temp_obst, construct_type);
3806 result = handle_type_attributes(env.attributes, result);
3812 * Check if the declaration of main is suspicious. main should be a
3813 * function with external linkage, returning int, taking either zero
3814 * arguments, two, or three arguments of appropriate types, ie.
3816 * int main([ int argc, char **argv [, char **env ] ]).
3818 * @param decl the declaration to check
3819 * @param type the function type of the declaration
3821 static void check_main(const entity_t *entity)
3823 const source_position_t *pos = &entity->base.source_position;
3824 if (entity->kind != ENTITY_FUNCTION) {
3825 warningf(WARN_MAIN, pos, "'main' is not a function");
3829 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3830 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3833 type_t *type = skip_typeref(entity->declaration.type);
3834 assert(is_type_function(type));
3836 function_type_t const *const func_type = &type->function;
3837 type_t *const ret_type = func_type->return_type;
3838 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3839 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3841 const function_parameter_t *parm = func_type->parameters;
3843 type_t *const first_type = skip_typeref(parm->type);
3844 type_t *const first_type_unqual = get_unqualified_type(first_type);
3845 if (!types_compatible(first_type_unqual, type_int)) {
3846 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3850 type_t *const second_type = skip_typeref(parm->type);
3851 type_t *const second_type_unqual
3852 = get_unqualified_type(second_type);
3853 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3854 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3858 type_t *const third_type = skip_typeref(parm->type);
3859 type_t *const third_type_unqual
3860 = get_unqualified_type(third_type);
3861 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3862 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3866 goto warn_arg_count;
3870 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3875 static void error_redefined_as_different_kind(const source_position_t *pos,
3876 const entity_t *old, entity_kind_t new_kind)
3878 char const *const what = get_entity_kind_name(new_kind);
3879 source_position_t const *const ppos = &old->base.source_position;
3880 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3883 static bool is_entity_valid(entity_t *const ent)
3885 if (is_declaration(ent)) {
3886 return is_type_valid(skip_typeref(ent->declaration.type));
3887 } else if (ent->kind == ENTITY_TYPEDEF) {
3888 return is_type_valid(skip_typeref(ent->typedefe.type));
3893 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3895 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3896 if (attributes_equal(tattr, attr))
3903 * test wether new_list contains any attributes not included in old_list
3905 static bool has_new_attributes(const attribute_t *old_list,
3906 const attribute_t *new_list)
3908 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3909 if (!contains_attribute(old_list, attr))
3916 * Merge in attributes from an attribute list (probably from a previous
3917 * declaration with the same name). Warning: destroys the old structure
3918 * of the attribute list - don't reuse attributes after this call.
3920 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3923 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3925 if (contains_attribute(decl->attributes, attr))
3928 /* move attribute to new declarations attributes list */
3929 attr->next = decl->attributes;
3930 decl->attributes = attr;
3934 static bool is_main(entity_t*);
3937 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3938 * for various problems that occur for multiple definitions
3940 entity_t *record_entity(entity_t *entity, const bool is_definition)
3942 const symbol_t *const symbol = entity->base.symbol;
3943 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3944 const source_position_t *pos = &entity->base.source_position;
3946 /* can happen in error cases */
3950 assert(!entity->base.parent_scope);
3951 assert(current_scope);
3952 entity->base.parent_scope = current_scope;
3954 entity_t *const previous_entity = get_entity(symbol, namespc);
3955 /* pushing the same entity twice will break the stack structure */
3956 assert(previous_entity != entity);
3958 if (entity->kind == ENTITY_FUNCTION) {
3959 type_t *const orig_type = entity->declaration.type;
3960 type_t *const type = skip_typeref(orig_type);
3962 assert(is_type_function(type));
3963 if (type->function.unspecified_parameters &&
3964 previous_entity == NULL &&
3965 !entity->declaration.implicit) {
3966 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3969 if (is_main(entity)) {
3974 if (is_declaration(entity) &&
3975 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3976 current_scope != file_scope &&
3977 !entity->declaration.implicit) {
3978 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3981 if (previous_entity != NULL) {
3982 source_position_t const *const ppos = &previous_entity->base.source_position;
3984 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3985 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3986 assert(previous_entity->kind == ENTITY_PARAMETER);
3987 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3991 if (previous_entity->base.parent_scope == current_scope) {
3992 if (previous_entity->kind != entity->kind) {
3993 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3994 error_redefined_as_different_kind(pos, previous_entity,
3999 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4000 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4003 if (previous_entity->kind == ENTITY_TYPEDEF) {
4004 type_t *const type = skip_typeref(entity->typedefe.type);
4005 type_t *const prev_type
4006 = skip_typeref(previous_entity->typedefe.type);
4007 if (c_mode & _CXX) {
4008 /* C++ allows double typedef if they are identical
4009 * (after skipping typedefs) */
4010 if (type == prev_type)
4013 /* GCC extension: redef in system headers is allowed */
4014 if ((pos->is_system_header || ppos->is_system_header) &&
4015 types_compatible(type, prev_type))
4018 errorf(pos, "redefinition of '%N' (declared %P)",
4023 /* at this point we should have only VARIABLES or FUNCTIONS */
4024 assert(is_declaration(previous_entity) && is_declaration(entity));
4026 declaration_t *const prev_decl = &previous_entity->declaration;
4027 declaration_t *const decl = &entity->declaration;
4029 /* can happen for K&R style declarations */
4030 if (prev_decl->type == NULL &&
4031 previous_entity->kind == ENTITY_PARAMETER &&
4032 entity->kind == ENTITY_PARAMETER) {
4033 prev_decl->type = decl->type;
4034 prev_decl->storage_class = decl->storage_class;
4035 prev_decl->declared_storage_class = decl->declared_storage_class;
4036 prev_decl->modifiers = decl->modifiers;
4037 return previous_entity;
4040 type_t *const type = skip_typeref(decl->type);
4041 type_t *const prev_type = skip_typeref(prev_decl->type);
4043 if (!types_compatible(type, prev_type)) {
4044 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4046 unsigned old_storage_class = prev_decl->storage_class;
4048 if (is_definition &&
4050 !(prev_decl->modifiers & DM_USED) &&
4051 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4052 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4055 storage_class_t new_storage_class = decl->storage_class;
4057 /* pretend no storage class means extern for function
4058 * declarations (except if the previous declaration is neither
4059 * none nor extern) */
4060 if (entity->kind == ENTITY_FUNCTION) {
4061 /* the previous declaration could have unspecified parameters or
4062 * be a typedef, so use the new type */
4063 if (prev_type->function.unspecified_parameters || is_definition)
4064 prev_decl->type = type;
4066 switch (old_storage_class) {
4067 case STORAGE_CLASS_NONE:
4068 old_storage_class = STORAGE_CLASS_EXTERN;
4071 case STORAGE_CLASS_EXTERN:
4072 if (is_definition) {
4073 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4074 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4076 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4077 new_storage_class = STORAGE_CLASS_EXTERN;
4084 } else if (is_type_incomplete(prev_type)) {
4085 prev_decl->type = type;
4088 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4089 new_storage_class == STORAGE_CLASS_EXTERN) {
4091 warn_redundant_declaration: ;
4093 = has_new_attributes(prev_decl->attributes,
4095 if (has_new_attrs) {
4096 merge_in_attributes(decl, prev_decl->attributes);
4097 } else if (!is_definition &&
4098 is_type_valid(prev_type) &&
4099 !pos->is_system_header) {
4100 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4102 } else if (current_function == NULL) {
4103 if (old_storage_class != STORAGE_CLASS_STATIC &&
4104 new_storage_class == STORAGE_CLASS_STATIC) {
4105 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4106 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4107 prev_decl->storage_class = STORAGE_CLASS_NONE;
4108 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4110 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4112 goto error_redeclaration;
4113 goto warn_redundant_declaration;
4115 } else if (is_type_valid(prev_type)) {
4116 if (old_storage_class == new_storage_class) {
4117 error_redeclaration:
4118 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4120 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4125 prev_decl->modifiers |= decl->modifiers;
4126 if (entity->kind == ENTITY_FUNCTION) {
4127 previous_entity->function.is_inline |= entity->function.is_inline;
4129 return previous_entity;
4133 if (is_warn_on(why = WARN_SHADOW) ||
4134 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4135 char const *const what = get_entity_kind_name(previous_entity->kind);
4136 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4140 if (entity->kind == ENTITY_FUNCTION) {
4141 if (is_definition &&
4142 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4144 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4145 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4147 goto warn_missing_declaration;
4150 } else if (entity->kind == ENTITY_VARIABLE) {
4151 if (current_scope == file_scope &&
4152 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4153 !entity->declaration.implicit) {
4154 warn_missing_declaration:
4155 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4160 environment_push(entity);
4161 append_entity(current_scope, entity);
4166 static void parser_error_multiple_definition(entity_t *entity,
4167 const source_position_t *source_position)
4169 errorf(source_position, "redefinition of '%N' (declared %P)", entity, &entity->base.source_position);
4172 static bool is_declaration_specifier(const token_t *token)
4174 switch (token->kind) {
4178 return is_typedef_symbol(token->base.symbol);
4185 static void parse_init_declarator_rest(entity_t *entity)
4187 type_t *orig_type = type_error_type;
4189 if (entity->base.kind == ENTITY_TYPEDEF) {
4190 source_position_t const *const pos = &entity->base.source_position;
4191 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4193 assert(is_declaration(entity));
4194 orig_type = entity->declaration.type;
4197 type_t *type = skip_typeref(orig_type);
4199 if (entity->kind == ENTITY_VARIABLE
4200 && entity->variable.initializer != NULL) {
4201 parser_error_multiple_definition(entity, HERE);
4205 declaration_t *const declaration = &entity->declaration;
4206 bool must_be_constant = false;
4207 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4208 entity->base.parent_scope == file_scope) {
4209 must_be_constant = true;
4212 if (is_type_function(type)) {
4213 source_position_t const *const pos = &entity->base.source_position;
4214 errorf(pos, "'%N' is initialized like a variable", entity);
4215 orig_type = type_error_type;
4218 parse_initializer_env_t env;
4219 env.type = orig_type;
4220 env.must_be_constant = must_be_constant;
4221 env.entity = entity;
4223 initializer_t *initializer = parse_initializer(&env);
4225 if (entity->kind == ENTITY_VARIABLE) {
4226 /* §6.7.5:22 array initializers for arrays with unknown size
4227 * determine the array type size */
4228 declaration->type = env.type;
4229 entity->variable.initializer = initializer;
4233 /* parse rest of a declaration without any declarator */
4234 static void parse_anonymous_declaration_rest(
4235 const declaration_specifiers_t *specifiers)
4238 anonymous_entity = NULL;
4240 source_position_t const *const pos = &specifiers->source_position;
4241 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4242 specifiers->thread_local) {
4243 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4246 type_t *type = specifiers->type;
4247 switch (type->kind) {
4248 case TYPE_COMPOUND_STRUCT:
4249 case TYPE_COMPOUND_UNION: {
4250 if (type->compound.compound->base.symbol == NULL) {
4251 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4260 warningf(WARN_OTHER, pos, "empty declaration");
4265 static void check_variable_type_complete(entity_t *ent)
4267 if (ent->kind != ENTITY_VARIABLE)
4270 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4271 * type for the object shall be complete [...] */
4272 declaration_t *decl = &ent->declaration;
4273 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4274 decl->storage_class == STORAGE_CLASS_STATIC)
4277 type_t *const type = skip_typeref(decl->type);
4278 if (!is_type_incomplete(type))
4281 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4282 * are given length one. */
4283 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4284 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4288 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4292 static void parse_declaration_rest(entity_t *ndeclaration,
4293 const declaration_specifiers_t *specifiers,
4294 parsed_declaration_func finished_declaration,
4295 declarator_flags_t flags)
4297 add_anchor_token(';');
4298 add_anchor_token(',');
4300 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4302 if (token.kind == '=') {
4303 parse_init_declarator_rest(entity);
4304 } else if (entity->kind == ENTITY_VARIABLE) {
4305 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4306 * [...] where the extern specifier is explicitly used. */
4307 declaration_t *decl = &entity->declaration;
4308 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4309 is_type_reference(skip_typeref(decl->type))) {
4310 source_position_t const *const pos = &entity->base.source_position;
4311 errorf(pos, "reference '%#N' must be initialized", entity);
4315 check_variable_type_complete(entity);
4320 add_anchor_token('=');
4321 ndeclaration = parse_declarator(specifiers, flags);
4322 rem_anchor_token('=');
4324 rem_anchor_token(',');
4325 rem_anchor_token(';');
4328 anonymous_entity = NULL;
4331 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4333 symbol_t *symbol = entity->base.symbol;
4337 assert(entity->base.namespc == NAMESPACE_NORMAL);
4338 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4339 if (previous_entity == NULL
4340 || previous_entity->base.parent_scope != current_scope) {
4341 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4346 if (is_definition) {
4347 errorf(HERE, "'%N' is initialised", entity);
4350 return record_entity(entity, false);
4353 static void parse_declaration(parsed_declaration_func finished_declaration,
4354 declarator_flags_t flags)
4356 add_anchor_token(';');
4357 declaration_specifiers_t specifiers;
4358 parse_declaration_specifiers(&specifiers);
4359 rem_anchor_token(';');
4361 if (token.kind == ';') {
4362 parse_anonymous_declaration_rest(&specifiers);
4364 entity_t *entity = parse_declarator(&specifiers, flags);
4365 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4370 static type_t *get_default_promoted_type(type_t *orig_type)
4372 type_t *result = orig_type;
4374 type_t *type = skip_typeref(orig_type);
4375 if (is_type_integer(type)) {
4376 result = promote_integer(type);
4377 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4378 result = type_double;
4384 static void parse_kr_declaration_list(entity_t *entity)
4386 if (entity->kind != ENTITY_FUNCTION)
4389 type_t *type = skip_typeref(entity->declaration.type);
4390 assert(is_type_function(type));
4391 if (!type->function.kr_style_parameters)
4394 add_anchor_token('{');
4396 PUSH_SCOPE(&entity->function.parameters);
4398 entity_t *parameter = entity->function.parameters.entities;
4399 for ( ; parameter != NULL; parameter = parameter->base.next) {
4400 assert(parameter->base.parent_scope == NULL);
4401 parameter->base.parent_scope = current_scope;
4402 environment_push(parameter);
4405 /* parse declaration list */
4407 switch (token.kind) {
4409 /* This covers symbols, which are no type, too, and results in
4410 * better error messages. The typical cases are misspelled type
4411 * names and missing includes. */
4413 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4423 /* update function type */
4424 type_t *new_type = duplicate_type(type);
4426 function_parameter_t *parameters = NULL;
4427 function_parameter_t **anchor = ¶meters;
4429 /* did we have an earlier prototype? */
4430 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4431 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4434 function_parameter_t *proto_parameter = NULL;
4435 if (proto_type != NULL) {
4436 type_t *proto_type_type = proto_type->declaration.type;
4437 proto_parameter = proto_type_type->function.parameters;
4438 /* If a K&R function definition has a variadic prototype earlier, then
4439 * make the function definition variadic, too. This should conform to
4440 * §6.7.5.3:15 and §6.9.1:8. */
4441 new_type->function.variadic = proto_type_type->function.variadic;
4443 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4445 new_type->function.unspecified_parameters = true;
4448 bool need_incompatible_warning = false;
4449 parameter = entity->function.parameters.entities;
4450 for (; parameter != NULL; parameter = parameter->base.next,
4452 proto_parameter == NULL ? NULL : proto_parameter->next) {
4453 if (parameter->kind != ENTITY_PARAMETER)
4456 type_t *parameter_type = parameter->declaration.type;
4457 if (parameter_type == NULL) {
4458 source_position_t const* const pos = ¶meter->base.source_position;
4460 errorf(pos, "no type specified for function '%N'", parameter);
4461 parameter_type = type_error_type;
4463 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4464 parameter_type = type_int;
4466 parameter->declaration.type = parameter_type;
4469 semantic_parameter_incomplete(parameter);
4471 /* we need the default promoted types for the function type */
4472 type_t *not_promoted = parameter_type;
4473 parameter_type = get_default_promoted_type(parameter_type);
4475 /* gcc special: if the type of the prototype matches the unpromoted
4476 * type don't promote */
4477 if (!strict_mode && proto_parameter != NULL) {
4478 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4479 type_t *promo_skip = skip_typeref(parameter_type);
4480 type_t *param_skip = skip_typeref(not_promoted);
4481 if (!types_compatible(proto_p_type, promo_skip)
4482 && types_compatible(proto_p_type, param_skip)) {
4484 need_incompatible_warning = true;
4485 parameter_type = not_promoted;
4488 function_parameter_t *const function_parameter
4489 = allocate_parameter(parameter_type);
4491 *anchor = function_parameter;
4492 anchor = &function_parameter->next;
4495 new_type->function.parameters = parameters;
4496 new_type = identify_new_type(new_type);
4498 if (need_incompatible_warning) {
4499 symbol_t const *const sym = entity->base.symbol;
4500 source_position_t const *const pos = &entity->base.source_position;
4501 source_position_t const *const ppos = &proto_type->base.source_position;
4502 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4504 entity->declaration.type = new_type;
4506 rem_anchor_token('{');
4509 static bool first_err = true;
4512 * When called with first_err set, prints the name of the current function,
4515 static void print_in_function(void)
4519 char const *const file = current_function->base.base.source_position.input_name;
4520 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4525 * Check if all labels are defined in the current function.
4526 * Check if all labels are used in the current function.
4528 static void check_labels(void)
4530 for (const goto_statement_t *goto_statement = goto_first;
4531 goto_statement != NULL;
4532 goto_statement = goto_statement->next) {
4533 label_t *label = goto_statement->label;
4534 if (label->base.source_position.input_name == NULL) {
4535 print_in_function();
4536 source_position_t const *const pos = &goto_statement->base.source_position;
4537 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4541 if (is_warn_on(WARN_UNUSED_LABEL)) {
4542 for (const label_statement_t *label_statement = label_first;
4543 label_statement != NULL;
4544 label_statement = label_statement->next) {
4545 label_t *label = label_statement->label;
4547 if (! label->used) {
4548 print_in_function();
4549 source_position_t const *const pos = &label_statement->base.source_position;
4550 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4556 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4558 entity_t const *const end = last != NULL ? last->base.next : NULL;
4559 for (; entity != end; entity = entity->base.next) {
4560 if (!is_declaration(entity))
4563 declaration_t *declaration = &entity->declaration;
4564 if (declaration->implicit)
4567 if (!declaration->used) {
4568 print_in_function();
4569 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4570 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4571 print_in_function();
4572 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4577 static void check_unused_variables(statement_t *const stmt, void *const env)
4581 switch (stmt->kind) {
4582 case STATEMENT_DECLARATION: {
4583 declaration_statement_t const *const decls = &stmt->declaration;
4584 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4589 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4598 * Check declarations of current_function for unused entities.
4600 static void check_declarations(void)
4602 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4603 const scope_t *scope = ¤t_function->parameters;
4604 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4606 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4607 walk_statements(current_function->statement, check_unused_variables,
4612 static int determine_truth(expression_t const* const cond)
4615 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4616 fold_constant_to_bool(cond) ? 1 :
4620 static void check_reachable(statement_t *);
4621 static bool reaches_end;
4623 static bool expression_returns(expression_t const *const expr)
4625 switch (expr->kind) {
4627 expression_t const *const func = expr->call.function;
4628 type_t const *const type = skip_typeref(func->base.type);
4629 if (type->kind == TYPE_POINTER) {
4630 type_t const *const points_to
4631 = skip_typeref(type->pointer.points_to);
4632 if (points_to->kind == TYPE_FUNCTION
4633 && points_to->function.modifiers & DM_NORETURN)
4637 if (!expression_returns(func))
4640 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4641 if (!expression_returns(arg->expression))
4648 case EXPR_REFERENCE:
4649 case EXPR_ENUM_CONSTANT:
4650 case EXPR_LITERAL_CASES:
4651 case EXPR_STRING_LITERAL:
4652 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4653 case EXPR_LABEL_ADDRESS:
4654 case EXPR_CLASSIFY_TYPE:
4655 case EXPR_SIZEOF: // TODO handle obscure VLA case
4658 case EXPR_BUILTIN_CONSTANT_P:
4659 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4664 case EXPR_STATEMENT: {
4665 bool old_reaches_end = reaches_end;
4666 reaches_end = false;
4667 check_reachable(expr->statement.statement);
4668 bool returns = reaches_end;
4669 reaches_end = old_reaches_end;
4673 case EXPR_CONDITIONAL:
4674 // TODO handle constant expression
4676 if (!expression_returns(expr->conditional.condition))
4679 if (expr->conditional.true_expression != NULL
4680 && expression_returns(expr->conditional.true_expression))
4683 return expression_returns(expr->conditional.false_expression);
4686 return expression_returns(expr->select.compound);
4688 case EXPR_ARRAY_ACCESS:
4690 expression_returns(expr->array_access.array_ref) &&
4691 expression_returns(expr->array_access.index);
4694 return expression_returns(expr->va_starte.ap);
4697 return expression_returns(expr->va_arge.ap);
4700 return expression_returns(expr->va_copye.src);
4702 case EXPR_UNARY_CASES_MANDATORY:
4703 return expression_returns(expr->unary.value);
4705 case EXPR_UNARY_THROW:
4708 case EXPR_BINARY_CASES:
4709 // TODO handle constant lhs of && and ||
4711 expression_returns(expr->binary.left) &&
4712 expression_returns(expr->binary.right);
4715 panic("unhandled expression");
4718 static bool initializer_returns(initializer_t const *const init)
4720 switch (init->kind) {
4721 case INITIALIZER_VALUE:
4722 return expression_returns(init->value.value);
4724 case INITIALIZER_LIST: {
4725 initializer_t * const* i = init->list.initializers;
4726 initializer_t * const* const end = i + init->list.len;
4727 bool returns = true;
4728 for (; i != end; ++i) {
4729 if (!initializer_returns(*i))
4735 case INITIALIZER_STRING:
4736 case INITIALIZER_WIDE_STRING:
4737 case INITIALIZER_DESIGNATOR: // designators have no payload
4740 panic("unhandled initializer");
4743 static bool noreturn_candidate;
4745 static void check_reachable(statement_t *const stmt)
4747 if (stmt->base.reachable)
4749 if (stmt->kind != STATEMENT_DO_WHILE)
4750 stmt->base.reachable = true;
4752 statement_t *last = stmt;
4754 switch (stmt->kind) {
4755 case STATEMENT_ERROR:
4756 case STATEMENT_EMPTY:
4758 next = stmt->base.next;
4761 case STATEMENT_DECLARATION: {
4762 declaration_statement_t const *const decl = &stmt->declaration;
4763 entity_t const * ent = decl->declarations_begin;
4764 entity_t const *const last_decl = decl->declarations_end;
4766 for (;; ent = ent->base.next) {
4767 if (ent->kind == ENTITY_VARIABLE &&
4768 ent->variable.initializer != NULL &&
4769 !initializer_returns(ent->variable.initializer)) {
4772 if (ent == last_decl)
4776 next = stmt->base.next;
4780 case STATEMENT_COMPOUND:
4781 next = stmt->compound.statements;
4783 next = stmt->base.next;
4786 case STATEMENT_RETURN: {
4787 expression_t const *const val = stmt->returns.value;
4788 if (val == NULL || expression_returns(val))
4789 noreturn_candidate = false;
4793 case STATEMENT_IF: {
4794 if_statement_t const *const ifs = &stmt->ifs;
4795 expression_t const *const cond = ifs->condition;
4797 if (!expression_returns(cond))
4800 int const val = determine_truth(cond);
4803 check_reachable(ifs->true_statement);
4808 if (ifs->false_statement != NULL) {
4809 check_reachable(ifs->false_statement);
4813 next = stmt->base.next;
4817 case STATEMENT_SWITCH: {
4818 switch_statement_t const *const switchs = &stmt->switchs;
4819 expression_t const *const expr = switchs->expression;
4821 if (!expression_returns(expr))
4824 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4825 long const val = fold_constant_to_int(expr);
4826 case_label_statement_t * defaults = NULL;
4827 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4828 if (i->expression == NULL) {
4833 if (i->first_case <= val && val <= i->last_case) {
4834 check_reachable((statement_t*)i);
4839 if (defaults != NULL) {
4840 check_reachable((statement_t*)defaults);
4844 bool has_default = false;
4845 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4846 if (i->expression == NULL)
4849 check_reachable((statement_t*)i);
4856 next = stmt->base.next;
4860 case STATEMENT_EXPRESSION: {
4861 /* Check for noreturn function call */
4862 expression_t const *const expr = stmt->expression.expression;
4863 if (!expression_returns(expr))
4866 next = stmt->base.next;
4870 case STATEMENT_CONTINUE:
4871 for (statement_t *parent = stmt;;) {
4872 parent = parent->base.parent;
4873 if (parent == NULL) /* continue not within loop */
4877 switch (parent->kind) {
4878 case STATEMENT_WHILE: goto continue_while;
4879 case STATEMENT_DO_WHILE: goto continue_do_while;
4880 case STATEMENT_FOR: goto continue_for;
4886 case STATEMENT_BREAK:
4887 for (statement_t *parent = stmt;;) {
4888 parent = parent->base.parent;
4889 if (parent == NULL) /* break not within loop/switch */
4892 switch (parent->kind) {
4893 case STATEMENT_SWITCH:
4894 case STATEMENT_WHILE:
4895 case STATEMENT_DO_WHILE:
4898 next = parent->base.next;
4899 goto found_break_parent;
4907 case STATEMENT_COMPUTED_GOTO: {
4908 if (!expression_returns(stmt->computed_goto.expression))
4911 statement_t *parent = stmt->base.parent;
4912 if (parent == NULL) /* top level goto */
4918 case STATEMENT_GOTO:
4919 next = stmt->gotos.label->statement;
4920 if (next == NULL) /* missing label */
4924 case STATEMENT_LABEL:
4925 next = stmt->label.statement;
4928 case STATEMENT_CASE_LABEL:
4929 next = stmt->case_label.statement;
4932 case STATEMENT_WHILE: {
4933 while_statement_t const *const whiles = &stmt->whiles;
4934 expression_t const *const cond = whiles->condition;
4936 if (!expression_returns(cond))
4939 int const val = determine_truth(cond);
4942 check_reachable(whiles->body);
4947 next = stmt->base.next;
4951 case STATEMENT_DO_WHILE:
4952 next = stmt->do_while.body;
4955 case STATEMENT_FOR: {
4956 for_statement_t *const fors = &stmt->fors;
4958 if (fors->condition_reachable)
4960 fors->condition_reachable = true;
4962 expression_t const *const cond = fors->condition;
4967 } else if (expression_returns(cond)) {
4968 val = determine_truth(cond);
4974 check_reachable(fors->body);
4979 next = stmt->base.next;
4983 case STATEMENT_MS_TRY: {
4984 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4985 check_reachable(ms_try->try_statement);
4986 next = ms_try->final_statement;
4990 case STATEMENT_LEAVE: {
4991 statement_t *parent = stmt;
4993 parent = parent->base.parent;
4994 if (parent == NULL) /* __leave not within __try */
4997 if (parent->kind == STATEMENT_MS_TRY) {
4999 next = parent->ms_try.final_statement;
5007 panic("invalid statement kind");
5010 while (next == NULL) {
5011 next = last->base.parent;
5013 noreturn_candidate = false;
5015 type_t *const type = skip_typeref(current_function->base.type);
5016 assert(is_type_function(type));
5017 type_t *const ret = skip_typeref(type->function.return_type);
5018 if (!is_type_void(ret) &&
5019 is_type_valid(ret) &&
5020 !is_main(current_entity)) {
5021 source_position_t const *const pos = &stmt->base.source_position;
5022 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5027 switch (next->kind) {
5028 case STATEMENT_ERROR:
5029 case STATEMENT_EMPTY:
5030 case STATEMENT_DECLARATION:
5031 case STATEMENT_EXPRESSION:
5033 case STATEMENT_RETURN:
5034 case STATEMENT_CONTINUE:
5035 case STATEMENT_BREAK:
5036 case STATEMENT_COMPUTED_GOTO:
5037 case STATEMENT_GOTO:
5038 case STATEMENT_LEAVE:
5039 panic("invalid control flow in function");
5041 case STATEMENT_COMPOUND:
5042 if (next->compound.stmt_expr) {
5048 case STATEMENT_SWITCH:
5049 case STATEMENT_LABEL:
5050 case STATEMENT_CASE_LABEL:
5052 next = next->base.next;
5055 case STATEMENT_WHILE: {
5057 if (next->base.reachable)
5059 next->base.reachable = true;
5061 while_statement_t const *const whiles = &next->whiles;
5062 expression_t const *const cond = whiles->condition;
5064 if (!expression_returns(cond))
5067 int const val = determine_truth(cond);
5070 check_reachable(whiles->body);
5076 next = next->base.next;
5080 case STATEMENT_DO_WHILE: {
5082 if (next->base.reachable)
5084 next->base.reachable = true;
5086 do_while_statement_t const *const dw = &next->do_while;
5087 expression_t const *const cond = dw->condition;
5089 if (!expression_returns(cond))
5092 int const val = determine_truth(cond);
5095 check_reachable(dw->body);
5101 next = next->base.next;
5105 case STATEMENT_FOR: {
5107 for_statement_t *const fors = &next->fors;
5109 fors->step_reachable = true;
5111 if (fors->condition_reachable)
5113 fors->condition_reachable = true;
5115 expression_t const *const cond = fors->condition;
5120 } else if (expression_returns(cond)) {
5121 val = determine_truth(cond);
5127 check_reachable(fors->body);
5133 next = next->base.next;
5137 case STATEMENT_MS_TRY:
5139 next = next->ms_try.final_statement;
5144 check_reachable(next);
5147 static void check_unreachable(statement_t* const stmt, void *const env)
5151 switch (stmt->kind) {
5152 case STATEMENT_DO_WHILE:
5153 if (!stmt->base.reachable) {
5154 expression_t const *const cond = stmt->do_while.condition;
5155 if (determine_truth(cond) >= 0) {
5156 source_position_t const *const pos = &cond->base.source_position;
5157 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5162 case STATEMENT_FOR: {
5163 for_statement_t const* const fors = &stmt->fors;
5165 // if init and step are unreachable, cond is unreachable, too
5166 if (!stmt->base.reachable && !fors->step_reachable) {
5167 goto warn_unreachable;
5169 if (!stmt->base.reachable && fors->initialisation != NULL) {
5170 source_position_t const *const pos = &fors->initialisation->base.source_position;
5171 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5174 if (!fors->condition_reachable && fors->condition != NULL) {
5175 source_position_t const *const pos = &fors->condition->base.source_position;
5176 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5179 if (!fors->step_reachable && fors->step != NULL) {
5180 source_position_t const *const pos = &fors->step->base.source_position;
5181 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5187 case STATEMENT_COMPOUND:
5188 if (stmt->compound.statements != NULL)
5190 goto warn_unreachable;
5192 case STATEMENT_DECLARATION: {
5193 /* Only warn if there is at least one declarator with an initializer.
5194 * This typically occurs in switch statements. */
5195 declaration_statement_t const *const decl = &stmt->declaration;
5196 entity_t const * ent = decl->declarations_begin;
5197 entity_t const *const last = decl->declarations_end;
5199 for (;; ent = ent->base.next) {
5200 if (ent->kind == ENTITY_VARIABLE &&
5201 ent->variable.initializer != NULL) {
5202 goto warn_unreachable;
5212 if (!stmt->base.reachable) {
5213 source_position_t const *const pos = &stmt->base.source_position;
5214 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5220 static bool is_main(entity_t *entity)
5222 static symbol_t *sym_main = NULL;
5223 if (sym_main == NULL) {
5224 sym_main = symbol_table_insert("main");
5227 if (entity->base.symbol != sym_main)
5229 /* must be in outermost scope */
5230 if (entity->base.parent_scope != file_scope)
5236 static void prepare_main_collect2(entity_t*);
5238 static void parse_external_declaration(void)
5240 /* function-definitions and declarations both start with declaration
5242 add_anchor_token(';');
5243 declaration_specifiers_t specifiers;
5244 parse_declaration_specifiers(&specifiers);
5245 rem_anchor_token(';');
5247 /* must be a declaration */
5248 if (token.kind == ';') {
5249 parse_anonymous_declaration_rest(&specifiers);
5253 add_anchor_token(',');
5254 add_anchor_token('=');
5255 add_anchor_token(';');
5256 add_anchor_token('{');
5258 /* declarator is common to both function-definitions and declarations */
5259 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5261 rem_anchor_token('{');
5262 rem_anchor_token(';');
5263 rem_anchor_token('=');
5264 rem_anchor_token(',');
5266 /* must be a declaration */
5267 switch (token.kind) {
5271 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5276 /* must be a function definition */
5277 parse_kr_declaration_list(ndeclaration);
5279 if (token.kind != '{') {
5280 parse_error_expected("while parsing function definition", '{', NULL);
5281 eat_until_matching_token(';');
5285 assert(is_declaration(ndeclaration));
5286 type_t *const orig_type = ndeclaration->declaration.type;
5287 type_t * type = skip_typeref(orig_type);
5289 if (!is_type_function(type)) {
5290 if (is_type_valid(type)) {
5291 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5297 source_position_t const *const pos = &ndeclaration->base.source_position;
5298 if (is_typeref(orig_type)) {
5300 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5303 if (is_type_compound(skip_typeref(type->function.return_type))) {
5304 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5306 if (type->function.unspecified_parameters) {
5307 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5309 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5312 /* §6.7.5.3:14 a function definition with () means no
5313 * parameters (and not unspecified parameters) */
5314 if (type->function.unspecified_parameters &&
5315 type->function.parameters == NULL) {
5316 type_t *copy = duplicate_type(type);
5317 copy->function.unspecified_parameters = false;
5318 type = identify_new_type(copy);
5320 ndeclaration->declaration.type = type;
5323 entity_t *const entity = record_entity(ndeclaration, true);
5324 assert(entity->kind == ENTITY_FUNCTION);
5325 assert(ndeclaration->kind == ENTITY_FUNCTION);
5327 function_t *const function = &entity->function;
5328 if (ndeclaration != entity) {
5329 function->parameters = ndeclaration->function.parameters;
5332 PUSH_SCOPE(&function->parameters);
5334 entity_t *parameter = function->parameters.entities;
5335 for (; parameter != NULL; parameter = parameter->base.next) {
5336 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5337 parameter->base.parent_scope = current_scope;
5339 assert(parameter->base.parent_scope == NULL
5340 || parameter->base.parent_scope == current_scope);
5341 parameter->base.parent_scope = current_scope;
5342 if (parameter->base.symbol == NULL) {
5343 errorf(¶meter->base.source_position, "parameter name omitted");
5346 environment_push(parameter);
5349 if (function->statement != NULL) {
5350 parser_error_multiple_definition(entity, HERE);
5353 /* parse function body */
5354 int label_stack_top = label_top();
5355 function_t *old_current_function = current_function;
5356 current_function = function;
5357 PUSH_CURRENT_ENTITY(entity);
5361 goto_anchor = &goto_first;
5363 label_anchor = &label_first;
5365 statement_t *const body = parse_compound_statement(false);
5366 function->statement = body;
5369 check_declarations();
5370 if (is_warn_on(WARN_RETURN_TYPE) ||
5371 is_warn_on(WARN_UNREACHABLE_CODE) ||
5372 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5373 noreturn_candidate = true;
5374 check_reachable(body);
5375 if (is_warn_on(WARN_UNREACHABLE_CODE))
5376 walk_statements(body, check_unreachable, NULL);
5377 if (noreturn_candidate &&
5378 !(function->base.modifiers & DM_NORETURN)) {
5379 source_position_t const *const pos = &body->base.source_position;
5380 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5384 if (is_main(entity)) {
5385 /* Force main to C linkage. */
5386 type_t *const type = entity->declaration.type;
5387 assert(is_type_function(type));
5388 if (type->function.linkage != LINKAGE_C) {
5389 type_t *new_type = duplicate_type(type);
5390 new_type->function.linkage = LINKAGE_C;
5391 entity->declaration.type = identify_new_type(new_type);
5394 if (enable_main_collect2_hack)
5395 prepare_main_collect2(entity);
5398 POP_CURRENT_ENTITY();
5400 assert(current_function == function);
5401 current_function = old_current_function;
5402 label_pop_to(label_stack_top);
5408 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5410 entity_t *iter = compound->members.entities;
5411 for (; iter != NULL; iter = iter->base.next) {
5412 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5415 if (iter->base.symbol == symbol) {
5417 } else if (iter->base.symbol == NULL) {
5418 /* search in anonymous structs and unions */
5419 type_t *type = skip_typeref(iter->declaration.type);
5420 if (is_type_compound(type)) {
5421 if (find_compound_entry(type->compound.compound, symbol)
5432 static void check_deprecated(const source_position_t *source_position,
5433 const entity_t *entity)
5435 if (!is_declaration(entity))
5437 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5440 source_position_t const *const epos = &entity->base.source_position;
5441 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5443 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5445 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5450 static expression_t *create_select(const source_position_t *pos,
5452 type_qualifiers_t qualifiers,
5455 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5457 check_deprecated(pos, entry);
5459 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5460 select->select.compound = addr;
5461 select->select.compound_entry = entry;
5463 type_t *entry_type = entry->declaration.type;
5464 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5466 /* bitfields need special treatment */
5467 if (entry->compound_member.bitfield) {
5468 unsigned bit_size = entry->compound_member.bit_size;
5469 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5470 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5471 res_type = type_int;
5475 /* we always do the auto-type conversions; the & and sizeof parser contains
5476 * code to revert this! */
5477 select->base.type = automatic_type_conversion(res_type);
5484 * Find entry with symbol in compound. Search anonymous structs and unions and
5485 * creates implicit select expressions for them.
5486 * Returns the adress for the innermost compound.
5488 static expression_t *find_create_select(const source_position_t *pos,
5490 type_qualifiers_t qualifiers,
5491 compound_t *compound, symbol_t *symbol)
5493 entity_t *iter = compound->members.entities;
5494 for (; iter != NULL; iter = iter->base.next) {
5495 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5498 symbol_t *iter_symbol = iter->base.symbol;
5499 if (iter_symbol == NULL) {
5500 type_t *type = iter->declaration.type;
5501 if (type->kind != TYPE_COMPOUND_STRUCT
5502 && type->kind != TYPE_COMPOUND_UNION)
5505 compound_t *sub_compound = type->compound.compound;
5507 if (find_compound_entry(sub_compound, symbol) == NULL)
5510 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5511 sub_addr->base.source_position = *pos;
5512 sub_addr->base.implicit = true;
5513 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5517 if (iter_symbol == symbol) {
5518 return create_select(pos, addr, qualifiers, iter);
5525 static void parse_bitfield_member(entity_t *entity)
5529 expression_t *size = parse_constant_expression();
5532 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5533 type_t *type = entity->declaration.type;
5534 if (!is_type_integer(skip_typeref(type))) {
5535 errorf(HERE, "bitfield base type '%T' is not an integer type",
5539 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5540 /* error already reported by parse_constant_expression */
5541 size_long = get_type_size(type) * 8;
5543 size_long = fold_constant_to_int(size);
5545 const symbol_t *symbol = entity->base.symbol;
5546 const symbol_t *user_symbol
5547 = symbol == NULL ? sym_anonymous : symbol;
5548 unsigned bit_size = get_type_size(type) * 8;
5549 if (size_long < 0) {
5550 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5551 } else if (size_long == 0 && symbol != NULL) {
5552 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5553 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5554 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5557 /* hope that people don't invent crazy types with more bits
5558 * than our struct can hold */
5560 (1 << sizeof(entity->compound_member.bit_size)*8));
5564 entity->compound_member.bitfield = true;
5565 entity->compound_member.bit_size = (unsigned char)size_long;
5568 static void parse_compound_declarators(compound_t *compound,
5569 const declaration_specifiers_t *specifiers)
5571 add_anchor_token(';');
5572 add_anchor_token(',');
5576 if (token.kind == ':') {
5577 /* anonymous bitfield */
5578 type_t *type = specifiers->type;
5579 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5580 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5581 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5582 entity->declaration.type = type;
5584 parse_bitfield_member(entity);
5586 attribute_t *attributes = parse_attributes(NULL);
5587 attribute_t **anchor = &attributes;
5588 while (*anchor != NULL)
5589 anchor = &(*anchor)->next;
5590 *anchor = specifiers->attributes;
5591 if (attributes != NULL) {
5592 handle_entity_attributes(attributes, entity);
5594 entity->declaration.attributes = attributes;
5596 append_entity(&compound->members, entity);
5598 entity = parse_declarator(specifiers,
5599 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5600 source_position_t const *const pos = &entity->base.source_position;
5601 if (entity->kind == ENTITY_TYPEDEF) {
5602 errorf(pos, "typedef not allowed as compound member");
5604 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5606 /* make sure we don't define a symbol multiple times */
5607 symbol_t *symbol = entity->base.symbol;
5608 if (symbol != NULL) {
5609 entity_t *prev = find_compound_entry(compound, symbol);
5611 source_position_t const *const ppos = &prev->base.source_position;
5612 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5616 if (token.kind == ':') {
5617 parse_bitfield_member(entity);
5619 attribute_t *attributes = parse_attributes(NULL);
5620 handle_entity_attributes(attributes, entity);
5622 type_t *orig_type = entity->declaration.type;
5623 type_t *type = skip_typeref(orig_type);
5624 if (is_type_function(type)) {
5625 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5626 } else if (is_type_incomplete(type)) {
5627 /* §6.7.2.1:16 flexible array member */
5628 if (!is_type_array(type) ||
5629 token.kind != ';' ||
5630 look_ahead(1)->kind != '}') {
5631 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5632 } else if (compound->members.entities == NULL) {
5633 errorf(pos, "flexible array member in otherwise empty struct");
5638 append_entity(&compound->members, entity);
5641 } while (next_if(','));
5642 rem_anchor_token(',');
5643 rem_anchor_token(';');
5646 anonymous_entity = NULL;
5649 static void parse_compound_type_entries(compound_t *compound)
5652 add_anchor_token('}');
5655 switch (token.kind) {
5657 case T___extension__:
5658 case T_IDENTIFIER: {
5660 declaration_specifiers_t specifiers;
5661 parse_declaration_specifiers(&specifiers);
5662 parse_compound_declarators(compound, &specifiers);
5668 rem_anchor_token('}');
5671 compound->complete = true;
5677 static type_t *parse_typename(void)
5679 declaration_specifiers_t specifiers;
5680 parse_declaration_specifiers(&specifiers);
5681 if (specifiers.storage_class != STORAGE_CLASS_NONE
5682 || specifiers.thread_local) {
5683 /* TODO: improve error message, user does probably not know what a
5684 * storage class is...
5686 errorf(&specifiers.source_position, "typename must not have a storage class");
5689 type_t *result = parse_abstract_declarator(specifiers.type);
5697 typedef expression_t* (*parse_expression_function)(void);
5698 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5700 typedef struct expression_parser_function_t expression_parser_function_t;
5701 struct expression_parser_function_t {
5702 parse_expression_function parser;
5703 precedence_t infix_precedence;
5704 parse_expression_infix_function infix_parser;
5707 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5709 static type_t *get_string_type(string_encoding_t const enc)
5711 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5713 case STRING_ENCODING_CHAR: return warn ? type_const_char_ptr : type_char_ptr;
5714 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5716 panic("invalid string encoding");
5720 * Parse a string constant.
5722 static expression_t *parse_string_literal(void)
5724 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5725 expr->string_literal.value = concat_string_literals(&expr->string_literal.encoding);
5726 expr->base.type = get_string_type(expr->string_literal.encoding);
5731 * Parse a boolean constant.
5733 static expression_t *parse_boolean_literal(bool value)
5735 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5736 literal->base.type = type_bool;
5737 literal->literal.value.begin = value ? "true" : "false";
5738 literal->literal.value.size = value ? 4 : 5;
5740 eat(value ? T_true : T_false);
5744 static void warn_traditional_suffix(void)
5746 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5747 &token.number.suffix);
5750 static void check_integer_suffix(void)
5752 const string_t *suffix = &token.number.suffix;
5753 if (suffix->size == 0)
5756 bool not_traditional = false;
5757 const char *c = suffix->begin;
5758 if (*c == 'l' || *c == 'L') {
5761 not_traditional = true;
5763 if (*c == 'u' || *c == 'U') {
5766 } else if (*c == 'u' || *c == 'U') {
5767 not_traditional = true;
5770 } else if (*c == 'u' || *c == 'U') {
5771 not_traditional = true;
5773 if (*c == 'l' || *c == 'L') {
5781 errorf(HERE, "invalid suffix '%S' on integer constant", suffix);
5782 } else if (not_traditional) {
5783 warn_traditional_suffix();
5787 static type_t *check_floatingpoint_suffix(void)
5789 const string_t *suffix = &token.number.suffix;
5790 type_t *type = type_double;
5791 if (suffix->size == 0)
5794 bool not_traditional = false;
5795 const char *c = suffix->begin;
5796 if (*c == 'f' || *c == 'F') {
5799 } else if (*c == 'l' || *c == 'L') {
5801 type = type_long_double;
5804 errorf(HERE, "invalid suffix '%S' on floatingpoint constant", suffix);
5805 } else if (not_traditional) {
5806 warn_traditional_suffix();
5813 * Parse an integer constant.
5815 static expression_t *parse_number_literal(void)
5817 expression_kind_t kind;
5820 switch (token.kind) {
5822 kind = EXPR_LITERAL_INTEGER;
5823 check_integer_suffix();
5827 case T_FLOATINGPOINT:
5828 kind = EXPR_LITERAL_FLOATINGPOINT;
5829 type = check_floatingpoint_suffix();
5833 panic("unexpected token type in parse_number_literal");
5836 expression_t *literal = allocate_expression_zero(kind);
5837 literal->base.type = type;
5838 literal->literal.value = token.number.number;
5839 literal->literal.suffix = token.number.suffix;
5842 /* integer type depends on the size of the number and the size
5843 * representable by the types. The backend/codegeneration has to determine
5846 determine_literal_type(&literal->literal);
5851 * Parse a character constant.
5853 static expression_t *parse_character_constant(void)
5855 expression_t *literal;
5856 switch (token.string.encoding) {
5857 case STRING_ENCODING_CHAR: {
5858 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");
5874 case STRING_ENCODING_WIDE: {
5875 literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5876 literal->base.type = type_int;
5877 literal->literal.value = token.string.string;
5879 size_t len = wstrlen(&literal->literal.value);
5881 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5887 eat(T_CHARACTER_CONSTANT);
5891 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5893 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5894 ntype->function.return_type = type_int;
5895 ntype->function.unspecified_parameters = true;
5896 ntype->function.linkage = LINKAGE_C;
5897 type_t *type = identify_new_type(ntype);
5899 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5900 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5901 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5902 entity->declaration.type = type;
5903 entity->declaration.implicit = true;
5905 if (current_scope != NULL)
5906 record_entity(entity, false);
5912 * Performs automatic type cast as described in §6.3.2.1.
5914 * @param orig_type the original type
5916 static type_t *automatic_type_conversion(type_t *orig_type)
5918 type_t *type = skip_typeref(orig_type);
5919 if (is_type_array(type)) {
5920 array_type_t *array_type = &type->array;
5921 type_t *element_type = array_type->element_type;
5922 unsigned qualifiers = array_type->base.qualifiers;
5924 return make_pointer_type(element_type, qualifiers);
5927 if (is_type_function(type)) {
5928 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5935 * reverts the automatic casts of array to pointer types and function
5936 * to function-pointer types as defined §6.3.2.1
5938 type_t *revert_automatic_type_conversion(const expression_t *expression)
5940 switch (expression->kind) {
5941 case EXPR_REFERENCE: {
5942 entity_t *entity = expression->reference.entity;
5943 if (is_declaration(entity)) {
5944 return entity->declaration.type;
5945 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5946 return entity->enum_value.enum_type;
5948 panic("no declaration or enum in reference");
5953 entity_t *entity = expression->select.compound_entry;
5954 assert(is_declaration(entity));
5955 type_t *type = entity->declaration.type;
5956 return get_qualified_type(type, expression->base.type->base.qualifiers);
5959 case EXPR_UNARY_DEREFERENCE: {
5960 const expression_t *const value = expression->unary.value;
5961 type_t *const type = skip_typeref(value->base.type);
5962 if (!is_type_pointer(type))
5963 return type_error_type;
5964 return type->pointer.points_to;
5967 case EXPR_ARRAY_ACCESS: {
5968 const expression_t *array_ref = expression->array_access.array_ref;
5969 type_t *type_left = skip_typeref(array_ref->base.type);
5970 if (!is_type_pointer(type_left))
5971 return type_error_type;
5972 return type_left->pointer.points_to;
5975 case EXPR_STRING_LITERAL: {
5976 size_t const size = expression->string_literal.value.size + 1;
5977 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
5978 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
5981 case EXPR_COMPOUND_LITERAL:
5982 return expression->compound_literal.type;
5987 return expression->base.type;
5991 * Find an entity matching a symbol in a scope.
5992 * Uses current scope if scope is NULL
5994 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
5995 namespace_tag_t namespc)
5997 if (scope == NULL) {
5998 return get_entity(symbol, namespc);
6001 /* we should optimize here, if scope grows above a certain size we should
6002 construct a hashmap here... */
6003 entity_t *entity = scope->entities;
6004 for ( ; entity != NULL; entity = entity->base.next) {
6005 if (entity->base.symbol == symbol
6006 && (namespace_tag_t)entity->base.namespc == namespc)
6013 static entity_t *parse_qualified_identifier(void)
6015 /* namespace containing the symbol */
6017 source_position_t pos;
6018 const scope_t *lookup_scope = NULL;
6020 if (next_if(T_COLONCOLON))
6021 lookup_scope = &unit->scope;
6025 symbol = expect_identifier("while parsing identifier", &pos);
6027 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6030 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6032 if (!next_if(T_COLONCOLON))
6035 switch (entity->kind) {
6036 case ENTITY_NAMESPACE:
6037 lookup_scope = &entity->namespacee.members;
6042 lookup_scope = &entity->compound.members;
6045 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6046 symbol, get_entity_kind_name(entity->kind));
6048 /* skip further qualifications */
6049 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6051 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6055 if (entity == NULL) {
6056 if (!strict_mode && token.kind == '(') {
6057 /* an implicitly declared function */
6058 entity = create_implicit_function(symbol, &pos);
6059 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6061 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6062 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6069 static expression_t *parse_reference(void)
6071 source_position_t const pos = *HERE;
6072 entity_t *const entity = parse_qualified_identifier();
6075 if (is_declaration(entity)) {
6076 orig_type = entity->declaration.type;
6077 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6078 orig_type = entity->enum_value.enum_type;
6080 panic("expected declaration or enum value in reference");
6083 /* we always do the auto-type conversions; the & and sizeof parser contains
6084 * code to revert this! */
6085 type_t *type = automatic_type_conversion(orig_type);
6087 expression_kind_t kind = EXPR_REFERENCE;
6088 if (entity->kind == ENTITY_ENUM_VALUE)
6089 kind = EXPR_ENUM_CONSTANT;
6091 expression_t *expression = allocate_expression_zero(kind);
6092 expression->base.source_position = pos;
6093 expression->base.type = type;
6094 expression->reference.entity = entity;
6096 /* this declaration is used */
6097 if (is_declaration(entity)) {
6098 entity->declaration.used = true;
6101 if (entity->base.parent_scope != file_scope
6102 && (current_function != NULL
6103 && entity->base.parent_scope->depth < current_function->parameters.depth)
6104 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6105 /* access of a variable from an outer function */
6106 entity->variable.address_taken = true;
6107 current_function->need_closure = true;
6110 check_deprecated(&pos, entity);
6115 static bool semantic_cast(expression_t *cast)
6117 expression_t *expression = cast->unary.value;
6118 type_t *orig_dest_type = cast->base.type;
6119 type_t *orig_type_right = expression->base.type;
6120 type_t const *dst_type = skip_typeref(orig_dest_type);
6121 type_t const *src_type = skip_typeref(orig_type_right);
6122 source_position_t const *pos = &cast->base.source_position;
6124 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6125 if (is_type_void(dst_type))
6128 /* only integer and pointer can be casted to pointer */
6129 if (is_type_pointer(dst_type) &&
6130 !is_type_pointer(src_type) &&
6131 !is_type_integer(src_type) &&
6132 is_type_valid(src_type)) {
6133 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6137 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6138 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6142 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6143 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6147 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6148 type_t *src = skip_typeref(src_type->pointer.points_to);
6149 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6150 unsigned missing_qualifiers =
6151 src->base.qualifiers & ~dst->base.qualifiers;
6152 if (missing_qualifiers != 0) {
6153 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6159 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6161 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6162 expression->base.source_position = *pos;
6164 parse_initializer_env_t env;
6167 env.must_be_constant = false;
6168 initializer_t *initializer = parse_initializer(&env);
6171 expression->compound_literal.initializer = initializer;
6172 expression->compound_literal.type = type;
6173 expression->base.type = automatic_type_conversion(type);
6179 * Parse a cast expression.
6181 static expression_t *parse_cast(void)
6183 source_position_t const pos = *HERE;
6186 add_anchor_token(')');
6188 type_t *type = parse_typename();
6190 rem_anchor_token(')');
6193 if (token.kind == '{') {
6194 return parse_compound_literal(&pos, type);
6197 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6198 cast->base.source_position = pos;
6200 expression_t *value = parse_subexpression(PREC_CAST);
6201 cast->base.type = type;
6202 cast->unary.value = value;
6204 if (! semantic_cast(cast)) {
6205 /* TODO: record the error in the AST. else it is impossible to detect it */
6212 * Parse a statement expression.
6214 static expression_t *parse_statement_expression(void)
6216 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6219 add_anchor_token(')');
6221 statement_t *statement = parse_compound_statement(true);
6222 statement->compound.stmt_expr = true;
6223 expression->statement.statement = statement;
6225 /* find last statement and use its type */
6226 type_t *type = type_void;
6227 const statement_t *stmt = statement->compound.statements;
6229 while (stmt->base.next != NULL)
6230 stmt = stmt->base.next;
6232 if (stmt->kind == STATEMENT_EXPRESSION) {
6233 type = stmt->expression.expression->base.type;
6236 source_position_t const *const pos = &expression->base.source_position;
6237 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6239 expression->base.type = type;
6241 rem_anchor_token(')');
6247 * Parse a parenthesized expression.
6249 static expression_t *parse_parenthesized_expression(void)
6251 token_t const* const la1 = look_ahead(1);
6252 switch (la1->kind) {
6254 /* gcc extension: a statement expression */
6255 return parse_statement_expression();
6258 if (is_typedef_symbol(la1->base.symbol)) {
6260 return parse_cast();
6265 add_anchor_token(')');
6266 expression_t *result = parse_expression();
6267 result->base.parenthesized = true;
6268 rem_anchor_token(')');
6274 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6276 if (current_function == NULL) {
6277 errorf(HERE, "'%K' used outside of a function", &token);
6280 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6281 expression->base.type = type_char_ptr;
6282 expression->funcname.kind = kind;
6289 static designator_t *parse_designator(void)
6291 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6292 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6293 if (!result->symbol)
6296 designator_t *last_designator = result;
6299 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6300 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6301 if (!designator->symbol)
6304 last_designator->next = designator;
6305 last_designator = designator;
6309 add_anchor_token(']');
6310 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6311 designator->source_position = *HERE;
6312 designator->array_index = parse_expression();
6313 rem_anchor_token(']');
6315 if (designator->array_index == NULL) {
6319 last_designator->next = designator;
6320 last_designator = designator;
6330 * Parse the __builtin_offsetof() expression.
6332 static expression_t *parse_offsetof(void)
6334 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6335 expression->base.type = type_size_t;
6337 eat(T___builtin_offsetof);
6339 add_anchor_token(')');
6340 add_anchor_token(',');
6342 type_t *type = parse_typename();
6343 rem_anchor_token(',');
6345 designator_t *designator = parse_designator();
6346 rem_anchor_token(')');
6349 expression->offsetofe.type = type;
6350 expression->offsetofe.designator = designator;
6353 memset(&path, 0, sizeof(path));
6354 path.top_type = type;
6355 path.path = NEW_ARR_F(type_path_entry_t, 0);
6357 descend_into_subtype(&path);
6359 if (!walk_designator(&path, designator, true)) {
6360 return create_error_expression();
6363 DEL_ARR_F(path.path);
6368 static bool is_last_parameter(expression_t *const param)
6370 if (param->kind == EXPR_REFERENCE) {
6371 entity_t *const entity = param->reference.entity;
6372 if (entity->kind == ENTITY_PARAMETER &&
6373 !entity->base.next &&
6374 entity->base.parent_scope == ¤t_function->parameters) {
6379 if (!is_type_valid(skip_typeref(param->base.type)))
6386 * Parses a __builtin_va_start() expression.
6388 static expression_t *parse_va_start(void)
6390 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6392 eat(T___builtin_va_start);
6394 add_anchor_token(')');
6395 add_anchor_token(',');
6397 expression->va_starte.ap = parse_assignment_expression();
6398 rem_anchor_token(',');
6400 expression_t *const param = parse_assignment_expression();
6401 expression->va_starte.parameter = param;
6402 rem_anchor_token(')');
6405 if (!current_function) {
6406 errorf(&expression->base.source_position, "'va_start' used outside of function");
6407 } else if (!current_function->base.type->function.variadic) {
6408 errorf(&expression->base.source_position, "'va_start' used in non-variadic function");
6409 } else if (!is_last_parameter(param)) {
6410 errorf(¶m->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
6417 * Parses a __builtin_va_arg() expression.
6419 static expression_t *parse_va_arg(void)
6421 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6423 eat(T___builtin_va_arg);
6425 add_anchor_token(')');
6426 add_anchor_token(',');
6429 ap.expression = parse_assignment_expression();
6430 expression->va_arge.ap = ap.expression;
6431 check_call_argument(type_valist, &ap, 1);
6433 rem_anchor_token(',');
6435 expression->base.type = parse_typename();
6436 rem_anchor_token(')');
6443 * Parses a __builtin_va_copy() expression.
6445 static expression_t *parse_va_copy(void)
6447 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6449 eat(T___builtin_va_copy);
6451 add_anchor_token(')');
6452 add_anchor_token(',');
6454 expression_t *dst = parse_assignment_expression();
6455 assign_error_t error = semantic_assign(type_valist, dst);
6456 report_assign_error(error, type_valist, dst, "call argument 1",
6457 &dst->base.source_position);
6458 expression->va_copye.dst = dst;
6460 rem_anchor_token(',');
6463 call_argument_t src;
6464 src.expression = parse_assignment_expression();
6465 check_call_argument(type_valist, &src, 2);
6466 expression->va_copye.src = src.expression;
6467 rem_anchor_token(')');
6474 * Parses a __builtin_constant_p() expression.
6476 static expression_t *parse_builtin_constant(void)
6478 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6480 eat(T___builtin_constant_p);
6482 add_anchor_token(')');
6484 expression->builtin_constant.value = parse_assignment_expression();
6485 rem_anchor_token(')');
6487 expression->base.type = type_int;
6493 * Parses a __builtin_types_compatible_p() expression.
6495 static expression_t *parse_builtin_types_compatible(void)
6497 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6499 eat(T___builtin_types_compatible_p);
6501 add_anchor_token(')');
6502 add_anchor_token(',');
6504 expression->builtin_types_compatible.left = parse_typename();
6505 rem_anchor_token(',');
6507 expression->builtin_types_compatible.right = parse_typename();
6508 rem_anchor_token(')');
6510 expression->base.type = type_int;
6516 * Parses a __builtin_is_*() compare expression.
6518 static expression_t *parse_compare_builtin(void)
6520 expression_kind_t kind;
6521 switch (token.kind) {
6522 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6523 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6524 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6525 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6526 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6527 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6528 default: internal_errorf(HERE, "invalid compare builtin found");
6530 expression_t *const expression = allocate_expression_zero(kind);
6533 add_anchor_token(')');
6534 add_anchor_token(',');
6536 expression->binary.left = parse_assignment_expression();
6537 rem_anchor_token(',');
6539 expression->binary.right = parse_assignment_expression();
6540 rem_anchor_token(')');
6543 type_t *const orig_type_left = expression->binary.left->base.type;
6544 type_t *const orig_type_right = expression->binary.right->base.type;
6546 type_t *const type_left = skip_typeref(orig_type_left);
6547 type_t *const type_right = skip_typeref(orig_type_right);
6548 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6549 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6550 type_error_incompatible("invalid operands in comparison",
6551 &expression->base.source_position, orig_type_left, orig_type_right);
6554 semantic_comparison(&expression->binary);
6561 * Parses a MS assume() expression.
6563 static expression_t *parse_assume(void)
6565 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6569 add_anchor_token(')');
6571 expression->unary.value = parse_assignment_expression();
6572 rem_anchor_token(')');
6575 expression->base.type = type_void;
6580 * Return the label for the current symbol or create a new one.
6582 static label_t *get_label(char const *const context)
6584 assert(current_function != NULL);
6586 symbol_t *const sym = expect_identifier(context, NULL);
6590 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6591 /* If we find a local label, we already created the declaration. */
6592 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6593 if (label->base.parent_scope != current_scope) {
6594 assert(label->base.parent_scope->depth < current_scope->depth);
6595 current_function->goto_to_outer = true;
6597 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6598 /* There is no matching label in the same function, so create a new one. */
6599 source_position_t const nowhere = { NULL, 0, 0, false };
6600 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6604 return &label->label;
6608 * Parses a GNU && label address expression.
6610 static expression_t *parse_label_address(void)
6612 source_position_t const source_position = *HERE;
6615 label_t *const label = get_label("while parsing label address");
6617 return create_error_expression();
6620 label->address_taken = true;
6622 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6623 expression->base.source_position = source_position;
6625 /* label address is treated as a void pointer */
6626 expression->base.type = type_void_ptr;
6627 expression->label_address.label = label;
6632 * Parse a microsoft __noop expression.
6634 static expression_t *parse_noop_expression(void)
6636 /* the result is a (int)0 */
6637 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6638 literal->base.type = type_int;
6639 literal->literal.value.begin = "__noop";
6640 literal->literal.value.size = 6;
6644 if (token.kind == '(') {
6645 /* parse arguments */
6647 add_anchor_token(')');
6648 add_anchor_token(',');
6650 if (token.kind != ')') do {
6651 (void)parse_assignment_expression();
6652 } while (next_if(','));
6654 rem_anchor_token(',');
6655 rem_anchor_token(')');
6663 * Parses a primary expression.
6665 static expression_t *parse_primary_expression(void)
6667 switch (token.kind) {
6668 case T_false: return parse_boolean_literal(false);
6669 case T_true: return parse_boolean_literal(true);
6671 case T_FLOATINGPOINT: return parse_number_literal();
6672 case T_CHARACTER_CONSTANT: return parse_character_constant();
6673 case T_STRING_LITERAL: return parse_string_literal();
6674 case T___FUNCTION__:
6675 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6676 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6677 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6678 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6679 case T___builtin_offsetof: return parse_offsetof();
6680 case T___builtin_va_start: return parse_va_start();
6681 case T___builtin_va_arg: return parse_va_arg();
6682 case T___builtin_va_copy: return parse_va_copy();
6683 case T___builtin_isgreater:
6684 case T___builtin_isgreaterequal:
6685 case T___builtin_isless:
6686 case T___builtin_islessequal:
6687 case T___builtin_islessgreater:
6688 case T___builtin_isunordered: return parse_compare_builtin();
6689 case T___builtin_constant_p: return parse_builtin_constant();
6690 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6691 case T__assume: return parse_assume();
6694 return parse_label_address();
6697 case '(': return parse_parenthesized_expression();
6698 case T___noop: return parse_noop_expression();
6700 /* Gracefully handle type names while parsing expressions. */
6702 return parse_reference();
6704 if (!is_typedef_symbol(token.base.symbol)) {
6705 return parse_reference();
6709 source_position_t const pos = *HERE;
6710 declaration_specifiers_t specifiers;
6711 parse_declaration_specifiers(&specifiers);
6712 type_t const *const type = parse_abstract_declarator(specifiers.type);
6713 errorf(&pos, "encountered type '%T' while parsing expression", type);
6714 return create_error_expression();
6718 errorf(HERE, "unexpected token %K, expected an expression", &token);
6720 return create_error_expression();
6723 static expression_t *parse_array_expression(expression_t *left)
6725 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6726 array_access_expression_t *const arr = &expr->array_access;
6729 add_anchor_token(']');
6731 expression_t *const inside = parse_expression();
6733 type_t *const orig_type_left = left->base.type;
6734 type_t *const orig_type_inside = inside->base.type;
6736 type_t *const type_left = skip_typeref(orig_type_left);
6737 type_t *const type_inside = skip_typeref(orig_type_inside);
6743 if (is_type_pointer(type_left)) {
6746 idx_type = type_inside;
6747 res_type = type_left->pointer.points_to;
6749 } else if (is_type_pointer(type_inside)) {
6750 arr->flipped = true;
6753 idx_type = type_left;
6754 res_type = type_inside->pointer.points_to;
6756 res_type = automatic_type_conversion(res_type);
6757 if (!is_type_integer(idx_type)) {
6758 errorf(&idx->base.source_position, "array subscript must have integer type");
6759 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6760 source_position_t const *const pos = &idx->base.source_position;
6761 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6764 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6765 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6767 res_type = type_error_type;
6772 arr->array_ref = ref;
6774 arr->base.type = res_type;
6776 rem_anchor_token(']');
6781 static bool is_bitfield(const expression_t *expression)
6783 return expression->kind == EXPR_SELECT
6784 && expression->select.compound_entry->compound_member.bitfield;
6787 static expression_t *parse_typeprop(expression_kind_t const kind)
6789 expression_t *tp_expression = allocate_expression_zero(kind);
6790 tp_expression->base.type = type_size_t;
6792 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6795 expression_t *expression;
6796 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6797 source_position_t const pos = *HERE;
6799 add_anchor_token(')');
6800 orig_type = parse_typename();
6801 rem_anchor_token(')');
6804 if (token.kind == '{') {
6805 /* It was not sizeof(type) after all. It is sizeof of an expression
6806 * starting with a compound literal */
6807 expression = parse_compound_literal(&pos, orig_type);
6808 goto typeprop_expression;
6811 expression = parse_subexpression(PREC_UNARY);
6813 typeprop_expression:
6814 if (is_bitfield(expression)) {
6815 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6816 errorf(&tp_expression->base.source_position,
6817 "operand of %s expression must not be a bitfield", what);
6820 tp_expression->typeprop.tp_expression = expression;
6822 orig_type = revert_automatic_type_conversion(expression);
6823 expression->base.type = orig_type;
6826 tp_expression->typeprop.type = orig_type;
6827 type_t const* const type = skip_typeref(orig_type);
6828 char const* wrong_type = NULL;
6829 if (is_type_incomplete(type)) {
6830 if (!is_type_void(type) || !GNU_MODE)
6831 wrong_type = "incomplete";
6832 } else if (type->kind == TYPE_FUNCTION) {
6834 /* function types are allowed (and return 1) */
6835 source_position_t const *const pos = &tp_expression->base.source_position;
6836 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6837 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6839 wrong_type = "function";
6843 if (wrong_type != NULL) {
6844 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6845 errorf(&tp_expression->base.source_position,
6846 "operand of %s expression must not be of %s type '%T'",
6847 what, wrong_type, orig_type);
6850 return tp_expression;
6853 static expression_t *parse_sizeof(void)
6855 return parse_typeprop(EXPR_SIZEOF);
6858 static expression_t *parse_alignof(void)
6860 return parse_typeprop(EXPR_ALIGNOF);
6863 static expression_t *parse_select_expression(expression_t *addr)
6865 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6866 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6867 source_position_t const pos = *HERE;
6870 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6872 return create_error_expression();
6874 type_t *const orig_type = addr->base.type;
6875 type_t *const type = skip_typeref(orig_type);
6878 bool saw_error = false;
6879 if (is_type_pointer(type)) {
6880 if (!select_left_arrow) {
6882 "request for member '%Y' in something not a struct or union, but '%T'",
6886 type_left = skip_typeref(type->pointer.points_to);
6888 if (select_left_arrow && is_type_valid(type)) {
6889 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6895 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6896 type_left->kind != TYPE_COMPOUND_UNION) {
6898 if (is_type_valid(type_left) && !saw_error) {
6900 "request for member '%Y' in something not a struct or union, but '%T'",
6903 return create_error_expression();
6906 compound_t *compound = type_left->compound.compound;
6907 if (!compound->complete) {
6908 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6910 return create_error_expression();
6913 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6914 expression_t *result =
6915 find_create_select(&pos, addr, qualifiers, compound, symbol);
6917 if (result == NULL) {
6918 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6919 return create_error_expression();
6925 static void check_call_argument(type_t *expected_type,
6926 call_argument_t *argument, unsigned pos)
6928 type_t *expected_type_skip = skip_typeref(expected_type);
6929 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6930 expression_t *arg_expr = argument->expression;
6931 type_t *arg_type = skip_typeref(arg_expr->base.type);
6933 /* handle transparent union gnu extension */
6934 if (is_type_union(expected_type_skip)
6935 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6936 compound_t *union_decl = expected_type_skip->compound.compound;
6937 type_t *best_type = NULL;
6938 entity_t *entry = union_decl->members.entities;
6939 for ( ; entry != NULL; entry = entry->base.next) {
6940 assert(is_declaration(entry));
6941 type_t *decl_type = entry->declaration.type;
6942 error = semantic_assign(decl_type, arg_expr);
6943 if (error == ASSIGN_ERROR_INCOMPATIBLE
6944 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6947 if (error == ASSIGN_SUCCESS) {
6948 best_type = decl_type;
6949 } else if (best_type == NULL) {
6950 best_type = decl_type;
6954 if (best_type != NULL) {
6955 expected_type = best_type;
6959 error = semantic_assign(expected_type, arg_expr);
6960 argument->expression = create_implicit_cast(arg_expr, expected_type);
6962 if (error != ASSIGN_SUCCESS) {
6963 /* report exact scope in error messages (like "in argument 3") */
6965 snprintf(buf, sizeof(buf), "call argument %u", pos);
6966 report_assign_error(error, expected_type, arg_expr, buf,
6967 &arg_expr->base.source_position);
6969 type_t *const promoted_type = get_default_promoted_type(arg_type);
6970 if (!types_compatible(expected_type_skip, promoted_type) &&
6971 !types_compatible(expected_type_skip, type_void_ptr) &&
6972 !types_compatible(type_void_ptr, promoted_type)) {
6973 /* Deliberately show the skipped types in this warning */
6974 source_position_t const *const apos = &arg_expr->base.source_position;
6975 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
6981 * Handle the semantic restrictions of builtin calls
6983 static void handle_builtin_argument_restrictions(call_expression_t *call)
6985 entity_t *entity = call->function->reference.entity;
6986 switch (entity->function.btk) {
6988 switch (entity->function.b.firm_builtin_kind) {
6989 case ir_bk_return_address:
6990 case ir_bk_frame_address: {
6991 /* argument must be constant */
6992 call_argument_t *argument = call->arguments;
6994 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
6995 errorf(&call->base.source_position,
6996 "argument of '%Y' must be a constant expression",
6997 call->function->reference.entity->base.symbol);
7001 case ir_bk_prefetch:
7002 /* second and third argument must be constant if existent */
7003 if (call->arguments == NULL)
7005 call_argument_t *rw = call->arguments->next;
7006 call_argument_t *locality = NULL;
7009 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7010 errorf(&call->base.source_position,
7011 "second argument of '%Y' must be a constant expression",
7012 call->function->reference.entity->base.symbol);
7014 locality = rw->next;
7016 if (locality != NULL) {
7017 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7018 errorf(&call->base.source_position,
7019 "third argument of '%Y' must be a constant expression",
7020 call->function->reference.entity->base.symbol);
7022 locality = rw->next;
7029 case BUILTIN_OBJECT_SIZE:
7030 if (call->arguments == NULL)
7033 call_argument_t *arg = call->arguments->next;
7034 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7035 errorf(&call->base.source_position,
7036 "second argument of '%Y' must be a constant expression",
7037 call->function->reference.entity->base.symbol);
7046 * Parse a call expression, ie. expression '( ... )'.
7048 * @param expression the function address
7050 static expression_t *parse_call_expression(expression_t *expression)
7052 expression_t *result = allocate_expression_zero(EXPR_CALL);
7053 call_expression_t *call = &result->call;
7054 call->function = expression;
7056 type_t *const orig_type = expression->base.type;
7057 type_t *const type = skip_typeref(orig_type);
7059 function_type_t *function_type = NULL;
7060 if (is_type_pointer(type)) {
7061 type_t *const to_type = skip_typeref(type->pointer.points_to);
7063 if (is_type_function(to_type)) {
7064 function_type = &to_type->function;
7065 call->base.type = function_type->return_type;
7069 if (function_type == NULL && is_type_valid(type)) {
7071 "called object '%E' (type '%T') is not a pointer to a function",
7072 expression, orig_type);
7075 /* parse arguments */
7077 add_anchor_token(')');
7078 add_anchor_token(',');
7080 if (token.kind != ')') {
7081 call_argument_t **anchor = &call->arguments;
7083 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7084 argument->expression = parse_assignment_expression();
7087 anchor = &argument->next;
7088 } while (next_if(','));
7090 rem_anchor_token(',');
7091 rem_anchor_token(')');
7094 if (function_type == NULL)
7097 /* check type and count of call arguments */
7098 function_parameter_t *parameter = function_type->parameters;
7099 call_argument_t *argument = call->arguments;
7100 if (!function_type->unspecified_parameters) {
7101 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7102 parameter = parameter->next, argument = argument->next) {
7103 check_call_argument(parameter->type, argument, ++pos);
7106 if (parameter != NULL) {
7107 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7108 } else if (argument != NULL && !function_type->variadic) {
7109 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7113 /* do default promotion for other arguments */
7114 for (; argument != NULL; argument = argument->next) {
7115 type_t *argument_type = argument->expression->base.type;
7116 if (!is_type_object(skip_typeref(argument_type))) {
7117 errorf(&argument->expression->base.source_position,
7118 "call argument '%E' must not be void", argument->expression);
7121 argument_type = get_default_promoted_type(argument_type);
7123 argument->expression
7124 = create_implicit_cast(argument->expression, argument_type);
7129 if (is_type_compound(skip_typeref(function_type->return_type))) {
7130 source_position_t const *const pos = &expression->base.source_position;
7131 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7134 if (expression->kind == EXPR_REFERENCE) {
7135 reference_expression_t *reference = &expression->reference;
7136 if (reference->entity->kind == ENTITY_FUNCTION &&
7137 reference->entity->function.btk != BUILTIN_NONE)
7138 handle_builtin_argument_restrictions(call);
7144 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7146 static bool same_compound_type(const type_t *type1, const type_t *type2)
7149 is_type_compound(type1) &&
7150 type1->kind == type2->kind &&
7151 type1->compound.compound == type2->compound.compound;
7154 static expression_t const *get_reference_address(expression_t const *expr)
7156 bool regular_take_address = true;
7158 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7159 expr = expr->unary.value;
7161 regular_take_address = false;
7164 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7167 expr = expr->unary.value;
7170 if (expr->kind != EXPR_REFERENCE)
7173 /* special case for functions which are automatically converted to a
7174 * pointer to function without an extra TAKE_ADDRESS operation */
7175 if (!regular_take_address &&
7176 expr->reference.entity->kind != ENTITY_FUNCTION) {
7183 static void warn_reference_address_as_bool(expression_t const* expr)
7185 expr = get_reference_address(expr);
7187 source_position_t const *const pos = &expr->base.source_position;
7188 entity_t const *const ent = expr->reference.entity;
7189 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7193 static void warn_assignment_in_condition(const expression_t *const expr)
7195 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7197 if (expr->base.parenthesized)
7199 source_position_t const *const pos = &expr->base.source_position;
7200 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7203 static void semantic_condition(expression_t const *const expr,
7204 char const *const context)
7206 type_t *const type = skip_typeref(expr->base.type);
7207 if (is_type_scalar(type)) {
7208 warn_reference_address_as_bool(expr);
7209 warn_assignment_in_condition(expr);
7210 } else if (is_type_valid(type)) {
7211 errorf(&expr->base.source_position,
7212 "%s must have scalar type", context);
7217 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7219 * @param expression the conditional expression
7221 static expression_t *parse_conditional_expression(expression_t *expression)
7223 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7225 conditional_expression_t *conditional = &result->conditional;
7226 conditional->condition = expression;
7229 add_anchor_token(':');
7231 /* §6.5.15:2 The first operand shall have scalar type. */
7232 semantic_condition(expression, "condition of conditional operator");
7234 expression_t *true_expression = expression;
7235 bool gnu_cond = false;
7236 if (GNU_MODE && token.kind == ':') {
7239 true_expression = parse_expression();
7241 rem_anchor_token(':');
7243 expression_t *false_expression =
7244 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7246 type_t *const orig_true_type = true_expression->base.type;
7247 type_t *const orig_false_type = false_expression->base.type;
7248 type_t *const true_type = skip_typeref(orig_true_type);
7249 type_t *const false_type = skip_typeref(orig_false_type);
7252 source_position_t const *const pos = &conditional->base.source_position;
7253 type_t *result_type;
7254 if (is_type_void(true_type) || is_type_void(false_type)) {
7255 /* ISO/IEC 14882:1998(E) §5.16:2 */
7256 if (true_expression->kind == EXPR_UNARY_THROW) {
7257 result_type = false_type;
7258 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7259 result_type = true_type;
7261 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7262 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7264 result_type = type_void;
7266 } else if (is_type_arithmetic(true_type)
7267 && is_type_arithmetic(false_type)) {
7268 result_type = semantic_arithmetic(true_type, false_type);
7269 } else if (same_compound_type(true_type, false_type)) {
7270 /* just take 1 of the 2 types */
7271 result_type = true_type;
7272 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7273 type_t *pointer_type;
7275 expression_t *other_expression;
7276 if (is_type_pointer(true_type) &&
7277 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7278 pointer_type = true_type;
7279 other_type = false_type;
7280 other_expression = false_expression;
7282 pointer_type = false_type;
7283 other_type = true_type;
7284 other_expression = true_expression;
7287 if (is_null_pointer_constant(other_expression)) {
7288 result_type = pointer_type;
7289 } else if (is_type_pointer(other_type)) {
7290 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7291 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7294 if (is_type_void(to1) || is_type_void(to2)) {
7296 } else if (types_compatible(get_unqualified_type(to1),
7297 get_unqualified_type(to2))) {
7300 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7304 type_t *const type =
7305 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7306 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7307 } else if (is_type_integer(other_type)) {
7308 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7309 result_type = pointer_type;
7311 goto types_incompatible;
7315 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7316 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7318 result_type = type_error_type;
7321 conditional->true_expression
7322 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7323 conditional->false_expression
7324 = create_implicit_cast(false_expression, result_type);
7325 conditional->base.type = result_type;
7330 * Parse an extension expression.
7332 static expression_t *parse_extension(void)
7335 expression_t *expression = parse_subexpression(PREC_UNARY);
7341 * Parse a __builtin_classify_type() expression.
7343 static expression_t *parse_builtin_classify_type(void)
7345 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7346 result->base.type = type_int;
7348 eat(T___builtin_classify_type);
7350 add_anchor_token(')');
7352 expression_t *expression = parse_expression();
7353 rem_anchor_token(')');
7355 result->classify_type.type_expression = expression;
7361 * Parse a delete expression
7362 * ISO/IEC 14882:1998(E) §5.3.5
7364 static expression_t *parse_delete(void)
7366 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7367 result->base.type = type_void;
7372 result->kind = EXPR_UNARY_DELETE_ARRAY;
7376 expression_t *const value = parse_subexpression(PREC_CAST);
7377 result->unary.value = value;
7379 type_t *const type = skip_typeref(value->base.type);
7380 if (!is_type_pointer(type)) {
7381 if (is_type_valid(type)) {
7382 errorf(&value->base.source_position,
7383 "operand of delete must have pointer type");
7385 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7386 source_position_t const *const pos = &value->base.source_position;
7387 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7394 * Parse a throw expression
7395 * ISO/IEC 14882:1998(E) §15:1
7397 static expression_t *parse_throw(void)
7399 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7400 result->base.type = type_void;
7404 expression_t *value = NULL;
7405 switch (token.kind) {
7407 value = parse_assignment_expression();
7408 /* ISO/IEC 14882:1998(E) §15.1:3 */
7409 type_t *const orig_type = value->base.type;
7410 type_t *const type = skip_typeref(orig_type);
7411 if (is_type_incomplete(type)) {
7412 errorf(&value->base.source_position,
7413 "cannot throw object of incomplete type '%T'", orig_type);
7414 } else if (is_type_pointer(type)) {
7415 type_t *const points_to = skip_typeref(type->pointer.points_to);
7416 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7417 errorf(&value->base.source_position,
7418 "cannot throw pointer to incomplete type '%T'", orig_type);
7426 result->unary.value = value;
7431 static bool check_pointer_arithmetic(const source_position_t *source_position,
7432 type_t *pointer_type,
7433 type_t *orig_pointer_type)
7435 type_t *points_to = pointer_type->pointer.points_to;
7436 points_to = skip_typeref(points_to);
7438 if (is_type_incomplete(points_to)) {
7439 if (!GNU_MODE || !is_type_void(points_to)) {
7440 errorf(source_position,
7441 "arithmetic with pointer to incomplete type '%T' not allowed",
7445 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7447 } else if (is_type_function(points_to)) {
7449 errorf(source_position,
7450 "arithmetic with pointer to function type '%T' not allowed",
7454 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7460 static bool is_lvalue(const expression_t *expression)
7462 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7463 switch (expression->kind) {
7464 case EXPR_ARRAY_ACCESS:
7465 case EXPR_COMPOUND_LITERAL:
7466 case EXPR_REFERENCE:
7468 case EXPR_UNARY_DEREFERENCE:
7472 type_t *type = skip_typeref(expression->base.type);
7474 /* ISO/IEC 14882:1998(E) §3.10:3 */
7475 is_type_reference(type) ||
7476 /* Claim it is an lvalue, if the type is invalid. There was a parse
7477 * error before, which maybe prevented properly recognizing it as
7479 !is_type_valid(type);
7484 static void semantic_incdec(unary_expression_t *expression)
7486 type_t *const orig_type = expression->value->base.type;
7487 type_t *const type = skip_typeref(orig_type);
7488 if (is_type_pointer(type)) {
7489 if (!check_pointer_arithmetic(&expression->base.source_position,
7493 } else if (!is_type_real(type) && is_type_valid(type)) {
7494 /* TODO: improve error message */
7495 errorf(&expression->base.source_position,
7496 "operation needs an arithmetic or pointer type");
7499 if (!is_lvalue(expression->value)) {
7500 /* TODO: improve error message */
7501 errorf(&expression->base.source_position, "lvalue required as operand");
7503 expression->base.type = orig_type;
7506 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7508 type_t *const res_type = promote_integer(type);
7509 expr->base.type = res_type;
7510 expr->value = create_implicit_cast(expr->value, res_type);
7513 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7515 type_t *const orig_type = expression->value->base.type;
7516 type_t *const type = skip_typeref(orig_type);
7517 if (!is_type_arithmetic(type)) {
7518 if (is_type_valid(type)) {
7519 /* TODO: improve error message */
7520 errorf(&expression->base.source_position,
7521 "operation needs an arithmetic type");
7524 } else if (is_type_integer(type)) {
7525 promote_unary_int_expr(expression, type);
7527 expression->base.type = orig_type;
7531 static void semantic_unexpr_plus(unary_expression_t *expression)
7533 semantic_unexpr_arithmetic(expression);
7534 source_position_t const *const pos = &expression->base.source_position;
7535 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7538 static void semantic_not(unary_expression_t *expression)
7540 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7541 semantic_condition(expression->value, "operand of !");
7542 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7545 static void semantic_unexpr_integer(unary_expression_t *expression)
7547 type_t *const orig_type = expression->value->base.type;
7548 type_t *const type = skip_typeref(orig_type);
7549 if (!is_type_integer(type)) {
7550 if (is_type_valid(type)) {
7551 errorf(&expression->base.source_position,
7552 "operand of ~ must be of integer type");
7557 promote_unary_int_expr(expression, type);
7560 static void semantic_dereference(unary_expression_t *expression)
7562 type_t *const orig_type = expression->value->base.type;
7563 type_t *const type = skip_typeref(orig_type);
7564 if (!is_type_pointer(type)) {
7565 if (is_type_valid(type)) {
7566 errorf(&expression->base.source_position,
7567 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7572 type_t *result_type = type->pointer.points_to;
7573 result_type = automatic_type_conversion(result_type);
7574 expression->base.type = result_type;
7578 * Record that an address is taken (expression represents an lvalue).
7580 * @param expression the expression
7581 * @param may_be_register if true, the expression might be an register
7583 static void set_address_taken(expression_t *expression, bool may_be_register)
7585 if (expression->kind != EXPR_REFERENCE)
7588 entity_t *const entity = expression->reference.entity;
7590 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7593 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7594 && !may_be_register) {
7595 source_position_t const *const pos = &expression->base.source_position;
7596 errorf(pos, "address of register '%N' requested", entity);
7599 entity->variable.address_taken = true;
7603 * Check the semantic of the address taken expression.
7605 static void semantic_take_addr(unary_expression_t *expression)
7607 expression_t *value = expression->value;
7608 value->base.type = revert_automatic_type_conversion(value);
7610 type_t *orig_type = value->base.type;
7611 type_t *type = skip_typeref(orig_type);
7612 if (!is_type_valid(type))
7616 if (!is_lvalue(value)) {
7617 errorf(&expression->base.source_position, "'&' requires an lvalue");
7619 if (is_bitfield(value)) {
7620 errorf(&expression->base.source_position,
7621 "'&' not allowed on bitfield");
7624 set_address_taken(value, false);
7626 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7629 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7630 static expression_t *parse_##unexpression_type(void) \
7632 expression_t *unary_expression \
7633 = allocate_expression_zero(unexpression_type); \
7635 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7637 sfunc(&unary_expression->unary); \
7639 return unary_expression; \
7642 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7643 semantic_unexpr_arithmetic)
7644 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7645 semantic_unexpr_plus)
7646 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7648 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7649 semantic_dereference)
7650 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7652 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7653 semantic_unexpr_integer)
7654 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7656 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7659 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7661 static expression_t *parse_##unexpression_type(expression_t *left) \
7663 expression_t *unary_expression \
7664 = allocate_expression_zero(unexpression_type); \
7666 unary_expression->unary.value = left; \
7668 sfunc(&unary_expression->unary); \
7670 return unary_expression; \
7673 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7674 EXPR_UNARY_POSTFIX_INCREMENT,
7676 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7677 EXPR_UNARY_POSTFIX_DECREMENT,
7680 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7682 /* TODO: handle complex + imaginary types */
7684 type_left = get_unqualified_type(type_left);
7685 type_right = get_unqualified_type(type_right);
7687 /* §6.3.1.8 Usual arithmetic conversions */
7688 if (type_left == type_long_double || type_right == type_long_double) {
7689 return type_long_double;
7690 } else if (type_left == type_double || type_right == type_double) {
7692 } else if (type_left == type_float || type_right == type_float) {
7696 type_left = promote_integer(type_left);
7697 type_right = promote_integer(type_right);
7699 if (type_left == type_right)
7702 bool const signed_left = is_type_signed(type_left);
7703 bool const signed_right = is_type_signed(type_right);
7704 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7705 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7707 if (signed_left == signed_right)
7708 return rank_left >= rank_right ? type_left : type_right;
7712 atomic_type_kind_t s_akind;
7713 atomic_type_kind_t u_akind;
7718 u_type = type_right;
7720 s_type = type_right;
7723 s_akind = get_akind(s_type);
7724 u_akind = get_akind(u_type);
7725 s_rank = get_akind_rank(s_akind);
7726 u_rank = get_akind_rank(u_akind);
7728 if (u_rank >= s_rank)
7731 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7735 case ATOMIC_TYPE_INT: return type_unsigned_int;
7736 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7737 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7739 default: panic("invalid atomic type");
7744 * Check the semantic restrictions for a binary expression.
7746 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7748 expression_t *const left = expression->left;
7749 expression_t *const right = expression->right;
7750 type_t *const orig_type_left = left->base.type;
7751 type_t *const orig_type_right = right->base.type;
7752 type_t *const type_left = skip_typeref(orig_type_left);
7753 type_t *const type_right = skip_typeref(orig_type_right);
7755 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7756 /* TODO: improve error message */
7757 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7758 errorf(&expression->base.source_position,
7759 "operation needs arithmetic types");
7764 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7765 expression->left = create_implicit_cast(left, arithmetic_type);
7766 expression->right = create_implicit_cast(right, arithmetic_type);
7767 expression->base.type = arithmetic_type;
7770 static void semantic_binexpr_integer(binary_expression_t *const expression)
7772 expression_t *const left = expression->left;
7773 expression_t *const right = expression->right;
7774 type_t *const orig_type_left = left->base.type;
7775 type_t *const orig_type_right = right->base.type;
7776 type_t *const type_left = skip_typeref(orig_type_left);
7777 type_t *const type_right = skip_typeref(orig_type_right);
7779 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7780 /* TODO: improve error message */
7781 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7782 errorf(&expression->base.source_position,
7783 "operation needs integer types");
7788 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7789 expression->left = create_implicit_cast(left, result_type);
7790 expression->right = create_implicit_cast(right, result_type);
7791 expression->base.type = result_type;
7794 static void warn_div_by_zero(binary_expression_t const *const expression)
7796 if (!is_type_integer(expression->base.type))
7799 expression_t const *const right = expression->right;
7800 /* The type of the right operand can be different for /= */
7801 if (is_type_integer(right->base.type) &&
7802 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7803 !fold_constant_to_bool(right)) {
7804 source_position_t const *const pos = &expression->base.source_position;
7805 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7810 * Check the semantic restrictions for a div/mod expression.
7812 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7814 semantic_binexpr_arithmetic(expression);
7815 warn_div_by_zero(expression);
7818 static void warn_addsub_in_shift(const expression_t *const expr)
7820 if (expr->base.parenthesized)
7824 switch (expr->kind) {
7825 case EXPR_BINARY_ADD: op = '+'; break;
7826 case EXPR_BINARY_SUB: op = '-'; break;
7830 source_position_t const *const pos = &expr->base.source_position;
7831 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7834 static bool semantic_shift(binary_expression_t *expression)
7836 expression_t *const left = expression->left;
7837 expression_t *const right = expression->right;
7838 type_t *const orig_type_left = left->base.type;
7839 type_t *const orig_type_right = right->base.type;
7840 type_t * type_left = skip_typeref(orig_type_left);
7841 type_t * type_right = skip_typeref(orig_type_right);
7843 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7844 /* TODO: improve error message */
7845 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7846 errorf(&expression->base.source_position,
7847 "operands of shift operation must have integer types");
7852 type_left = promote_integer(type_left);
7854 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7855 source_position_t const *const pos = &right->base.source_position;
7856 long const count = fold_constant_to_int(right);
7858 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7859 } else if ((unsigned long)count >=
7860 get_atomic_type_size(type_left->atomic.akind) * 8) {
7861 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7865 type_right = promote_integer(type_right);
7866 expression->right = create_implicit_cast(right, type_right);
7871 static void semantic_shift_op(binary_expression_t *expression)
7873 expression_t *const left = expression->left;
7874 expression_t *const right = expression->right;
7876 if (!semantic_shift(expression))
7879 warn_addsub_in_shift(left);
7880 warn_addsub_in_shift(right);
7882 type_t *const orig_type_left = left->base.type;
7883 type_t * type_left = skip_typeref(orig_type_left);
7885 type_left = promote_integer(type_left);
7886 expression->left = create_implicit_cast(left, type_left);
7887 expression->base.type = type_left;
7890 static void semantic_add(binary_expression_t *expression)
7892 expression_t *const left = expression->left;
7893 expression_t *const right = expression->right;
7894 type_t *const orig_type_left = left->base.type;
7895 type_t *const orig_type_right = right->base.type;
7896 type_t *const type_left = skip_typeref(orig_type_left);
7897 type_t *const type_right = skip_typeref(orig_type_right);
7900 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7901 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7902 expression->left = create_implicit_cast(left, arithmetic_type);
7903 expression->right = create_implicit_cast(right, arithmetic_type);
7904 expression->base.type = arithmetic_type;
7905 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7906 check_pointer_arithmetic(&expression->base.source_position,
7907 type_left, orig_type_left);
7908 expression->base.type = type_left;
7909 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7910 check_pointer_arithmetic(&expression->base.source_position,
7911 type_right, orig_type_right);
7912 expression->base.type = type_right;
7913 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7914 errorf(&expression->base.source_position,
7915 "invalid operands to binary + ('%T', '%T')",
7916 orig_type_left, orig_type_right);
7920 static void semantic_sub(binary_expression_t *expression)
7922 expression_t *const left = expression->left;
7923 expression_t *const right = expression->right;
7924 type_t *const orig_type_left = left->base.type;
7925 type_t *const orig_type_right = right->base.type;
7926 type_t *const type_left = skip_typeref(orig_type_left);
7927 type_t *const type_right = skip_typeref(orig_type_right);
7928 source_position_t const *const pos = &expression->base.source_position;
7931 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7932 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7933 expression->left = create_implicit_cast(left, arithmetic_type);
7934 expression->right = create_implicit_cast(right, arithmetic_type);
7935 expression->base.type = arithmetic_type;
7936 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7937 check_pointer_arithmetic(&expression->base.source_position,
7938 type_left, orig_type_left);
7939 expression->base.type = type_left;
7940 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7941 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7942 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7943 if (!types_compatible(unqual_left, unqual_right)) {
7945 "subtracting pointers to incompatible types '%T' and '%T'",
7946 orig_type_left, orig_type_right);
7947 } else if (!is_type_object(unqual_left)) {
7948 if (!is_type_void(unqual_left)) {
7949 errorf(pos, "subtracting pointers to non-object types '%T'",
7952 warningf(WARN_OTHER, pos, "subtracting pointers to void");
7955 expression->base.type = type_ptrdiff_t;
7956 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7957 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7958 orig_type_left, orig_type_right);
7962 static void warn_string_literal_address(expression_t const* expr)
7964 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7965 expr = expr->unary.value;
7966 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7968 expr = expr->unary.value;
7971 if (expr->kind == EXPR_STRING_LITERAL) {
7972 source_position_t const *const pos = &expr->base.source_position;
7973 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
7977 static bool maybe_negative(expression_t const *const expr)
7979 switch (is_constant_expression(expr)) {
7980 case EXPR_CLASS_ERROR: return false;
7981 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
7982 default: return true;
7986 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
7988 warn_string_literal_address(expr);
7990 expression_t const* const ref = get_reference_address(expr);
7991 if (ref != NULL && is_null_pointer_constant(other)) {
7992 entity_t const *const ent = ref->reference.entity;
7993 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
7996 if (!expr->base.parenthesized) {
7997 switch (expr->base.kind) {
7998 case EXPR_BINARY_LESS:
7999 case EXPR_BINARY_GREATER:
8000 case EXPR_BINARY_LESSEQUAL:
8001 case EXPR_BINARY_GREATEREQUAL:
8002 case EXPR_BINARY_NOTEQUAL:
8003 case EXPR_BINARY_EQUAL:
8004 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8013 * Check the semantics of comparison expressions.
8015 * @param expression The expression to check.
8017 static void semantic_comparison(binary_expression_t *expression)
8019 source_position_t const *const pos = &expression->base.source_position;
8020 expression_t *const left = expression->left;
8021 expression_t *const right = expression->right;
8023 warn_comparison(pos, left, right);
8024 warn_comparison(pos, right, left);
8026 type_t *orig_type_left = left->base.type;
8027 type_t *orig_type_right = right->base.type;
8028 type_t *type_left = skip_typeref(orig_type_left);
8029 type_t *type_right = skip_typeref(orig_type_right);
8031 /* TODO non-arithmetic types */
8032 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8033 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8035 /* test for signed vs unsigned compares */
8036 if (is_type_integer(arithmetic_type)) {
8037 bool const signed_left = is_type_signed(type_left);
8038 bool const signed_right = is_type_signed(type_right);
8039 if (signed_left != signed_right) {
8040 /* FIXME long long needs better const folding magic */
8041 /* TODO check whether constant value can be represented by other type */
8042 if ((signed_left && maybe_negative(left)) ||
8043 (signed_right && maybe_negative(right))) {
8044 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8049 expression->left = create_implicit_cast(left, arithmetic_type);
8050 expression->right = create_implicit_cast(right, arithmetic_type);
8051 expression->base.type = arithmetic_type;
8052 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8053 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8054 is_type_float(arithmetic_type)) {
8055 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8057 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8058 /* TODO check compatibility */
8059 } else if (is_type_pointer(type_left)) {
8060 expression->right = create_implicit_cast(right, type_left);
8061 } else if (is_type_pointer(type_right)) {
8062 expression->left = create_implicit_cast(left, type_right);
8063 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8064 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8066 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8070 * Checks if a compound type has constant fields.
8072 static bool has_const_fields(const compound_type_t *type)
8074 compound_t *compound = type->compound;
8075 entity_t *entry = compound->members.entities;
8077 for (; entry != NULL; entry = entry->base.next) {
8078 if (!is_declaration(entry))
8081 const type_t *decl_type = skip_typeref(entry->declaration.type);
8082 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8089 static bool is_valid_assignment_lhs(expression_t const* const left)
8091 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8092 type_t *const type_left = skip_typeref(orig_type_left);
8094 if (!is_lvalue(left)) {
8095 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8100 if (left->kind == EXPR_REFERENCE
8101 && left->reference.entity->kind == ENTITY_FUNCTION) {
8102 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8106 if (is_type_array(type_left)) {
8107 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8110 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8111 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8115 if (is_type_incomplete(type_left)) {
8116 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8117 left, orig_type_left);
8120 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8121 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8122 left, orig_type_left);
8129 static void semantic_arithmetic_assign(binary_expression_t *expression)
8131 expression_t *left = expression->left;
8132 expression_t *right = expression->right;
8133 type_t *orig_type_left = left->base.type;
8134 type_t *orig_type_right = right->base.type;
8136 if (!is_valid_assignment_lhs(left))
8139 type_t *type_left = skip_typeref(orig_type_left);
8140 type_t *type_right = skip_typeref(orig_type_right);
8142 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8143 /* TODO: improve error message */
8144 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8145 errorf(&expression->base.source_position,
8146 "operation needs arithmetic types");
8151 /* combined instructions are tricky. We can't create an implicit cast on
8152 * the left side, because we need the uncasted form for the store.
8153 * The ast2firm pass has to know that left_type must be right_type
8154 * for the arithmetic operation and create a cast by itself */
8155 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8156 expression->right = create_implicit_cast(right, arithmetic_type);
8157 expression->base.type = type_left;
8160 static void semantic_divmod_assign(binary_expression_t *expression)
8162 semantic_arithmetic_assign(expression);
8163 warn_div_by_zero(expression);
8166 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8168 expression_t *const left = expression->left;
8169 expression_t *const right = expression->right;
8170 type_t *const orig_type_left = left->base.type;
8171 type_t *const orig_type_right = right->base.type;
8172 type_t *const type_left = skip_typeref(orig_type_left);
8173 type_t *const type_right = skip_typeref(orig_type_right);
8175 if (!is_valid_assignment_lhs(left))
8178 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8179 /* combined instructions are tricky. We can't create an implicit cast on
8180 * the left side, because we need the uncasted form for the store.
8181 * The ast2firm pass has to know that left_type must be right_type
8182 * for the arithmetic operation and create a cast by itself */
8183 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8184 expression->right = create_implicit_cast(right, arithmetic_type);
8185 expression->base.type = type_left;
8186 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8187 check_pointer_arithmetic(&expression->base.source_position,
8188 type_left, orig_type_left);
8189 expression->base.type = type_left;
8190 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8191 errorf(&expression->base.source_position,
8192 "incompatible types '%T' and '%T' in assignment",
8193 orig_type_left, orig_type_right);
8197 static void semantic_integer_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_integer(type_left) || !is_type_integer(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 integer 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_shift_assign(binary_expression_t *expression)
8230 expression_t *left = expression->left;
8232 if (!is_valid_assignment_lhs(left))
8235 if (!semantic_shift(expression))
8238 expression->base.type = skip_typeref(left->base.type);
8241 static void warn_logical_and_within_or(const expression_t *const expr)
8243 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8245 if (expr->base.parenthesized)
8247 source_position_t const *const pos = &expr->base.source_position;
8248 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8252 * Check the semantic restrictions of a logical expression.
8254 static void semantic_logical_op(binary_expression_t *expression)
8256 /* §6.5.13:2 Each of the operands shall have scalar type.
8257 * §6.5.14:2 Each of the operands shall have scalar type. */
8258 semantic_condition(expression->left, "left operand of logical operator");
8259 semantic_condition(expression->right, "right operand of logical operator");
8260 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8261 warn_logical_and_within_or(expression->left);
8262 warn_logical_and_within_or(expression->right);
8264 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8268 * Check the semantic restrictions of a binary assign expression.
8270 static void semantic_binexpr_assign(binary_expression_t *expression)
8272 expression_t *left = expression->left;
8273 type_t *orig_type_left = left->base.type;
8275 if (!is_valid_assignment_lhs(left))
8278 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8279 report_assign_error(error, orig_type_left, expression->right,
8280 "assignment", &left->base.source_position);
8281 expression->right = create_implicit_cast(expression->right, orig_type_left);
8282 expression->base.type = orig_type_left;
8286 * Determine if the outermost operation (or parts thereof) of the given
8287 * expression has no effect in order to generate a warning about this fact.
8288 * Therefore in some cases this only examines some of the operands of the
8289 * expression (see comments in the function and examples below).
8291 * f() + 23; // warning, because + has no effect
8292 * x || f(); // no warning, because x controls execution of f()
8293 * x ? y : f(); // warning, because y has no effect
8294 * (void)x; // no warning to be able to suppress the warning
8295 * This function can NOT be used for an "expression has definitely no effect"-
8297 static bool expression_has_effect(const expression_t *const expr)
8299 switch (expr->kind) {
8300 case EXPR_ERROR: return true; /* do NOT warn */
8301 case EXPR_REFERENCE: return false;
8302 case EXPR_ENUM_CONSTANT: return false;
8303 case EXPR_LABEL_ADDRESS: return false;
8305 /* suppress the warning for microsoft __noop operations */
8306 case EXPR_LITERAL_MS_NOOP: return true;
8307 case EXPR_LITERAL_BOOLEAN:
8308 case EXPR_LITERAL_CHARACTER:
8309 case EXPR_LITERAL_WIDE_CHARACTER:
8310 case EXPR_LITERAL_INTEGER:
8311 case EXPR_LITERAL_FLOATINGPOINT:
8312 case EXPR_STRING_LITERAL: return false;
8315 const call_expression_t *const call = &expr->call;
8316 if (call->function->kind != EXPR_REFERENCE)
8319 switch (call->function->reference.entity->function.btk) {
8320 /* FIXME: which builtins have no effect? */
8321 default: return true;
8325 /* Generate the warning if either the left or right hand side of a
8326 * conditional expression has no effect */
8327 case EXPR_CONDITIONAL: {
8328 conditional_expression_t const *const cond = &expr->conditional;
8329 expression_t const *const t = cond->true_expression;
8331 (t == NULL || expression_has_effect(t)) &&
8332 expression_has_effect(cond->false_expression);
8335 case EXPR_SELECT: return false;
8336 case EXPR_ARRAY_ACCESS: return false;
8337 case EXPR_SIZEOF: return false;
8338 case EXPR_CLASSIFY_TYPE: return false;
8339 case EXPR_ALIGNOF: return false;
8341 case EXPR_FUNCNAME: return false;
8342 case EXPR_BUILTIN_CONSTANT_P: return false;
8343 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8344 case EXPR_OFFSETOF: return false;
8345 case EXPR_VA_START: return true;
8346 case EXPR_VA_ARG: return true;
8347 case EXPR_VA_COPY: return true;
8348 case EXPR_STATEMENT: return true; // TODO
8349 case EXPR_COMPOUND_LITERAL: return false;
8351 case EXPR_UNARY_NEGATE: return false;
8352 case EXPR_UNARY_PLUS: return false;
8353 case EXPR_UNARY_BITWISE_NEGATE: return false;
8354 case EXPR_UNARY_NOT: return false;
8355 case EXPR_UNARY_DEREFERENCE: return false;
8356 case EXPR_UNARY_TAKE_ADDRESS: return false;
8357 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8358 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8359 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8360 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8362 /* Treat void casts as if they have an effect in order to being able to
8363 * suppress the warning */
8364 case EXPR_UNARY_CAST: {
8365 type_t *const type = skip_typeref(expr->base.type);
8366 return is_type_void(type);
8369 case EXPR_UNARY_ASSUME: return true;
8370 case EXPR_UNARY_DELETE: return true;
8371 case EXPR_UNARY_DELETE_ARRAY: return true;
8372 case EXPR_UNARY_THROW: return true;
8374 case EXPR_BINARY_ADD: return false;
8375 case EXPR_BINARY_SUB: return false;
8376 case EXPR_BINARY_MUL: return false;
8377 case EXPR_BINARY_DIV: return false;
8378 case EXPR_BINARY_MOD: return false;
8379 case EXPR_BINARY_EQUAL: return false;
8380 case EXPR_BINARY_NOTEQUAL: return false;
8381 case EXPR_BINARY_LESS: return false;
8382 case EXPR_BINARY_LESSEQUAL: return false;
8383 case EXPR_BINARY_GREATER: return false;
8384 case EXPR_BINARY_GREATEREQUAL: return false;
8385 case EXPR_BINARY_BITWISE_AND: return false;
8386 case EXPR_BINARY_BITWISE_OR: return false;
8387 case EXPR_BINARY_BITWISE_XOR: return false;
8388 case EXPR_BINARY_SHIFTLEFT: return false;
8389 case EXPR_BINARY_SHIFTRIGHT: return false;
8390 case EXPR_BINARY_ASSIGN: return true;
8391 case EXPR_BINARY_MUL_ASSIGN: return true;
8392 case EXPR_BINARY_DIV_ASSIGN: return true;
8393 case EXPR_BINARY_MOD_ASSIGN: return true;
8394 case EXPR_BINARY_ADD_ASSIGN: return true;
8395 case EXPR_BINARY_SUB_ASSIGN: return true;
8396 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8397 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8398 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8399 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8400 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8402 /* Only examine the right hand side of && and ||, because the left hand
8403 * side already has the effect of controlling the execution of the right
8405 case EXPR_BINARY_LOGICAL_AND:
8406 case EXPR_BINARY_LOGICAL_OR:
8407 /* Only examine the right hand side of a comma expression, because the left
8408 * hand side has a separate warning */
8409 case EXPR_BINARY_COMMA:
8410 return expression_has_effect(expr->binary.right);
8412 case EXPR_BINARY_ISGREATER: return false;
8413 case EXPR_BINARY_ISGREATEREQUAL: return false;
8414 case EXPR_BINARY_ISLESS: return false;
8415 case EXPR_BINARY_ISLESSEQUAL: return false;
8416 case EXPR_BINARY_ISLESSGREATER: return false;
8417 case EXPR_BINARY_ISUNORDERED: return false;
8420 internal_errorf(HERE, "unexpected expression");
8423 static void semantic_comma(binary_expression_t *expression)
8425 const expression_t *const left = expression->left;
8426 if (!expression_has_effect(left)) {
8427 source_position_t const *const pos = &left->base.source_position;
8428 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8430 expression->base.type = expression->right->base.type;
8434 * @param prec_r precedence of the right operand
8436 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8437 static expression_t *parse_##binexpression_type(expression_t *left) \
8439 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8440 binexpr->binary.left = left; \
8443 expression_t *right = parse_subexpression(prec_r); \
8445 binexpr->binary.right = right; \
8446 sfunc(&binexpr->binary); \
8451 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8452 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8453 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8454 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8455 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8456 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8457 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8458 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8459 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8460 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8461 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8462 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8463 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8464 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8465 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8466 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8467 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8468 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8469 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8470 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8471 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8472 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8473 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8474 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8475 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8476 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8477 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8478 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8479 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8480 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8483 static expression_t *parse_subexpression(precedence_t precedence)
8485 expression_parser_function_t *parser
8486 = &expression_parsers[token.kind];
8489 if (parser->parser != NULL) {
8490 left = parser->parser();
8492 left = parse_primary_expression();
8494 assert(left != NULL);
8497 parser = &expression_parsers[token.kind];
8498 if (parser->infix_parser == NULL)
8500 if (parser->infix_precedence < precedence)
8503 left = parser->infix_parser(left);
8505 assert(left != NULL);
8512 * Parse an expression.
8514 static expression_t *parse_expression(void)
8516 return parse_subexpression(PREC_EXPRESSION);
8520 * Register a parser for a prefix-like operator.
8522 * @param parser the parser function
8523 * @param token_kind the token type of the prefix token
8525 static void register_expression_parser(parse_expression_function parser,
8528 expression_parser_function_t *entry = &expression_parsers[token_kind];
8530 if (entry->parser != NULL) {
8531 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8532 panic("trying to register multiple expression parsers for a token");
8534 entry->parser = parser;
8538 * Register a parser for an infix operator with given precedence.
8540 * @param parser the parser function
8541 * @param token_kind the token type of the infix operator
8542 * @param precedence the precedence of the operator
8544 static void register_infix_parser(parse_expression_infix_function parser,
8545 int token_kind, precedence_t precedence)
8547 expression_parser_function_t *entry = &expression_parsers[token_kind];
8549 if (entry->infix_parser != NULL) {
8550 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8551 panic("trying to register multiple infix expression parsers for a "
8554 entry->infix_parser = parser;
8555 entry->infix_precedence = precedence;
8559 * Initialize the expression parsers.
8561 static void init_expression_parsers(void)
8563 memset(&expression_parsers, 0, sizeof(expression_parsers));
8565 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8566 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8567 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8568 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8569 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8570 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8571 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8572 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8573 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8574 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8575 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8576 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8577 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8578 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8579 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8580 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8581 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8582 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8583 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8584 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8585 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8586 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8587 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8588 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8589 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8590 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8591 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8592 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8593 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8594 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8595 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8596 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8597 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8598 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8599 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8600 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8601 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8603 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8604 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8605 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8606 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8607 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8608 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8609 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8610 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8611 register_expression_parser(parse_sizeof, T_sizeof);
8612 register_expression_parser(parse_alignof, T___alignof__);
8613 register_expression_parser(parse_extension, T___extension__);
8614 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8615 register_expression_parser(parse_delete, T_delete);
8616 register_expression_parser(parse_throw, T_throw);
8620 * Parse a asm statement arguments specification.
8622 static asm_argument_t *parse_asm_arguments(bool is_out)
8624 asm_argument_t *result = NULL;
8625 asm_argument_t **anchor = &result;
8627 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8628 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8631 add_anchor_token(']');
8632 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8633 rem_anchor_token(']');
8635 if (!argument->symbol)
8639 argument->constraints = parse_string_literals();
8640 add_anchor_token(')');
8642 expression_t *expression = parse_expression();
8643 rem_anchor_token(')');
8645 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8646 * change size or type representation (e.g. int -> long is ok, but
8647 * int -> float is not) */
8648 if (expression->kind == EXPR_UNARY_CAST) {
8649 type_t *const type = expression->base.type;
8650 type_kind_t const kind = type->kind;
8651 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8654 if (kind == TYPE_ATOMIC) {
8655 atomic_type_kind_t const akind = type->atomic.akind;
8656 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8657 size = get_atomic_type_size(akind);
8659 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8660 size = get_type_size(type_void_ptr);
8664 expression_t *const value = expression->unary.value;
8665 type_t *const value_type = value->base.type;
8666 type_kind_t const value_kind = value_type->kind;
8668 unsigned value_flags;
8669 unsigned value_size;
8670 if (value_kind == TYPE_ATOMIC) {
8671 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8672 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8673 value_size = get_atomic_type_size(value_akind);
8674 } else if (value_kind == TYPE_POINTER) {
8675 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8676 value_size = get_type_size(type_void_ptr);
8681 if (value_flags != flags || value_size != size)
8685 } while (expression->kind == EXPR_UNARY_CAST);
8689 if (!is_lvalue(expression)) {
8690 errorf(&expression->base.source_position,
8691 "asm output argument is not an lvalue");
8694 if (argument->constraints.begin[0] == '=')
8695 determine_lhs_ent(expression, NULL);
8697 mark_vars_read(expression, NULL);
8699 mark_vars_read(expression, NULL);
8701 argument->expression = expression;
8704 set_address_taken(expression, true);
8707 anchor = &argument->next;
8717 * Parse a asm statement clobber specification.
8719 static asm_clobber_t *parse_asm_clobbers(void)
8721 asm_clobber_t *result = NULL;
8722 asm_clobber_t **anchor = &result;
8724 while (token.kind == T_STRING_LITERAL) {
8725 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8726 clobber->clobber = parse_string_literals();
8729 anchor = &clobber->next;
8739 * Parse an asm statement.
8741 static statement_t *parse_asm_statement(void)
8743 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8744 asm_statement_t *asm_statement = &statement->asms;
8748 if (next_if(T_volatile))
8749 asm_statement->is_volatile = true;
8752 add_anchor_token(')');
8753 if (token.kind != T_STRING_LITERAL) {
8754 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8757 asm_statement->asm_text = parse_string_literals();
8759 add_anchor_token(':');
8760 if (!next_if(':')) {
8761 rem_anchor_token(':');
8765 asm_statement->outputs = parse_asm_arguments(true);
8766 if (!next_if(':')) {
8767 rem_anchor_token(':');
8771 asm_statement->inputs = parse_asm_arguments(false);
8772 if (!next_if(':')) {
8773 rem_anchor_token(':');
8776 rem_anchor_token(':');
8778 asm_statement->clobbers = parse_asm_clobbers();
8781 rem_anchor_token(')');
8785 if (asm_statement->outputs == NULL) {
8786 /* GCC: An 'asm' instruction without any output operands will be treated
8787 * identically to a volatile 'asm' instruction. */
8788 asm_statement->is_volatile = true;
8794 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8796 statement_t *inner_stmt;
8797 switch (token.kind) {
8799 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8800 inner_stmt = create_error_statement();
8804 if (label->kind == STATEMENT_LABEL) {
8805 /* Eat an empty statement here, to avoid the warning about an empty
8806 * statement after a label. label:; is commonly used to have a label
8807 * before a closing brace. */
8808 inner_stmt = create_empty_statement();
8815 inner_stmt = parse_statement();
8816 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8817 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8818 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8819 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8827 * Parse a case statement.
8829 static statement_t *parse_case_statement(void)
8831 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8832 source_position_t *const pos = &statement->base.source_position;
8835 add_anchor_token(':');
8837 expression_t *expression = parse_expression();
8838 type_t *expression_type = expression->base.type;
8839 type_t *skipped = skip_typeref(expression_type);
8840 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8841 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8842 expression, expression_type);
8845 type_t *type = expression_type;
8846 if (current_switch != NULL) {
8847 type_t *switch_type = current_switch->expression->base.type;
8848 if (is_type_valid(switch_type)) {
8849 expression = create_implicit_cast(expression, switch_type);
8853 statement->case_label.expression = expression;
8854 expression_classification_t const expr_class = is_constant_expression(expression);
8855 if (expr_class != EXPR_CLASS_CONSTANT) {
8856 if (expr_class != EXPR_CLASS_ERROR) {
8857 errorf(pos, "case label does not reduce to an integer constant");
8859 statement->case_label.is_bad = true;
8861 long const val = fold_constant_to_int(expression);
8862 statement->case_label.first_case = val;
8863 statement->case_label.last_case = val;
8867 if (next_if(T_DOTDOTDOT)) {
8868 expression_t *end_range = parse_expression();
8869 expression_type = expression->base.type;
8870 skipped = skip_typeref(expression_type);
8871 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8872 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8873 expression, expression_type);
8876 end_range = create_implicit_cast(end_range, type);
8877 statement->case_label.end_range = end_range;
8878 expression_classification_t const end_class = is_constant_expression(end_range);
8879 if (end_class != EXPR_CLASS_CONSTANT) {
8880 if (end_class != EXPR_CLASS_ERROR) {
8881 errorf(pos, "case range does not reduce to an integer constant");
8883 statement->case_label.is_bad = true;
8885 long const val = fold_constant_to_int(end_range);
8886 statement->case_label.last_case = val;
8888 if (val < statement->case_label.first_case) {
8889 statement->case_label.is_empty_range = true;
8890 warningf(WARN_OTHER, pos, "empty range specified");
8896 PUSH_PARENT(statement);
8898 rem_anchor_token(':');
8901 if (current_switch != NULL) {
8902 if (! statement->case_label.is_bad) {
8903 /* Check for duplicate case values */
8904 case_label_statement_t *c = &statement->case_label;
8905 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8906 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8909 if (c->last_case < l->first_case || c->first_case > l->last_case)
8912 errorf(pos, "duplicate case value (previously used %P)",
8913 &l->base.source_position);
8917 /* link all cases into the switch statement */
8918 if (current_switch->last_case == NULL) {
8919 current_switch->first_case = &statement->case_label;
8921 current_switch->last_case->next = &statement->case_label;
8923 current_switch->last_case = &statement->case_label;
8925 errorf(pos, "case label not within a switch statement");
8928 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
8935 * Parse a default statement.
8937 static statement_t *parse_default_statement(void)
8939 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8943 PUSH_PARENT(statement);
8947 if (current_switch != NULL) {
8948 const case_label_statement_t *def_label = current_switch->default_label;
8949 if (def_label != NULL) {
8950 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
8952 current_switch->default_label = &statement->case_label;
8954 /* link all cases into the switch statement */
8955 if (current_switch->last_case == NULL) {
8956 current_switch->first_case = &statement->case_label;
8958 current_switch->last_case->next = &statement->case_label;
8960 current_switch->last_case = &statement->case_label;
8963 errorf(&statement->base.source_position,
8964 "'default' label not within a switch statement");
8967 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
8974 * Parse a label statement.
8976 static statement_t *parse_label_statement(void)
8978 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8979 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
8980 statement->label.label = label;
8982 PUSH_PARENT(statement);
8984 /* if statement is already set then the label is defined twice,
8985 * otherwise it was just mentioned in a goto/local label declaration so far
8987 source_position_t const* const pos = &statement->base.source_position;
8988 if (label->statement != NULL) {
8989 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
8991 label->base.source_position = *pos;
8992 label->statement = statement;
8997 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
8998 parse_attributes(NULL); // TODO process attributes
9001 statement->label.statement = parse_label_inner_statement(statement, "label");
9003 /* remember the labels in a list for later checking */
9004 *label_anchor = &statement->label;
9005 label_anchor = &statement->label.next;
9011 static statement_t *parse_inner_statement(void)
9013 statement_t *const stmt = parse_statement();
9014 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9015 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9016 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9017 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9023 * Parse an expression in parentheses and mark its variables as read.
9025 static expression_t *parse_condition(void)
9027 add_anchor_token(')');
9029 expression_t *const expr = parse_expression();
9030 mark_vars_read(expr, NULL);
9031 rem_anchor_token(')');
9037 * Parse an if statement.
9039 static statement_t *parse_if(void)
9041 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9045 PUSH_PARENT(statement);
9046 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9048 add_anchor_token(T_else);
9050 expression_t *const expr = parse_condition();
9051 statement->ifs.condition = expr;
9052 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9054 semantic_condition(expr, "condition of 'if'-statment");
9056 statement_t *const true_stmt = parse_inner_statement();
9057 statement->ifs.true_statement = true_stmt;
9058 rem_anchor_token(T_else);
9060 if (true_stmt->kind == STATEMENT_EMPTY) {
9061 warningf(WARN_EMPTY_BODY, HERE,
9062 "suggest braces around empty body in an ‘if’ statement");
9065 if (next_if(T_else)) {
9066 statement->ifs.false_statement = parse_inner_statement();
9068 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9069 warningf(WARN_EMPTY_BODY, HERE,
9070 "suggest braces around empty body in an ‘if’ statement");
9072 } else if (true_stmt->kind == STATEMENT_IF &&
9073 true_stmt->ifs.false_statement != NULL) {
9074 source_position_t const *const pos = &true_stmt->base.source_position;
9075 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9084 * Check that all enums are handled in a switch.
9086 * @param statement the switch statement to check
9088 static void check_enum_cases(const switch_statement_t *statement)
9090 if (!is_warn_on(WARN_SWITCH_ENUM))
9092 const type_t *type = skip_typeref(statement->expression->base.type);
9093 if (! is_type_enum(type))
9095 const enum_type_t *enumt = &type->enumt;
9097 /* if we have a default, no warnings */
9098 if (statement->default_label != NULL)
9101 /* FIXME: calculation of value should be done while parsing */
9102 /* TODO: quadratic algorithm here. Change to an n log n one */
9103 long last_value = -1;
9104 const entity_t *entry = enumt->enume->base.next;
9105 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9106 entry = entry->base.next) {
9107 const expression_t *expression = entry->enum_value.value;
9108 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9110 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9111 if (l->expression == NULL)
9113 if (l->first_case <= value && value <= l->last_case) {
9119 source_position_t const *const pos = &statement->base.source_position;
9120 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9127 * Parse a switch statement.
9129 static statement_t *parse_switch(void)
9131 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9135 PUSH_PARENT(statement);
9136 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9138 expression_t *const expr = parse_condition();
9139 type_t * type = skip_typeref(expr->base.type);
9140 if (is_type_integer(type)) {
9141 type = promote_integer(type);
9142 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9143 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9145 } else if (is_type_valid(type)) {
9146 errorf(&expr->base.source_position,
9147 "switch quantity is not an integer, but '%T'", type);
9148 type = type_error_type;
9150 statement->switchs.expression = create_implicit_cast(expr, type);
9152 switch_statement_t *rem = current_switch;
9153 current_switch = &statement->switchs;
9154 statement->switchs.body = parse_inner_statement();
9155 current_switch = rem;
9157 if (statement->switchs.default_label == NULL) {
9158 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9160 check_enum_cases(&statement->switchs);
9167 static statement_t *parse_loop_body(statement_t *const loop)
9169 statement_t *const rem = current_loop;
9170 current_loop = loop;
9172 statement_t *const body = parse_inner_statement();
9179 * Parse a while statement.
9181 static statement_t *parse_while(void)
9183 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9187 PUSH_PARENT(statement);
9188 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9190 expression_t *const cond = parse_condition();
9191 statement->whiles.condition = cond;
9192 /* §6.8.5:2 The controlling expression of an iteration statement shall
9193 * have scalar type. */
9194 semantic_condition(cond, "condition of 'while'-statement");
9196 statement->whiles.body = parse_loop_body(statement);
9204 * Parse a do statement.
9206 static statement_t *parse_do(void)
9208 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9212 PUSH_PARENT(statement);
9213 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9215 add_anchor_token(T_while);
9216 statement->do_while.body = parse_loop_body(statement);
9217 rem_anchor_token(T_while);
9220 expression_t *const cond = parse_condition();
9221 statement->do_while.condition = cond;
9222 /* §6.8.5:2 The controlling expression of an iteration statement shall
9223 * have scalar type. */
9224 semantic_condition(cond, "condition of 'do-while'-statement");
9233 * Parse a for statement.
9235 static statement_t *parse_for(void)
9237 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9241 PUSH_PARENT(statement);
9242 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9244 add_anchor_token(')');
9250 } else if (is_declaration_specifier(&token)) {
9251 parse_declaration(record_entity, DECL_FLAGS_NONE);
9253 add_anchor_token(';');
9254 expression_t *const init = parse_expression();
9255 statement->fors.initialisation = init;
9256 mark_vars_read(init, ENT_ANY);
9257 if (!expression_has_effect(init)) {
9258 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9260 rem_anchor_token(';');
9266 if (token.kind != ';') {
9267 add_anchor_token(';');
9268 expression_t *const cond = parse_expression();
9269 statement->fors.condition = cond;
9270 /* §6.8.5:2 The controlling expression of an iteration statement
9271 * shall have scalar type. */
9272 semantic_condition(cond, "condition of 'for'-statement");
9273 mark_vars_read(cond, NULL);
9274 rem_anchor_token(';');
9277 if (token.kind != ')') {
9278 expression_t *const step = parse_expression();
9279 statement->fors.step = step;
9280 mark_vars_read(step, ENT_ANY);
9281 if (!expression_has_effect(step)) {
9282 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9285 rem_anchor_token(')');
9287 statement->fors.body = parse_loop_body(statement);
9295 * Parse a goto statement.
9297 static statement_t *parse_goto(void)
9299 statement_t *statement;
9300 if (GNU_MODE && look_ahead(1)->kind == '*') {
9301 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9305 expression_t *expression = parse_expression();
9306 mark_vars_read(expression, NULL);
9308 /* Argh: although documentation says the expression must be of type void*,
9309 * gcc accepts anything that can be casted into void* without error */
9310 type_t *type = expression->base.type;
9312 if (type != type_error_type) {
9313 if (!is_type_pointer(type) && !is_type_integer(type)) {
9314 errorf(&expression->base.source_position,
9315 "cannot convert to a pointer type");
9316 } else if (type != type_void_ptr) {
9317 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9319 expression = create_implicit_cast(expression, type_void_ptr);
9322 statement->computed_goto.expression = expression;
9324 statement = allocate_statement_zero(STATEMENT_GOTO);
9327 label_t *const label = get_label("while parsing goto");
9330 statement->gotos.label = label;
9332 /* remember the goto's in a list for later checking */
9333 *goto_anchor = &statement->gotos;
9334 goto_anchor = &statement->gotos.next;
9336 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9345 * Parse a continue statement.
9347 static statement_t *parse_continue(void)
9349 if (current_loop == NULL) {
9350 errorf(HERE, "continue statement not within loop");
9353 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9361 * Parse a break statement.
9363 static statement_t *parse_break(void)
9365 if (current_switch == NULL && current_loop == NULL) {
9366 errorf(HERE, "break statement not within loop or switch");
9369 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9377 * Parse a __leave statement.
9379 static statement_t *parse_leave_statement(void)
9381 if (current_try == NULL) {
9382 errorf(HERE, "__leave statement not within __try");
9385 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9393 * Check if a given entity represents a local variable.
9395 static bool is_local_variable(const entity_t *entity)
9397 if (entity->kind != ENTITY_VARIABLE)
9400 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9401 case STORAGE_CLASS_AUTO:
9402 case STORAGE_CLASS_REGISTER: {
9403 const type_t *type = skip_typeref(entity->declaration.type);
9404 if (is_type_function(type)) {
9416 * Check if a given expression represents a local variable.
9418 static bool expression_is_local_variable(const expression_t *expression)
9420 if (expression->base.kind != EXPR_REFERENCE) {
9423 const entity_t *entity = expression->reference.entity;
9424 return is_local_variable(entity);
9428 * Check if a given expression represents a local variable and
9429 * return its declaration then, else return NULL.
9431 entity_t *expression_is_variable(const expression_t *expression)
9433 if (expression->base.kind != EXPR_REFERENCE) {
9436 entity_t *entity = expression->reference.entity;
9437 if (entity->kind != ENTITY_VARIABLE)
9443 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9445 if (c_mode & _CXX || strict_mode) {
9448 warningf(WARN_OTHER, pos, msg);
9453 * Parse a return statement.
9455 static statement_t *parse_return(void)
9457 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9460 expression_t *return_value = NULL;
9461 if (token.kind != ';') {
9462 return_value = parse_expression();
9463 mark_vars_read(return_value, NULL);
9466 const type_t *const func_type = skip_typeref(current_function->base.type);
9467 assert(is_type_function(func_type));
9468 type_t *const return_type = skip_typeref(func_type->function.return_type);
9470 source_position_t const *const pos = &statement->base.source_position;
9471 if (return_value != NULL) {
9472 type_t *return_value_type = skip_typeref(return_value->base.type);
9474 if (is_type_void(return_type)) {
9475 if (!is_type_void(return_value_type)) {
9476 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9477 /* Only warn in C mode, because GCC does the same */
9478 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9479 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9480 /* Only warn in C mode, because GCC does the same */
9481 err_or_warn(pos, "'return' with expression in function returning 'void'");
9484 assign_error_t error = semantic_assign(return_type, return_value);
9485 report_assign_error(error, return_type, return_value, "'return'",
9488 return_value = create_implicit_cast(return_value, return_type);
9489 /* check for returning address of a local var */
9490 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9491 const expression_t *expression = return_value->unary.value;
9492 if (expression_is_local_variable(expression)) {
9493 warningf(WARN_OTHER, pos, "function returns address of local variable");
9496 } else if (!is_type_void(return_type)) {
9497 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9498 err_or_warn(pos, "'return' without value, in function returning non-void");
9500 statement->returns.value = return_value;
9507 * Parse a declaration statement.
9509 static statement_t *parse_declaration_statement(void)
9511 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9513 entity_t *before = current_scope->last_entity;
9515 parse_external_declaration();
9517 parse_declaration(record_entity, DECL_FLAGS_NONE);
9520 declaration_statement_t *const decl = &statement->declaration;
9521 entity_t *const begin =
9522 before != NULL ? before->base.next : current_scope->entities;
9523 decl->declarations_begin = begin;
9524 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9530 * Parse an expression statement, ie. expr ';'.
9532 static statement_t *parse_expression_statement(void)
9534 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9536 expression_t *const expr = parse_expression();
9537 statement->expression.expression = expr;
9538 mark_vars_read(expr, ENT_ANY);
9545 * Parse a microsoft __try { } __finally { } or
9546 * __try{ } __except() { }
9548 static statement_t *parse_ms_try_statment(void)
9550 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9553 PUSH_PARENT(statement);
9555 ms_try_statement_t *rem = current_try;
9556 current_try = &statement->ms_try;
9557 statement->ms_try.try_statement = parse_compound_statement(false);
9562 if (next_if(T___except)) {
9563 expression_t *const expr = parse_condition();
9564 type_t * type = skip_typeref(expr->base.type);
9565 if (is_type_integer(type)) {
9566 type = promote_integer(type);
9567 } else if (is_type_valid(type)) {
9568 errorf(&expr->base.source_position,
9569 "__expect expression is not an integer, but '%T'", type);
9570 type = type_error_type;
9572 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9573 } else if (!next_if(T__finally)) {
9574 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9576 statement->ms_try.final_statement = parse_compound_statement(false);
9580 static statement_t *parse_empty_statement(void)
9582 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9583 statement_t *const statement = create_empty_statement();
9588 static statement_t *parse_local_label_declaration(void)
9590 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9594 entity_t *begin = NULL;
9595 entity_t *end = NULL;
9596 entity_t **anchor = &begin;
9597 add_anchor_token(';');
9598 add_anchor_token(',');
9600 source_position_t pos;
9601 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9603 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9604 if (entity != NULL && entity->base.parent_scope == current_scope) {
9605 source_position_t const *const ppos = &entity->base.source_position;
9606 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9608 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9609 entity->base.parent_scope = current_scope;
9612 anchor = &entity->base.next;
9615 environment_push(entity);
9618 } while (next_if(','));
9619 rem_anchor_token(',');
9620 rem_anchor_token(';');
9622 statement->declaration.declarations_begin = begin;
9623 statement->declaration.declarations_end = end;
9627 static void parse_namespace_definition(void)
9631 entity_t *entity = NULL;
9632 symbol_t *symbol = NULL;
9634 if (token.kind == T_IDENTIFIER) {
9635 symbol = token.base.symbol;
9636 entity = get_entity(symbol, NAMESPACE_NORMAL);
9637 if (entity && entity->kind != ENTITY_NAMESPACE) {
9639 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9640 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9646 if (entity == NULL) {
9647 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9648 entity->base.parent_scope = current_scope;
9651 if (token.kind == '=') {
9652 /* TODO: parse namespace alias */
9653 panic("namespace alias definition not supported yet");
9656 environment_push(entity);
9657 append_entity(current_scope, entity);
9659 PUSH_SCOPE(&entity->namespacee.members);
9660 PUSH_CURRENT_ENTITY(entity);
9662 add_anchor_token('}');
9665 rem_anchor_token('}');
9668 POP_CURRENT_ENTITY();
9673 * Parse a statement.
9674 * There's also parse_statement() which additionally checks for
9675 * "statement has no effect" warnings
9677 static statement_t *intern_parse_statement(void)
9679 /* declaration or statement */
9680 statement_t *statement;
9681 switch (token.kind) {
9682 case T_IDENTIFIER: {
9683 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9684 if (la1_type == ':') {
9685 statement = parse_label_statement();
9686 } else if (is_typedef_symbol(token.base.symbol)) {
9687 statement = parse_declaration_statement();
9689 /* it's an identifier, the grammar says this must be an
9690 * expression statement. However it is common that users mistype
9691 * declaration types, so we guess a bit here to improve robustness
9692 * for incorrect programs */
9696 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9698 statement = parse_expression_statement();
9702 statement = parse_declaration_statement();
9710 case T___extension__: {
9711 /* This can be a prefix to a declaration or an expression statement.
9712 * We simply eat it now and parse the rest with tail recursion. */
9714 statement = intern_parse_statement();
9720 statement = parse_declaration_statement();
9724 statement = parse_local_label_declaration();
9727 case ';': statement = parse_empty_statement(); break;
9728 case '{': statement = parse_compound_statement(false); break;
9729 case T___leave: statement = parse_leave_statement(); break;
9730 case T___try: statement = parse_ms_try_statment(); break;
9731 case T_asm: statement = parse_asm_statement(); break;
9732 case T_break: statement = parse_break(); break;
9733 case T_case: statement = parse_case_statement(); break;
9734 case T_continue: statement = parse_continue(); break;
9735 case T_default: statement = parse_default_statement(); break;
9736 case T_do: statement = parse_do(); break;
9737 case T_for: statement = parse_for(); break;
9738 case T_goto: statement = parse_goto(); break;
9739 case T_if: statement = parse_if(); break;
9740 case T_return: statement = parse_return(); break;
9741 case T_switch: statement = parse_switch(); break;
9742 case T_while: statement = parse_while(); break;
9745 statement = parse_expression_statement();
9749 errorf(HERE, "unexpected token %K while parsing statement", &token);
9750 statement = create_error_statement();
9759 * parse a statement and emits "statement has no effect" warning if needed
9760 * (This is really a wrapper around intern_parse_statement with check for 1
9761 * single warning. It is needed, because for statement expressions we have
9762 * to avoid the warning on the last statement)
9764 static statement_t *parse_statement(void)
9766 statement_t *statement = intern_parse_statement();
9768 if (statement->kind == STATEMENT_EXPRESSION) {
9769 expression_t *expression = statement->expression.expression;
9770 if (!expression_has_effect(expression)) {
9771 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9779 * Parse a compound statement.
9781 static statement_t *parse_compound_statement(bool inside_expression_statement)
9783 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9785 PUSH_PARENT(statement);
9786 PUSH_SCOPE(&statement->compound.scope);
9789 add_anchor_token('}');
9790 /* tokens, which can start a statement */
9791 /* TODO MS, __builtin_FOO */
9792 add_anchor_token('!');
9793 add_anchor_token('&');
9794 add_anchor_token('(');
9795 add_anchor_token('*');
9796 add_anchor_token('+');
9797 add_anchor_token('-');
9798 add_anchor_token(';');
9799 add_anchor_token('{');
9800 add_anchor_token('~');
9801 add_anchor_token(T_CHARACTER_CONSTANT);
9802 add_anchor_token(T_COLONCOLON);
9803 add_anchor_token(T_FLOATINGPOINT);
9804 add_anchor_token(T_IDENTIFIER);
9805 add_anchor_token(T_INTEGER);
9806 add_anchor_token(T_MINUSMINUS);
9807 add_anchor_token(T_PLUSPLUS);
9808 add_anchor_token(T_STRING_LITERAL);
9809 add_anchor_token(T__Bool);
9810 add_anchor_token(T__Complex);
9811 add_anchor_token(T__Imaginary);
9812 add_anchor_token(T___FUNCTION__);
9813 add_anchor_token(T___PRETTY_FUNCTION__);
9814 add_anchor_token(T___alignof__);
9815 add_anchor_token(T___attribute__);
9816 add_anchor_token(T___builtin_va_start);
9817 add_anchor_token(T___extension__);
9818 add_anchor_token(T___func__);
9819 add_anchor_token(T___imag__);
9820 add_anchor_token(T___label__);
9821 add_anchor_token(T___real__);
9822 add_anchor_token(T___thread);
9823 add_anchor_token(T_asm);
9824 add_anchor_token(T_auto);
9825 add_anchor_token(T_bool);
9826 add_anchor_token(T_break);
9827 add_anchor_token(T_case);
9828 add_anchor_token(T_char);
9829 add_anchor_token(T_class);
9830 add_anchor_token(T_const);
9831 add_anchor_token(T_const_cast);
9832 add_anchor_token(T_continue);
9833 add_anchor_token(T_default);
9834 add_anchor_token(T_delete);
9835 add_anchor_token(T_double);
9836 add_anchor_token(T_do);
9837 add_anchor_token(T_dynamic_cast);
9838 add_anchor_token(T_enum);
9839 add_anchor_token(T_extern);
9840 add_anchor_token(T_false);
9841 add_anchor_token(T_float);
9842 add_anchor_token(T_for);
9843 add_anchor_token(T_goto);
9844 add_anchor_token(T_if);
9845 add_anchor_token(T_inline);
9846 add_anchor_token(T_int);
9847 add_anchor_token(T_long);
9848 add_anchor_token(T_new);
9849 add_anchor_token(T_operator);
9850 add_anchor_token(T_register);
9851 add_anchor_token(T_reinterpret_cast);
9852 add_anchor_token(T_restrict);
9853 add_anchor_token(T_return);
9854 add_anchor_token(T_short);
9855 add_anchor_token(T_signed);
9856 add_anchor_token(T_sizeof);
9857 add_anchor_token(T_static);
9858 add_anchor_token(T_static_cast);
9859 add_anchor_token(T_struct);
9860 add_anchor_token(T_switch);
9861 add_anchor_token(T_template);
9862 add_anchor_token(T_this);
9863 add_anchor_token(T_throw);
9864 add_anchor_token(T_true);
9865 add_anchor_token(T_try);
9866 add_anchor_token(T_typedef);
9867 add_anchor_token(T_typeid);
9868 add_anchor_token(T_typename);
9869 add_anchor_token(T_typeof);
9870 add_anchor_token(T_union);
9871 add_anchor_token(T_unsigned);
9872 add_anchor_token(T_using);
9873 add_anchor_token(T_void);
9874 add_anchor_token(T_volatile);
9875 add_anchor_token(T_wchar_t);
9876 add_anchor_token(T_while);
9878 statement_t **anchor = &statement->compound.statements;
9879 bool only_decls_so_far = true;
9880 while (token.kind != '}' && token.kind != T_EOF) {
9881 statement_t *sub_statement = intern_parse_statement();
9882 if (sub_statement->kind == STATEMENT_ERROR) {
9886 if (sub_statement->kind != STATEMENT_DECLARATION) {
9887 only_decls_so_far = false;
9888 } else if (!only_decls_so_far) {
9889 source_position_t const *const pos = &sub_statement->base.source_position;
9890 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9893 *anchor = sub_statement;
9894 anchor = &sub_statement->base.next;
9898 /* look over all statements again to produce no effect warnings */
9899 if (is_warn_on(WARN_UNUSED_VALUE)) {
9900 statement_t *sub_statement = statement->compound.statements;
9901 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9902 if (sub_statement->kind != STATEMENT_EXPRESSION)
9904 /* don't emit a warning for the last expression in an expression
9905 * statement as it has always an effect */
9906 if (inside_expression_statement && sub_statement->base.next == NULL)
9909 expression_t *expression = sub_statement->expression.expression;
9910 if (!expression_has_effect(expression)) {
9911 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9916 rem_anchor_token(T_while);
9917 rem_anchor_token(T_wchar_t);
9918 rem_anchor_token(T_volatile);
9919 rem_anchor_token(T_void);
9920 rem_anchor_token(T_using);
9921 rem_anchor_token(T_unsigned);
9922 rem_anchor_token(T_union);
9923 rem_anchor_token(T_typeof);
9924 rem_anchor_token(T_typename);
9925 rem_anchor_token(T_typeid);
9926 rem_anchor_token(T_typedef);
9927 rem_anchor_token(T_try);
9928 rem_anchor_token(T_true);
9929 rem_anchor_token(T_throw);
9930 rem_anchor_token(T_this);
9931 rem_anchor_token(T_template);
9932 rem_anchor_token(T_switch);
9933 rem_anchor_token(T_struct);
9934 rem_anchor_token(T_static_cast);
9935 rem_anchor_token(T_static);
9936 rem_anchor_token(T_sizeof);
9937 rem_anchor_token(T_signed);
9938 rem_anchor_token(T_short);
9939 rem_anchor_token(T_return);
9940 rem_anchor_token(T_restrict);
9941 rem_anchor_token(T_reinterpret_cast);
9942 rem_anchor_token(T_register);
9943 rem_anchor_token(T_operator);
9944 rem_anchor_token(T_new);
9945 rem_anchor_token(T_long);
9946 rem_anchor_token(T_int);
9947 rem_anchor_token(T_inline);
9948 rem_anchor_token(T_if);
9949 rem_anchor_token(T_goto);
9950 rem_anchor_token(T_for);
9951 rem_anchor_token(T_float);
9952 rem_anchor_token(T_false);
9953 rem_anchor_token(T_extern);
9954 rem_anchor_token(T_enum);
9955 rem_anchor_token(T_dynamic_cast);
9956 rem_anchor_token(T_do);
9957 rem_anchor_token(T_double);
9958 rem_anchor_token(T_delete);
9959 rem_anchor_token(T_default);
9960 rem_anchor_token(T_continue);
9961 rem_anchor_token(T_const_cast);
9962 rem_anchor_token(T_const);
9963 rem_anchor_token(T_class);
9964 rem_anchor_token(T_char);
9965 rem_anchor_token(T_case);
9966 rem_anchor_token(T_break);
9967 rem_anchor_token(T_bool);
9968 rem_anchor_token(T_auto);
9969 rem_anchor_token(T_asm);
9970 rem_anchor_token(T___thread);
9971 rem_anchor_token(T___real__);
9972 rem_anchor_token(T___label__);
9973 rem_anchor_token(T___imag__);
9974 rem_anchor_token(T___func__);
9975 rem_anchor_token(T___extension__);
9976 rem_anchor_token(T___builtin_va_start);
9977 rem_anchor_token(T___attribute__);
9978 rem_anchor_token(T___alignof__);
9979 rem_anchor_token(T___PRETTY_FUNCTION__);
9980 rem_anchor_token(T___FUNCTION__);
9981 rem_anchor_token(T__Imaginary);
9982 rem_anchor_token(T__Complex);
9983 rem_anchor_token(T__Bool);
9984 rem_anchor_token(T_STRING_LITERAL);
9985 rem_anchor_token(T_PLUSPLUS);
9986 rem_anchor_token(T_MINUSMINUS);
9987 rem_anchor_token(T_INTEGER);
9988 rem_anchor_token(T_IDENTIFIER);
9989 rem_anchor_token(T_FLOATINGPOINT);
9990 rem_anchor_token(T_COLONCOLON);
9991 rem_anchor_token(T_CHARACTER_CONSTANT);
9992 rem_anchor_token('~');
9993 rem_anchor_token('{');
9994 rem_anchor_token(';');
9995 rem_anchor_token('-');
9996 rem_anchor_token('+');
9997 rem_anchor_token('*');
9998 rem_anchor_token('(');
9999 rem_anchor_token('&');
10000 rem_anchor_token('!');
10001 rem_anchor_token('}');
10009 * Check for unused global static functions and variables
10011 static void check_unused_globals(void)
10013 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10016 for (const entity_t *entity = file_scope->entities; entity != NULL;
10017 entity = entity->base.next) {
10018 if (!is_declaration(entity))
10021 const declaration_t *declaration = &entity->declaration;
10022 if (declaration->used ||
10023 declaration->modifiers & DM_UNUSED ||
10024 declaration->modifiers & DM_USED ||
10025 declaration->storage_class != STORAGE_CLASS_STATIC)
10030 if (entity->kind == ENTITY_FUNCTION) {
10031 /* inhibit warning for static inline functions */
10032 if (entity->function.is_inline)
10035 why = WARN_UNUSED_FUNCTION;
10036 s = entity->function.statement != NULL ? "defined" : "declared";
10038 why = WARN_UNUSED_VARIABLE;
10042 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10046 static void parse_global_asm(void)
10048 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10051 add_anchor_token(';');
10052 add_anchor_token(')');
10053 add_anchor_token(T_STRING_LITERAL);
10056 rem_anchor_token(T_STRING_LITERAL);
10057 statement->asms.asm_text = parse_string_literals();
10058 statement->base.next = unit->global_asm;
10059 unit->global_asm = statement;
10061 rem_anchor_token(')');
10063 rem_anchor_token(';');
10067 static void parse_linkage_specification(void)
10071 source_position_t const pos = *HERE;
10072 char const *const linkage = parse_string_literals().begin;
10074 linkage_kind_t old_linkage = current_linkage;
10075 linkage_kind_t new_linkage;
10076 if (streq(linkage, "C")) {
10077 new_linkage = LINKAGE_C;
10078 } else if (streq(linkage, "C++")) {
10079 new_linkage = LINKAGE_CXX;
10081 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10082 new_linkage = LINKAGE_C;
10084 current_linkage = new_linkage;
10086 if (next_if('{')) {
10093 assert(current_linkage == new_linkage);
10094 current_linkage = old_linkage;
10097 static void parse_external(void)
10099 switch (token.kind) {
10101 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10102 parse_linkage_specification();
10104 DECLARATION_START_NO_EXTERN
10106 case T___extension__:
10107 /* tokens below are for implicit int */
10108 case '&': /* & x; -> int& x; (and error later, because C++ has no
10110 case '*': /* * x; -> int* x; */
10111 case '(': /* (x); -> int (x); */
10113 parse_external_declaration();
10119 parse_global_asm();
10123 parse_namespace_definition();
10127 if (!strict_mode) {
10128 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10135 errorf(HERE, "stray %K outside of function", &token);
10136 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10137 eat_until_matching_token(token.kind);
10143 static void parse_externals(void)
10145 add_anchor_token('}');
10146 add_anchor_token(T_EOF);
10149 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10150 unsigned short token_anchor_copy[T_LAST_TOKEN];
10151 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10154 while (token.kind != T_EOF && token.kind != '}') {
10156 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10157 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10159 /* the anchor set and its copy differs */
10160 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10163 if (in_gcc_extension) {
10164 /* an gcc extension scope was not closed */
10165 internal_errorf(HERE, "Leaked __extension__");
10172 rem_anchor_token(T_EOF);
10173 rem_anchor_token('}');
10177 * Parse a translation unit.
10179 static void parse_translation_unit(void)
10181 add_anchor_token(T_EOF);
10186 if (token.kind == T_EOF)
10189 errorf(HERE, "stray %K outside of function", &token);
10190 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10191 eat_until_matching_token(token.kind);
10196 void set_default_visibility(elf_visibility_tag_t visibility)
10198 default_visibility = visibility;
10204 * @return the translation unit or NULL if errors occurred.
10206 void start_parsing(void)
10208 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10209 label_stack = NEW_ARR_F(stack_entry_t, 0);
10210 diagnostic_count = 0;
10214 print_to_file(stderr);
10216 assert(unit == NULL);
10217 unit = allocate_ast_zero(sizeof(unit[0]));
10219 assert(file_scope == NULL);
10220 file_scope = &unit->scope;
10222 assert(current_scope == NULL);
10223 scope_push(&unit->scope);
10225 create_gnu_builtins();
10227 create_microsoft_intrinsics();
10230 translation_unit_t *finish_parsing(void)
10232 assert(current_scope == &unit->scope);
10235 assert(file_scope == &unit->scope);
10236 check_unused_globals();
10239 DEL_ARR_F(environment_stack);
10240 DEL_ARR_F(label_stack);
10242 translation_unit_t *result = unit;
10247 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10248 * are given length one. */
10249 static void complete_incomplete_arrays(void)
10251 size_t n = ARR_LEN(incomplete_arrays);
10252 for (size_t i = 0; i != n; ++i) {
10253 declaration_t *const decl = incomplete_arrays[i];
10254 type_t *const type = skip_typeref(decl->type);
10256 if (!is_type_incomplete(type))
10259 source_position_t const *const pos = &decl->base.source_position;
10260 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10262 type_t *const new_type = duplicate_type(type);
10263 new_type->array.size_constant = true;
10264 new_type->array.has_implicit_size = true;
10265 new_type->array.size = 1;
10267 type_t *const result = identify_new_type(new_type);
10269 decl->type = result;
10273 static void prepare_main_collect2(entity_t *const entity)
10275 PUSH_SCOPE(&entity->function.statement->compound.scope);
10277 // create call to __main
10278 symbol_t *symbol = symbol_table_insert("__main");
10279 entity_t *subsubmain_ent
10280 = create_implicit_function(symbol, &builtin_source_position);
10282 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10283 type_t *ftype = subsubmain_ent->declaration.type;
10284 ref->base.source_position = builtin_source_position;
10285 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10286 ref->reference.entity = subsubmain_ent;
10288 expression_t *call = allocate_expression_zero(EXPR_CALL);
10289 call->base.source_position = builtin_source_position;
10290 call->base.type = type_void;
10291 call->call.function = ref;
10293 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10294 expr_statement->base.source_position = builtin_source_position;
10295 expr_statement->expression.expression = call;
10297 statement_t *statement = entity->function.statement;
10298 assert(statement->kind == STATEMENT_COMPOUND);
10299 compound_statement_t *compounds = &statement->compound;
10301 expr_statement->base.next = compounds->statements;
10302 compounds->statements = expr_statement;
10309 lookahead_bufpos = 0;
10310 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10313 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10314 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10315 parse_translation_unit();
10316 complete_incomplete_arrays();
10317 DEL_ARR_F(incomplete_arrays);
10318 incomplete_arrays = NULL;
10322 * Initialize the parser.
10324 void init_parser(void)
10326 sym_anonymous = symbol_table_insert("<anonymous>");
10328 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10330 init_expression_parsers();
10331 obstack_init(&temp_obst);
10335 * Terminate the parser.
10337 void exit_parser(void)
10339 obstack_free(&temp_obst, NULL);