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
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static switch_statement_t *current_switch = NULL;
93 static statement_t *current_loop = NULL;
94 static statement_t *current_parent = NULL;
95 static ms_try_statement_t *current_try = NULL;
96 static linkage_kind_t current_linkage = LINKAGE_INVALID;
97 static goto_statement_t *goto_first = NULL;
98 static goto_statement_t **goto_anchor = NULL;
99 static label_statement_t *label_first = NULL;
100 static label_statement_t **label_anchor = NULL;
101 /** current translation unit. */
102 static translation_unit_t *unit = NULL;
103 /** true if we are in an __extension__ context. */
104 static bool in_gcc_extension = false;
105 static struct obstack temp_obst;
106 static entity_t *anonymous_entity;
107 static declaration_t **incomplete_arrays;
108 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
111 #define PUSH_PARENT(stmt) \
112 statement_t *const new_parent = (stmt); \
113 statement_t *const old_parent = current_parent; \
114 ((void)(current_parent = new_parent))
115 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
117 #define PUSH_SCOPE(scope) \
118 size_t const top = environment_top(); \
119 scope_t *const new_scope = (scope); \
120 scope_t *const old_scope = scope_push(new_scope)
121 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
123 #define PUSH_EXTENSION() \
125 bool const old_gcc_extension = in_gcc_extension; \
126 while (next_if(T___extension__)) { \
127 in_gcc_extension = true; \
130 #define POP_EXTENSION() \
131 ((void)(in_gcc_extension = old_gcc_extension))
133 /** special symbol used for anonymous entities. */
134 static symbol_t *sym_anonymous = NULL;
136 /** The token anchor set */
137 static unsigned char token_anchor_set[T_LAST_TOKEN];
139 /** The current source position. */
140 #define HERE (&token.source_position)
142 /** true if we are in GCC mode. */
143 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
145 static statement_t *parse_compound_statement(bool inside_expression_statement);
146 static statement_t *parse_statement(void);
148 static expression_t *parse_subexpression(precedence_t);
149 static expression_t *parse_expression(void);
150 static type_t *parse_typename(void);
151 static void parse_externals(void);
152 static void parse_external(void);
154 static void parse_compound_type_entries(compound_t *compound_declaration);
156 static void check_call_argument(type_t *expected_type,
157 call_argument_t *argument, unsigned pos);
159 typedef enum declarator_flags_t {
161 DECL_MAY_BE_ABSTRACT = 1U << 0,
162 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
163 DECL_IS_PARAMETER = 1U << 2
164 } declarator_flags_t;
166 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
167 declarator_flags_t flags);
169 static void semantic_comparison(binary_expression_t *expression);
171 #define STORAGE_CLASSES \
172 STORAGE_CLASSES_NO_EXTERN \
175 #define STORAGE_CLASSES_NO_EXTERN \
182 #define TYPE_QUALIFIERS \
187 case T__forceinline: \
188 case T___attribute__:
190 #define COMPLEX_SPECIFIERS \
192 #define IMAGINARY_SPECIFIERS \
195 #define TYPE_SPECIFIERS \
197 case T___builtin_va_list: \
222 #define DECLARATION_START \
227 #define DECLARATION_START_NO_EXTERN \
228 STORAGE_CLASSES_NO_EXTERN \
232 #define EXPRESSION_START \
241 case T_CHARACTER_CONSTANT: \
242 case T_FLOATINGPOINT: \
243 case T_FLOATINGPOINT_HEXADECIMAL: \
245 case T_INTEGER_HEXADECIMAL: \
246 case T_INTEGER_OCTAL: \
249 case T_STRING_LITERAL: \
250 case T_WIDE_CHARACTER_CONSTANT: \
251 case T_WIDE_STRING_LITERAL: \
252 case T___FUNCDNAME__: \
253 case T___FUNCSIG__: \
254 case T___FUNCTION__: \
255 case T___PRETTY_FUNCTION__: \
256 case T___alignof__: \
257 case T___builtin_classify_type: \
258 case T___builtin_constant_p: \
259 case T___builtin_isgreater: \
260 case T___builtin_isgreaterequal: \
261 case T___builtin_isless: \
262 case T___builtin_islessequal: \
263 case T___builtin_islessgreater: \
264 case T___builtin_isunordered: \
265 case T___builtin_offsetof: \
266 case T___builtin_va_arg: \
267 case T___builtin_va_copy: \
268 case T___builtin_va_start: \
279 * Returns the size of a statement node.
281 * @param kind the statement kind
283 static size_t get_statement_struct_size(statement_kind_t kind)
285 static const size_t sizes[] = {
286 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
287 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
288 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
289 [STATEMENT_RETURN] = sizeof(return_statement_t),
290 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
291 [STATEMENT_IF] = sizeof(if_statement_t),
292 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
293 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
294 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
295 [STATEMENT_BREAK] = sizeof(statement_base_t),
296 [STATEMENT_GOTO] = sizeof(goto_statement_t),
297 [STATEMENT_LABEL] = sizeof(label_statement_t),
298 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
299 [STATEMENT_WHILE] = sizeof(while_statement_t),
300 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
301 [STATEMENT_FOR] = sizeof(for_statement_t),
302 [STATEMENT_ASM] = sizeof(asm_statement_t),
303 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
304 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
306 assert((size_t)kind < lengthof(sizes));
307 assert(sizes[kind] != 0);
312 * Returns the size of an expression node.
314 * @param kind the expression kind
316 static size_t get_expression_struct_size(expression_kind_t kind)
318 static const size_t sizes[] = {
319 [EXPR_INVALID] = sizeof(expression_base_t),
320 [EXPR_REFERENCE] = sizeof(reference_expression_t),
321 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
322 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
323 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
324 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
326 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
330 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
331 [EXPR_WIDE_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 = token.source_position;
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 = token.source_position;
397 * Creates a new invalid expression at the source position
398 * of the current token.
400 static expression_t *create_invalid_expression(void)
402 return allocate_expression_zero(EXPR_INVALID);
406 * Creates a new invalid statement.
408 static statement_t *create_invalid_statement(void)
410 return allocate_statement_zero(STATEMENT_INVALID);
414 * Allocate a new empty statement.
416 static statement_t *create_empty_statement(void)
418 return allocate_statement_zero(STATEMENT_EMPTY);
422 * Returns the size of an initializer node.
424 * @param kind the initializer kind
426 static size_t get_initializer_size(initializer_kind_t kind)
428 static const size_t sizes[] = {
429 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
430 [INITIALIZER_STRING] = sizeof(initializer_string_t),
431 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
432 [INITIALIZER_LIST] = sizeof(initializer_list_t),
433 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
435 assert((size_t)kind < lengthof(sizes));
436 assert(sizes[kind] != 0);
441 * Allocate an initializer node of given kind and initialize all
444 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
446 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
453 * Returns the index of the top element of the environment stack.
455 static size_t environment_top(void)
457 return ARR_LEN(environment_stack);
461 * Returns the index of the top element of the global label stack.
463 static size_t label_top(void)
465 return ARR_LEN(label_stack);
469 * Return the next token.
471 static inline void next_token(void)
473 token = lookahead_buffer[lookahead_bufpos];
474 lookahead_buffer[lookahead_bufpos] = lexer_token;
477 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
480 print_token(stderr, &token);
481 fprintf(stderr, "\n");
485 static inline bool next_if(int const type)
487 if (token.type == type) {
496 * Return the next token with a given lookahead.
498 static inline const token_t *look_ahead(size_t num)
500 assert(0 < num && num <= MAX_LOOKAHEAD);
501 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
502 return &lookahead_buffer[pos];
506 * Adds a token type to the token type anchor set (a multi-set).
508 static void add_anchor_token(int token_type)
510 assert(0 <= token_type && token_type < T_LAST_TOKEN);
511 ++token_anchor_set[token_type];
515 * Set the number of tokens types of the given type
516 * to zero and return the old count.
518 static int save_and_reset_anchor_state(int token_type)
520 assert(0 <= token_type && token_type < T_LAST_TOKEN);
521 int count = token_anchor_set[token_type];
522 token_anchor_set[token_type] = 0;
527 * Restore the number of token types to the given count.
529 static void restore_anchor_state(int token_type, int count)
531 assert(0 <= token_type && token_type < T_LAST_TOKEN);
532 token_anchor_set[token_type] = count;
536 * Remove a token type from the token type anchor set (a multi-set).
538 static void rem_anchor_token(int token_type)
540 assert(0 <= token_type && token_type < T_LAST_TOKEN);
541 assert(token_anchor_set[token_type] != 0);
542 --token_anchor_set[token_type];
546 * Return true if the token type of the current token is
549 static bool at_anchor(void)
553 return token_anchor_set[token.type];
557 * Eat tokens until a matching token type is found.
559 static void eat_until_matching_token(int type)
563 case '(': end_token = ')'; break;
564 case '{': end_token = '}'; break;
565 case '[': end_token = ']'; break;
566 default: end_token = type; break;
569 unsigned parenthesis_count = 0;
570 unsigned brace_count = 0;
571 unsigned bracket_count = 0;
572 while (token.type != end_token ||
573 parenthesis_count != 0 ||
575 bracket_count != 0) {
576 switch (token.type) {
578 case '(': ++parenthesis_count; break;
579 case '{': ++brace_count; break;
580 case '[': ++bracket_count; break;
583 if (parenthesis_count > 0)
593 if (bracket_count > 0)
596 if (token.type == end_token &&
597 parenthesis_count == 0 &&
611 * Eat input tokens until an anchor is found.
613 static void eat_until_anchor(void)
615 while (token_anchor_set[token.type] == 0) {
616 if (token.type == '(' || token.type == '{' || token.type == '[')
617 eat_until_matching_token(token.type);
623 * Eat a whole block from input tokens.
625 static void eat_block(void)
627 eat_until_matching_token('{');
631 #define eat(token_type) (assert(token.type == (token_type)), next_token())
634 * Report a parse error because an expected token was not found.
637 #if defined __GNUC__ && __GNUC__ >= 4
638 __attribute__((sentinel))
640 void parse_error_expected(const char *message, ...)
642 if (message != NULL) {
643 errorf(HERE, "%s", message);
646 va_start(ap, message);
647 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
652 * Report an incompatible type.
654 static void type_error_incompatible(const char *msg,
655 const source_position_t *source_position, type_t *type1, type_t *type2)
657 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
662 * Expect the current token is the expected token.
663 * If not, generate an error, eat the current statement,
664 * and goto the error_label label.
666 #define expect(expected, error_label) \
668 if (UNLIKELY(token.type != (expected))) { \
669 parse_error_expected(NULL, (expected), NULL); \
670 add_anchor_token(expected); \
671 eat_until_anchor(); \
672 rem_anchor_token(expected); \
673 if (token.type != (expected)) \
680 * Push a given scope on the scope stack and make it the
683 static scope_t *scope_push(scope_t *new_scope)
685 if (current_scope != NULL) {
686 new_scope->depth = current_scope->depth + 1;
689 scope_t *old_scope = current_scope;
690 current_scope = new_scope;
695 * Pop the current scope from the scope stack.
697 static void scope_pop(scope_t *old_scope)
699 current_scope = old_scope;
703 * Search an entity by its symbol in a given namespace.
705 static entity_t *get_entity(const symbol_t *const symbol,
706 namespace_tag_t namespc)
708 assert(namespc != NAMESPACE_INVALID);
709 entity_t *entity = symbol->entity;
710 for (; entity != NULL; entity = entity->base.symbol_next) {
711 if ((namespace_tag_t)entity->base.namespc == namespc)
718 /* §6.2.3:1 24) There is only one name space for tags even though three are
720 static entity_t *get_tag(symbol_t const *const symbol,
721 entity_kind_tag_t const kind)
723 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
724 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
726 "'%Y' defined as wrong kind of tag (previous definition %P)",
727 symbol, &entity->base.source_position);
734 * pushs an entity on the environment stack and links the corresponding symbol
737 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
739 symbol_t *symbol = entity->base.symbol;
740 entity_namespace_t namespc = entity->base.namespc;
741 assert(namespc != NAMESPACE_INVALID);
743 /* replace/add entity into entity list of the symbol */
746 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
751 /* replace an entry? */
752 if (iter->base.namespc == namespc) {
753 entity->base.symbol_next = iter->base.symbol_next;
759 /* remember old declaration */
761 entry.symbol = symbol;
762 entry.old_entity = iter;
763 entry.namespc = namespc;
764 ARR_APP1(stack_entry_t, *stack_ptr, entry);
768 * Push an entity on the environment stack.
770 static void environment_push(entity_t *entity)
772 assert(entity->base.source_position.input_name != NULL);
773 assert(entity->base.parent_scope != NULL);
774 stack_push(&environment_stack, entity);
778 * Push a declaration on the global label stack.
780 * @param declaration the declaration
782 static void label_push(entity_t *label)
784 /* we abuse the parameters scope as parent for the labels */
785 label->base.parent_scope = ¤t_function->parameters;
786 stack_push(&label_stack, label);
790 * pops symbols from the environment stack until @p new_top is the top element
792 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
794 stack_entry_t *stack = *stack_ptr;
795 size_t top = ARR_LEN(stack);
798 assert(new_top <= top);
802 for (i = top; i > new_top; --i) {
803 stack_entry_t *entry = &stack[i - 1];
805 entity_t *old_entity = entry->old_entity;
806 symbol_t *symbol = entry->symbol;
807 entity_namespace_t namespc = entry->namespc;
809 /* replace with old_entity/remove */
812 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
814 assert(iter != NULL);
815 /* replace an entry? */
816 if (iter->base.namespc == namespc)
820 /* restore definition from outer scopes (if there was one) */
821 if (old_entity != NULL) {
822 old_entity->base.symbol_next = iter->base.symbol_next;
823 *anchor = old_entity;
825 /* remove entry from list */
826 *anchor = iter->base.symbol_next;
830 ARR_SHRINKLEN(*stack_ptr, new_top);
834 * Pop all entries from the environment stack until the new_top
837 * @param new_top the new stack top
839 static void environment_pop_to(size_t new_top)
841 stack_pop_to(&environment_stack, new_top);
845 * Pop all entries from the global label stack until the new_top
848 * @param new_top the new stack top
850 static void label_pop_to(size_t new_top)
852 stack_pop_to(&label_stack, new_top);
855 static int get_akind_rank(atomic_type_kind_t akind)
861 * Return the type rank for an atomic type.
863 static int get_rank(const type_t *type)
865 assert(!is_typeref(type));
866 if (type->kind == TYPE_ENUM)
867 return get_akind_rank(type->enumt.akind);
869 assert(type->kind == TYPE_ATOMIC);
870 return get_akind_rank(type->atomic.akind);
874 * §6.3.1.1:2 Do integer promotion for a given type.
876 * @param type the type to promote
877 * @return the promoted type
879 static type_t *promote_integer(type_t *type)
881 if (type->kind == TYPE_BITFIELD)
882 type = type->bitfield.base_type;
884 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
891 * Create a cast expression.
893 * @param expression the expression to cast
894 * @param dest_type the destination type
896 static expression_t *create_cast_expression(expression_t *expression,
899 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
901 cast->unary.value = expression;
902 cast->base.type = dest_type;
908 * Check if a given expression represents a null pointer constant.
910 * @param expression the expression to check
912 static bool is_null_pointer_constant(const expression_t *expression)
914 /* skip void* cast */
915 if (expression->kind == EXPR_UNARY_CAST ||
916 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
917 type_t *const type = skip_typeref(expression->base.type);
918 if (types_compatible(type, type_void_ptr))
919 expression = expression->unary.value;
922 type_t *const type = skip_typeref(expression->base.type);
923 if (!is_type_integer(type))
925 switch (is_constant_expression(expression)) {
926 case EXPR_CLASS_ERROR: return true;
927 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
928 default: return false;
933 * Create an implicit cast expression.
935 * @param expression the expression to cast
936 * @param dest_type the destination type
938 static expression_t *create_implicit_cast(expression_t *expression,
941 type_t *const source_type = expression->base.type;
943 if (source_type == dest_type)
946 return create_cast_expression(expression, dest_type);
949 typedef enum assign_error_t {
951 ASSIGN_ERROR_INCOMPATIBLE,
952 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
953 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
954 ASSIGN_WARNING_POINTER_FROM_INT,
955 ASSIGN_WARNING_INT_FROM_POINTER
958 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)
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);
967 case ASSIGN_ERROR_INCOMPATIBLE:
968 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
971 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
972 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
973 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
975 /* the left type has all qualifiers from the right type */
976 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
977 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);
981 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
982 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
985 case ASSIGN_WARNING_POINTER_FROM_INT:
986 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
989 case ASSIGN_WARNING_INT_FROM_POINTER:
990 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
994 panic("invalid error value");
998 /** Implements the rules from §6.5.16.1 */
999 static assign_error_t semantic_assign(type_t *orig_type_left,
1000 const expression_t *const right)
1002 type_t *const orig_type_right = right->base.type;
1003 type_t *const type_left = skip_typeref(orig_type_left);
1004 type_t *const type_right = skip_typeref(orig_type_right);
1006 if (is_type_pointer(type_left)) {
1007 if (is_null_pointer_constant(right)) {
1008 return ASSIGN_SUCCESS;
1009 } else if (is_type_pointer(type_right)) {
1010 type_t *points_to_left
1011 = skip_typeref(type_left->pointer.points_to);
1012 type_t *points_to_right
1013 = skip_typeref(type_right->pointer.points_to);
1014 assign_error_t res = ASSIGN_SUCCESS;
1016 /* the left type has all qualifiers from the right type */
1017 unsigned missing_qualifiers
1018 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1019 if (missing_qualifiers != 0) {
1020 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1023 points_to_left = get_unqualified_type(points_to_left);
1024 points_to_right = get_unqualified_type(points_to_right);
1026 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1029 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1030 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1031 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1034 if (!types_compatible(points_to_left, points_to_right)) {
1035 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1039 } else if (is_type_integer(type_right)) {
1040 return ASSIGN_WARNING_POINTER_FROM_INT;
1042 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1043 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1044 && is_type_pointer(type_right))) {
1045 return ASSIGN_SUCCESS;
1046 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1047 type_t *const unqual_type_left = get_unqualified_type(type_left);
1048 type_t *const unqual_type_right = get_unqualified_type(type_right);
1049 if (types_compatible(unqual_type_left, unqual_type_right)) {
1050 return ASSIGN_SUCCESS;
1052 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1053 return ASSIGN_WARNING_INT_FROM_POINTER;
1056 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1057 return ASSIGN_SUCCESS;
1059 return ASSIGN_ERROR_INCOMPATIBLE;
1062 static expression_t *parse_constant_expression(void)
1064 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1066 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1067 errorf(&result->base.source_position,
1068 "expression '%E' is not constant", result);
1074 static expression_t *parse_assignment_expression(void)
1076 return parse_subexpression(PREC_ASSIGNMENT);
1079 static void warn_string_concat(const source_position_t *pos)
1081 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1084 static string_t parse_string_literals(void)
1086 assert(token.type == T_STRING_LITERAL);
1087 string_t result = token.literal;
1091 while (token.type == T_STRING_LITERAL) {
1092 warn_string_concat(&token.source_position);
1093 result = concat_strings(&result, &token.literal);
1101 * compare two string, ignoring double underscores on the second.
1103 static int strcmp_underscore(const char *s1, const char *s2)
1105 if (s2[0] == '_' && s2[1] == '_') {
1106 size_t len2 = strlen(s2);
1107 size_t len1 = strlen(s1);
1108 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1109 return strncmp(s1, s2+2, len2-4);
1113 return strcmp(s1, s2);
1116 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1118 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1119 attribute->kind = kind;
1120 attribute->source_position = *HERE;
1125 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1128 * __attribute__ ( ( attribute-list ) )
1132 * attribute_list , attrib
1137 * any-word ( identifier )
1138 * any-word ( identifier , nonempty-expr-list )
1139 * any-word ( expr-list )
1141 * where the "identifier" must not be declared as a type, and
1142 * "any-word" may be any identifier (including one declared as a
1143 * type), a reserved word storage class specifier, type specifier or
1144 * type qualifier. ??? This still leaves out most reserved keywords
1145 * (following the old parser), shouldn't we include them, and why not
1146 * allow identifiers declared as types to start the arguments?
1148 * Matze: this all looks confusing and little systematic, so we're even less
1149 * strict and parse any list of things which are identifiers or
1150 * (assignment-)expressions.
1152 static attribute_argument_t *parse_attribute_arguments(void)
1154 attribute_argument_t *first = NULL;
1155 attribute_argument_t **anchor = &first;
1156 if (token.type != ')') do {
1157 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1159 /* is it an identifier */
1160 if (token.type == T_IDENTIFIER
1161 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1162 symbol_t *symbol = token.symbol;
1163 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1164 argument->v.symbol = symbol;
1167 /* must be an expression */
1168 expression_t *expression = parse_assignment_expression();
1170 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1171 argument->v.expression = expression;
1174 /* append argument */
1176 anchor = &argument->next;
1177 } while (next_if(','));
1178 expect(')', end_error);
1187 static attribute_t *parse_attribute_asm(void)
1189 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1192 expect('(', end_error);
1193 attribute->a.arguments = parse_attribute_arguments();
1200 static symbol_t *get_symbol_from_token(void)
1202 switch(token.type) {
1204 return token.symbol;
1233 /* maybe we need more tokens ... add them on demand */
1234 return get_token_symbol(&token);
1240 static attribute_t *parse_attribute_gnu_single(void)
1242 /* parse "any-word" */
1243 symbol_t *symbol = get_symbol_from_token();
1244 if (symbol == NULL) {
1245 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1249 attribute_kind_t kind;
1250 char const *const name = symbol->string;
1251 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1252 if (kind > ATTRIBUTE_GNU_LAST) {
1253 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1254 /* TODO: we should still save the attribute in the list... */
1255 kind = ATTRIBUTE_UNKNOWN;
1259 const char *attribute_name = get_attribute_name(kind);
1260 if (attribute_name != NULL
1261 && strcmp_underscore(attribute_name, name) == 0)
1265 attribute_t *attribute = allocate_attribute_zero(kind);
1268 /* parse arguments */
1270 attribute->a.arguments = parse_attribute_arguments();
1275 static attribute_t *parse_attribute_gnu(void)
1277 attribute_t *first = NULL;
1278 attribute_t **anchor = &first;
1280 eat(T___attribute__);
1281 expect('(', end_error);
1282 expect('(', end_error);
1284 if (token.type != ')') do {
1285 attribute_t *attribute = parse_attribute_gnu_single();
1286 if (attribute == NULL)
1289 *anchor = attribute;
1290 anchor = &attribute->next;
1291 } while (next_if(','));
1292 expect(')', end_error);
1293 expect(')', end_error);
1299 /** Parse attributes. */
1300 static attribute_t *parse_attributes(attribute_t *first)
1302 attribute_t **anchor = &first;
1304 while (*anchor != NULL)
1305 anchor = &(*anchor)->next;
1307 attribute_t *attribute;
1308 switch (token.type) {
1309 case T___attribute__:
1310 attribute = parse_attribute_gnu();
1311 if (attribute == NULL)
1316 attribute = parse_attribute_asm();
1320 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1325 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1329 case T__forceinline:
1330 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1331 eat(T__forceinline);
1335 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1340 /* TODO record modifier */
1341 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1342 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1350 *anchor = attribute;
1351 anchor = &attribute->next;
1355 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1357 static entity_t *determine_lhs_ent(expression_t *const expr,
1360 switch (expr->kind) {
1361 case EXPR_REFERENCE: {
1362 entity_t *const entity = expr->reference.entity;
1363 /* we should only find variables as lvalues... */
1364 if (entity->base.kind != ENTITY_VARIABLE
1365 && entity->base.kind != ENTITY_PARAMETER)
1371 case EXPR_ARRAY_ACCESS: {
1372 expression_t *const ref = expr->array_access.array_ref;
1373 entity_t * ent = NULL;
1374 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1375 ent = determine_lhs_ent(ref, lhs_ent);
1378 mark_vars_read(expr->select.compound, lhs_ent);
1380 mark_vars_read(expr->array_access.index, lhs_ent);
1385 if (is_type_compound(skip_typeref(expr->base.type))) {
1386 return determine_lhs_ent(expr->select.compound, lhs_ent);
1388 mark_vars_read(expr->select.compound, lhs_ent);
1393 case EXPR_UNARY_DEREFERENCE: {
1394 expression_t *const val = expr->unary.value;
1395 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1397 return determine_lhs_ent(val->unary.value, lhs_ent);
1399 mark_vars_read(val, NULL);
1405 mark_vars_read(expr, NULL);
1410 #define ENT_ANY ((entity_t*)-1)
1413 * Mark declarations, which are read. This is used to detect variables, which
1417 * x is not marked as "read", because it is only read to calculate its own new
1421 * x and y are not detected as "not read", because multiple variables are
1424 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1426 switch (expr->kind) {
1427 case EXPR_REFERENCE: {
1428 entity_t *const entity = expr->reference.entity;
1429 if (entity->kind != ENTITY_VARIABLE
1430 && entity->kind != ENTITY_PARAMETER)
1433 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1434 if (entity->kind == ENTITY_VARIABLE) {
1435 entity->variable.read = true;
1437 entity->parameter.read = true;
1444 // TODO respect pure/const
1445 mark_vars_read(expr->call.function, NULL);
1446 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1447 mark_vars_read(arg->expression, NULL);
1451 case EXPR_CONDITIONAL:
1452 // TODO lhs_decl should depend on whether true/false have an effect
1453 mark_vars_read(expr->conditional.condition, NULL);
1454 if (expr->conditional.true_expression != NULL)
1455 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1456 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1460 if (lhs_ent == ENT_ANY
1461 && !is_type_compound(skip_typeref(expr->base.type)))
1463 mark_vars_read(expr->select.compound, lhs_ent);
1466 case EXPR_ARRAY_ACCESS: {
1467 expression_t *const ref = expr->array_access.array_ref;
1468 mark_vars_read(ref, lhs_ent);
1469 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1470 mark_vars_read(expr->array_access.index, lhs_ent);
1475 mark_vars_read(expr->va_arge.ap, lhs_ent);
1479 mark_vars_read(expr->va_copye.src, lhs_ent);
1482 case EXPR_UNARY_CAST:
1483 /* Special case: Use void cast to mark a variable as "read" */
1484 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1489 case EXPR_UNARY_THROW:
1490 if (expr->unary.value == NULL)
1493 case EXPR_UNARY_DEREFERENCE:
1494 case EXPR_UNARY_DELETE:
1495 case EXPR_UNARY_DELETE_ARRAY:
1496 if (lhs_ent == ENT_ANY)
1500 case EXPR_UNARY_NEGATE:
1501 case EXPR_UNARY_PLUS:
1502 case EXPR_UNARY_BITWISE_NEGATE:
1503 case EXPR_UNARY_NOT:
1504 case EXPR_UNARY_TAKE_ADDRESS:
1505 case EXPR_UNARY_POSTFIX_INCREMENT:
1506 case EXPR_UNARY_POSTFIX_DECREMENT:
1507 case EXPR_UNARY_PREFIX_INCREMENT:
1508 case EXPR_UNARY_PREFIX_DECREMENT:
1509 case EXPR_UNARY_CAST_IMPLICIT:
1510 case EXPR_UNARY_ASSUME:
1512 mark_vars_read(expr->unary.value, lhs_ent);
1515 case EXPR_BINARY_ADD:
1516 case EXPR_BINARY_SUB:
1517 case EXPR_BINARY_MUL:
1518 case EXPR_BINARY_DIV:
1519 case EXPR_BINARY_MOD:
1520 case EXPR_BINARY_EQUAL:
1521 case EXPR_BINARY_NOTEQUAL:
1522 case EXPR_BINARY_LESS:
1523 case EXPR_BINARY_LESSEQUAL:
1524 case EXPR_BINARY_GREATER:
1525 case EXPR_BINARY_GREATEREQUAL:
1526 case EXPR_BINARY_BITWISE_AND:
1527 case EXPR_BINARY_BITWISE_OR:
1528 case EXPR_BINARY_BITWISE_XOR:
1529 case EXPR_BINARY_LOGICAL_AND:
1530 case EXPR_BINARY_LOGICAL_OR:
1531 case EXPR_BINARY_SHIFTLEFT:
1532 case EXPR_BINARY_SHIFTRIGHT:
1533 case EXPR_BINARY_COMMA:
1534 case EXPR_BINARY_ISGREATER:
1535 case EXPR_BINARY_ISGREATEREQUAL:
1536 case EXPR_BINARY_ISLESS:
1537 case EXPR_BINARY_ISLESSEQUAL:
1538 case EXPR_BINARY_ISLESSGREATER:
1539 case EXPR_BINARY_ISUNORDERED:
1540 mark_vars_read(expr->binary.left, lhs_ent);
1541 mark_vars_read(expr->binary.right, lhs_ent);
1544 case EXPR_BINARY_ASSIGN:
1545 case EXPR_BINARY_MUL_ASSIGN:
1546 case EXPR_BINARY_DIV_ASSIGN:
1547 case EXPR_BINARY_MOD_ASSIGN:
1548 case EXPR_BINARY_ADD_ASSIGN:
1549 case EXPR_BINARY_SUB_ASSIGN:
1550 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1551 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1552 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1553 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1554 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1555 if (lhs_ent == ENT_ANY)
1557 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1558 mark_vars_read(expr->binary.right, lhs_ent);
1563 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1569 case EXPR_STRING_LITERAL:
1570 case EXPR_WIDE_STRING_LITERAL:
1571 case EXPR_COMPOUND_LITERAL: // TODO init?
1573 case EXPR_CLASSIFY_TYPE:
1576 case EXPR_BUILTIN_CONSTANT_P:
1577 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1579 case EXPR_STATEMENT: // TODO
1580 case EXPR_LABEL_ADDRESS:
1581 case EXPR_REFERENCE_ENUM_VALUE:
1585 panic("unhandled expression");
1588 static designator_t *parse_designation(void)
1590 designator_t *result = NULL;
1591 designator_t **anchor = &result;
1594 designator_t *designator;
1595 switch (token.type) {
1597 designator = allocate_ast_zero(sizeof(designator[0]));
1598 designator->source_position = token.source_position;
1600 add_anchor_token(']');
1601 designator->array_index = parse_constant_expression();
1602 rem_anchor_token(']');
1603 expect(']', end_error);
1606 designator = allocate_ast_zero(sizeof(designator[0]));
1607 designator->source_position = token.source_position;
1609 if (token.type != T_IDENTIFIER) {
1610 parse_error_expected("while parsing designator",
1611 T_IDENTIFIER, NULL);
1614 designator->symbol = token.symbol;
1618 expect('=', end_error);
1622 assert(designator != NULL);
1623 *anchor = designator;
1624 anchor = &designator->next;
1630 static initializer_t *initializer_from_string(array_type_t *const type,
1631 const string_t *const string)
1633 /* TODO: check len vs. size of array type */
1636 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1637 initializer->string.string = *string;
1642 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1643 const string_t *const string)
1645 /* TODO: check len vs. size of array type */
1648 initializer_t *const initializer =
1649 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1650 initializer->wide_string.string = *string;
1656 * Build an initializer from a given expression.
1658 static initializer_t *initializer_from_expression(type_t *orig_type,
1659 expression_t *expression)
1661 /* TODO check that expression is a constant expression */
1663 /* §6.7.8.14/15 char array may be initialized by string literals */
1664 type_t *type = skip_typeref(orig_type);
1665 type_t *expr_type_orig = expression->base.type;
1666 type_t *expr_type = skip_typeref(expr_type_orig);
1668 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1669 array_type_t *const array_type = &type->array;
1670 type_t *const element_type = skip_typeref(array_type->element_type);
1672 if (element_type->kind == TYPE_ATOMIC) {
1673 atomic_type_kind_t akind = element_type->atomic.akind;
1674 switch (expression->kind) {
1675 case EXPR_STRING_LITERAL:
1676 if (akind == ATOMIC_TYPE_CHAR
1677 || akind == ATOMIC_TYPE_SCHAR
1678 || akind == ATOMIC_TYPE_UCHAR) {
1679 return initializer_from_string(array_type,
1680 &expression->string_literal.value);
1684 case EXPR_WIDE_STRING_LITERAL: {
1685 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1686 if (get_unqualified_type(element_type) == bare_wchar_type) {
1687 return initializer_from_wide_string(array_type,
1688 &expression->string_literal.value);
1699 assign_error_t error = semantic_assign(type, expression);
1700 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1702 report_assign_error(error, type, expression, "initializer",
1703 &expression->base.source_position);
1705 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1706 result->value.value = create_implicit_cast(expression, type);
1712 * Checks if a given expression can be used as a constant initializer.
1714 static bool is_initializer_constant(const expression_t *expression)
1716 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1717 is_linker_constant(expression) != EXPR_CLASS_VARIABLE;
1721 * Parses an scalar initializer.
1723 * §6.7.8.11; eat {} without warning
1725 static initializer_t *parse_scalar_initializer(type_t *type,
1726 bool must_be_constant)
1728 /* there might be extra {} hierarchies */
1730 if (token.type == '{') {
1731 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1735 } while (token.type == '{');
1738 expression_t *expression = parse_assignment_expression();
1739 mark_vars_read(expression, NULL);
1740 if (must_be_constant && !is_initializer_constant(expression)) {
1741 errorf(&expression->base.source_position,
1742 "initialisation expression '%E' is not constant",
1746 initializer_t *initializer = initializer_from_expression(type, expression);
1748 if (initializer == NULL) {
1749 errorf(&expression->base.source_position,
1750 "expression '%E' (type '%T') doesn't match expected type '%T'",
1751 expression, expression->base.type, type);
1756 bool additional_warning_displayed = false;
1757 while (braces > 0) {
1759 if (token.type != '}') {
1760 if (!additional_warning_displayed) {
1761 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1762 additional_warning_displayed = true;
1773 * An entry in the type path.
1775 typedef struct type_path_entry_t type_path_entry_t;
1776 struct type_path_entry_t {
1777 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1779 size_t index; /**< For array types: the current index. */
1780 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1785 * A type path expression a position inside compound or array types.
1787 typedef struct type_path_t type_path_t;
1788 struct type_path_t {
1789 type_path_entry_t *path; /**< An flexible array containing the current path. */
1790 type_t *top_type; /**< type of the element the path points */
1791 size_t max_index; /**< largest index in outermost array */
1795 * Prints a type path for debugging.
1797 static __attribute__((unused)) void debug_print_type_path(
1798 const type_path_t *path)
1800 size_t len = ARR_LEN(path->path);
1802 for (size_t i = 0; i < len; ++i) {
1803 const type_path_entry_t *entry = & path->path[i];
1805 type_t *type = skip_typeref(entry->type);
1806 if (is_type_compound(type)) {
1807 /* in gcc mode structs can have no members */
1808 if (entry->v.compound_entry == NULL) {
1812 fprintf(stderr, ".%s",
1813 entry->v.compound_entry->base.symbol->string);
1814 } else if (is_type_array(type)) {
1815 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1817 fprintf(stderr, "-INVALID-");
1820 if (path->top_type != NULL) {
1821 fprintf(stderr, " (");
1822 print_type(path->top_type);
1823 fprintf(stderr, ")");
1828 * Return the top type path entry, ie. in a path
1829 * (type).a.b returns the b.
1831 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1833 size_t len = ARR_LEN(path->path);
1835 return &path->path[len-1];
1839 * Enlarge the type path by an (empty) element.
1841 static type_path_entry_t *append_to_type_path(type_path_t *path)
1843 size_t len = ARR_LEN(path->path);
1844 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1846 type_path_entry_t *result = & path->path[len];
1847 memset(result, 0, sizeof(result[0]));
1852 * Descending into a sub-type. Enter the scope of the current top_type.
1854 static void descend_into_subtype(type_path_t *path)
1856 type_t *orig_top_type = path->top_type;
1857 type_t *top_type = skip_typeref(orig_top_type);
1859 type_path_entry_t *top = append_to_type_path(path);
1860 top->type = top_type;
1862 if (is_type_compound(top_type)) {
1863 compound_t *compound = top_type->compound.compound;
1864 entity_t *entry = compound->members.entities;
1866 if (entry != NULL) {
1867 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1868 top->v.compound_entry = &entry->declaration;
1869 path->top_type = entry->declaration.type;
1871 path->top_type = NULL;
1873 } else if (is_type_array(top_type)) {
1875 path->top_type = top_type->array.element_type;
1877 assert(!is_type_valid(top_type));
1882 * Pop an entry from the given type path, ie. returning from
1883 * (type).a.b to (type).a
1885 static void ascend_from_subtype(type_path_t *path)
1887 type_path_entry_t *top = get_type_path_top(path);
1889 path->top_type = top->type;
1891 size_t len = ARR_LEN(path->path);
1892 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1896 * Pop entries from the given type path until the given
1897 * path level is reached.
1899 static void ascend_to(type_path_t *path, size_t top_path_level)
1901 size_t len = ARR_LEN(path->path);
1903 while (len > top_path_level) {
1904 ascend_from_subtype(path);
1905 len = ARR_LEN(path->path);
1909 static bool walk_designator(type_path_t *path, const designator_t *designator,
1910 bool used_in_offsetof)
1912 for (; designator != NULL; designator = designator->next) {
1913 type_path_entry_t *top = get_type_path_top(path);
1914 type_t *orig_type = top->type;
1916 type_t *type = skip_typeref(orig_type);
1918 if (designator->symbol != NULL) {
1919 symbol_t *symbol = designator->symbol;
1920 if (!is_type_compound(type)) {
1921 if (is_type_valid(type)) {
1922 errorf(&designator->source_position,
1923 "'.%Y' designator used for non-compound type '%T'",
1927 top->type = type_error_type;
1928 top->v.compound_entry = NULL;
1929 orig_type = type_error_type;
1931 compound_t *compound = type->compound.compound;
1932 entity_t *iter = compound->members.entities;
1933 for (; iter != NULL; iter = iter->base.next) {
1934 if (iter->base.symbol == symbol) {
1939 errorf(&designator->source_position,
1940 "'%T' has no member named '%Y'", orig_type, symbol);
1943 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1944 if (used_in_offsetof) {
1945 type_t *real_type = skip_typeref(iter->declaration.type);
1946 if (real_type->kind == TYPE_BITFIELD) {
1947 errorf(&designator->source_position,
1948 "offsetof designator '%Y' must not specify bitfield",
1954 top->type = orig_type;
1955 top->v.compound_entry = &iter->declaration;
1956 orig_type = iter->declaration.type;
1959 expression_t *array_index = designator->array_index;
1960 assert(designator->array_index != NULL);
1962 if (!is_type_array(type)) {
1963 if (is_type_valid(type)) {
1964 errorf(&designator->source_position,
1965 "[%E] designator used for non-array type '%T'",
1966 array_index, orig_type);
1971 long index = fold_constant_to_int(array_index);
1972 if (!used_in_offsetof) {
1974 errorf(&designator->source_position,
1975 "array index [%E] must be positive", array_index);
1976 } else if (type->array.size_constant) {
1977 long array_size = type->array.size;
1978 if (index >= array_size) {
1979 errorf(&designator->source_position,
1980 "designator [%E] (%d) exceeds array size %d",
1981 array_index, index, array_size);
1986 top->type = orig_type;
1987 top->v.index = (size_t) index;
1988 orig_type = type->array.element_type;
1990 path->top_type = orig_type;
1992 if (designator->next != NULL) {
1993 descend_into_subtype(path);
1999 static void advance_current_object(type_path_t *path, size_t top_path_level)
2001 type_path_entry_t *top = get_type_path_top(path);
2003 type_t *type = skip_typeref(top->type);
2004 if (is_type_union(type)) {
2005 /* in unions only the first element is initialized */
2006 top->v.compound_entry = NULL;
2007 } else if (is_type_struct(type)) {
2008 declaration_t *entry = top->v.compound_entry;
2010 entity_t *next_entity = entry->base.next;
2011 if (next_entity != NULL) {
2012 assert(is_declaration(next_entity));
2013 entry = &next_entity->declaration;
2018 top->v.compound_entry = entry;
2019 if (entry != NULL) {
2020 path->top_type = entry->type;
2023 } else if (is_type_array(type)) {
2024 assert(is_type_array(type));
2028 if (!type->array.size_constant || top->v.index < type->array.size) {
2032 assert(!is_type_valid(type));
2036 /* we're past the last member of the current sub-aggregate, try if we
2037 * can ascend in the type hierarchy and continue with another subobject */
2038 size_t len = ARR_LEN(path->path);
2040 if (len > top_path_level) {
2041 ascend_from_subtype(path);
2042 advance_current_object(path, top_path_level);
2044 path->top_type = NULL;
2049 * skip any {...} blocks until a closing bracket is reached.
2051 static void skip_initializers(void)
2055 while (token.type != '}') {
2056 if (token.type == T_EOF)
2058 if (token.type == '{') {
2066 static initializer_t *create_empty_initializer(void)
2068 static initializer_t empty_initializer
2069 = { .list = { { INITIALIZER_LIST }, 0 } };
2070 return &empty_initializer;
2074 * Parse a part of an initialiser for a struct or union,
2076 static initializer_t *parse_sub_initializer(type_path_t *path,
2077 type_t *outer_type, size_t top_path_level,
2078 parse_initializer_env_t *env)
2080 if (token.type == '}') {
2081 /* empty initializer */
2082 return create_empty_initializer();
2085 type_t *orig_type = path->top_type;
2086 type_t *type = NULL;
2088 if (orig_type == NULL) {
2089 /* We are initializing an empty compound. */
2091 type = skip_typeref(orig_type);
2094 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2097 designator_t *designator = NULL;
2098 if (token.type == '.' || token.type == '[') {
2099 designator = parse_designation();
2100 goto finish_designator;
2101 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2102 /* GNU-style designator ("identifier: value") */
2103 designator = allocate_ast_zero(sizeof(designator[0]));
2104 designator->source_position = token.source_position;
2105 designator->symbol = token.symbol;
2110 /* reset path to toplevel, evaluate designator from there */
2111 ascend_to(path, top_path_level);
2112 if (!walk_designator(path, designator, false)) {
2113 /* can't continue after designation error */
2117 initializer_t *designator_initializer
2118 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2119 designator_initializer->designator.designator = designator;
2120 ARR_APP1(initializer_t*, initializers, designator_initializer);
2122 orig_type = path->top_type;
2123 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2128 if (token.type == '{') {
2129 if (type != NULL && is_type_scalar(type)) {
2130 sub = parse_scalar_initializer(type, env->must_be_constant);
2133 if (env->entity != NULL) {
2135 "extra brace group at end of initializer for '%Y'",
2136 env->entity->base.symbol);
2138 errorf(HERE, "extra brace group at end of initializer");
2143 descend_into_subtype(path);
2146 add_anchor_token('}');
2147 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2149 rem_anchor_token('}');
2152 ascend_from_subtype(path);
2153 expect('}', end_error);
2155 expect('}', end_error);
2156 goto error_parse_next;
2160 /* must be an expression */
2161 expression_t *expression = parse_assignment_expression();
2162 mark_vars_read(expression, NULL);
2164 if (env->must_be_constant && !is_initializer_constant(expression)) {
2165 errorf(&expression->base.source_position,
2166 "Initialisation expression '%E' is not constant",
2171 /* we are already outside, ... */
2172 if (outer_type == NULL)
2173 goto error_parse_next;
2174 type_t *const outer_type_skip = skip_typeref(outer_type);
2175 if (is_type_compound(outer_type_skip) &&
2176 !outer_type_skip->compound.compound->complete) {
2177 goto error_parse_next;
2180 source_position_t const* const pos = &expression->base.source_position;
2181 if (env->entity != NULL) {
2182 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2184 warningf(WARN_OTHER, pos, "excess elements in initializer");
2186 goto error_parse_next;
2189 /* handle { "string" } special case */
2190 if ((expression->kind == EXPR_STRING_LITERAL
2191 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2192 && outer_type != NULL) {
2193 sub = initializer_from_expression(outer_type, expression);
2196 if (token.type != '}') {
2197 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2199 /* TODO: eat , ... */
2204 /* descend into subtypes until expression matches type */
2206 orig_type = path->top_type;
2207 type = skip_typeref(orig_type);
2209 sub = initializer_from_expression(orig_type, expression);
2213 if (!is_type_valid(type)) {
2216 if (is_type_scalar(type)) {
2217 errorf(&expression->base.source_position,
2218 "expression '%E' doesn't match expected type '%T'",
2219 expression, orig_type);
2223 descend_into_subtype(path);
2227 /* update largest index of top array */
2228 const type_path_entry_t *first = &path->path[0];
2229 type_t *first_type = first->type;
2230 first_type = skip_typeref(first_type);
2231 if (is_type_array(first_type)) {
2232 size_t index = first->v.index;
2233 if (index > path->max_index)
2234 path->max_index = index;
2237 /* append to initializers list */
2238 ARR_APP1(initializer_t*, initializers, sub);
2241 if (token.type == '}') {
2244 expect(',', end_error);
2245 if (token.type == '}') {
2250 /* advance to the next declaration if we are not at the end */
2251 advance_current_object(path, top_path_level);
2252 orig_type = path->top_type;
2253 if (orig_type != NULL)
2254 type = skip_typeref(orig_type);
2260 size_t len = ARR_LEN(initializers);
2261 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2262 initializer_t *result = allocate_ast_zero(size);
2263 result->kind = INITIALIZER_LIST;
2264 result->list.len = len;
2265 memcpy(&result->list.initializers, initializers,
2266 len * sizeof(initializers[0]));
2268 DEL_ARR_F(initializers);
2269 ascend_to(path, top_path_level+1);
2274 skip_initializers();
2275 DEL_ARR_F(initializers);
2276 ascend_to(path, top_path_level+1);
2280 static expression_t *make_size_literal(size_t value)
2282 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2283 literal->base.type = type_size_t;
2286 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2287 literal->literal.value = make_string(buf);
2293 * Parses an initializer. Parsers either a compound literal
2294 * (env->declaration == NULL) or an initializer of a declaration.
2296 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2298 type_t *type = skip_typeref(env->type);
2299 size_t max_index = 0;
2300 initializer_t *result;
2302 if (is_type_scalar(type)) {
2303 result = parse_scalar_initializer(type, env->must_be_constant);
2304 } else if (token.type == '{') {
2308 memset(&path, 0, sizeof(path));
2309 path.top_type = env->type;
2310 path.path = NEW_ARR_F(type_path_entry_t, 0);
2312 descend_into_subtype(&path);
2314 add_anchor_token('}');
2315 result = parse_sub_initializer(&path, env->type, 1, env);
2316 rem_anchor_token('}');
2318 max_index = path.max_index;
2319 DEL_ARR_F(path.path);
2321 expect('}', end_error);
2324 /* parse_scalar_initializer() also works in this case: we simply
2325 * have an expression without {} around it */
2326 result = parse_scalar_initializer(type, env->must_be_constant);
2329 /* §6.7.8:22 array initializers for arrays with unknown size determine
2330 * the array type size */
2331 if (is_type_array(type) && type->array.size_expression == NULL
2332 && result != NULL) {
2334 switch (result->kind) {
2335 case INITIALIZER_LIST:
2336 assert(max_index != 0xdeadbeaf);
2337 size = max_index + 1;
2340 case INITIALIZER_STRING:
2341 size = result->string.string.size;
2344 case INITIALIZER_WIDE_STRING:
2345 size = result->wide_string.string.size;
2348 case INITIALIZER_DESIGNATOR:
2349 case INITIALIZER_VALUE:
2350 /* can happen for parse errors */
2355 internal_errorf(HERE, "invalid initializer type");
2358 type_t *new_type = duplicate_type(type);
2360 new_type->array.size_expression = make_size_literal(size);
2361 new_type->array.size_constant = true;
2362 new_type->array.has_implicit_size = true;
2363 new_type->array.size = size;
2364 env->type = new_type;
2370 static void append_entity(scope_t *scope, entity_t *entity)
2372 if (scope->last_entity != NULL) {
2373 scope->last_entity->base.next = entity;
2375 scope->entities = entity;
2377 entity->base.parent_entity = current_entity;
2378 scope->last_entity = entity;
2382 static compound_t *parse_compound_type_specifier(bool is_struct)
2384 source_position_t const pos = *HERE;
2385 eat(is_struct ? T_struct : T_union);
2387 symbol_t *symbol = NULL;
2388 entity_t *entity = NULL;
2389 attribute_t *attributes = NULL;
2391 if (token.type == T___attribute__) {
2392 attributes = parse_attributes(NULL);
2395 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2396 if (token.type == T_IDENTIFIER) {
2397 /* the compound has a name, check if we have seen it already */
2398 symbol = token.symbol;
2399 entity = get_tag(symbol, kind);
2402 if (entity != NULL) {
2403 if (entity->base.parent_scope != current_scope &&
2404 (token.type == '{' || token.type == ';')) {
2405 /* we're in an inner scope and have a definition. Shadow
2406 * existing definition in outer scope */
2408 } else if (entity->compound.complete && token.type == '{') {
2409 source_position_t const *const ppos = &entity->base.source_position;
2410 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2411 /* clear members in the hope to avoid further errors */
2412 entity->compound.members.entities = NULL;
2415 } else if (token.type != '{') {
2416 char const *const msg =
2417 is_struct ? "while parsing struct type specifier" :
2418 "while parsing union type specifier";
2419 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2424 if (entity == NULL) {
2425 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2426 entity->compound.alignment = 1;
2427 entity->base.source_position = pos;
2428 entity->base.parent_scope = current_scope;
2429 if (symbol != NULL) {
2430 environment_push(entity);
2432 append_entity(current_scope, entity);
2435 if (token.type == '{') {
2436 parse_compound_type_entries(&entity->compound);
2438 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2439 if (symbol == NULL) {
2440 assert(anonymous_entity == NULL);
2441 anonymous_entity = entity;
2445 if (attributes != NULL) {
2446 handle_entity_attributes(attributes, entity);
2449 return &entity->compound;
2452 static void parse_enum_entries(type_t *const enum_type)
2456 if (token.type == '}') {
2457 errorf(HERE, "empty enum not allowed");
2462 add_anchor_token('}');
2464 if (token.type != T_IDENTIFIER) {
2465 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2467 rem_anchor_token('}');
2471 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, token.symbol);
2472 entity->enum_value.enum_type = enum_type;
2473 entity->base.source_position = token.source_position;
2477 expression_t *value = parse_constant_expression();
2479 value = create_implicit_cast(value, enum_type);
2480 entity->enum_value.value = value;
2485 record_entity(entity, false);
2486 } while (next_if(',') && token.type != '}');
2487 rem_anchor_token('}');
2489 expect('}', end_error);
2495 static type_t *parse_enum_specifier(void)
2497 source_position_t const pos = *HERE;
2502 switch (token.type) {
2504 symbol = token.symbol;
2505 entity = get_tag(symbol, ENTITY_ENUM);
2508 if (entity != NULL) {
2509 if (entity->base.parent_scope != current_scope &&
2510 (token.type == '{' || token.type == ';')) {
2511 /* we're in an inner scope and have a definition. Shadow
2512 * existing definition in outer scope */
2514 } else if (entity->enume.complete && token.type == '{') {
2515 source_position_t const *const ppos = &entity->base.source_position;
2516 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2527 parse_error_expected("while parsing enum type specifier",
2528 T_IDENTIFIER, '{', NULL);
2532 if (entity == NULL) {
2533 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2534 entity->base.source_position = pos;
2535 entity->base.parent_scope = current_scope;
2538 type_t *const type = allocate_type_zero(TYPE_ENUM);
2539 type->enumt.enume = &entity->enume;
2540 type->enumt.akind = ATOMIC_TYPE_INT;
2542 if (token.type == '{') {
2543 if (symbol != NULL) {
2544 environment_push(entity);
2546 append_entity(current_scope, entity);
2547 entity->enume.complete = true;
2549 parse_enum_entries(type);
2550 parse_attributes(NULL);
2552 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2553 if (symbol == NULL) {
2554 assert(anonymous_entity == NULL);
2555 anonymous_entity = entity;
2557 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2558 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2565 * if a symbol is a typedef to another type, return true
2567 static bool is_typedef_symbol(symbol_t *symbol)
2569 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2570 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2573 static type_t *parse_typeof(void)
2579 expect('(', end_error);
2580 add_anchor_token(')');
2582 expression_t *expression = NULL;
2584 switch (token.type) {
2586 if (is_typedef_symbol(token.symbol)) {
2588 type = parse_typename();
2591 expression = parse_expression();
2592 type = revert_automatic_type_conversion(expression);
2597 rem_anchor_token(')');
2598 expect(')', end_error);
2600 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2601 typeof_type->typeoft.expression = expression;
2602 typeof_type->typeoft.typeof_type = type;
2609 typedef enum specifiers_t {
2610 SPECIFIER_SIGNED = 1 << 0,
2611 SPECIFIER_UNSIGNED = 1 << 1,
2612 SPECIFIER_LONG = 1 << 2,
2613 SPECIFIER_INT = 1 << 3,
2614 SPECIFIER_DOUBLE = 1 << 4,
2615 SPECIFIER_CHAR = 1 << 5,
2616 SPECIFIER_WCHAR_T = 1 << 6,
2617 SPECIFIER_SHORT = 1 << 7,
2618 SPECIFIER_LONG_LONG = 1 << 8,
2619 SPECIFIER_FLOAT = 1 << 9,
2620 SPECIFIER_BOOL = 1 << 10,
2621 SPECIFIER_VOID = 1 << 11,
2622 SPECIFIER_INT8 = 1 << 12,
2623 SPECIFIER_INT16 = 1 << 13,
2624 SPECIFIER_INT32 = 1 << 14,
2625 SPECIFIER_INT64 = 1 << 15,
2626 SPECIFIER_INT128 = 1 << 16,
2627 SPECIFIER_COMPLEX = 1 << 17,
2628 SPECIFIER_IMAGINARY = 1 << 18,
2631 static type_t *get_typedef_type(symbol_t *symbol)
2633 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2634 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2637 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2638 type->typedeft.typedefe = &entity->typedefe;
2643 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2645 expect('(', end_error);
2647 attribute_property_argument_t *property
2648 = allocate_ast_zero(sizeof(*property));
2651 if (token.type != T_IDENTIFIER) {
2652 parse_error_expected("while parsing property declspec",
2653 T_IDENTIFIER, NULL);
2658 symbol_t *symbol = token.symbol;
2659 if (strcmp(symbol->string, "put") == 0) {
2660 prop = &property->put_symbol;
2661 } else if (strcmp(symbol->string, "get") == 0) {
2662 prop = &property->get_symbol;
2664 errorf(HERE, "expected put or get in property declspec");
2668 expect('=', end_error);
2669 if (token.type != T_IDENTIFIER) {
2670 parse_error_expected("while parsing property declspec",
2671 T_IDENTIFIER, NULL);
2675 *prop = token.symbol;
2677 } while (next_if(','));
2679 attribute->a.property = property;
2681 expect(')', end_error);
2687 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2689 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2690 if (next_if(T_restrict)) {
2691 kind = ATTRIBUTE_MS_RESTRICT;
2692 } else if (token.type == T_IDENTIFIER) {
2693 const char *name = token.symbol->string;
2694 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2696 const char *attribute_name = get_attribute_name(k);
2697 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2703 if (kind == ATTRIBUTE_UNKNOWN) {
2704 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2707 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2711 attribute_t *attribute = allocate_attribute_zero(kind);
2714 if (kind == ATTRIBUTE_MS_PROPERTY) {
2715 return parse_attribute_ms_property(attribute);
2718 /* parse arguments */
2720 attribute->a.arguments = parse_attribute_arguments();
2725 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2729 expect('(', end_error);
2734 add_anchor_token(')');
2736 attribute_t **anchor = &first;
2738 while (*anchor != NULL)
2739 anchor = &(*anchor)->next;
2741 attribute_t *attribute
2742 = parse_microsoft_extended_decl_modifier_single();
2743 if (attribute == NULL)
2746 *anchor = attribute;
2747 anchor = &attribute->next;
2748 } while (next_if(','));
2750 rem_anchor_token(')');
2751 expect(')', end_error);
2755 rem_anchor_token(')');
2759 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2761 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2762 entity->base.source_position = *HERE;
2763 if (is_declaration(entity)) {
2764 entity->declaration.type = type_error_type;
2765 entity->declaration.implicit = true;
2766 } else if (kind == ENTITY_TYPEDEF) {
2767 entity->typedefe.type = type_error_type;
2768 entity->typedefe.builtin = true;
2770 if (kind != ENTITY_COMPOUND_MEMBER)
2771 record_entity(entity, false);
2775 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2777 type_t *type = NULL;
2778 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2779 unsigned type_specifiers = 0;
2780 bool newtype = false;
2781 bool saw_error = false;
2783 memset(specifiers, 0, sizeof(*specifiers));
2784 specifiers->source_position = token.source_position;
2787 specifiers->attributes = parse_attributes(specifiers->attributes);
2789 switch (token.type) {
2791 #define MATCH_STORAGE_CLASS(token, class) \
2793 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2794 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2796 specifiers->storage_class = class; \
2797 if (specifiers->thread_local) \
2798 goto check_thread_storage_class; \
2802 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2803 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2804 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2805 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2806 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2809 specifiers->attributes
2810 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2814 if (specifiers->thread_local) {
2815 errorf(HERE, "duplicate '__thread'");
2817 specifiers->thread_local = true;
2818 check_thread_storage_class:
2819 switch (specifiers->storage_class) {
2820 case STORAGE_CLASS_EXTERN:
2821 case STORAGE_CLASS_NONE:
2822 case STORAGE_CLASS_STATIC:
2826 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2827 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2828 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2829 wrong_thread_storage_class:
2830 errorf(HERE, "'__thread' used with '%s'", wrong);
2837 /* type qualifiers */
2838 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2840 qualifiers |= qualifier; \
2844 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2845 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2846 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2847 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2848 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2849 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2850 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2851 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2853 /* type specifiers */
2854 #define MATCH_SPECIFIER(token, specifier, name) \
2856 if (type_specifiers & specifier) { \
2857 errorf(HERE, "multiple " name " type specifiers given"); \
2859 type_specifiers |= specifier; \
2864 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2865 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2866 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2867 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2868 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2869 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2870 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2871 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2872 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2873 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2874 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2875 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2876 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2877 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2878 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2879 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2880 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2881 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2885 specifiers->is_inline = true;
2889 case T__forceinline:
2891 specifiers->modifiers |= DM_FORCEINLINE;
2896 if (type_specifiers & SPECIFIER_LONG_LONG) {
2897 errorf(HERE, "too many long type specifiers given");
2898 } else if (type_specifiers & SPECIFIER_LONG) {
2899 type_specifiers |= SPECIFIER_LONG_LONG;
2901 type_specifiers |= SPECIFIER_LONG;
2906 #define CHECK_DOUBLE_TYPE() \
2907 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2910 CHECK_DOUBLE_TYPE();
2911 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2913 type->compound.compound = parse_compound_type_specifier(true);
2916 CHECK_DOUBLE_TYPE();
2917 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2918 type->compound.compound = parse_compound_type_specifier(false);
2921 CHECK_DOUBLE_TYPE();
2922 type = parse_enum_specifier();
2925 CHECK_DOUBLE_TYPE();
2926 type = parse_typeof();
2928 case T___builtin_va_list:
2929 CHECK_DOUBLE_TYPE();
2930 type = duplicate_type(type_valist);
2934 case T_IDENTIFIER: {
2935 /* only parse identifier if we haven't found a type yet */
2936 if (type != NULL || type_specifiers != 0) {
2937 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2938 * declaration, so it doesn't generate errors about expecting '(' or
2940 switch (look_ahead(1)->type) {
2947 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2951 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2956 goto finish_specifiers;
2960 type_t *const typedef_type = get_typedef_type(token.symbol);
2961 if (typedef_type == NULL) {
2962 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2963 * declaration, so it doesn't generate 'implicit int' followed by more
2964 * errors later on. */
2965 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
2971 errorf(HERE, "%K does not name a type", &token);
2974 create_error_entity(token.symbol, ENTITY_TYPEDEF);
2976 type = allocate_type_zero(TYPE_TYPEDEF);
2977 type->typedeft.typedefe = &entity->typedefe;
2985 goto finish_specifiers;
2990 type = typedef_type;
2994 /* function specifier */
2996 goto finish_specifiers;
3001 specifiers->attributes = parse_attributes(specifiers->attributes);
3003 if (type == NULL || (saw_error && type_specifiers != 0)) {
3004 atomic_type_kind_t atomic_type;
3006 /* match valid basic types */
3007 switch (type_specifiers) {
3008 case SPECIFIER_VOID:
3009 atomic_type = ATOMIC_TYPE_VOID;
3011 case SPECIFIER_WCHAR_T:
3012 atomic_type = ATOMIC_TYPE_WCHAR_T;
3014 case SPECIFIER_CHAR:
3015 atomic_type = ATOMIC_TYPE_CHAR;
3017 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3018 atomic_type = ATOMIC_TYPE_SCHAR;
3020 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3021 atomic_type = ATOMIC_TYPE_UCHAR;
3023 case SPECIFIER_SHORT:
3024 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3025 case SPECIFIER_SHORT | SPECIFIER_INT:
3026 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3027 atomic_type = ATOMIC_TYPE_SHORT;
3029 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3030 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3031 atomic_type = ATOMIC_TYPE_USHORT;
3034 case SPECIFIER_SIGNED:
3035 case SPECIFIER_SIGNED | SPECIFIER_INT:
3036 atomic_type = ATOMIC_TYPE_INT;
3038 case SPECIFIER_UNSIGNED:
3039 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3040 atomic_type = ATOMIC_TYPE_UINT;
3042 case SPECIFIER_LONG:
3043 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3044 case SPECIFIER_LONG | SPECIFIER_INT:
3045 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3046 atomic_type = ATOMIC_TYPE_LONG;
3048 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3049 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3050 atomic_type = ATOMIC_TYPE_ULONG;
3053 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3054 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3055 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3056 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3058 atomic_type = ATOMIC_TYPE_LONGLONG;
3059 goto warn_about_long_long;
3061 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3062 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3064 atomic_type = ATOMIC_TYPE_ULONGLONG;
3065 warn_about_long_long:
3066 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3069 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3070 atomic_type = unsigned_int8_type_kind;
3073 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3074 atomic_type = unsigned_int16_type_kind;
3077 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3078 atomic_type = unsigned_int32_type_kind;
3081 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3082 atomic_type = unsigned_int64_type_kind;
3085 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3086 atomic_type = unsigned_int128_type_kind;
3089 case SPECIFIER_INT8:
3090 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3091 atomic_type = int8_type_kind;
3094 case SPECIFIER_INT16:
3095 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3096 atomic_type = int16_type_kind;
3099 case SPECIFIER_INT32:
3100 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3101 atomic_type = int32_type_kind;
3104 case SPECIFIER_INT64:
3105 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3106 atomic_type = int64_type_kind;
3109 case SPECIFIER_INT128:
3110 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3111 atomic_type = int128_type_kind;
3114 case SPECIFIER_FLOAT:
3115 atomic_type = ATOMIC_TYPE_FLOAT;
3117 case SPECIFIER_DOUBLE:
3118 atomic_type = ATOMIC_TYPE_DOUBLE;
3120 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3121 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3123 case SPECIFIER_BOOL:
3124 atomic_type = ATOMIC_TYPE_BOOL;
3126 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3127 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3128 atomic_type = ATOMIC_TYPE_FLOAT;
3130 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3131 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3132 atomic_type = ATOMIC_TYPE_DOUBLE;
3134 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3135 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3136 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3139 /* invalid specifier combination, give an error message */
3140 source_position_t const* const pos = &specifiers->source_position;
3141 if (type_specifiers == 0) {
3143 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3144 if (!(c_mode & _CXX) && !strict_mode) {
3145 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3146 atomic_type = ATOMIC_TYPE_INT;
3149 errorf(pos, "no type specifiers given in declaration");
3152 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3153 (type_specifiers & SPECIFIER_UNSIGNED)) {
3154 errorf(pos, "signed and unsigned specifiers given");
3155 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3156 errorf(pos, "only integer types can be signed or unsigned");
3158 errorf(pos, "multiple datatypes in declaration");
3164 if (type_specifiers & SPECIFIER_COMPLEX) {
3165 type = allocate_type_zero(TYPE_COMPLEX);
3166 type->complex.akind = atomic_type;
3167 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3168 type = allocate_type_zero(TYPE_IMAGINARY);
3169 type->imaginary.akind = atomic_type;
3171 type = allocate_type_zero(TYPE_ATOMIC);
3172 type->atomic.akind = atomic_type;
3175 } else if (type_specifiers != 0) {
3176 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3179 /* FIXME: check type qualifiers here */
3180 type->base.qualifiers = qualifiers;
3183 type = identify_new_type(type);
3185 type = typehash_insert(type);
3188 if (specifiers->attributes != NULL)
3189 type = handle_type_attributes(specifiers->attributes, type);
3190 specifiers->type = type;
3194 specifiers->type = type_error_type;
3197 static type_qualifiers_t parse_type_qualifiers(void)
3199 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3202 switch (token.type) {
3203 /* type qualifiers */
3204 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3205 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3206 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3207 /* microsoft extended type modifiers */
3208 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3209 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3210 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3211 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3212 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3221 * Parses an K&R identifier list
3223 static void parse_identifier_list(scope_t *scope)
3226 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.symbol);
3227 entity->base.source_position = token.source_position;
3228 /* a K&R parameter has no type, yet */
3232 append_entity(scope, entity);
3233 } while (next_if(',') && token.type == T_IDENTIFIER);
3236 static entity_t *parse_parameter(void)
3238 declaration_specifiers_t specifiers;
3239 parse_declaration_specifiers(&specifiers);
3241 entity_t *entity = parse_declarator(&specifiers,
3242 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3243 anonymous_entity = NULL;
3247 static void semantic_parameter_incomplete(const entity_t *entity)
3249 assert(entity->kind == ENTITY_PARAMETER);
3251 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3252 * list in a function declarator that is part of a
3253 * definition of that function shall not have
3254 * incomplete type. */
3255 type_t *type = skip_typeref(entity->declaration.type);
3256 if (is_type_incomplete(type)) {
3257 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3261 static bool has_parameters(void)
3263 /* func(void) is not a parameter */
3264 if (token.type == T_IDENTIFIER) {
3265 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3268 if (entity->kind != ENTITY_TYPEDEF)
3270 if (skip_typeref(entity->typedefe.type) != type_void)
3272 } else if (token.type != T_void) {
3275 if (look_ahead(1)->type != ')')
3282 * Parses function type parameters (and optionally creates variable_t entities
3283 * for them in a scope)
3285 static void parse_parameters(function_type_t *type, scope_t *scope)
3288 add_anchor_token(')');
3289 int saved_comma_state = save_and_reset_anchor_state(',');
3291 if (token.type == T_IDENTIFIER &&
3292 !is_typedef_symbol(token.symbol)) {
3293 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3294 if (la1_type == ',' || la1_type == ')') {
3295 type->kr_style_parameters = true;
3296 parse_identifier_list(scope);
3297 goto parameters_finished;
3301 if (token.type == ')') {
3302 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3303 if (!(c_mode & _CXX))
3304 type->unspecified_parameters = true;
3305 } else if (has_parameters()) {
3306 function_parameter_t **anchor = &type->parameters;
3308 switch (token.type) {
3311 type->variadic = true;
3312 goto parameters_finished;
3317 entity_t *entity = parse_parameter();
3318 if (entity->kind == ENTITY_TYPEDEF) {
3319 errorf(&entity->base.source_position,
3320 "typedef not allowed as function parameter");
3323 assert(is_declaration(entity));
3325 semantic_parameter_incomplete(entity);
3327 function_parameter_t *const parameter =
3328 allocate_parameter(entity->declaration.type);
3330 if (scope != NULL) {
3331 append_entity(scope, entity);
3334 *anchor = parameter;
3335 anchor = ¶meter->next;
3340 goto parameters_finished;
3342 } while (next_if(','));
3345 parameters_finished:
3346 rem_anchor_token(')');
3347 expect(')', end_error);
3350 restore_anchor_state(',', saved_comma_state);
3353 typedef enum construct_type_kind_t {
3356 CONSTRUCT_REFERENCE,
3359 } construct_type_kind_t;
3361 typedef union construct_type_t construct_type_t;
3363 typedef struct construct_type_base_t {
3364 construct_type_kind_t kind;
3365 source_position_t pos;
3366 construct_type_t *next;
3367 } construct_type_base_t;
3369 typedef struct parsed_pointer_t {
3370 construct_type_base_t base;
3371 type_qualifiers_t type_qualifiers;
3372 variable_t *base_variable; /**< MS __based extension. */
3375 typedef struct parsed_reference_t {
3376 construct_type_base_t base;
3377 } parsed_reference_t;
3379 typedef struct construct_function_type_t {
3380 construct_type_base_t base;
3381 type_t *function_type;
3382 } construct_function_type_t;
3384 typedef struct parsed_array_t {
3385 construct_type_base_t base;
3386 type_qualifiers_t type_qualifiers;
3392 union construct_type_t {
3393 construct_type_kind_t kind;
3394 construct_type_base_t base;
3395 parsed_pointer_t pointer;
3396 parsed_reference_t reference;
3397 construct_function_type_t function;
3398 parsed_array_t array;
3401 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3403 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3404 memset(cons, 0, size);
3406 cons->base.pos = *HERE;
3411 static construct_type_t *parse_pointer_declarator(void)
3413 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3415 cons->pointer.type_qualifiers = parse_type_qualifiers();
3416 //cons->pointer.base_variable = base_variable;
3421 /* ISO/IEC 14882:1998(E) §8.3.2 */
3422 static construct_type_t *parse_reference_declarator(void)
3424 if (!(c_mode & _CXX))
3425 errorf(HERE, "references are only available for C++");
3427 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3434 static construct_type_t *parse_array_declarator(void)
3436 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3437 parsed_array_t *const array = &cons->array;
3440 add_anchor_token(']');
3442 bool is_static = next_if(T_static);
3444 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3447 is_static = next_if(T_static);
3449 array->type_qualifiers = type_qualifiers;
3450 array->is_static = is_static;
3452 expression_t *size = NULL;
3453 if (token.type == '*' && look_ahead(1)->type == ']') {
3454 array->is_variable = true;
3456 } else if (token.type != ']') {
3457 size = parse_assignment_expression();
3459 /* §6.7.5.2:1 Array size must have integer type */
3460 type_t *const orig_type = size->base.type;
3461 type_t *const type = skip_typeref(orig_type);
3462 if (!is_type_integer(type) && is_type_valid(type)) {
3463 errorf(&size->base.source_position,
3464 "array size '%E' must have integer type but has type '%T'",
3469 mark_vars_read(size, NULL);
3472 if (is_static && size == NULL)
3473 errorf(&array->base.pos, "static array parameters require a size");
3475 rem_anchor_token(']');
3476 expect(']', end_error);
3483 static construct_type_t *parse_function_declarator(scope_t *scope)
3485 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3487 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3488 function_type_t *ftype = &type->function;
3490 ftype->linkage = current_linkage;
3491 ftype->calling_convention = CC_DEFAULT;
3493 parse_parameters(ftype, scope);
3495 cons->function.function_type = type;
3500 typedef struct parse_declarator_env_t {
3501 bool may_be_abstract : 1;
3502 bool must_be_abstract : 1;
3503 decl_modifiers_t modifiers;
3505 source_position_t source_position;
3507 attribute_t *attributes;
3508 } parse_declarator_env_t;
3511 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3513 /* construct a single linked list of construct_type_t's which describe
3514 * how to construct the final declarator type */
3515 construct_type_t *first = NULL;
3516 construct_type_t **anchor = &first;
3518 env->attributes = parse_attributes(env->attributes);
3521 construct_type_t *type;
3522 //variable_t *based = NULL; /* MS __based extension */
3523 switch (token.type) {
3525 type = parse_reference_declarator();
3529 panic("based not supported anymore");
3534 type = parse_pointer_declarator();
3538 goto ptr_operator_end;
3542 anchor = &type->base.next;
3544 /* TODO: find out if this is correct */
3545 env->attributes = parse_attributes(env->attributes);
3549 construct_type_t *inner_types = NULL;
3551 switch (token.type) {
3553 if (env->must_be_abstract) {
3554 errorf(HERE, "no identifier expected in typename");
3556 env->symbol = token.symbol;
3557 env->source_position = token.source_position;
3563 /* Parenthesized declarator or function declarator? */
3564 token_t const *const la1 = look_ahead(1);
3565 switch (la1->type) {
3567 if (is_typedef_symbol(la1->symbol)) {
3569 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3570 * interpreted as ``function with no parameter specification'', rather
3571 * than redundant parentheses around the omitted identifier. */
3573 /* Function declarator. */
3574 if (!env->may_be_abstract) {
3575 errorf(HERE, "function declarator must have a name");
3582 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3583 /* Paranthesized declarator. */
3585 add_anchor_token(')');
3586 inner_types = parse_inner_declarator(env);
3587 if (inner_types != NULL) {
3588 /* All later declarators only modify the return type */
3589 env->must_be_abstract = true;
3591 rem_anchor_token(')');
3592 expect(')', end_error);
3600 if (env->may_be_abstract)
3602 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3607 construct_type_t **const p = anchor;
3610 construct_type_t *type;
3611 switch (token.type) {
3613 scope_t *scope = NULL;
3614 if (!env->must_be_abstract) {
3615 scope = &env->parameters;
3618 type = parse_function_declarator(scope);
3622 type = parse_array_declarator();
3625 goto declarator_finished;
3628 /* insert in the middle of the list (at p) */
3629 type->base.next = *p;
3632 anchor = &type->base.next;
3635 declarator_finished:
3636 /* append inner_types at the end of the list, we don't to set anchor anymore
3637 * as it's not needed anymore */
3638 *anchor = inner_types;
3645 static type_t *construct_declarator_type(construct_type_t *construct_list,
3648 construct_type_t *iter = construct_list;
3649 for (; iter != NULL; iter = iter->base.next) {
3650 source_position_t const* const pos = &iter->base.pos;
3651 switch (iter->kind) {
3652 case CONSTRUCT_INVALID:
3654 case CONSTRUCT_FUNCTION: {
3655 construct_function_type_t *function = &iter->function;
3656 type_t *function_type = function->function_type;
3658 function_type->function.return_type = type;
3660 type_t *skipped_return_type = skip_typeref(type);
3662 if (is_type_function(skipped_return_type)) {
3663 errorf(pos, "function returning function is not allowed");
3664 } else if (is_type_array(skipped_return_type)) {
3665 errorf(pos, "function returning array is not allowed");
3667 if (skipped_return_type->base.qualifiers != 0) {
3668 warningf(WARN_OTHER, pos, "type qualifiers in return type of function type are meaningless");
3672 /* The function type was constructed earlier. Freeing it here will
3673 * destroy other types. */
3674 type = typehash_insert(function_type);
3678 case CONSTRUCT_POINTER: {
3679 if (is_type_reference(skip_typeref(type)))
3680 errorf(pos, "cannot declare a pointer to reference");
3682 parsed_pointer_t *pointer = &iter->pointer;
3683 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3687 case CONSTRUCT_REFERENCE:
3688 if (is_type_reference(skip_typeref(type)))
3689 errorf(pos, "cannot declare a reference to reference");
3691 type = make_reference_type(type);
3694 case CONSTRUCT_ARRAY: {
3695 if (is_type_reference(skip_typeref(type)))
3696 errorf(pos, "cannot declare an array of references");
3698 parsed_array_t *array = &iter->array;
3699 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3701 expression_t *size_expression = array->size;
3702 if (size_expression != NULL) {
3704 = create_implicit_cast(size_expression, type_size_t);
3707 array_type->base.qualifiers = array->type_qualifiers;
3708 array_type->array.element_type = type;
3709 array_type->array.is_static = array->is_static;
3710 array_type->array.is_variable = array->is_variable;
3711 array_type->array.size_expression = size_expression;
3713 if (size_expression != NULL) {
3714 switch (is_constant_expression(size_expression)) {
3715 case EXPR_CLASS_CONSTANT: {
3716 long const size = fold_constant_to_int(size_expression);
3717 array_type->array.size = size;
3718 array_type->array.size_constant = true;
3719 /* §6.7.5.2:1 If the expression is a constant expression,
3720 * it shall have a value greater than zero. */
3722 errorf(&size_expression->base.source_position,
3723 "size of array must be greater than zero");
3724 } else if (size == 0 && !GNU_MODE) {
3725 errorf(&size_expression->base.source_position,
3726 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3731 case EXPR_CLASS_VARIABLE:
3732 array_type->array.is_vla = true;
3735 case EXPR_CLASS_ERROR:
3740 type_t *skipped_type = skip_typeref(type);
3742 if (is_type_incomplete(skipped_type)) {
3743 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3744 } else if (is_type_function(skipped_type)) {
3745 errorf(pos, "array of functions is not allowed");
3747 type = identify_new_type(array_type);
3751 internal_errorf(pos, "invalid type construction found");
3757 static type_t *automatic_type_conversion(type_t *orig_type);
3759 static type_t *semantic_parameter(const source_position_t *pos,
3761 const declaration_specifiers_t *specifiers,
3762 entity_t const *const param)
3764 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3765 * shall be adjusted to ``qualified pointer to type'',
3767 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3768 * type'' shall be adjusted to ``pointer to function
3769 * returning type'', as in 6.3.2.1. */
3770 type = automatic_type_conversion(type);
3772 if (specifiers->is_inline && is_type_valid(type)) {
3773 errorf(pos, "'%N' declared 'inline'", param);
3776 /* §6.9.1:6 The declarations in the declaration list shall contain
3777 * no storage-class specifier other than register and no
3778 * initializations. */
3779 if (specifiers->thread_local || (
3780 specifiers->storage_class != STORAGE_CLASS_NONE &&
3781 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3783 errorf(pos, "invalid storage class for '%N'", param);
3786 /* delay test for incomplete type, because we might have (void)
3787 * which is legal but incomplete... */
3792 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3793 declarator_flags_t flags)
3795 parse_declarator_env_t env;
3796 memset(&env, 0, sizeof(env));
3797 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3799 construct_type_t *construct_type = parse_inner_declarator(&env);
3801 construct_declarator_type(construct_type, specifiers->type);
3802 type_t *type = skip_typeref(orig_type);
3804 if (construct_type != NULL) {
3805 obstack_free(&temp_obst, construct_type);
3808 attribute_t *attributes = parse_attributes(env.attributes);
3809 /* append (shared) specifier attribute behind attributes of this
3811 attribute_t **anchor = &attributes;
3812 while (*anchor != NULL)
3813 anchor = &(*anchor)->next;
3814 *anchor = specifiers->attributes;
3817 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3818 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3819 entity->base.source_position = env.source_position;
3820 entity->typedefe.type = orig_type;
3822 if (anonymous_entity != NULL) {
3823 if (is_type_compound(type)) {
3824 assert(anonymous_entity->compound.alias == NULL);
3825 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3826 anonymous_entity->kind == ENTITY_UNION);
3827 anonymous_entity->compound.alias = entity;
3828 anonymous_entity = NULL;
3829 } else if (is_type_enum(type)) {
3830 assert(anonymous_entity->enume.alias == NULL);
3831 assert(anonymous_entity->kind == ENTITY_ENUM);
3832 anonymous_entity->enume.alias = entity;
3833 anonymous_entity = NULL;
3837 /* create a declaration type entity */
3838 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3839 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3841 if (env.symbol != NULL) {
3842 if (specifiers->is_inline && is_type_valid(type)) {
3843 errorf(&env.source_position,
3844 "compound member '%Y' declared 'inline'", env.symbol);
3847 if (specifiers->thread_local ||
3848 specifiers->storage_class != STORAGE_CLASS_NONE) {
3849 errorf(&env.source_position,
3850 "compound member '%Y' must have no storage class",
3854 } else if (flags & DECL_IS_PARAMETER) {
3855 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3856 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3857 } else if (is_type_function(type)) {
3858 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3859 entity->function.is_inline = specifiers->is_inline;
3860 entity->function.elf_visibility = default_visibility;
3861 entity->function.parameters = env.parameters;
3863 if (env.symbol != NULL) {
3864 /* this needs fixes for C++ */
3865 bool in_function_scope = current_function != NULL;
3867 if (specifiers->thread_local || (
3868 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3869 specifiers->storage_class != STORAGE_CLASS_NONE &&
3870 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3872 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3876 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3877 entity->variable.elf_visibility = default_visibility;
3878 entity->variable.thread_local = specifiers->thread_local;
3880 if (env.symbol != NULL) {
3881 if (specifiers->is_inline && is_type_valid(type)) {
3882 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3885 bool invalid_storage_class = false;
3886 if (current_scope == file_scope) {
3887 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3888 specifiers->storage_class != STORAGE_CLASS_NONE &&
3889 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3890 invalid_storage_class = true;
3893 if (specifiers->thread_local &&
3894 specifiers->storage_class == STORAGE_CLASS_NONE) {
3895 invalid_storage_class = true;
3898 if (invalid_storage_class) {
3899 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3904 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3905 entity->declaration.type = orig_type;
3906 entity->declaration.alignment = get_type_alignment(orig_type);
3907 entity->declaration.modifiers = env.modifiers;
3908 entity->declaration.attributes = attributes;
3910 storage_class_t storage_class = specifiers->storage_class;
3911 entity->declaration.declared_storage_class = storage_class;
3913 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3914 storage_class = STORAGE_CLASS_AUTO;
3915 entity->declaration.storage_class = storage_class;
3918 if (attributes != NULL) {
3919 handle_entity_attributes(attributes, entity);
3925 static type_t *parse_abstract_declarator(type_t *base_type)
3927 parse_declarator_env_t env;
3928 memset(&env, 0, sizeof(env));
3929 env.may_be_abstract = true;
3930 env.must_be_abstract = true;
3932 construct_type_t *construct_type = parse_inner_declarator(&env);
3934 type_t *result = construct_declarator_type(construct_type, base_type);
3935 if (construct_type != NULL) {
3936 obstack_free(&temp_obst, construct_type);
3938 result = handle_type_attributes(env.attributes, result);
3944 * Check if the declaration of main is suspicious. main should be a
3945 * function with external linkage, returning int, taking either zero
3946 * arguments, two, or three arguments of appropriate types, ie.
3948 * int main([ int argc, char **argv [, char **env ] ]).
3950 * @param decl the declaration to check
3951 * @param type the function type of the declaration
3953 static void check_main(const entity_t *entity)
3955 const source_position_t *pos = &entity->base.source_position;
3956 if (entity->kind != ENTITY_FUNCTION) {
3957 warningf(WARN_MAIN, pos, "'main' is not a function");
3961 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3962 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3965 type_t *type = skip_typeref(entity->declaration.type);
3966 assert(is_type_function(type));
3968 function_type_t const *const func_type = &type->function;
3969 type_t *const ret_type = func_type->return_type;
3970 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3971 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3973 const function_parameter_t *parm = func_type->parameters;
3975 type_t *const first_type = skip_typeref(parm->type);
3976 type_t *const first_type_unqual = get_unqualified_type(first_type);
3977 if (!types_compatible(first_type_unqual, type_int)) {
3978 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3982 type_t *const second_type = skip_typeref(parm->type);
3983 type_t *const second_type_unqual
3984 = get_unqualified_type(second_type);
3985 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3986 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3990 type_t *const third_type = skip_typeref(parm->type);
3991 type_t *const third_type_unqual
3992 = get_unqualified_type(third_type);
3993 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3994 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3998 goto warn_arg_count;
4002 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
4008 * Check if a symbol is the equal to "main".
4010 static bool is_sym_main(const symbol_t *const sym)
4012 return strcmp(sym->string, "main") == 0;
4015 static void error_redefined_as_different_kind(const source_position_t *pos,
4016 const entity_t *old, entity_kind_t new_kind)
4018 char const *const what = get_entity_kind_name(new_kind);
4019 source_position_t const *const ppos = &old->base.source_position;
4020 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4023 static bool is_entity_valid(entity_t *const ent)
4025 if (is_declaration(ent)) {
4026 return is_type_valid(skip_typeref(ent->declaration.type));
4027 } else if (ent->kind == ENTITY_TYPEDEF) {
4028 return is_type_valid(skip_typeref(ent->typedefe.type));
4033 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4035 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4036 if (attributes_equal(tattr, attr))
4043 * test wether new_list contains any attributes not included in old_list
4045 static bool has_new_attributes(const attribute_t *old_list,
4046 const attribute_t *new_list)
4048 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4049 if (!contains_attribute(old_list, attr))
4056 * Merge in attributes from an attribute list (probably from a previous
4057 * declaration with the same name). Warning: destroys the old structure
4058 * of the attribute list - don't reuse attributes after this call.
4060 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4063 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4065 if (contains_attribute(decl->attributes, attr))
4068 /* move attribute to new declarations attributes list */
4069 attr->next = decl->attributes;
4070 decl->attributes = attr;
4075 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4076 * for various problems that occur for multiple definitions
4078 entity_t *record_entity(entity_t *entity, const bool is_definition)
4080 const symbol_t *const symbol = entity->base.symbol;
4081 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4082 const source_position_t *pos = &entity->base.source_position;
4084 /* can happen in error cases */
4088 entity_t *const previous_entity = get_entity(symbol, namespc);
4089 /* pushing the same entity twice will break the stack structure */
4090 assert(previous_entity != entity);
4092 if (entity->kind == ENTITY_FUNCTION) {
4093 type_t *const orig_type = entity->declaration.type;
4094 type_t *const type = skip_typeref(orig_type);
4096 assert(is_type_function(type));
4097 if (type->function.unspecified_parameters &&
4098 previous_entity == NULL &&
4099 !entity->declaration.implicit) {
4100 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4103 if (current_scope == file_scope && is_sym_main(symbol)) {
4108 if (is_declaration(entity) &&
4109 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4110 current_scope != file_scope &&
4111 !entity->declaration.implicit) {
4112 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4115 if (previous_entity != NULL) {
4116 source_position_t const *const ppos = &previous_entity->base.source_position;
4118 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4119 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4120 assert(previous_entity->kind == ENTITY_PARAMETER);
4121 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4125 if (previous_entity->base.parent_scope == current_scope) {
4126 if (previous_entity->kind != entity->kind) {
4127 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4128 error_redefined_as_different_kind(pos, previous_entity,
4133 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4134 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4137 if (previous_entity->kind == ENTITY_TYPEDEF) {
4138 /* TODO: C++ allows this for exactly the same type */
4139 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4143 /* at this point we should have only VARIABLES or FUNCTIONS */
4144 assert(is_declaration(previous_entity) && is_declaration(entity));
4146 declaration_t *const prev_decl = &previous_entity->declaration;
4147 declaration_t *const decl = &entity->declaration;
4149 /* can happen for K&R style declarations */
4150 if (prev_decl->type == NULL &&
4151 previous_entity->kind == ENTITY_PARAMETER &&
4152 entity->kind == ENTITY_PARAMETER) {
4153 prev_decl->type = decl->type;
4154 prev_decl->storage_class = decl->storage_class;
4155 prev_decl->declared_storage_class = decl->declared_storage_class;
4156 prev_decl->modifiers = decl->modifiers;
4157 return previous_entity;
4160 type_t *const type = skip_typeref(decl->type);
4161 type_t *const prev_type = skip_typeref(prev_decl->type);
4163 if (!types_compatible(type, prev_type)) {
4164 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4166 unsigned old_storage_class = prev_decl->storage_class;
4168 if (is_definition &&
4170 !(prev_decl->modifiers & DM_USED) &&
4171 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4172 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4175 storage_class_t new_storage_class = decl->storage_class;
4177 /* pretend no storage class means extern for function
4178 * declarations (except if the previous declaration is neither
4179 * none nor extern) */
4180 if (entity->kind == ENTITY_FUNCTION) {
4181 /* the previous declaration could have unspecified parameters or
4182 * be a typedef, so use the new type */
4183 if (prev_type->function.unspecified_parameters || is_definition)
4184 prev_decl->type = type;
4186 switch (old_storage_class) {
4187 case STORAGE_CLASS_NONE:
4188 old_storage_class = STORAGE_CLASS_EXTERN;
4191 case STORAGE_CLASS_EXTERN:
4192 if (is_definition) {
4193 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4194 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4196 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4197 new_storage_class = STORAGE_CLASS_EXTERN;
4204 } else if (is_type_incomplete(prev_type)) {
4205 prev_decl->type = type;
4208 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4209 new_storage_class == STORAGE_CLASS_EXTERN) {
4211 warn_redundant_declaration: ;
4213 = has_new_attributes(prev_decl->attributes,
4215 if (has_new_attrs) {
4216 merge_in_attributes(decl, prev_decl->attributes);
4217 } else if (!is_definition &&
4218 is_type_valid(prev_type) &&
4219 strcmp(ppos->input_name, "<builtin>") != 0) {
4220 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4222 } else if (current_function == NULL) {
4223 if (old_storage_class != STORAGE_CLASS_STATIC &&
4224 new_storage_class == STORAGE_CLASS_STATIC) {
4225 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4226 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4227 prev_decl->storage_class = STORAGE_CLASS_NONE;
4228 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4230 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4232 goto error_redeclaration;
4233 goto warn_redundant_declaration;
4235 } else if (is_type_valid(prev_type)) {
4236 if (old_storage_class == new_storage_class) {
4237 error_redeclaration:
4238 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4240 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4245 prev_decl->modifiers |= decl->modifiers;
4246 if (entity->kind == ENTITY_FUNCTION) {
4247 previous_entity->function.is_inline |= entity->function.is_inline;
4249 return previous_entity;
4253 if (is_warn_on(why = WARN_SHADOW) ||
4254 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4255 char const *const what = get_entity_kind_name(previous_entity->kind);
4256 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4260 if (entity->kind == ENTITY_FUNCTION) {
4261 if (is_definition &&
4262 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4263 !is_sym_main(symbol)) {
4264 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4265 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4267 goto warn_missing_declaration;
4270 } else if (entity->kind == ENTITY_VARIABLE) {
4271 if (current_scope == file_scope &&
4272 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4273 !entity->declaration.implicit) {
4274 warn_missing_declaration:
4275 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4280 assert(entity->base.parent_scope == NULL);
4281 assert(current_scope != NULL);
4283 entity->base.parent_scope = current_scope;
4284 environment_push(entity);
4285 append_entity(current_scope, entity);
4290 static void parser_error_multiple_definition(entity_t *entity,
4291 const source_position_t *source_position)
4293 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4294 entity->base.symbol, &entity->base.source_position);
4297 static bool is_declaration_specifier(const token_t *token)
4299 switch (token->type) {
4303 return is_typedef_symbol(token->symbol);
4310 static void parse_init_declarator_rest(entity_t *entity)
4312 type_t *orig_type = type_error_type;
4314 if (entity->base.kind == ENTITY_TYPEDEF) {
4315 source_position_t const *const pos = &entity->base.source_position;
4316 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4318 assert(is_declaration(entity));
4319 orig_type = entity->declaration.type;
4322 type_t *type = skip_typeref(orig_type);
4324 if (entity->kind == ENTITY_VARIABLE
4325 && entity->variable.initializer != NULL) {
4326 parser_error_multiple_definition(entity, HERE);
4330 declaration_t *const declaration = &entity->declaration;
4331 bool must_be_constant = false;
4332 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4333 entity->base.parent_scope == file_scope) {
4334 must_be_constant = true;
4337 if (is_type_function(type)) {
4338 source_position_t const *const pos = &entity->base.source_position;
4339 errorf(pos, "'%N' is initialized like a variable", entity);
4340 orig_type = type_error_type;
4343 parse_initializer_env_t env;
4344 env.type = orig_type;
4345 env.must_be_constant = must_be_constant;
4346 env.entity = entity;
4348 initializer_t *initializer = parse_initializer(&env);
4350 if (entity->kind == ENTITY_VARIABLE) {
4351 /* §6.7.5:22 array initializers for arrays with unknown size
4352 * determine the array type size */
4353 declaration->type = env.type;
4354 entity->variable.initializer = initializer;
4358 /* parse rest of a declaration without any declarator */
4359 static void parse_anonymous_declaration_rest(
4360 const declaration_specifiers_t *specifiers)
4363 anonymous_entity = NULL;
4365 source_position_t const *const pos = &specifiers->source_position;
4366 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4367 specifiers->thread_local) {
4368 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4371 type_t *type = specifiers->type;
4372 switch (type->kind) {
4373 case TYPE_COMPOUND_STRUCT:
4374 case TYPE_COMPOUND_UNION: {
4375 if (type->compound.compound->base.symbol == NULL) {
4376 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4385 warningf(WARN_OTHER, pos, "empty declaration");
4390 static void check_variable_type_complete(entity_t *ent)
4392 if (ent->kind != ENTITY_VARIABLE)
4395 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4396 * type for the object shall be complete [...] */
4397 declaration_t *decl = &ent->declaration;
4398 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4399 decl->storage_class == STORAGE_CLASS_STATIC)
4402 type_t *const type = skip_typeref(decl->type);
4403 if (!is_type_incomplete(type))
4406 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4407 * are given length one. */
4408 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4409 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4413 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4417 static void parse_declaration_rest(entity_t *ndeclaration,
4418 const declaration_specifiers_t *specifiers,
4419 parsed_declaration_func finished_declaration,
4420 declarator_flags_t flags)
4422 add_anchor_token(';');
4423 add_anchor_token(',');
4425 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4427 if (token.type == '=') {
4428 parse_init_declarator_rest(entity);
4429 } else if (entity->kind == ENTITY_VARIABLE) {
4430 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4431 * [...] where the extern specifier is explicitly used. */
4432 declaration_t *decl = &entity->declaration;
4433 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4434 type_t *type = decl->type;
4435 if (is_type_reference(skip_typeref(type))) {
4436 source_position_t const *const pos = &entity->base.source_position;
4437 errorf(pos, "reference '%#N' must be initialized", entity);
4442 check_variable_type_complete(entity);
4447 add_anchor_token('=');
4448 ndeclaration = parse_declarator(specifiers, flags);
4449 rem_anchor_token('=');
4451 expect(';', end_error);
4454 anonymous_entity = NULL;
4455 rem_anchor_token(';');
4456 rem_anchor_token(',');
4459 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4461 symbol_t *symbol = entity->base.symbol;
4465 assert(entity->base.namespc == NAMESPACE_NORMAL);
4466 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4467 if (previous_entity == NULL
4468 || previous_entity->base.parent_scope != current_scope) {
4469 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4474 if (is_definition) {
4475 errorf(HERE, "'%N' is initialised", entity);
4478 return record_entity(entity, false);
4481 static void parse_declaration(parsed_declaration_func finished_declaration,
4482 declarator_flags_t flags)
4484 add_anchor_token(';');
4485 declaration_specifiers_t specifiers;
4486 parse_declaration_specifiers(&specifiers);
4487 rem_anchor_token(';');
4489 if (token.type == ';') {
4490 parse_anonymous_declaration_rest(&specifiers);
4492 entity_t *entity = parse_declarator(&specifiers, flags);
4493 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4498 static type_t *get_default_promoted_type(type_t *orig_type)
4500 type_t *result = orig_type;
4502 type_t *type = skip_typeref(orig_type);
4503 if (is_type_integer(type)) {
4504 result = promote_integer(type);
4505 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4506 result = type_double;
4512 static void parse_kr_declaration_list(entity_t *entity)
4514 if (entity->kind != ENTITY_FUNCTION)
4517 type_t *type = skip_typeref(entity->declaration.type);
4518 assert(is_type_function(type));
4519 if (!type->function.kr_style_parameters)
4522 add_anchor_token('{');
4524 PUSH_SCOPE(&entity->function.parameters);
4526 entity_t *parameter = entity->function.parameters.entities;
4527 for ( ; parameter != NULL; parameter = parameter->base.next) {
4528 assert(parameter->base.parent_scope == NULL);
4529 parameter->base.parent_scope = current_scope;
4530 environment_push(parameter);
4533 /* parse declaration list */
4535 switch (token.type) {
4537 /* This covers symbols, which are no type, too, and results in
4538 * better error messages. The typical cases are misspelled type
4539 * names and missing includes. */
4541 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4551 /* update function type */
4552 type_t *new_type = duplicate_type(type);
4554 function_parameter_t *parameters = NULL;
4555 function_parameter_t **anchor = ¶meters;
4557 /* did we have an earlier prototype? */
4558 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4559 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4562 function_parameter_t *proto_parameter = NULL;
4563 if (proto_type != NULL) {
4564 type_t *proto_type_type = proto_type->declaration.type;
4565 proto_parameter = proto_type_type->function.parameters;
4566 /* If a K&R function definition has a variadic prototype earlier, then
4567 * make the function definition variadic, too. This should conform to
4568 * §6.7.5.3:15 and §6.9.1:8. */
4569 new_type->function.variadic = proto_type_type->function.variadic;
4571 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4573 new_type->function.unspecified_parameters = true;
4576 bool need_incompatible_warning = false;
4577 parameter = entity->function.parameters.entities;
4578 for (; parameter != NULL; parameter = parameter->base.next,
4580 proto_parameter == NULL ? NULL : proto_parameter->next) {
4581 if (parameter->kind != ENTITY_PARAMETER)
4584 type_t *parameter_type = parameter->declaration.type;
4585 if (parameter_type == NULL) {
4586 source_position_t const* const pos = ¶meter->base.source_position;
4588 errorf(pos, "no type specified for function '%N'", parameter);
4589 parameter_type = type_error_type;
4591 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4592 parameter_type = type_int;
4594 parameter->declaration.type = parameter_type;
4597 semantic_parameter_incomplete(parameter);
4599 /* we need the default promoted types for the function type */
4600 type_t *not_promoted = parameter_type;
4601 parameter_type = get_default_promoted_type(parameter_type);
4603 /* gcc special: if the type of the prototype matches the unpromoted
4604 * type don't promote */
4605 if (!strict_mode && proto_parameter != NULL) {
4606 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4607 type_t *promo_skip = skip_typeref(parameter_type);
4608 type_t *param_skip = skip_typeref(not_promoted);
4609 if (!types_compatible(proto_p_type, promo_skip)
4610 && types_compatible(proto_p_type, param_skip)) {
4612 need_incompatible_warning = true;
4613 parameter_type = not_promoted;
4616 function_parameter_t *const function_parameter
4617 = allocate_parameter(parameter_type);
4619 *anchor = function_parameter;
4620 anchor = &function_parameter->next;
4623 new_type->function.parameters = parameters;
4624 new_type = identify_new_type(new_type);
4626 if (need_incompatible_warning) {
4627 symbol_t const *const sym = entity->base.symbol;
4628 source_position_t const *const pos = &entity->base.source_position;
4629 source_position_t const *const ppos = &proto_type->base.source_position;
4630 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4632 entity->declaration.type = new_type;
4634 rem_anchor_token('{');
4637 static bool first_err = true;
4640 * When called with first_err set, prints the name of the current function,
4643 static void print_in_function(void)
4647 char const *const file = current_function->base.base.source_position.input_name;
4648 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4653 * Check if all labels are defined in the current function.
4654 * Check if all labels are used in the current function.
4656 static void check_labels(void)
4658 for (const goto_statement_t *goto_statement = goto_first;
4659 goto_statement != NULL;
4660 goto_statement = goto_statement->next) {
4661 /* skip computed gotos */
4662 if (goto_statement->expression != NULL)
4665 label_t *label = goto_statement->label;
4666 if (label->base.source_position.input_name == NULL) {
4667 print_in_function();
4668 source_position_t const *const pos = &goto_statement->base.source_position;
4669 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4673 if (is_warn_on(WARN_UNUSED_LABEL)) {
4674 for (const label_statement_t *label_statement = label_first;
4675 label_statement != NULL;
4676 label_statement = label_statement->next) {
4677 label_t *label = label_statement->label;
4679 if (! label->used) {
4680 print_in_function();
4681 source_position_t const *const pos = &label_statement->base.source_position;
4682 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4688 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4690 entity_t const *const end = last != NULL ? last->base.next : NULL;
4691 for (; entity != end; entity = entity->base.next) {
4692 if (!is_declaration(entity))
4695 declaration_t *declaration = &entity->declaration;
4696 if (declaration->implicit)
4699 if (!declaration->used) {
4700 print_in_function();
4701 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4702 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4703 print_in_function();
4704 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4709 static void check_unused_variables(statement_t *const stmt, void *const env)
4713 switch (stmt->kind) {
4714 case STATEMENT_DECLARATION: {
4715 declaration_statement_t const *const decls = &stmt->declaration;
4716 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4721 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4730 * Check declarations of current_function for unused entities.
4732 static void check_declarations(void)
4734 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4735 const scope_t *scope = ¤t_function->parameters;
4737 /* do not issue unused warnings for main */
4738 if (!is_sym_main(current_function->base.base.symbol)) {
4739 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4742 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4743 walk_statements(current_function->statement, check_unused_variables,
4748 static int determine_truth(expression_t const* const cond)
4751 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4752 fold_constant_to_bool(cond) ? 1 :
4756 static void check_reachable(statement_t *);
4757 static bool reaches_end;
4759 static bool expression_returns(expression_t const *const expr)
4761 switch (expr->kind) {
4763 expression_t const *const func = expr->call.function;
4764 if (func->kind == EXPR_REFERENCE) {
4765 entity_t *entity = func->reference.entity;
4766 if (entity->kind == ENTITY_FUNCTION
4767 && entity->declaration.modifiers & DM_NORETURN)
4771 if (!expression_returns(func))
4774 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4775 if (!expression_returns(arg->expression))
4782 case EXPR_REFERENCE:
4783 case EXPR_REFERENCE_ENUM_VALUE:
4785 case EXPR_STRING_LITERAL:
4786 case EXPR_WIDE_STRING_LITERAL:
4787 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4788 case EXPR_LABEL_ADDRESS:
4789 case EXPR_CLASSIFY_TYPE:
4790 case EXPR_SIZEOF: // TODO handle obscure VLA case
4793 case EXPR_BUILTIN_CONSTANT_P:
4794 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4799 case EXPR_STATEMENT: {
4800 bool old_reaches_end = reaches_end;
4801 reaches_end = false;
4802 check_reachable(expr->statement.statement);
4803 bool returns = reaches_end;
4804 reaches_end = old_reaches_end;
4808 case EXPR_CONDITIONAL:
4809 // TODO handle constant expression
4811 if (!expression_returns(expr->conditional.condition))
4814 if (expr->conditional.true_expression != NULL
4815 && expression_returns(expr->conditional.true_expression))
4818 return expression_returns(expr->conditional.false_expression);
4821 return expression_returns(expr->select.compound);
4823 case EXPR_ARRAY_ACCESS:
4825 expression_returns(expr->array_access.array_ref) &&
4826 expression_returns(expr->array_access.index);
4829 return expression_returns(expr->va_starte.ap);
4832 return expression_returns(expr->va_arge.ap);
4835 return expression_returns(expr->va_copye.src);
4837 EXPR_UNARY_CASES_MANDATORY
4838 return expression_returns(expr->unary.value);
4840 case EXPR_UNARY_THROW:
4844 // TODO handle constant lhs of && and ||
4846 expression_returns(expr->binary.left) &&
4847 expression_returns(expr->binary.right);
4853 panic("unhandled expression");
4856 static bool initializer_returns(initializer_t const *const init)
4858 switch (init->kind) {
4859 case INITIALIZER_VALUE:
4860 return expression_returns(init->value.value);
4862 case INITIALIZER_LIST: {
4863 initializer_t * const* i = init->list.initializers;
4864 initializer_t * const* const end = i + init->list.len;
4865 bool returns = true;
4866 for (; i != end; ++i) {
4867 if (!initializer_returns(*i))
4873 case INITIALIZER_STRING:
4874 case INITIALIZER_WIDE_STRING:
4875 case INITIALIZER_DESIGNATOR: // designators have no payload
4878 panic("unhandled initializer");
4881 static bool noreturn_candidate;
4883 static void check_reachable(statement_t *const stmt)
4885 if (stmt->base.reachable)
4887 if (stmt->kind != STATEMENT_DO_WHILE)
4888 stmt->base.reachable = true;
4890 statement_t *last = stmt;
4892 switch (stmt->kind) {
4893 case STATEMENT_INVALID:
4894 case STATEMENT_EMPTY:
4896 next = stmt->base.next;
4899 case STATEMENT_DECLARATION: {
4900 declaration_statement_t const *const decl = &stmt->declaration;
4901 entity_t const * ent = decl->declarations_begin;
4902 entity_t const *const last_decl = decl->declarations_end;
4904 for (;; ent = ent->base.next) {
4905 if (ent->kind == ENTITY_VARIABLE &&
4906 ent->variable.initializer != NULL &&
4907 !initializer_returns(ent->variable.initializer)) {
4910 if (ent == last_decl)
4914 next = stmt->base.next;
4918 case STATEMENT_COMPOUND:
4919 next = stmt->compound.statements;
4921 next = stmt->base.next;
4924 case STATEMENT_RETURN: {
4925 expression_t const *const val = stmt->returns.value;
4926 if (val == NULL || expression_returns(val))
4927 noreturn_candidate = false;
4931 case STATEMENT_IF: {
4932 if_statement_t const *const ifs = &stmt->ifs;
4933 expression_t const *const cond = ifs->condition;
4935 if (!expression_returns(cond))
4938 int const val = determine_truth(cond);
4941 check_reachable(ifs->true_statement);
4946 if (ifs->false_statement != NULL) {
4947 check_reachable(ifs->false_statement);
4951 next = stmt->base.next;
4955 case STATEMENT_SWITCH: {
4956 switch_statement_t const *const switchs = &stmt->switchs;
4957 expression_t const *const expr = switchs->expression;
4959 if (!expression_returns(expr))
4962 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4963 long const val = fold_constant_to_int(expr);
4964 case_label_statement_t * defaults = NULL;
4965 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4966 if (i->expression == NULL) {
4971 if (i->first_case <= val && val <= i->last_case) {
4972 check_reachable((statement_t*)i);
4977 if (defaults != NULL) {
4978 check_reachable((statement_t*)defaults);
4982 bool has_default = false;
4983 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4984 if (i->expression == NULL)
4987 check_reachable((statement_t*)i);
4994 next = stmt->base.next;
4998 case STATEMENT_EXPRESSION: {
4999 /* Check for noreturn function call */
5000 expression_t const *const expr = stmt->expression.expression;
5001 if (!expression_returns(expr))
5004 next = stmt->base.next;
5008 case STATEMENT_CONTINUE:
5009 for (statement_t *parent = stmt;;) {
5010 parent = parent->base.parent;
5011 if (parent == NULL) /* continue not within loop */
5015 switch (parent->kind) {
5016 case STATEMENT_WHILE: goto continue_while;
5017 case STATEMENT_DO_WHILE: goto continue_do_while;
5018 case STATEMENT_FOR: goto continue_for;
5024 case STATEMENT_BREAK:
5025 for (statement_t *parent = stmt;;) {
5026 parent = parent->base.parent;
5027 if (parent == NULL) /* break not within loop/switch */
5030 switch (parent->kind) {
5031 case STATEMENT_SWITCH:
5032 case STATEMENT_WHILE:
5033 case STATEMENT_DO_WHILE:
5036 next = parent->base.next;
5037 goto found_break_parent;
5045 case STATEMENT_GOTO:
5046 if (stmt->gotos.expression) {
5047 if (!expression_returns(stmt->gotos.expression))
5050 statement_t *parent = stmt->base.parent;
5051 if (parent == NULL) /* top level goto */
5055 next = stmt->gotos.label->statement;
5056 if (next == NULL) /* missing label */
5061 case STATEMENT_LABEL:
5062 next = stmt->label.statement;
5065 case STATEMENT_CASE_LABEL:
5066 next = stmt->case_label.statement;
5069 case STATEMENT_WHILE: {
5070 while_statement_t const *const whiles = &stmt->whiles;
5071 expression_t const *const cond = whiles->condition;
5073 if (!expression_returns(cond))
5076 int const val = determine_truth(cond);
5079 check_reachable(whiles->body);
5084 next = stmt->base.next;
5088 case STATEMENT_DO_WHILE:
5089 next = stmt->do_while.body;
5092 case STATEMENT_FOR: {
5093 for_statement_t *const fors = &stmt->fors;
5095 if (fors->condition_reachable)
5097 fors->condition_reachable = true;
5099 expression_t const *const cond = fors->condition;
5104 } else if (expression_returns(cond)) {
5105 val = determine_truth(cond);
5111 check_reachable(fors->body);
5116 next = stmt->base.next;
5120 case STATEMENT_MS_TRY: {
5121 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5122 check_reachable(ms_try->try_statement);
5123 next = ms_try->final_statement;
5127 case STATEMENT_LEAVE: {
5128 statement_t *parent = stmt;
5130 parent = parent->base.parent;
5131 if (parent == NULL) /* __leave not within __try */
5134 if (parent->kind == STATEMENT_MS_TRY) {
5136 next = parent->ms_try.final_statement;
5144 panic("invalid statement kind");
5147 while (next == NULL) {
5148 next = last->base.parent;
5150 noreturn_candidate = false;
5152 type_t *const type = skip_typeref(current_function->base.type);
5153 assert(is_type_function(type));
5154 type_t *const ret = skip_typeref(type->function.return_type);
5155 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5156 is_type_valid(ret) &&
5157 !is_sym_main(current_function->base.base.symbol)) {
5158 source_position_t const *const pos = &stmt->base.source_position;
5159 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5164 switch (next->kind) {
5165 case STATEMENT_INVALID:
5166 case STATEMENT_EMPTY:
5167 case STATEMENT_DECLARATION:
5168 case STATEMENT_EXPRESSION:
5170 case STATEMENT_RETURN:
5171 case STATEMENT_CONTINUE:
5172 case STATEMENT_BREAK:
5173 case STATEMENT_GOTO:
5174 case STATEMENT_LEAVE:
5175 panic("invalid control flow in function");
5177 case STATEMENT_COMPOUND:
5178 if (next->compound.stmt_expr) {
5184 case STATEMENT_SWITCH:
5185 case STATEMENT_LABEL:
5186 case STATEMENT_CASE_LABEL:
5188 next = next->base.next;
5191 case STATEMENT_WHILE: {
5193 if (next->base.reachable)
5195 next->base.reachable = true;
5197 while_statement_t const *const whiles = &next->whiles;
5198 expression_t const *const cond = whiles->condition;
5200 if (!expression_returns(cond))
5203 int const val = determine_truth(cond);
5206 check_reachable(whiles->body);
5212 next = next->base.next;
5216 case STATEMENT_DO_WHILE: {
5218 if (next->base.reachable)
5220 next->base.reachable = true;
5222 do_while_statement_t const *const dw = &next->do_while;
5223 expression_t const *const cond = dw->condition;
5225 if (!expression_returns(cond))
5228 int const val = determine_truth(cond);
5231 check_reachable(dw->body);
5237 next = next->base.next;
5241 case STATEMENT_FOR: {
5243 for_statement_t *const fors = &next->fors;
5245 fors->step_reachable = true;
5247 if (fors->condition_reachable)
5249 fors->condition_reachable = true;
5251 expression_t const *const cond = fors->condition;
5256 } else if (expression_returns(cond)) {
5257 val = determine_truth(cond);
5263 check_reachable(fors->body);
5269 next = next->base.next;
5273 case STATEMENT_MS_TRY:
5275 next = next->ms_try.final_statement;
5280 check_reachable(next);
5283 static void check_unreachable(statement_t* const stmt, void *const env)
5287 switch (stmt->kind) {
5288 case STATEMENT_DO_WHILE:
5289 if (!stmt->base.reachable) {
5290 expression_t const *const cond = stmt->do_while.condition;
5291 if (determine_truth(cond) >= 0) {
5292 source_position_t const *const pos = &cond->base.source_position;
5293 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5298 case STATEMENT_FOR: {
5299 for_statement_t const* const fors = &stmt->fors;
5301 // if init and step are unreachable, cond is unreachable, too
5302 if (!stmt->base.reachable && !fors->step_reachable) {
5303 goto warn_unreachable;
5305 if (!stmt->base.reachable && fors->initialisation != NULL) {
5306 source_position_t const *const pos = &fors->initialisation->base.source_position;
5307 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5310 if (!fors->condition_reachable && fors->condition != NULL) {
5311 source_position_t const *const pos = &fors->condition->base.source_position;
5312 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5315 if (!fors->step_reachable && fors->step != NULL) {
5316 source_position_t const *const pos = &fors->step->base.source_position;
5317 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5323 case STATEMENT_COMPOUND:
5324 if (stmt->compound.statements != NULL)
5326 goto warn_unreachable;
5328 case STATEMENT_DECLARATION: {
5329 /* Only warn if there is at least one declarator with an initializer.
5330 * This typically occurs in switch statements. */
5331 declaration_statement_t const *const decl = &stmt->declaration;
5332 entity_t const * ent = decl->declarations_begin;
5333 entity_t const *const last = decl->declarations_end;
5335 for (;; ent = ent->base.next) {
5336 if (ent->kind == ENTITY_VARIABLE &&
5337 ent->variable.initializer != NULL) {
5338 goto warn_unreachable;
5348 if (!stmt->base.reachable) {
5349 source_position_t const *const pos = &stmt->base.source_position;
5350 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5356 static void parse_external_declaration(void)
5358 /* function-definitions and declarations both start with declaration
5360 add_anchor_token(';');
5361 declaration_specifiers_t specifiers;
5362 parse_declaration_specifiers(&specifiers);
5363 rem_anchor_token(';');
5365 /* must be a declaration */
5366 if (token.type == ';') {
5367 parse_anonymous_declaration_rest(&specifiers);
5371 add_anchor_token(',');
5372 add_anchor_token('=');
5373 add_anchor_token(';');
5374 add_anchor_token('{');
5376 /* declarator is common to both function-definitions and declarations */
5377 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5379 rem_anchor_token('{');
5380 rem_anchor_token(';');
5381 rem_anchor_token('=');
5382 rem_anchor_token(',');
5384 /* must be a declaration */
5385 switch (token.type) {
5389 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5394 /* must be a function definition */
5395 parse_kr_declaration_list(ndeclaration);
5397 if (token.type != '{') {
5398 parse_error_expected("while parsing function definition", '{', NULL);
5399 eat_until_matching_token(';');
5403 assert(is_declaration(ndeclaration));
5404 type_t *const orig_type = ndeclaration->declaration.type;
5405 type_t * type = skip_typeref(orig_type);
5407 if (!is_type_function(type)) {
5408 if (is_type_valid(type)) {
5409 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5415 source_position_t const *const pos = &ndeclaration->base.source_position;
5416 if (is_typeref(orig_type)) {
5418 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5421 if (is_type_compound(skip_typeref(type->function.return_type))) {
5422 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5424 if (type->function.unspecified_parameters) {
5425 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5427 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5430 /* §6.7.5.3:14 a function definition with () means no
5431 * parameters (and not unspecified parameters) */
5432 if (type->function.unspecified_parameters &&
5433 type->function.parameters == NULL) {
5434 type_t *copy = duplicate_type(type);
5435 copy->function.unspecified_parameters = false;
5436 type = identify_new_type(copy);
5438 ndeclaration->declaration.type = type;
5441 entity_t *const entity = record_entity(ndeclaration, true);
5442 assert(entity->kind == ENTITY_FUNCTION);
5443 assert(ndeclaration->kind == ENTITY_FUNCTION);
5445 function_t *const function = &entity->function;
5446 if (ndeclaration != entity) {
5447 function->parameters = ndeclaration->function.parameters;
5449 assert(is_declaration(entity));
5450 type = skip_typeref(entity->declaration.type);
5452 PUSH_SCOPE(&function->parameters);
5454 entity_t *parameter = function->parameters.entities;
5455 for (; parameter != NULL; parameter = parameter->base.next) {
5456 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5457 parameter->base.parent_scope = current_scope;
5459 assert(parameter->base.parent_scope == NULL
5460 || parameter->base.parent_scope == current_scope);
5461 parameter->base.parent_scope = current_scope;
5462 if (parameter->base.symbol == NULL) {
5463 errorf(¶meter->base.source_position, "parameter name omitted");
5466 environment_push(parameter);
5469 if (function->statement != NULL) {
5470 parser_error_multiple_definition(entity, HERE);
5473 /* parse function body */
5474 int label_stack_top = label_top();
5475 function_t *old_current_function = current_function;
5476 entity_t *old_current_entity = current_entity;
5477 current_function = function;
5478 current_entity = entity;
5482 goto_anchor = &goto_first;
5484 label_anchor = &label_first;
5486 statement_t *const body = parse_compound_statement(false);
5487 function->statement = body;
5490 check_declarations();
5491 if (is_warn_on(WARN_RETURN_TYPE) ||
5492 is_warn_on(WARN_UNREACHABLE_CODE) ||
5493 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5494 noreturn_candidate = true;
5495 check_reachable(body);
5496 if (is_warn_on(WARN_UNREACHABLE_CODE))
5497 walk_statements(body, check_unreachable, NULL);
5498 if (noreturn_candidate &&
5499 !(function->base.modifiers & DM_NORETURN)) {
5500 source_position_t const *const pos = &body->base.source_position;
5501 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5506 assert(current_function == function);
5507 assert(current_entity == entity);
5508 current_entity = old_current_entity;
5509 current_function = old_current_function;
5510 label_pop_to(label_stack_top);
5516 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5517 source_position_t *source_position,
5518 const symbol_t *symbol)
5520 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5522 type->bitfield.base_type = base_type;
5523 type->bitfield.size_expression = size;
5526 type_t *skipped_type = skip_typeref(base_type);
5527 if (!is_type_integer(skipped_type)) {
5528 errorf(source_position, "bitfield base type '%T' is not an integer type", base_type);
5531 bit_size = get_type_size(base_type) * 8;
5534 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5535 long v = fold_constant_to_int(size);
5536 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5539 errorf(source_position, "negative width in bit-field '%Y'",
5541 } else if (v == 0 && symbol != NULL) {
5542 errorf(source_position, "zero width for bit-field '%Y'",
5544 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5545 errorf(source_position, "width of '%Y' exceeds its type",
5548 type->bitfield.bit_size = v;
5555 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5557 entity_t *iter = compound->members.entities;
5558 for (; iter != NULL; iter = iter->base.next) {
5559 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5562 if (iter->base.symbol == symbol) {
5564 } else if (iter->base.symbol == NULL) {
5565 /* search in anonymous structs and unions */
5566 type_t *type = skip_typeref(iter->declaration.type);
5567 if (is_type_compound(type)) {
5568 if (find_compound_entry(type->compound.compound, symbol)
5579 static void check_deprecated(const source_position_t *source_position,
5580 const entity_t *entity)
5582 if (!is_declaration(entity))
5584 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5587 source_position_t const *const epos = &entity->base.source_position;
5588 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5590 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5592 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5597 static expression_t *create_select(const source_position_t *pos,
5599 type_qualifiers_t qualifiers,
5602 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5604 check_deprecated(pos, entry);
5606 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5607 select->select.compound = addr;
5608 select->select.compound_entry = entry;
5610 type_t *entry_type = entry->declaration.type;
5611 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5613 /* we always do the auto-type conversions; the & and sizeof parser contains
5614 * code to revert this! */
5615 select->base.type = automatic_type_conversion(res_type);
5616 if (res_type->kind == TYPE_BITFIELD) {
5617 select->base.type = res_type->bitfield.base_type;
5624 * Find entry with symbol in compound. Search anonymous structs and unions and
5625 * creates implicit select expressions for them.
5626 * Returns the adress for the innermost compound.
5628 static expression_t *find_create_select(const source_position_t *pos,
5630 type_qualifiers_t qualifiers,
5631 compound_t *compound, symbol_t *symbol)
5633 entity_t *iter = compound->members.entities;
5634 for (; iter != NULL; iter = iter->base.next) {
5635 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5638 symbol_t *iter_symbol = iter->base.symbol;
5639 if (iter_symbol == NULL) {
5640 type_t *type = iter->declaration.type;
5641 if (type->kind != TYPE_COMPOUND_STRUCT
5642 && type->kind != TYPE_COMPOUND_UNION)
5645 compound_t *sub_compound = type->compound.compound;
5647 if (find_compound_entry(sub_compound, symbol) == NULL)
5650 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5651 sub_addr->base.source_position = *pos;
5652 sub_addr->select.implicit = true;
5653 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5657 if (iter_symbol == symbol) {
5658 return create_select(pos, addr, qualifiers, iter);
5665 static void parse_compound_declarators(compound_t *compound,
5666 const declaration_specifiers_t *specifiers)
5671 if (token.type == ':') {
5672 source_position_t source_position = *HERE;
5675 type_t *base_type = specifiers->type;
5676 expression_t *size = parse_constant_expression();
5678 type_t *type = make_bitfield_type(base_type, size,
5679 &source_position, NULL);
5681 attribute_t *attributes = parse_attributes(NULL);
5682 attribute_t **anchor = &attributes;
5683 while (*anchor != NULL)
5684 anchor = &(*anchor)->next;
5685 *anchor = specifiers->attributes;
5687 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL);
5688 entity->base.source_position = source_position;
5689 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5690 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5691 entity->declaration.type = type;
5692 entity->declaration.attributes = attributes;
5694 if (attributes != NULL) {
5695 handle_entity_attributes(attributes, entity);
5697 append_entity(&compound->members, entity);
5699 entity = parse_declarator(specifiers,
5700 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5701 source_position_t const *const pos = &entity->base.source_position;
5702 if (entity->kind == ENTITY_TYPEDEF) {
5703 errorf(pos, "typedef not allowed as compound member");
5705 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5707 /* make sure we don't define a symbol multiple times */
5708 symbol_t *symbol = entity->base.symbol;
5709 if (symbol != NULL) {
5710 entity_t *prev = find_compound_entry(compound, symbol);
5712 source_position_t const *const ppos = &prev->base.source_position;
5713 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5717 if (token.type == ':') {
5718 source_position_t source_position = *HERE;
5720 expression_t *size = parse_constant_expression();
5722 type_t *type = entity->declaration.type;
5723 type_t *bitfield_type = make_bitfield_type(type, size,
5724 &source_position, entity->base.symbol);
5726 attribute_t *attributes = parse_attributes(NULL);
5727 entity->declaration.type = bitfield_type;
5728 handle_entity_attributes(attributes, entity);
5730 type_t *orig_type = entity->declaration.type;
5731 type_t *type = skip_typeref(orig_type);
5732 if (is_type_function(type)) {
5733 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5734 } else if (is_type_incomplete(type)) {
5735 /* §6.7.2.1:16 flexible array member */
5736 if (!is_type_array(type) ||
5737 token.type != ';' ||
5738 look_ahead(1)->type != '}') {
5739 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5744 append_entity(&compound->members, entity);
5747 } while (next_if(','));
5748 expect(';', end_error);
5751 anonymous_entity = NULL;
5754 static void parse_compound_type_entries(compound_t *compound)
5757 add_anchor_token('}');
5760 switch (token.type) {
5762 case T___extension__:
5763 case T_IDENTIFIER: {
5765 declaration_specifiers_t specifiers;
5766 parse_declaration_specifiers(&specifiers);
5767 parse_compound_declarators(compound, &specifiers);
5773 rem_anchor_token('}');
5774 expect('}', end_error);
5777 compound->complete = true;
5783 static type_t *parse_typename(void)
5785 declaration_specifiers_t specifiers;
5786 parse_declaration_specifiers(&specifiers);
5787 if (specifiers.storage_class != STORAGE_CLASS_NONE
5788 || specifiers.thread_local) {
5789 /* TODO: improve error message, user does probably not know what a
5790 * storage class is...
5792 errorf(&specifiers.source_position, "typename must not have a storage class");
5795 type_t *result = parse_abstract_declarator(specifiers.type);
5803 typedef expression_t* (*parse_expression_function)(void);
5804 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5806 typedef struct expression_parser_function_t expression_parser_function_t;
5807 struct expression_parser_function_t {
5808 parse_expression_function parser;
5809 precedence_t infix_precedence;
5810 parse_expression_infix_function infix_parser;
5813 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5816 * Prints an error message if an expression was expected but not read
5818 static expression_t *expected_expression_error(void)
5820 /* skip the error message if the error token was read */
5821 if (token.type != T_ERROR) {
5822 errorf(HERE, "expected expression, got token %K", &token);
5826 return create_invalid_expression();
5829 static type_t *get_string_type(void)
5831 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5834 static type_t *get_wide_string_type(void)
5836 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5840 * Parse a string constant.
5842 static expression_t *parse_string_literal(void)
5844 source_position_t begin = token.source_position;
5845 string_t res = token.literal;
5846 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5849 while (token.type == T_STRING_LITERAL
5850 || token.type == T_WIDE_STRING_LITERAL) {
5851 warn_string_concat(&token.source_position);
5852 res = concat_strings(&res, &token.literal);
5854 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5857 expression_t *literal;
5859 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5860 literal->base.type = get_wide_string_type();
5862 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5863 literal->base.type = get_string_type();
5865 literal->base.source_position = begin;
5866 literal->literal.value = res;
5872 * Parse a boolean constant.
5874 static expression_t *parse_boolean_literal(bool value)
5876 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5877 literal->base.type = type_bool;
5878 literal->literal.value.begin = value ? "true" : "false";
5879 literal->literal.value.size = value ? 4 : 5;
5885 static void warn_traditional_suffix(void)
5887 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%Y' suffix", token.symbol);
5890 static void check_integer_suffix(void)
5892 symbol_t *suffix = token.symbol;
5896 bool not_traditional = false;
5897 const char *c = suffix->string;
5898 if (*c == 'l' || *c == 'L') {
5901 not_traditional = true;
5903 if (*c == 'u' || *c == 'U') {
5906 } else if (*c == 'u' || *c == 'U') {
5907 not_traditional = true;
5910 } else if (*c == 'u' || *c == 'U') {
5911 not_traditional = true;
5913 if (*c == 'l' || *c == 'L') {
5921 errorf(&token.source_position,
5922 "invalid suffix '%s' on integer constant", suffix->string);
5923 } else if (not_traditional) {
5924 warn_traditional_suffix();
5928 static type_t *check_floatingpoint_suffix(void)
5930 symbol_t *suffix = token.symbol;
5931 type_t *type = type_double;
5935 bool not_traditional = false;
5936 const char *c = suffix->string;
5937 if (*c == 'f' || *c == 'F') {
5940 } else if (*c == 'l' || *c == 'L') {
5942 type = type_long_double;
5945 errorf(&token.source_position,
5946 "invalid suffix '%s' on floatingpoint constant", suffix->string);
5947 } else if (not_traditional) {
5948 warn_traditional_suffix();
5955 * Parse an integer constant.
5957 static expression_t *parse_number_literal(void)
5959 expression_kind_t kind;
5962 switch (token.type) {
5964 kind = EXPR_LITERAL_INTEGER;
5965 check_integer_suffix();
5968 case T_INTEGER_OCTAL:
5969 kind = EXPR_LITERAL_INTEGER_OCTAL;
5970 check_integer_suffix();
5973 case T_INTEGER_HEXADECIMAL:
5974 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5975 check_integer_suffix();
5978 case T_FLOATINGPOINT:
5979 kind = EXPR_LITERAL_FLOATINGPOINT;
5980 type = check_floatingpoint_suffix();
5982 case T_FLOATINGPOINT_HEXADECIMAL:
5983 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5984 type = check_floatingpoint_suffix();
5987 panic("unexpected token type in parse_number_literal");
5990 expression_t *literal = allocate_expression_zero(kind);
5991 literal->base.type = type;
5992 literal->literal.value = token.literal;
5993 literal->literal.suffix = token.symbol;
5996 /* integer type depends on the size of the number and the size
5997 * representable by the types. The backend/codegeneration has to determine
6000 determine_literal_type(&literal->literal);
6005 * Parse a character constant.
6007 static expression_t *parse_character_constant(void)
6009 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6010 literal->base.type = c_mode & _CXX ? type_char : type_int;
6011 literal->literal.value = token.literal;
6013 size_t len = literal->literal.value.size;
6015 if (!GNU_MODE && !(c_mode & _C99)) {
6016 errorf(HERE, "more than 1 character in character constant");
6018 literal->base.type = type_int;
6019 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6028 * Parse a wide character constant.
6030 static expression_t *parse_wide_character_constant(void)
6032 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6033 literal->base.type = type_int;
6034 literal->literal.value = token.literal;
6036 size_t len = wstrlen(&literal->literal.value);
6038 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6045 static entity_t *create_implicit_function(symbol_t *symbol,
6046 const source_position_t *source_position)
6048 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6049 ntype->function.return_type = type_int;
6050 ntype->function.unspecified_parameters = true;
6051 ntype->function.linkage = LINKAGE_C;
6052 type_t *type = identify_new_type(ntype);
6054 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6055 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6056 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6057 entity->declaration.type = type;
6058 entity->declaration.implicit = true;
6059 entity->base.source_position = *source_position;
6061 if (current_scope != NULL)
6062 record_entity(entity, false);
6068 * Performs automatic type cast as described in §6.3.2.1.
6070 * @param orig_type the original type
6072 static type_t *automatic_type_conversion(type_t *orig_type)
6074 type_t *type = skip_typeref(orig_type);
6075 if (is_type_array(type)) {
6076 array_type_t *array_type = &type->array;
6077 type_t *element_type = array_type->element_type;
6078 unsigned qualifiers = array_type->base.qualifiers;
6080 return make_pointer_type(element_type, qualifiers);
6083 if (is_type_function(type)) {
6084 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6091 * reverts the automatic casts of array to pointer types and function
6092 * to function-pointer types as defined §6.3.2.1
6094 type_t *revert_automatic_type_conversion(const expression_t *expression)
6096 switch (expression->kind) {
6097 case EXPR_REFERENCE: {
6098 entity_t *entity = expression->reference.entity;
6099 if (is_declaration(entity)) {
6100 return entity->declaration.type;
6101 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6102 return entity->enum_value.enum_type;
6104 panic("no declaration or enum in reference");
6109 entity_t *entity = expression->select.compound_entry;
6110 assert(is_declaration(entity));
6111 type_t *type = entity->declaration.type;
6112 return get_qualified_type(type,
6113 expression->base.type->base.qualifiers);
6116 case EXPR_UNARY_DEREFERENCE: {
6117 const expression_t *const value = expression->unary.value;
6118 type_t *const type = skip_typeref(value->base.type);
6119 if (!is_type_pointer(type))
6120 return type_error_type;
6121 return type->pointer.points_to;
6124 case EXPR_ARRAY_ACCESS: {
6125 const expression_t *array_ref = expression->array_access.array_ref;
6126 type_t *type_left = skip_typeref(array_ref->base.type);
6127 if (!is_type_pointer(type_left))
6128 return type_error_type;
6129 return type_left->pointer.points_to;
6132 case EXPR_STRING_LITERAL: {
6133 size_t size = expression->string_literal.value.size;
6134 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6137 case EXPR_WIDE_STRING_LITERAL: {
6138 size_t size = wstrlen(&expression->string_literal.value);
6139 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6142 case EXPR_COMPOUND_LITERAL:
6143 return expression->compound_literal.type;
6148 return expression->base.type;
6152 * Find an entity matching a symbol in a scope.
6153 * Uses current scope if scope is NULL
6155 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6156 namespace_tag_t namespc)
6158 if (scope == NULL) {
6159 return get_entity(symbol, namespc);
6162 /* we should optimize here, if scope grows above a certain size we should
6163 construct a hashmap here... */
6164 entity_t *entity = scope->entities;
6165 for ( ; entity != NULL; entity = entity->base.next) {
6166 if (entity->base.symbol == symbol
6167 && (namespace_tag_t)entity->base.namespc == namespc)
6174 static entity_t *parse_qualified_identifier(void)
6176 /* namespace containing the symbol */
6178 source_position_t pos;
6179 const scope_t *lookup_scope = NULL;
6181 if (next_if(T_COLONCOLON))
6182 lookup_scope = &unit->scope;
6186 if (token.type != T_IDENTIFIER) {
6187 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6188 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6190 symbol = token.symbol;
6195 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6197 if (!next_if(T_COLONCOLON))
6200 switch (entity->kind) {
6201 case ENTITY_NAMESPACE:
6202 lookup_scope = &entity->namespacee.members;
6207 lookup_scope = &entity->compound.members;
6210 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6211 symbol, get_entity_kind_name(entity->kind));
6213 /* skip further qualifications */
6214 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6216 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6220 if (entity == NULL) {
6221 if (!strict_mode && token.type == '(') {
6222 /* an implicitly declared function */
6223 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6224 entity = create_implicit_function(symbol, &pos);
6226 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6227 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6234 static expression_t *parse_reference(void)
6236 source_position_t const pos = token.source_position;
6237 entity_t *const entity = parse_qualified_identifier();
6240 if (is_declaration(entity)) {
6241 orig_type = entity->declaration.type;
6242 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6243 orig_type = entity->enum_value.enum_type;
6245 panic("expected declaration or enum value in reference");
6248 /* we always do the auto-type conversions; the & and sizeof parser contains
6249 * code to revert this! */
6250 type_t *type = automatic_type_conversion(orig_type);
6252 expression_kind_t kind = EXPR_REFERENCE;
6253 if (entity->kind == ENTITY_ENUM_VALUE)
6254 kind = EXPR_REFERENCE_ENUM_VALUE;
6256 expression_t *expression = allocate_expression_zero(kind);
6257 expression->base.source_position = pos;
6258 expression->base.type = type;
6259 expression->reference.entity = entity;
6261 /* this declaration is used */
6262 if (is_declaration(entity)) {
6263 entity->declaration.used = true;
6266 if (entity->base.parent_scope != file_scope
6267 && (current_function != NULL
6268 && entity->base.parent_scope->depth < current_function->parameters.depth)
6269 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6270 if (entity->kind == ENTITY_VARIABLE) {
6271 /* access of a variable from an outer function */
6272 entity->variable.address_taken = true;
6273 } else if (entity->kind == ENTITY_PARAMETER) {
6274 entity->parameter.address_taken = true;
6276 current_function->need_closure = true;
6279 check_deprecated(&pos, entity);
6284 static bool semantic_cast(expression_t *cast)
6286 expression_t *expression = cast->unary.value;
6287 type_t *orig_dest_type = cast->base.type;
6288 type_t *orig_type_right = expression->base.type;
6289 type_t const *dst_type = skip_typeref(orig_dest_type);
6290 type_t const *src_type = skip_typeref(orig_type_right);
6291 source_position_t const *pos = &cast->base.source_position;
6293 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6294 if (dst_type == type_void)
6297 /* only integer and pointer can be casted to pointer */
6298 if (is_type_pointer(dst_type) &&
6299 !is_type_pointer(src_type) &&
6300 !is_type_integer(src_type) &&
6301 is_type_valid(src_type)) {
6302 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6306 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6307 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6311 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6312 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6316 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6317 type_t *src = skip_typeref(src_type->pointer.points_to);
6318 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6319 unsigned missing_qualifiers =
6320 src->base.qualifiers & ~dst->base.qualifiers;
6321 if (missing_qualifiers != 0) {
6322 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6328 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6330 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6331 expression->base.source_position = *pos;
6333 parse_initializer_env_t env;
6336 env.must_be_constant = false;
6337 initializer_t *initializer = parse_initializer(&env);
6340 expression->compound_literal.initializer = initializer;
6341 expression->compound_literal.type = type;
6342 expression->base.type = automatic_type_conversion(type);
6348 * Parse a cast expression.
6350 static expression_t *parse_cast(void)
6352 source_position_t const pos = *HERE;
6355 add_anchor_token(')');
6357 type_t *type = parse_typename();
6359 rem_anchor_token(')');
6360 expect(')', end_error);
6362 if (token.type == '{') {
6363 return parse_compound_literal(&pos, type);
6366 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6367 cast->base.source_position = pos;
6369 expression_t *value = parse_subexpression(PREC_CAST);
6370 cast->base.type = type;
6371 cast->unary.value = value;
6373 if (! semantic_cast(cast)) {
6374 /* TODO: record the error in the AST. else it is impossible to detect it */
6379 return create_invalid_expression();
6383 * Parse a statement expression.
6385 static expression_t *parse_statement_expression(void)
6387 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6390 add_anchor_token(')');
6392 statement_t *statement = parse_compound_statement(true);
6393 statement->compound.stmt_expr = true;
6394 expression->statement.statement = statement;
6396 /* find last statement and use its type */
6397 type_t *type = type_void;
6398 const statement_t *stmt = statement->compound.statements;
6400 while (stmt->base.next != NULL)
6401 stmt = stmt->base.next;
6403 if (stmt->kind == STATEMENT_EXPRESSION) {
6404 type = stmt->expression.expression->base.type;
6407 source_position_t const *const pos = &expression->base.source_position;
6408 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6410 expression->base.type = type;
6412 rem_anchor_token(')');
6413 expect(')', end_error);
6420 * Parse a parenthesized expression.
6422 static expression_t *parse_parenthesized_expression(void)
6424 token_t const* const la1 = look_ahead(1);
6425 switch (la1->type) {
6427 /* gcc extension: a statement expression */
6428 return parse_statement_expression();
6431 if (is_typedef_symbol(la1->symbol)) {
6433 return parse_cast();
6438 add_anchor_token(')');
6439 expression_t *result = parse_expression();
6440 result->base.parenthesized = true;
6441 rem_anchor_token(')');
6442 expect(')', end_error);
6448 static expression_t *parse_function_keyword(void)
6452 if (current_function == NULL) {
6453 errorf(HERE, "'__func__' used outside of a function");
6456 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6457 expression->base.type = type_char_ptr;
6458 expression->funcname.kind = FUNCNAME_FUNCTION;
6465 static expression_t *parse_pretty_function_keyword(void)
6467 if (current_function == NULL) {
6468 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6471 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6472 expression->base.type = type_char_ptr;
6473 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6475 eat(T___PRETTY_FUNCTION__);
6480 static expression_t *parse_funcsig_keyword(void)
6482 if (current_function == NULL) {
6483 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6486 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6487 expression->base.type = type_char_ptr;
6488 expression->funcname.kind = FUNCNAME_FUNCSIG;
6495 static expression_t *parse_funcdname_keyword(void)
6497 if (current_function == NULL) {
6498 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6501 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6502 expression->base.type = type_char_ptr;
6503 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6505 eat(T___FUNCDNAME__);
6510 static designator_t *parse_designator(void)
6512 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6513 result->source_position = *HERE;
6515 if (token.type != T_IDENTIFIER) {
6516 parse_error_expected("while parsing member designator",
6517 T_IDENTIFIER, NULL);
6520 result->symbol = token.symbol;
6523 designator_t *last_designator = result;
6526 if (token.type != T_IDENTIFIER) {
6527 parse_error_expected("while parsing member designator",
6528 T_IDENTIFIER, NULL);
6531 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6532 designator->source_position = *HERE;
6533 designator->symbol = token.symbol;
6536 last_designator->next = designator;
6537 last_designator = designator;
6541 add_anchor_token(']');
6542 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6543 designator->source_position = *HERE;
6544 designator->array_index = parse_expression();
6545 rem_anchor_token(']');
6546 expect(']', end_error);
6547 if (designator->array_index == NULL) {
6551 last_designator->next = designator;
6552 last_designator = designator;
6564 * Parse the __builtin_offsetof() expression.
6566 static expression_t *parse_offsetof(void)
6568 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6569 expression->base.type = type_size_t;
6571 eat(T___builtin_offsetof);
6573 expect('(', end_error);
6574 add_anchor_token(',');
6575 type_t *type = parse_typename();
6576 rem_anchor_token(',');
6577 expect(',', end_error);
6578 add_anchor_token(')');
6579 designator_t *designator = parse_designator();
6580 rem_anchor_token(')');
6581 expect(')', end_error);
6583 expression->offsetofe.type = type;
6584 expression->offsetofe.designator = designator;
6587 memset(&path, 0, sizeof(path));
6588 path.top_type = type;
6589 path.path = NEW_ARR_F(type_path_entry_t, 0);
6591 descend_into_subtype(&path);
6593 if (!walk_designator(&path, designator, true)) {
6594 return create_invalid_expression();
6597 DEL_ARR_F(path.path);
6601 return create_invalid_expression();
6605 * Parses a _builtin_va_start() expression.
6607 static expression_t *parse_va_start(void)
6609 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6611 eat(T___builtin_va_start);
6613 expect('(', end_error);
6614 add_anchor_token(',');
6615 expression->va_starte.ap = parse_assignment_expression();
6616 rem_anchor_token(',');
6617 expect(',', end_error);
6618 expression_t *const expr = parse_assignment_expression();
6619 if (expr->kind == EXPR_REFERENCE) {
6620 entity_t *const entity = expr->reference.entity;
6621 if (!current_function->base.type->function.variadic) {
6622 errorf(&expr->base.source_position,
6623 "'va_start' used in non-variadic function");
6624 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6625 entity->base.next != NULL ||
6626 entity->kind != ENTITY_PARAMETER) {
6627 errorf(&expr->base.source_position,
6628 "second argument of 'va_start' must be last parameter of the current function");
6630 expression->va_starte.parameter = &entity->variable;
6632 expect(')', end_error);
6635 expect(')', end_error);
6637 return create_invalid_expression();
6641 * Parses a __builtin_va_arg() expression.
6643 static expression_t *parse_va_arg(void)
6645 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6647 eat(T___builtin_va_arg);
6649 expect('(', end_error);
6651 ap.expression = parse_assignment_expression();
6652 expression->va_arge.ap = ap.expression;
6653 check_call_argument(type_valist, &ap, 1);
6655 expect(',', end_error);
6656 expression->base.type = parse_typename();
6657 expect(')', end_error);
6661 return create_invalid_expression();
6665 * Parses a __builtin_va_copy() expression.
6667 static expression_t *parse_va_copy(void)
6669 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6671 eat(T___builtin_va_copy);
6673 expect('(', end_error);
6674 expression_t *dst = parse_assignment_expression();
6675 assign_error_t error = semantic_assign(type_valist, dst);
6676 report_assign_error(error, type_valist, dst, "call argument 1",
6677 &dst->base.source_position);
6678 expression->va_copye.dst = dst;
6680 expect(',', end_error);
6682 call_argument_t src;
6683 src.expression = parse_assignment_expression();
6684 check_call_argument(type_valist, &src, 2);
6685 expression->va_copye.src = src.expression;
6686 expect(')', end_error);
6690 return create_invalid_expression();
6694 * Parses a __builtin_constant_p() expression.
6696 static expression_t *parse_builtin_constant(void)
6698 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6700 eat(T___builtin_constant_p);
6702 expect('(', end_error);
6703 add_anchor_token(')');
6704 expression->builtin_constant.value = parse_assignment_expression();
6705 rem_anchor_token(')');
6706 expect(')', end_error);
6707 expression->base.type = type_int;
6711 return create_invalid_expression();
6715 * Parses a __builtin_types_compatible_p() expression.
6717 static expression_t *parse_builtin_types_compatible(void)
6719 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6721 eat(T___builtin_types_compatible_p);
6723 expect('(', end_error);
6724 add_anchor_token(')');
6725 add_anchor_token(',');
6726 expression->builtin_types_compatible.left = parse_typename();
6727 rem_anchor_token(',');
6728 expect(',', end_error);
6729 expression->builtin_types_compatible.right = parse_typename();
6730 rem_anchor_token(')');
6731 expect(')', end_error);
6732 expression->base.type = type_int;
6736 return create_invalid_expression();
6740 * Parses a __builtin_is_*() compare expression.
6742 static expression_t *parse_compare_builtin(void)
6744 expression_t *expression;
6746 switch (token.type) {
6747 case T___builtin_isgreater:
6748 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6750 case T___builtin_isgreaterequal:
6751 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6753 case T___builtin_isless:
6754 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6756 case T___builtin_islessequal:
6757 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6759 case T___builtin_islessgreater:
6760 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6762 case T___builtin_isunordered:
6763 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6766 internal_errorf(HERE, "invalid compare builtin found");
6768 expression->base.source_position = *HERE;
6771 expect('(', end_error);
6772 expression->binary.left = parse_assignment_expression();
6773 expect(',', end_error);
6774 expression->binary.right = parse_assignment_expression();
6775 expect(')', end_error);
6777 type_t *const orig_type_left = expression->binary.left->base.type;
6778 type_t *const orig_type_right = expression->binary.right->base.type;
6780 type_t *const type_left = skip_typeref(orig_type_left);
6781 type_t *const type_right = skip_typeref(orig_type_right);
6782 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6783 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6784 type_error_incompatible("invalid operands in comparison",
6785 &expression->base.source_position, orig_type_left, orig_type_right);
6788 semantic_comparison(&expression->binary);
6793 return create_invalid_expression();
6797 * Parses a MS assume() expression.
6799 static expression_t *parse_assume(void)
6801 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6805 expect('(', end_error);
6806 add_anchor_token(')');
6807 expression->unary.value = parse_assignment_expression();
6808 rem_anchor_token(')');
6809 expect(')', end_error);
6811 expression->base.type = type_void;
6814 return create_invalid_expression();
6818 * Return the label for the current symbol or create a new one.
6820 static label_t *get_label(void)
6822 assert(token.type == T_IDENTIFIER);
6823 assert(current_function != NULL);
6825 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6826 /* If we find a local label, we already created the declaration. */
6827 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6828 if (label->base.parent_scope != current_scope) {
6829 assert(label->base.parent_scope->depth < current_scope->depth);
6830 current_function->goto_to_outer = true;
6832 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6833 /* There is no matching label in the same function, so create a new one. */
6834 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6839 return &label->label;
6843 * Parses a GNU && label address expression.
6845 static expression_t *parse_label_address(void)
6847 source_position_t source_position = token.source_position;
6849 if (token.type != T_IDENTIFIER) {
6850 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6851 return create_invalid_expression();
6854 label_t *const label = get_label();
6856 label->address_taken = true;
6858 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6859 expression->base.source_position = source_position;
6861 /* label address is treated as a void pointer */
6862 expression->base.type = type_void_ptr;
6863 expression->label_address.label = label;
6868 * Parse a microsoft __noop expression.
6870 static expression_t *parse_noop_expression(void)
6872 /* the result is a (int)0 */
6873 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6874 literal->base.type = type_int;
6875 literal->literal.value.begin = "__noop";
6876 literal->literal.value.size = 6;
6880 if (token.type == '(') {
6881 /* parse arguments */
6883 add_anchor_token(')');
6884 add_anchor_token(',');
6886 if (token.type != ')') do {
6887 (void)parse_assignment_expression();
6888 } while (next_if(','));
6890 rem_anchor_token(',');
6891 rem_anchor_token(')');
6892 expect(')', end_error);
6899 * Parses a primary expression.
6901 static expression_t *parse_primary_expression(void)
6903 switch (token.type) {
6904 case T_false: return parse_boolean_literal(false);
6905 case T_true: return parse_boolean_literal(true);
6907 case T_INTEGER_OCTAL:
6908 case T_INTEGER_HEXADECIMAL:
6909 case T_FLOATINGPOINT:
6910 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6911 case T_CHARACTER_CONSTANT: return parse_character_constant();
6912 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6913 case T_STRING_LITERAL:
6914 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6915 case T___FUNCTION__:
6916 case T___func__: return parse_function_keyword();
6917 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6918 case T___FUNCSIG__: return parse_funcsig_keyword();
6919 case T___FUNCDNAME__: return parse_funcdname_keyword();
6920 case T___builtin_offsetof: return parse_offsetof();
6921 case T___builtin_va_start: return parse_va_start();
6922 case T___builtin_va_arg: return parse_va_arg();
6923 case T___builtin_va_copy: return parse_va_copy();
6924 case T___builtin_isgreater:
6925 case T___builtin_isgreaterequal:
6926 case T___builtin_isless:
6927 case T___builtin_islessequal:
6928 case T___builtin_islessgreater:
6929 case T___builtin_isunordered: return parse_compare_builtin();
6930 case T___builtin_constant_p: return parse_builtin_constant();
6931 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6932 case T__assume: return parse_assume();
6935 return parse_label_address();
6938 case '(': return parse_parenthesized_expression();
6939 case T___noop: return parse_noop_expression();
6941 /* Gracefully handle type names while parsing expressions. */
6943 return parse_reference();
6945 if (!is_typedef_symbol(token.symbol)) {
6946 return parse_reference();
6950 source_position_t const pos = *HERE;
6951 declaration_specifiers_t specifiers;
6952 parse_declaration_specifiers(&specifiers);
6953 type_t const *const type = parse_abstract_declarator(specifiers.type);
6954 errorf(&pos, "encountered type '%T' while parsing expression", type);
6955 return create_invalid_expression();
6959 errorf(HERE, "unexpected token %K, expected an expression", &token);
6961 return create_invalid_expression();
6964 static expression_t *parse_array_expression(expression_t *left)
6966 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6967 array_access_expression_t *const arr = &expr->array_access;
6970 add_anchor_token(']');
6972 expression_t *const inside = parse_expression();
6974 type_t *const orig_type_left = left->base.type;
6975 type_t *const orig_type_inside = inside->base.type;
6977 type_t *const type_left = skip_typeref(orig_type_left);
6978 type_t *const type_inside = skip_typeref(orig_type_inside);
6984 if (is_type_pointer(type_left)) {
6987 idx_type = type_inside;
6988 res_type = type_left->pointer.points_to;
6990 } else if (is_type_pointer(type_inside)) {
6991 arr->flipped = true;
6994 idx_type = type_left;
6995 res_type = type_inside->pointer.points_to;
6997 res_type = automatic_type_conversion(res_type);
6998 if (!is_type_integer(idx_type)) {
6999 errorf(&idx->base.source_position, "array subscript must have integer type");
7000 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
7001 source_position_t const *const pos = &idx->base.source_position;
7002 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
7005 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7006 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7008 res_type = type_error_type;
7013 arr->array_ref = ref;
7015 arr->base.type = res_type;
7017 rem_anchor_token(']');
7018 expect(']', end_error);
7023 static expression_t *parse_typeprop(expression_kind_t const kind)
7025 expression_t *tp_expression = allocate_expression_zero(kind);
7026 tp_expression->base.type = type_size_t;
7028 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7031 expression_t *expression;
7032 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7033 source_position_t const pos = *HERE;
7035 add_anchor_token(')');
7036 orig_type = parse_typename();
7037 rem_anchor_token(')');
7038 expect(')', end_error);
7040 if (token.type == '{') {
7041 /* It was not sizeof(type) after all. It is sizeof of an expression
7042 * starting with a compound literal */
7043 expression = parse_compound_literal(&pos, orig_type);
7044 goto typeprop_expression;
7047 expression = parse_subexpression(PREC_UNARY);
7049 typeprop_expression:
7050 tp_expression->typeprop.tp_expression = expression;
7052 orig_type = revert_automatic_type_conversion(expression);
7053 expression->base.type = orig_type;
7056 tp_expression->typeprop.type = orig_type;
7057 type_t const* const type = skip_typeref(orig_type);
7058 char const* wrong_type = NULL;
7059 if (is_type_incomplete(type)) {
7060 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7061 wrong_type = "incomplete";
7062 } else if (type->kind == TYPE_FUNCTION) {
7064 /* function types are allowed (and return 1) */
7065 source_position_t const *const pos = &tp_expression->base.source_position;
7066 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7067 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7069 wrong_type = "function";
7072 if (is_type_incomplete(type))
7073 wrong_type = "incomplete";
7075 if (type->kind == TYPE_BITFIELD)
7076 wrong_type = "bitfield";
7078 if (wrong_type != NULL) {
7079 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7080 errorf(&tp_expression->base.source_position,
7081 "operand of %s expression must not be of %s type '%T'",
7082 what, wrong_type, orig_type);
7086 return tp_expression;
7089 static expression_t *parse_sizeof(void)
7091 return parse_typeprop(EXPR_SIZEOF);
7094 static expression_t *parse_alignof(void)
7096 return parse_typeprop(EXPR_ALIGNOF);
7099 static expression_t *parse_select_expression(expression_t *addr)
7101 assert(token.type == '.' || token.type == T_MINUSGREATER);
7102 bool select_left_arrow = (token.type == T_MINUSGREATER);
7103 source_position_t const pos = *HERE;
7106 if (token.type != T_IDENTIFIER) {
7107 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7108 return create_invalid_expression();
7110 symbol_t *symbol = token.symbol;
7113 type_t *const orig_type = addr->base.type;
7114 type_t *const type = skip_typeref(orig_type);
7117 bool saw_error = false;
7118 if (is_type_pointer(type)) {
7119 if (!select_left_arrow) {
7121 "request for member '%Y' in something not a struct or union, but '%T'",
7125 type_left = skip_typeref(type->pointer.points_to);
7127 if (select_left_arrow && is_type_valid(type)) {
7128 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7134 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7135 type_left->kind != TYPE_COMPOUND_UNION) {
7137 if (is_type_valid(type_left) && !saw_error) {
7139 "request for member '%Y' in something not a struct or union, but '%T'",
7142 return create_invalid_expression();
7145 compound_t *compound = type_left->compound.compound;
7146 if (!compound->complete) {
7147 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7149 return create_invalid_expression();
7152 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7153 expression_t *result =
7154 find_create_select(&pos, addr, qualifiers, compound, symbol);
7156 if (result == NULL) {
7157 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7158 return create_invalid_expression();
7164 static void check_call_argument(type_t *expected_type,
7165 call_argument_t *argument, unsigned pos)
7167 type_t *expected_type_skip = skip_typeref(expected_type);
7168 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7169 expression_t *arg_expr = argument->expression;
7170 type_t *arg_type = skip_typeref(arg_expr->base.type);
7172 /* handle transparent union gnu extension */
7173 if (is_type_union(expected_type_skip)
7174 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7175 compound_t *union_decl = expected_type_skip->compound.compound;
7176 type_t *best_type = NULL;
7177 entity_t *entry = union_decl->members.entities;
7178 for ( ; entry != NULL; entry = entry->base.next) {
7179 assert(is_declaration(entry));
7180 type_t *decl_type = entry->declaration.type;
7181 error = semantic_assign(decl_type, arg_expr);
7182 if (error == ASSIGN_ERROR_INCOMPATIBLE
7183 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7186 if (error == ASSIGN_SUCCESS) {
7187 best_type = decl_type;
7188 } else if (best_type == NULL) {
7189 best_type = decl_type;
7193 if (best_type != NULL) {
7194 expected_type = best_type;
7198 error = semantic_assign(expected_type, arg_expr);
7199 argument->expression = create_implicit_cast(arg_expr, expected_type);
7201 if (error != ASSIGN_SUCCESS) {
7202 /* report exact scope in error messages (like "in argument 3") */
7204 snprintf(buf, sizeof(buf), "call argument %u", pos);
7205 report_assign_error(error, expected_type, arg_expr, buf,
7206 &arg_expr->base.source_position);
7208 type_t *const promoted_type = get_default_promoted_type(arg_type);
7209 if (!types_compatible(expected_type_skip, promoted_type) &&
7210 !types_compatible(expected_type_skip, type_void_ptr) &&
7211 !types_compatible(type_void_ptr, promoted_type)) {
7212 /* Deliberately show the skipped types in this warning */
7213 source_position_t const *const apos = &arg_expr->base.source_position;
7214 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7220 * Handle the semantic restrictions of builtin calls
7222 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7223 switch (call->function->reference.entity->function.btk) {
7224 case bk_gnu_builtin_return_address:
7225 case bk_gnu_builtin_frame_address: {
7226 /* argument must be constant */
7227 call_argument_t *argument = call->arguments;
7229 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7230 errorf(&call->base.source_position,
7231 "argument of '%Y' must be a constant expression",
7232 call->function->reference.entity->base.symbol);
7236 case bk_gnu_builtin_object_size:
7237 if (call->arguments == NULL)
7240 call_argument_t *arg = call->arguments->next;
7241 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7242 errorf(&call->base.source_position,
7243 "second argument of '%Y' must be a constant expression",
7244 call->function->reference.entity->base.symbol);
7247 case bk_gnu_builtin_prefetch:
7248 /* second and third argument must be constant if existent */
7249 if (call->arguments == NULL)
7251 call_argument_t *rw = call->arguments->next;
7252 call_argument_t *locality = NULL;
7255 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7256 errorf(&call->base.source_position,
7257 "second argument of '%Y' must be a constant expression",
7258 call->function->reference.entity->base.symbol);
7260 locality = rw->next;
7262 if (locality != NULL) {
7263 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7264 errorf(&call->base.source_position,
7265 "third argument of '%Y' must be a constant expression",
7266 call->function->reference.entity->base.symbol);
7268 locality = rw->next;
7277 * Parse a call expression, ie. expression '( ... )'.
7279 * @param expression the function address
7281 static expression_t *parse_call_expression(expression_t *expression)
7283 expression_t *result = allocate_expression_zero(EXPR_CALL);
7284 call_expression_t *call = &result->call;
7285 call->function = expression;
7287 type_t *const orig_type = expression->base.type;
7288 type_t *const type = skip_typeref(orig_type);
7290 function_type_t *function_type = NULL;
7291 if (is_type_pointer(type)) {
7292 type_t *const to_type = skip_typeref(type->pointer.points_to);
7294 if (is_type_function(to_type)) {
7295 function_type = &to_type->function;
7296 call->base.type = function_type->return_type;
7300 if (function_type == NULL && is_type_valid(type)) {
7302 "called object '%E' (type '%T') is not a pointer to a function",
7303 expression, orig_type);
7306 /* parse arguments */
7308 add_anchor_token(')');
7309 add_anchor_token(',');
7311 if (token.type != ')') {
7312 call_argument_t **anchor = &call->arguments;
7314 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7315 argument->expression = parse_assignment_expression();
7318 anchor = &argument->next;
7319 } while (next_if(','));
7321 rem_anchor_token(',');
7322 rem_anchor_token(')');
7323 expect(')', end_error);
7325 if (function_type == NULL)
7328 /* check type and count of call arguments */
7329 function_parameter_t *parameter = function_type->parameters;
7330 call_argument_t *argument = call->arguments;
7331 if (!function_type->unspecified_parameters) {
7332 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7333 parameter = parameter->next, argument = argument->next) {
7334 check_call_argument(parameter->type, argument, ++pos);
7337 if (parameter != NULL) {
7338 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7339 } else if (argument != NULL && !function_type->variadic) {
7340 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7344 /* do default promotion for other arguments */
7345 for (; argument != NULL; argument = argument->next) {
7346 type_t *argument_type = argument->expression->base.type;
7347 if (!is_type_object(skip_typeref(argument_type))) {
7348 errorf(&argument->expression->base.source_position,
7349 "call argument '%E' must not be void", argument->expression);
7352 argument_type = get_default_promoted_type(argument_type);
7354 argument->expression
7355 = create_implicit_cast(argument->expression, argument_type);
7360 if (is_type_compound(skip_typeref(function_type->return_type))) {
7361 source_position_t const *const pos = &expression->base.source_position;
7362 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7365 if (expression->kind == EXPR_REFERENCE) {
7366 reference_expression_t *reference = &expression->reference;
7367 if (reference->entity->kind == ENTITY_FUNCTION &&
7368 reference->entity->function.btk != bk_none)
7369 handle_builtin_argument_restrictions(call);
7376 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7378 static bool same_compound_type(const type_t *type1, const type_t *type2)
7381 is_type_compound(type1) &&
7382 type1->kind == type2->kind &&
7383 type1->compound.compound == type2->compound.compound;
7386 static expression_t const *get_reference_address(expression_t const *expr)
7388 bool regular_take_address = true;
7390 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7391 expr = expr->unary.value;
7393 regular_take_address = false;
7396 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7399 expr = expr->unary.value;
7402 if (expr->kind != EXPR_REFERENCE)
7405 /* special case for functions which are automatically converted to a
7406 * pointer to function without an extra TAKE_ADDRESS operation */
7407 if (!regular_take_address &&
7408 expr->reference.entity->kind != ENTITY_FUNCTION) {
7415 static void warn_reference_address_as_bool(expression_t const* expr)
7417 expr = get_reference_address(expr);
7419 source_position_t const *const pos = &expr->base.source_position;
7420 entity_t const *const ent = expr->reference.entity;
7421 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7425 static void warn_assignment_in_condition(const expression_t *const expr)
7427 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7429 if (expr->base.parenthesized)
7431 source_position_t const *const pos = &expr->base.source_position;
7432 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7435 static void semantic_condition(expression_t const *const expr,
7436 char const *const context)
7438 type_t *const type = skip_typeref(expr->base.type);
7439 if (is_type_scalar(type)) {
7440 warn_reference_address_as_bool(expr);
7441 warn_assignment_in_condition(expr);
7442 } else if (is_type_valid(type)) {
7443 errorf(&expr->base.source_position,
7444 "%s must have scalar type", context);
7449 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7451 * @param expression the conditional expression
7453 static expression_t *parse_conditional_expression(expression_t *expression)
7455 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7457 conditional_expression_t *conditional = &result->conditional;
7458 conditional->condition = expression;
7461 add_anchor_token(':');
7463 /* §6.5.15:2 The first operand shall have scalar type. */
7464 semantic_condition(expression, "condition of conditional operator");
7466 expression_t *true_expression = expression;
7467 bool gnu_cond = false;
7468 if (GNU_MODE && token.type == ':') {
7471 true_expression = parse_expression();
7473 rem_anchor_token(':');
7474 expect(':', end_error);
7476 expression_t *false_expression =
7477 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7479 type_t *const orig_true_type = true_expression->base.type;
7480 type_t *const orig_false_type = false_expression->base.type;
7481 type_t *const true_type = skip_typeref(orig_true_type);
7482 type_t *const false_type = skip_typeref(orig_false_type);
7485 source_position_t const *const pos = &conditional->base.source_position;
7486 type_t *result_type;
7487 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7488 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7489 /* ISO/IEC 14882:1998(E) §5.16:2 */
7490 if (true_expression->kind == EXPR_UNARY_THROW) {
7491 result_type = false_type;
7492 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7493 result_type = true_type;
7495 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7496 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7497 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7499 result_type = type_void;
7501 } else if (is_type_arithmetic(true_type)
7502 && is_type_arithmetic(false_type)) {
7503 result_type = semantic_arithmetic(true_type, false_type);
7504 } else if (same_compound_type(true_type, false_type)) {
7505 /* just take 1 of the 2 types */
7506 result_type = true_type;
7507 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7508 type_t *pointer_type;
7510 expression_t *other_expression;
7511 if (is_type_pointer(true_type) &&
7512 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7513 pointer_type = true_type;
7514 other_type = false_type;
7515 other_expression = false_expression;
7517 pointer_type = false_type;
7518 other_type = true_type;
7519 other_expression = true_expression;
7522 if (is_null_pointer_constant(other_expression)) {
7523 result_type = pointer_type;
7524 } else if (is_type_pointer(other_type)) {
7525 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7526 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7529 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7530 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7532 } else if (types_compatible(get_unqualified_type(to1),
7533 get_unqualified_type(to2))) {
7536 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7540 type_t *const type =
7541 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7542 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7543 } else if (is_type_integer(other_type)) {
7544 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7545 result_type = pointer_type;
7547 goto types_incompatible;
7551 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7552 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7554 result_type = type_error_type;
7557 conditional->true_expression
7558 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7559 conditional->false_expression
7560 = create_implicit_cast(false_expression, result_type);
7561 conditional->base.type = result_type;
7566 * Parse an extension expression.
7568 static expression_t *parse_extension(void)
7571 expression_t *expression = parse_subexpression(PREC_UNARY);
7577 * Parse a __builtin_classify_type() expression.
7579 static expression_t *parse_builtin_classify_type(void)
7581 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7582 result->base.type = type_int;
7584 eat(T___builtin_classify_type);
7586 expect('(', end_error);
7587 add_anchor_token(')');
7588 expression_t *expression = parse_expression();
7589 rem_anchor_token(')');
7590 expect(')', end_error);
7591 result->classify_type.type_expression = expression;
7595 return create_invalid_expression();
7599 * Parse a delete expression
7600 * ISO/IEC 14882:1998(E) §5.3.5
7602 static expression_t *parse_delete(void)
7604 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7605 result->base.type = type_void;
7610 result->kind = EXPR_UNARY_DELETE_ARRAY;
7611 expect(']', end_error);
7615 expression_t *const value = parse_subexpression(PREC_CAST);
7616 result->unary.value = value;
7618 type_t *const type = skip_typeref(value->base.type);
7619 if (!is_type_pointer(type)) {
7620 if (is_type_valid(type)) {
7621 errorf(&value->base.source_position,
7622 "operand of delete must have pointer type");
7624 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7625 source_position_t const *const pos = &value->base.source_position;
7626 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7633 * Parse a throw expression
7634 * ISO/IEC 14882:1998(E) §15:1
7636 static expression_t *parse_throw(void)
7638 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7639 result->base.type = type_void;
7643 expression_t *value = NULL;
7644 switch (token.type) {
7646 value = parse_assignment_expression();
7647 /* ISO/IEC 14882:1998(E) §15.1:3 */
7648 type_t *const orig_type = value->base.type;
7649 type_t *const type = skip_typeref(orig_type);
7650 if (is_type_incomplete(type)) {
7651 errorf(&value->base.source_position,
7652 "cannot throw object of incomplete type '%T'", orig_type);
7653 } else if (is_type_pointer(type)) {
7654 type_t *const points_to = skip_typeref(type->pointer.points_to);
7655 if (is_type_incomplete(points_to) &&
7656 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7657 errorf(&value->base.source_position,
7658 "cannot throw pointer to incomplete type '%T'", orig_type);
7666 result->unary.value = value;
7671 static bool check_pointer_arithmetic(const source_position_t *source_position,
7672 type_t *pointer_type,
7673 type_t *orig_pointer_type)
7675 type_t *points_to = pointer_type->pointer.points_to;
7676 points_to = skip_typeref(points_to);
7678 if (is_type_incomplete(points_to)) {
7679 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7680 errorf(source_position,
7681 "arithmetic with pointer to incomplete type '%T' not allowed",
7685 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7687 } else if (is_type_function(points_to)) {
7689 errorf(source_position,
7690 "arithmetic with pointer to function type '%T' not allowed",
7694 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7700 static bool is_lvalue(const expression_t *expression)
7702 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7703 switch (expression->kind) {
7704 case EXPR_ARRAY_ACCESS:
7705 case EXPR_COMPOUND_LITERAL:
7706 case EXPR_REFERENCE:
7708 case EXPR_UNARY_DEREFERENCE:
7712 type_t *type = skip_typeref(expression->base.type);
7714 /* ISO/IEC 14882:1998(E) §3.10:3 */
7715 is_type_reference(type) ||
7716 /* Claim it is an lvalue, if the type is invalid. There was a parse
7717 * error before, which maybe prevented properly recognizing it as
7719 !is_type_valid(type);
7724 static void semantic_incdec(unary_expression_t *expression)
7726 type_t *const orig_type = expression->value->base.type;
7727 type_t *const type = skip_typeref(orig_type);
7728 if (is_type_pointer(type)) {
7729 if (!check_pointer_arithmetic(&expression->base.source_position,
7733 } else if (!is_type_real(type) && is_type_valid(type)) {
7734 /* TODO: improve error message */
7735 errorf(&expression->base.source_position,
7736 "operation needs an arithmetic or pointer type");
7739 if (!is_lvalue(expression->value)) {
7740 /* TODO: improve error message */
7741 errorf(&expression->base.source_position, "lvalue required as operand");
7743 expression->base.type = orig_type;
7746 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7748 type_t *const orig_type = expression->value->base.type;
7749 type_t *const type = skip_typeref(orig_type);
7750 if (!is_type_arithmetic(type)) {
7751 if (is_type_valid(type)) {
7752 /* TODO: improve error message */
7753 errorf(&expression->base.source_position,
7754 "operation needs an arithmetic type");
7759 expression->base.type = orig_type;
7762 static void semantic_unexpr_plus(unary_expression_t *expression)
7764 semantic_unexpr_arithmetic(expression);
7765 source_position_t const *const pos = &expression->base.source_position;
7766 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7769 static void semantic_not(unary_expression_t *expression)
7771 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7772 semantic_condition(expression->value, "operand of !");
7773 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7776 static void semantic_unexpr_integer(unary_expression_t *expression)
7778 type_t *const orig_type = expression->value->base.type;
7779 type_t *const type = skip_typeref(orig_type);
7780 if (!is_type_integer(type)) {
7781 if (is_type_valid(type)) {
7782 errorf(&expression->base.source_position,
7783 "operand of ~ must be of integer type");
7788 expression->base.type = orig_type;
7791 static void semantic_dereference(unary_expression_t *expression)
7793 type_t *const orig_type = expression->value->base.type;
7794 type_t *const type = skip_typeref(orig_type);
7795 if (!is_type_pointer(type)) {
7796 if (is_type_valid(type)) {
7797 errorf(&expression->base.source_position,
7798 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7803 type_t *result_type = type->pointer.points_to;
7804 result_type = automatic_type_conversion(result_type);
7805 expression->base.type = result_type;
7809 * Record that an address is taken (expression represents an lvalue).
7811 * @param expression the expression
7812 * @param may_be_register if true, the expression might be an register
7814 static void set_address_taken(expression_t *expression, bool may_be_register)
7816 if (expression->kind != EXPR_REFERENCE)
7819 entity_t *const entity = expression->reference.entity;
7821 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7824 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7825 && !may_be_register) {
7826 source_position_t const *const pos = &expression->base.source_position;
7827 errorf(pos, "address of register '%N' requested", entity);
7830 if (entity->kind == ENTITY_VARIABLE) {
7831 entity->variable.address_taken = true;
7833 assert(entity->kind == ENTITY_PARAMETER);
7834 entity->parameter.address_taken = true;
7839 * Check the semantic of the address taken expression.
7841 static void semantic_take_addr(unary_expression_t *expression)
7843 expression_t *value = expression->value;
7844 value->base.type = revert_automatic_type_conversion(value);
7846 type_t *orig_type = value->base.type;
7847 type_t *type = skip_typeref(orig_type);
7848 if (!is_type_valid(type))
7852 if (!is_lvalue(value)) {
7853 errorf(&expression->base.source_position, "'&' requires an lvalue");
7855 if (type->kind == TYPE_BITFIELD) {
7856 errorf(&expression->base.source_position,
7857 "'&' not allowed on object with bitfield type '%T'",
7861 set_address_taken(value, false);
7863 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7866 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7867 static expression_t *parse_##unexpression_type(void) \
7869 expression_t *unary_expression \
7870 = allocate_expression_zero(unexpression_type); \
7872 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7874 sfunc(&unary_expression->unary); \
7876 return unary_expression; \
7879 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7880 semantic_unexpr_arithmetic)
7881 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7882 semantic_unexpr_plus)
7883 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7885 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7886 semantic_dereference)
7887 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7889 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7890 semantic_unexpr_integer)
7891 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7893 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7896 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7898 static expression_t *parse_##unexpression_type(expression_t *left) \
7900 expression_t *unary_expression \
7901 = allocate_expression_zero(unexpression_type); \
7903 unary_expression->unary.value = left; \
7905 sfunc(&unary_expression->unary); \
7907 return unary_expression; \
7910 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7911 EXPR_UNARY_POSTFIX_INCREMENT,
7913 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7914 EXPR_UNARY_POSTFIX_DECREMENT,
7917 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7919 /* TODO: handle complex + imaginary types */
7921 type_left = get_unqualified_type(type_left);
7922 type_right = get_unqualified_type(type_right);
7924 /* §6.3.1.8 Usual arithmetic conversions */
7925 if (type_left == type_long_double || type_right == type_long_double) {
7926 return type_long_double;
7927 } else if (type_left == type_double || type_right == type_double) {
7929 } else if (type_left == type_float || type_right == type_float) {
7933 type_left = promote_integer(type_left);
7934 type_right = promote_integer(type_right);
7936 if (type_left == type_right)
7939 bool const signed_left = is_type_signed(type_left);
7940 bool const signed_right = is_type_signed(type_right);
7941 int const rank_left = get_rank(type_left);
7942 int const rank_right = get_rank(type_right);
7944 if (signed_left == signed_right)
7945 return rank_left >= rank_right ? type_left : type_right;
7954 u_rank = rank_right;
7955 u_type = type_right;
7957 s_rank = rank_right;
7958 s_type = type_right;
7963 if (u_rank >= s_rank)
7966 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7968 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7969 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7973 case ATOMIC_TYPE_INT: return type_unsigned_int;
7974 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7975 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7977 default: panic("invalid atomic type");
7982 * Check the semantic restrictions for a binary expression.
7984 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7986 expression_t *const left = expression->left;
7987 expression_t *const right = expression->right;
7988 type_t *const orig_type_left = left->base.type;
7989 type_t *const orig_type_right = right->base.type;
7990 type_t *const type_left = skip_typeref(orig_type_left);
7991 type_t *const type_right = skip_typeref(orig_type_right);
7993 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7994 /* TODO: improve error message */
7995 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7996 errorf(&expression->base.source_position,
7997 "operation needs arithmetic types");
8002 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8003 expression->left = create_implicit_cast(left, arithmetic_type);
8004 expression->right = create_implicit_cast(right, arithmetic_type);
8005 expression->base.type = arithmetic_type;
8008 static void semantic_binexpr_integer(binary_expression_t *const expression)
8010 expression_t *const left = expression->left;
8011 expression_t *const right = expression->right;
8012 type_t *const orig_type_left = left->base.type;
8013 type_t *const orig_type_right = right->base.type;
8014 type_t *const type_left = skip_typeref(orig_type_left);
8015 type_t *const type_right = skip_typeref(orig_type_right);
8017 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8018 /* TODO: improve error message */
8019 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8020 errorf(&expression->base.source_position,
8021 "operation needs integer types");
8026 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8027 expression->left = create_implicit_cast(left, result_type);
8028 expression->right = create_implicit_cast(right, result_type);
8029 expression->base.type = result_type;
8032 static void warn_div_by_zero(binary_expression_t const *const expression)
8034 if (!is_type_integer(expression->base.type))
8037 expression_t const *const right = expression->right;
8038 /* The type of the right operand can be different for /= */
8039 if (is_type_integer(right->base.type) &&
8040 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8041 !fold_constant_to_bool(right)) {
8042 source_position_t const *const pos = &expression->base.source_position;
8043 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8048 * Check the semantic restrictions for a div/mod expression.
8050 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8052 semantic_binexpr_arithmetic(expression);
8053 warn_div_by_zero(expression);
8056 static void warn_addsub_in_shift(const expression_t *const expr)
8058 if (expr->base.parenthesized)
8062 switch (expr->kind) {
8063 case EXPR_BINARY_ADD: op = '+'; break;
8064 case EXPR_BINARY_SUB: op = '-'; break;
8068 source_position_t const *const pos = &expr->base.source_position;
8069 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8072 static bool semantic_shift(binary_expression_t *expression)
8074 expression_t *const left = expression->left;
8075 expression_t *const right = expression->right;
8076 type_t *const orig_type_left = left->base.type;
8077 type_t *const orig_type_right = right->base.type;
8078 type_t * type_left = skip_typeref(orig_type_left);
8079 type_t * type_right = skip_typeref(orig_type_right);
8081 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8082 /* TODO: improve error message */
8083 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8084 errorf(&expression->base.source_position,
8085 "operands of shift operation must have integer types");
8090 type_left = promote_integer(type_left);
8092 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8093 source_position_t const *const pos = &right->base.source_position;
8094 long const count = fold_constant_to_int(right);
8096 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8097 } else if ((unsigned long)count >=
8098 get_atomic_type_size(type_left->atomic.akind) * 8) {
8099 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8103 type_right = promote_integer(type_right);
8104 expression->right = create_implicit_cast(right, type_right);
8109 static void semantic_shift_op(binary_expression_t *expression)
8111 expression_t *const left = expression->left;
8112 expression_t *const right = expression->right;
8114 if (!semantic_shift(expression))
8117 warn_addsub_in_shift(left);
8118 warn_addsub_in_shift(right);
8120 type_t *const orig_type_left = left->base.type;
8121 type_t * type_left = skip_typeref(orig_type_left);
8123 type_left = promote_integer(type_left);
8124 expression->left = create_implicit_cast(left, type_left);
8125 expression->base.type = type_left;
8128 static void semantic_add(binary_expression_t *expression)
8130 expression_t *const left = expression->left;
8131 expression_t *const right = expression->right;
8132 type_t *const orig_type_left = left->base.type;
8133 type_t *const orig_type_right = right->base.type;
8134 type_t *const type_left = skip_typeref(orig_type_left);
8135 type_t *const type_right = skip_typeref(orig_type_right);
8138 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8139 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8140 expression->left = create_implicit_cast(left, arithmetic_type);
8141 expression->right = create_implicit_cast(right, arithmetic_type);
8142 expression->base.type = arithmetic_type;
8143 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8144 check_pointer_arithmetic(&expression->base.source_position,
8145 type_left, orig_type_left);
8146 expression->base.type = type_left;
8147 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8148 check_pointer_arithmetic(&expression->base.source_position,
8149 type_right, orig_type_right);
8150 expression->base.type = type_right;
8151 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8152 errorf(&expression->base.source_position,
8153 "invalid operands to binary + ('%T', '%T')",
8154 orig_type_left, orig_type_right);
8158 static void semantic_sub(binary_expression_t *expression)
8160 expression_t *const left = expression->left;
8161 expression_t *const right = expression->right;
8162 type_t *const orig_type_left = left->base.type;
8163 type_t *const orig_type_right = right->base.type;
8164 type_t *const type_left = skip_typeref(orig_type_left);
8165 type_t *const type_right = skip_typeref(orig_type_right);
8166 source_position_t const *const pos = &expression->base.source_position;
8169 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8170 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8171 expression->left = create_implicit_cast(left, arithmetic_type);
8172 expression->right = create_implicit_cast(right, arithmetic_type);
8173 expression->base.type = arithmetic_type;
8174 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8175 check_pointer_arithmetic(&expression->base.source_position,
8176 type_left, orig_type_left);
8177 expression->base.type = type_left;
8178 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8179 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8180 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8181 if (!types_compatible(unqual_left, unqual_right)) {
8183 "subtracting pointers to incompatible types '%T' and '%T'",
8184 orig_type_left, orig_type_right);
8185 } else if (!is_type_object(unqual_left)) {
8186 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8187 errorf(pos, "subtracting pointers to non-object types '%T'",
8190 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8193 expression->base.type = type_ptrdiff_t;
8194 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8195 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8196 orig_type_left, orig_type_right);
8200 static void warn_string_literal_address(expression_t const* expr)
8202 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8203 expr = expr->unary.value;
8204 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8206 expr = expr->unary.value;
8209 if (expr->kind == EXPR_STRING_LITERAL
8210 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8211 source_position_t const *const pos = &expr->base.source_position;
8212 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8216 static bool maybe_negative(expression_t const *const expr)
8218 switch (is_constant_expression(expr)) {
8219 case EXPR_CLASS_ERROR: return false;
8220 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8221 default: return true;
8225 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8227 warn_string_literal_address(expr);
8229 expression_t const* const ref = get_reference_address(expr);
8230 if (ref != NULL && is_null_pointer_constant(other)) {
8231 entity_t const *const ent = ref->reference.entity;
8232 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8235 if (!expr->base.parenthesized) {
8236 switch (expr->base.kind) {
8237 case EXPR_BINARY_LESS:
8238 case EXPR_BINARY_GREATER:
8239 case EXPR_BINARY_LESSEQUAL:
8240 case EXPR_BINARY_GREATEREQUAL:
8241 case EXPR_BINARY_NOTEQUAL:
8242 case EXPR_BINARY_EQUAL:
8243 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8252 * Check the semantics of comparison expressions.
8254 * @param expression The expression to check.
8256 static void semantic_comparison(binary_expression_t *expression)
8258 source_position_t const *const pos = &expression->base.source_position;
8259 expression_t *const left = expression->left;
8260 expression_t *const right = expression->right;
8262 warn_comparison(pos, left, right);
8263 warn_comparison(pos, right, left);
8265 type_t *orig_type_left = left->base.type;
8266 type_t *orig_type_right = right->base.type;
8267 type_t *type_left = skip_typeref(orig_type_left);
8268 type_t *type_right = skip_typeref(orig_type_right);
8270 /* TODO non-arithmetic types */
8271 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8272 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8274 /* test for signed vs unsigned compares */
8275 if (is_type_integer(arithmetic_type)) {
8276 bool const signed_left = is_type_signed(type_left);
8277 bool const signed_right = is_type_signed(type_right);
8278 if (signed_left != signed_right) {
8279 /* FIXME long long needs better const folding magic */
8280 /* TODO check whether constant value can be represented by other type */
8281 if ((signed_left && maybe_negative(left)) ||
8282 (signed_right && maybe_negative(right))) {
8283 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8288 expression->left = create_implicit_cast(left, arithmetic_type);
8289 expression->right = create_implicit_cast(right, arithmetic_type);
8290 expression->base.type = arithmetic_type;
8291 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8292 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8293 is_type_float(arithmetic_type)) {
8294 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8296 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8297 /* TODO check compatibility */
8298 } else if (is_type_pointer(type_left)) {
8299 expression->right = create_implicit_cast(right, type_left);
8300 } else if (is_type_pointer(type_right)) {
8301 expression->left = create_implicit_cast(left, type_right);
8302 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8303 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8305 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8309 * Checks if a compound type has constant fields.
8311 static bool has_const_fields(const compound_type_t *type)
8313 compound_t *compound = type->compound;
8314 entity_t *entry = compound->members.entities;
8316 for (; entry != NULL; entry = entry->base.next) {
8317 if (!is_declaration(entry))
8320 const type_t *decl_type = skip_typeref(entry->declaration.type);
8321 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8328 static bool is_valid_assignment_lhs(expression_t const* const left)
8330 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8331 type_t *const type_left = skip_typeref(orig_type_left);
8333 if (!is_lvalue(left)) {
8334 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8339 if (left->kind == EXPR_REFERENCE
8340 && left->reference.entity->kind == ENTITY_FUNCTION) {
8341 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8345 if (is_type_array(type_left)) {
8346 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8349 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8350 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8354 if (is_type_incomplete(type_left)) {
8355 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8356 left, orig_type_left);
8359 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8360 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8361 left, orig_type_left);
8368 static void semantic_arithmetic_assign(binary_expression_t *expression)
8370 expression_t *left = expression->left;
8371 expression_t *right = expression->right;
8372 type_t *orig_type_left = left->base.type;
8373 type_t *orig_type_right = right->base.type;
8375 if (!is_valid_assignment_lhs(left))
8378 type_t *type_left = skip_typeref(orig_type_left);
8379 type_t *type_right = skip_typeref(orig_type_right);
8381 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8382 /* TODO: improve error message */
8383 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8384 errorf(&expression->base.source_position,
8385 "operation needs arithmetic types");
8390 /* combined instructions are tricky. We can't create an implicit cast on
8391 * the left side, because we need the uncasted form for the store.
8392 * The ast2firm pass has to know that left_type must be right_type
8393 * for the arithmetic operation and create a cast by itself */
8394 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8395 expression->right = create_implicit_cast(right, arithmetic_type);
8396 expression->base.type = type_left;
8399 static void semantic_divmod_assign(binary_expression_t *expression)
8401 semantic_arithmetic_assign(expression);
8402 warn_div_by_zero(expression);
8405 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8407 expression_t *const left = expression->left;
8408 expression_t *const right = expression->right;
8409 type_t *const orig_type_left = left->base.type;
8410 type_t *const orig_type_right = right->base.type;
8411 type_t *const type_left = skip_typeref(orig_type_left);
8412 type_t *const type_right = skip_typeref(orig_type_right);
8414 if (!is_valid_assignment_lhs(left))
8417 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8418 /* combined instructions are tricky. We can't create an implicit cast on
8419 * the left side, because we need the uncasted form for the store.
8420 * The ast2firm pass has to know that left_type must be right_type
8421 * for the arithmetic operation and create a cast by itself */
8422 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8423 expression->right = create_implicit_cast(right, arithmetic_type);
8424 expression->base.type = type_left;
8425 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8426 check_pointer_arithmetic(&expression->base.source_position,
8427 type_left, orig_type_left);
8428 expression->base.type = type_left;
8429 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8430 errorf(&expression->base.source_position,
8431 "incompatible types '%T' and '%T' in assignment",
8432 orig_type_left, orig_type_right);
8436 static void semantic_integer_assign(binary_expression_t *expression)
8438 expression_t *left = expression->left;
8439 expression_t *right = expression->right;
8440 type_t *orig_type_left = left->base.type;
8441 type_t *orig_type_right = right->base.type;
8443 if (!is_valid_assignment_lhs(left))
8446 type_t *type_left = skip_typeref(orig_type_left);
8447 type_t *type_right = skip_typeref(orig_type_right);
8449 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8450 /* TODO: improve error message */
8451 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8452 errorf(&expression->base.source_position,
8453 "operation needs integer types");
8458 /* combined instructions are tricky. We can't create an implicit cast on
8459 * the left side, because we need the uncasted form for the store.
8460 * The ast2firm pass has to know that left_type must be right_type
8461 * for the arithmetic operation and create a cast by itself */
8462 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8463 expression->right = create_implicit_cast(right, arithmetic_type);
8464 expression->base.type = type_left;
8467 static void semantic_shift_assign(binary_expression_t *expression)
8469 expression_t *left = expression->left;
8471 if (!is_valid_assignment_lhs(left))
8474 if (!semantic_shift(expression))
8477 expression->base.type = skip_typeref(left->base.type);
8480 static void warn_logical_and_within_or(const expression_t *const expr)
8482 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8484 if (expr->base.parenthesized)
8486 source_position_t const *const pos = &expr->base.source_position;
8487 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8491 * Check the semantic restrictions of a logical expression.
8493 static void semantic_logical_op(binary_expression_t *expression)
8495 /* §6.5.13:2 Each of the operands shall have scalar type.
8496 * §6.5.14:2 Each of the operands shall have scalar type. */
8497 semantic_condition(expression->left, "left operand of logical operator");
8498 semantic_condition(expression->right, "right operand of logical operator");
8499 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8500 warn_logical_and_within_or(expression->left);
8501 warn_logical_and_within_or(expression->right);
8503 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8507 * Check the semantic restrictions of a binary assign expression.
8509 static void semantic_binexpr_assign(binary_expression_t *expression)
8511 expression_t *left = expression->left;
8512 type_t *orig_type_left = left->base.type;
8514 if (!is_valid_assignment_lhs(left))
8517 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8518 report_assign_error(error, orig_type_left, expression->right,
8519 "assignment", &left->base.source_position);
8520 expression->right = create_implicit_cast(expression->right, orig_type_left);
8521 expression->base.type = orig_type_left;
8525 * Determine if the outermost operation (or parts thereof) of the given
8526 * expression has no effect in order to generate a warning about this fact.
8527 * Therefore in some cases this only examines some of the operands of the
8528 * expression (see comments in the function and examples below).
8530 * f() + 23; // warning, because + has no effect
8531 * x || f(); // no warning, because x controls execution of f()
8532 * x ? y : f(); // warning, because y has no effect
8533 * (void)x; // no warning to be able to suppress the warning
8534 * This function can NOT be used for an "expression has definitely no effect"-
8536 static bool expression_has_effect(const expression_t *const expr)
8538 switch (expr->kind) {
8539 case EXPR_UNKNOWN: break;
8540 case EXPR_INVALID: return true; /* do NOT warn */
8541 case EXPR_REFERENCE: return false;
8542 case EXPR_REFERENCE_ENUM_VALUE: return false;
8543 case EXPR_LABEL_ADDRESS: return false;
8545 /* suppress the warning for microsoft __noop operations */
8546 case EXPR_LITERAL_MS_NOOP: return true;
8547 case EXPR_LITERAL_BOOLEAN:
8548 case EXPR_LITERAL_CHARACTER:
8549 case EXPR_LITERAL_WIDE_CHARACTER:
8550 case EXPR_LITERAL_INTEGER:
8551 case EXPR_LITERAL_INTEGER_OCTAL:
8552 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8553 case EXPR_LITERAL_FLOATINGPOINT:
8554 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8555 case EXPR_STRING_LITERAL: return false;
8556 case EXPR_WIDE_STRING_LITERAL: return false;
8559 const call_expression_t *const call = &expr->call;
8560 if (call->function->kind != EXPR_REFERENCE)
8563 switch (call->function->reference.entity->function.btk) {
8564 /* FIXME: which builtins have no effect? */
8565 default: return true;
8569 /* Generate the warning if either the left or right hand side of a
8570 * conditional expression has no effect */
8571 case EXPR_CONDITIONAL: {
8572 conditional_expression_t const *const cond = &expr->conditional;
8573 expression_t const *const t = cond->true_expression;
8575 (t == NULL || expression_has_effect(t)) &&
8576 expression_has_effect(cond->false_expression);
8579 case EXPR_SELECT: return false;
8580 case EXPR_ARRAY_ACCESS: return false;
8581 case EXPR_SIZEOF: return false;
8582 case EXPR_CLASSIFY_TYPE: return false;
8583 case EXPR_ALIGNOF: return false;
8585 case EXPR_FUNCNAME: return false;
8586 case EXPR_BUILTIN_CONSTANT_P: return false;
8587 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8588 case EXPR_OFFSETOF: return false;
8589 case EXPR_VA_START: return true;
8590 case EXPR_VA_ARG: return true;
8591 case EXPR_VA_COPY: return true;
8592 case EXPR_STATEMENT: return true; // TODO
8593 case EXPR_COMPOUND_LITERAL: return false;
8595 case EXPR_UNARY_NEGATE: return false;
8596 case EXPR_UNARY_PLUS: return false;
8597 case EXPR_UNARY_BITWISE_NEGATE: return false;
8598 case EXPR_UNARY_NOT: return false;
8599 case EXPR_UNARY_DEREFERENCE: return false;
8600 case EXPR_UNARY_TAKE_ADDRESS: return false;
8601 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8602 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8603 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8604 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8606 /* Treat void casts as if they have an effect in order to being able to
8607 * suppress the warning */
8608 case EXPR_UNARY_CAST: {
8609 type_t *const type = skip_typeref(expr->base.type);
8610 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8613 case EXPR_UNARY_CAST_IMPLICIT: return true;
8614 case EXPR_UNARY_ASSUME: return true;
8615 case EXPR_UNARY_DELETE: return true;
8616 case EXPR_UNARY_DELETE_ARRAY: return true;
8617 case EXPR_UNARY_THROW: return true;
8619 case EXPR_BINARY_ADD: return false;
8620 case EXPR_BINARY_SUB: return false;
8621 case EXPR_BINARY_MUL: return false;
8622 case EXPR_BINARY_DIV: return false;
8623 case EXPR_BINARY_MOD: return false;
8624 case EXPR_BINARY_EQUAL: return false;
8625 case EXPR_BINARY_NOTEQUAL: return false;
8626 case EXPR_BINARY_LESS: return false;
8627 case EXPR_BINARY_LESSEQUAL: return false;
8628 case EXPR_BINARY_GREATER: return false;
8629 case EXPR_BINARY_GREATEREQUAL: return false;
8630 case EXPR_BINARY_BITWISE_AND: return false;
8631 case EXPR_BINARY_BITWISE_OR: return false;
8632 case EXPR_BINARY_BITWISE_XOR: return false;
8633 case EXPR_BINARY_SHIFTLEFT: return false;
8634 case EXPR_BINARY_SHIFTRIGHT: return false;
8635 case EXPR_BINARY_ASSIGN: return true;
8636 case EXPR_BINARY_MUL_ASSIGN: return true;
8637 case EXPR_BINARY_DIV_ASSIGN: return true;
8638 case EXPR_BINARY_MOD_ASSIGN: return true;
8639 case EXPR_BINARY_ADD_ASSIGN: return true;
8640 case EXPR_BINARY_SUB_ASSIGN: return true;
8641 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8642 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8643 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8644 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8645 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8647 /* Only examine the right hand side of && and ||, because the left hand
8648 * side already has the effect of controlling the execution of the right
8650 case EXPR_BINARY_LOGICAL_AND:
8651 case EXPR_BINARY_LOGICAL_OR:
8652 /* Only examine the right hand side of a comma expression, because the left
8653 * hand side has a separate warning */
8654 case EXPR_BINARY_COMMA:
8655 return expression_has_effect(expr->binary.right);
8657 case EXPR_BINARY_ISGREATER: return false;
8658 case EXPR_BINARY_ISGREATEREQUAL: return false;
8659 case EXPR_BINARY_ISLESS: return false;
8660 case EXPR_BINARY_ISLESSEQUAL: return false;
8661 case EXPR_BINARY_ISLESSGREATER: return false;
8662 case EXPR_BINARY_ISUNORDERED: return false;
8665 internal_errorf(HERE, "unexpected expression");
8668 static void semantic_comma(binary_expression_t *expression)
8670 const expression_t *const left = expression->left;
8671 if (!expression_has_effect(left)) {
8672 source_position_t const *const pos = &left->base.source_position;
8673 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8675 expression->base.type = expression->right->base.type;
8679 * @param prec_r precedence of the right operand
8681 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8682 static expression_t *parse_##binexpression_type(expression_t *left) \
8684 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8685 binexpr->binary.left = left; \
8688 expression_t *right = parse_subexpression(prec_r); \
8690 binexpr->binary.right = right; \
8691 sfunc(&binexpr->binary); \
8696 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8697 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8698 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8699 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8700 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8701 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8702 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8703 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8704 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8705 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8706 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8707 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8708 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8709 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8710 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8711 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8712 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8713 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8714 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8715 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8716 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8717 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8718 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8719 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8720 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8721 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8722 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8723 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8724 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8725 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8728 static expression_t *parse_subexpression(precedence_t precedence)
8730 if (token.type < 0) {
8731 return expected_expression_error();
8734 expression_parser_function_t *parser
8735 = &expression_parsers[token.type];
8738 if (parser->parser != NULL) {
8739 left = parser->parser();
8741 left = parse_primary_expression();
8743 assert(left != NULL);
8746 if (token.type < 0) {
8747 return expected_expression_error();
8750 parser = &expression_parsers[token.type];
8751 if (parser->infix_parser == NULL)
8753 if (parser->infix_precedence < precedence)
8756 left = parser->infix_parser(left);
8758 assert(left != NULL);
8759 assert(left->kind != EXPR_UNKNOWN);
8766 * Parse an expression.
8768 static expression_t *parse_expression(void)
8770 return parse_subexpression(PREC_EXPRESSION);
8774 * Register a parser for a prefix-like operator.
8776 * @param parser the parser function
8777 * @param token_type the token type of the prefix token
8779 static void register_expression_parser(parse_expression_function parser,
8782 expression_parser_function_t *entry = &expression_parsers[token_type];
8784 if (entry->parser != NULL) {
8785 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8786 panic("trying to register multiple expression parsers for a token");
8788 entry->parser = parser;
8792 * Register a parser for an infix operator with given precedence.
8794 * @param parser the parser function
8795 * @param token_type the token type of the infix operator
8796 * @param precedence the precedence of the operator
8798 static void register_infix_parser(parse_expression_infix_function parser,
8799 int token_type, precedence_t precedence)
8801 expression_parser_function_t *entry = &expression_parsers[token_type];
8803 if (entry->infix_parser != NULL) {
8804 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8805 panic("trying to register multiple infix expression parsers for a "
8808 entry->infix_parser = parser;
8809 entry->infix_precedence = precedence;
8813 * Initialize the expression parsers.
8815 static void init_expression_parsers(void)
8817 memset(&expression_parsers, 0, sizeof(expression_parsers));
8819 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8820 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8821 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8822 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8823 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8824 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8825 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8826 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8827 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8828 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8829 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8830 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8831 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8832 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8833 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8834 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8835 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8836 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8837 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8838 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8839 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8840 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8841 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8842 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8843 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8844 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8845 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8846 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8847 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8848 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8849 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8850 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8851 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8852 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8853 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8854 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8855 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8857 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8858 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8859 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8860 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8861 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8862 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8863 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8864 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8865 register_expression_parser(parse_sizeof, T_sizeof);
8866 register_expression_parser(parse_alignof, T___alignof__);
8867 register_expression_parser(parse_extension, T___extension__);
8868 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8869 register_expression_parser(parse_delete, T_delete);
8870 register_expression_parser(parse_throw, T_throw);
8874 * Parse a asm statement arguments specification.
8876 static asm_argument_t *parse_asm_arguments(bool is_out)
8878 asm_argument_t *result = NULL;
8879 asm_argument_t **anchor = &result;
8881 while (token.type == T_STRING_LITERAL || token.type == '[') {
8882 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8883 memset(argument, 0, sizeof(argument[0]));
8886 if (token.type != T_IDENTIFIER) {
8887 parse_error_expected("while parsing asm argument",
8888 T_IDENTIFIER, NULL);
8891 argument->symbol = token.symbol;
8893 expect(']', end_error);
8896 argument->constraints = parse_string_literals();
8897 expect('(', end_error);
8898 add_anchor_token(')');
8899 expression_t *expression = parse_expression();
8900 rem_anchor_token(')');
8902 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8903 * change size or type representation (e.g. int -> long is ok, but
8904 * int -> float is not) */
8905 if (expression->kind == EXPR_UNARY_CAST) {
8906 type_t *const type = expression->base.type;
8907 type_kind_t const kind = type->kind;
8908 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8911 if (kind == TYPE_ATOMIC) {
8912 atomic_type_kind_t const akind = type->atomic.akind;
8913 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8914 size = get_atomic_type_size(akind);
8916 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8917 size = get_atomic_type_size(get_intptr_kind());
8921 expression_t *const value = expression->unary.value;
8922 type_t *const value_type = value->base.type;
8923 type_kind_t const value_kind = value_type->kind;
8925 unsigned value_flags;
8926 unsigned value_size;
8927 if (value_kind == TYPE_ATOMIC) {
8928 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8929 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8930 value_size = get_atomic_type_size(value_akind);
8931 } else if (value_kind == TYPE_POINTER) {
8932 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8933 value_size = get_atomic_type_size(get_intptr_kind());
8938 if (value_flags != flags || value_size != size)
8942 } while (expression->kind == EXPR_UNARY_CAST);
8946 if (!is_lvalue(expression)) {
8947 errorf(&expression->base.source_position,
8948 "asm output argument is not an lvalue");
8951 if (argument->constraints.begin[0] == '=')
8952 determine_lhs_ent(expression, NULL);
8954 mark_vars_read(expression, NULL);
8956 mark_vars_read(expression, NULL);
8958 argument->expression = expression;
8959 expect(')', end_error);
8961 set_address_taken(expression, true);
8964 anchor = &argument->next;
8976 * Parse a asm statement clobber specification.
8978 static asm_clobber_t *parse_asm_clobbers(void)
8980 asm_clobber_t *result = NULL;
8981 asm_clobber_t **anchor = &result;
8983 while (token.type == T_STRING_LITERAL) {
8984 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8985 clobber->clobber = parse_string_literals();
8988 anchor = &clobber->next;
8998 * Parse an asm statement.
9000 static statement_t *parse_asm_statement(void)
9002 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9003 asm_statement_t *asm_statement = &statement->asms;
9007 if (next_if(T_volatile))
9008 asm_statement->is_volatile = true;
9010 expect('(', end_error);
9011 add_anchor_token(')');
9012 if (token.type != T_STRING_LITERAL) {
9013 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9016 asm_statement->asm_text = parse_string_literals();
9018 add_anchor_token(':');
9019 if (!next_if(':')) {
9020 rem_anchor_token(':');
9024 asm_statement->outputs = parse_asm_arguments(true);
9025 if (!next_if(':')) {
9026 rem_anchor_token(':');
9030 asm_statement->inputs = parse_asm_arguments(false);
9031 if (!next_if(':')) {
9032 rem_anchor_token(':');
9035 rem_anchor_token(':');
9037 asm_statement->clobbers = parse_asm_clobbers();
9040 rem_anchor_token(')');
9041 expect(')', end_error);
9042 expect(';', end_error);
9044 if (asm_statement->outputs == NULL) {
9045 /* GCC: An 'asm' instruction without any output operands will be treated
9046 * identically to a volatile 'asm' instruction. */
9047 asm_statement->is_volatile = true;
9052 return create_invalid_statement();
9055 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9057 statement_t *inner_stmt;
9058 switch (token.type) {
9060 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9061 inner_stmt = create_invalid_statement();
9065 if (label->kind == STATEMENT_LABEL) {
9066 /* Eat an empty statement here, to avoid the warning about an empty
9067 * statement after a label. label:; is commonly used to have a label
9068 * before a closing brace. */
9069 inner_stmt = create_empty_statement();
9076 inner_stmt = parse_statement();
9077 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9078 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9079 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9080 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9088 * Parse a case statement.
9090 static statement_t *parse_case_statement(void)
9092 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9093 source_position_t *const pos = &statement->base.source_position;
9097 expression_t *const expression = parse_expression();
9098 statement->case_label.expression = expression;
9099 expression_classification_t const expr_class = is_constant_expression(expression);
9100 if (expr_class != EXPR_CLASS_CONSTANT) {
9101 if (expr_class != EXPR_CLASS_ERROR) {
9102 errorf(pos, "case label does not reduce to an integer constant");
9104 statement->case_label.is_bad = true;
9106 long const val = fold_constant_to_int(expression);
9107 statement->case_label.first_case = val;
9108 statement->case_label.last_case = val;
9112 if (next_if(T_DOTDOTDOT)) {
9113 expression_t *const end_range = parse_expression();
9114 statement->case_label.end_range = end_range;
9115 expression_classification_t const end_class = is_constant_expression(end_range);
9116 if (end_class != EXPR_CLASS_CONSTANT) {
9117 if (end_class != EXPR_CLASS_ERROR) {
9118 errorf(pos, "case range does not reduce to an integer constant");
9120 statement->case_label.is_bad = true;
9122 long const val = fold_constant_to_int(end_range);
9123 statement->case_label.last_case = val;
9125 if (val < statement->case_label.first_case) {
9126 statement->case_label.is_empty_range = true;
9127 warningf(WARN_OTHER, pos, "empty range specified");
9133 PUSH_PARENT(statement);
9135 expect(':', end_error);
9138 if (current_switch != NULL) {
9139 if (! statement->case_label.is_bad) {
9140 /* Check for duplicate case values */
9141 case_label_statement_t *c = &statement->case_label;
9142 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9143 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9146 if (c->last_case < l->first_case || c->first_case > l->last_case)
9149 errorf(pos, "duplicate case value (previously used %P)",
9150 &l->base.source_position);
9154 /* link all cases into the switch statement */
9155 if (current_switch->last_case == NULL) {
9156 current_switch->first_case = &statement->case_label;
9158 current_switch->last_case->next = &statement->case_label;
9160 current_switch->last_case = &statement->case_label;
9162 errorf(pos, "case label not within a switch statement");
9165 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9172 * Parse a default statement.
9174 static statement_t *parse_default_statement(void)
9176 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9180 PUSH_PARENT(statement);
9182 expect(':', end_error);
9185 if (current_switch != NULL) {
9186 const case_label_statement_t *def_label = current_switch->default_label;
9187 if (def_label != NULL) {
9188 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9190 current_switch->default_label = &statement->case_label;
9192 /* link all cases into the switch statement */
9193 if (current_switch->last_case == NULL) {
9194 current_switch->first_case = &statement->case_label;
9196 current_switch->last_case->next = &statement->case_label;
9198 current_switch->last_case = &statement->case_label;
9201 errorf(&statement->base.source_position,
9202 "'default' label not within a switch statement");
9205 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9212 * Parse a label statement.
9214 static statement_t *parse_label_statement(void)
9216 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9217 label_t *const label = get_label();
9218 statement->label.label = label;
9220 PUSH_PARENT(statement);
9222 /* if statement is already set then the label is defined twice,
9223 * otherwise it was just mentioned in a goto/local label declaration so far
9225 source_position_t const* const pos = &statement->base.source_position;
9226 if (label->statement != NULL) {
9227 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9229 label->base.source_position = *pos;
9230 label->statement = statement;
9235 statement->label.statement = parse_label_inner_statement(statement, "label");
9237 /* remember the labels in a list for later checking */
9238 *label_anchor = &statement->label;
9239 label_anchor = &statement->label.next;
9245 static statement_t *parse_inner_statement(void)
9247 statement_t *const stmt = parse_statement();
9248 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9249 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9250 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9251 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9257 * Parse an if statement.
9259 static statement_t *parse_if(void)
9261 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9265 PUSH_PARENT(statement);
9267 add_anchor_token('{');
9269 expect('(', end_error);
9270 add_anchor_token(')');
9271 expression_t *const expr = parse_expression();
9272 statement->ifs.condition = expr;
9273 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9275 semantic_condition(expr, "condition of 'if'-statment");
9276 mark_vars_read(expr, NULL);
9277 rem_anchor_token(')');
9278 expect(')', end_error);
9281 rem_anchor_token('{');
9283 add_anchor_token(T_else);
9284 statement_t *const true_stmt = parse_inner_statement();
9285 statement->ifs.true_statement = true_stmt;
9286 rem_anchor_token(T_else);
9288 if (next_if(T_else)) {
9289 statement->ifs.false_statement = parse_inner_statement();
9290 } else if (true_stmt->kind == STATEMENT_IF &&
9291 true_stmt->ifs.false_statement != NULL) {
9292 source_position_t const *const pos = &true_stmt->base.source_position;
9293 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9301 * Check that all enums are handled in a switch.
9303 * @param statement the switch statement to check
9305 static void check_enum_cases(const switch_statement_t *statement)
9307 if (!is_warn_on(WARN_SWITCH_ENUM))
9309 const type_t *type = skip_typeref(statement->expression->base.type);
9310 if (! is_type_enum(type))
9312 const enum_type_t *enumt = &type->enumt;
9314 /* if we have a default, no warnings */
9315 if (statement->default_label != NULL)
9318 /* FIXME: calculation of value should be done while parsing */
9319 /* TODO: quadratic algorithm here. Change to an n log n one */
9320 long last_value = -1;
9321 const entity_t *entry = enumt->enume->base.next;
9322 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9323 entry = entry->base.next) {
9324 const expression_t *expression = entry->enum_value.value;
9325 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9327 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9328 if (l->expression == NULL)
9330 if (l->first_case <= value && value <= l->last_case) {
9336 source_position_t const *const pos = &statement->base.source_position;
9337 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9344 * Parse a switch statement.
9346 static statement_t *parse_switch(void)
9348 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9352 PUSH_PARENT(statement);
9354 expect('(', end_error);
9355 add_anchor_token(')');
9356 expression_t *const expr = parse_expression();
9357 mark_vars_read(expr, NULL);
9358 type_t * type = skip_typeref(expr->base.type);
9359 if (is_type_integer(type)) {
9360 type = promote_integer(type);
9361 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9362 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9364 } else if (is_type_valid(type)) {
9365 errorf(&expr->base.source_position,
9366 "switch quantity is not an integer, but '%T'", type);
9367 type = type_error_type;
9369 statement->switchs.expression = create_implicit_cast(expr, type);
9370 expect(')', end_error);
9371 rem_anchor_token(')');
9373 switch_statement_t *rem = current_switch;
9374 current_switch = &statement->switchs;
9375 statement->switchs.body = parse_inner_statement();
9376 current_switch = rem;
9378 if (statement->switchs.default_label == NULL) {
9379 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9381 check_enum_cases(&statement->switchs);
9387 return create_invalid_statement();
9390 static statement_t *parse_loop_body(statement_t *const loop)
9392 statement_t *const rem = current_loop;
9393 current_loop = loop;
9395 statement_t *const body = parse_inner_statement();
9402 * Parse a while statement.
9404 static statement_t *parse_while(void)
9406 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9410 PUSH_PARENT(statement);
9412 expect('(', end_error);
9413 add_anchor_token(')');
9414 expression_t *const cond = parse_expression();
9415 statement->whiles.condition = cond;
9416 /* §6.8.5:2 The controlling expression of an iteration statement shall
9417 * have scalar type. */
9418 semantic_condition(cond, "condition of 'while'-statement");
9419 mark_vars_read(cond, NULL);
9420 rem_anchor_token(')');
9421 expect(')', end_error);
9423 statement->whiles.body = parse_loop_body(statement);
9429 return create_invalid_statement();
9433 * Parse a do statement.
9435 static statement_t *parse_do(void)
9437 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9441 PUSH_PARENT(statement);
9443 add_anchor_token(T_while);
9444 statement->do_while.body = parse_loop_body(statement);
9445 rem_anchor_token(T_while);
9447 expect(T_while, end_error);
9448 expect('(', end_error);
9449 add_anchor_token(')');
9450 expression_t *const cond = parse_expression();
9451 statement->do_while.condition = cond;
9452 /* §6.8.5:2 The controlling expression of an iteration statement shall
9453 * have scalar type. */
9454 semantic_condition(cond, "condition of 'do-while'-statement");
9455 mark_vars_read(cond, NULL);
9456 rem_anchor_token(')');
9457 expect(')', end_error);
9458 expect(';', end_error);
9464 return create_invalid_statement();
9468 * Parse a for statement.
9470 static statement_t *parse_for(void)
9472 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9476 expect('(', end_error1);
9477 add_anchor_token(')');
9479 PUSH_PARENT(statement);
9480 PUSH_SCOPE(&statement->fors.scope);
9485 } else if (is_declaration_specifier(&token)) {
9486 parse_declaration(record_entity, DECL_FLAGS_NONE);
9488 add_anchor_token(';');
9489 expression_t *const init = parse_expression();
9490 statement->fors.initialisation = init;
9491 mark_vars_read(init, ENT_ANY);
9492 if (!expression_has_effect(init)) {
9493 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9495 rem_anchor_token(';');
9496 expect(';', end_error2);
9501 if (token.type != ';') {
9502 add_anchor_token(';');
9503 expression_t *const cond = parse_expression();
9504 statement->fors.condition = cond;
9505 /* §6.8.5:2 The controlling expression of an iteration statement
9506 * shall have scalar type. */
9507 semantic_condition(cond, "condition of 'for'-statement");
9508 mark_vars_read(cond, NULL);
9509 rem_anchor_token(';');
9511 expect(';', end_error2);
9512 if (token.type != ')') {
9513 expression_t *const step = parse_expression();
9514 statement->fors.step = step;
9515 mark_vars_read(step, ENT_ANY);
9516 if (!expression_has_effect(step)) {
9517 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9520 expect(')', end_error2);
9521 rem_anchor_token(')');
9522 statement->fors.body = parse_loop_body(statement);
9530 rem_anchor_token(')');
9535 return create_invalid_statement();
9539 * Parse a goto statement.
9541 static statement_t *parse_goto(void)
9543 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9546 if (GNU_MODE && next_if('*')) {
9547 expression_t *expression = parse_expression();
9548 mark_vars_read(expression, NULL);
9550 /* Argh: although documentation says the expression must be of type void*,
9551 * gcc accepts anything that can be casted into void* without error */
9552 type_t *type = expression->base.type;
9554 if (type != type_error_type) {
9555 if (!is_type_pointer(type) && !is_type_integer(type)) {
9556 errorf(&expression->base.source_position,
9557 "cannot convert to a pointer type");
9558 } else if (type != type_void_ptr) {
9559 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9561 expression = create_implicit_cast(expression, type_void_ptr);
9564 statement->gotos.expression = expression;
9565 } else if (token.type == T_IDENTIFIER) {
9566 label_t *const label = get_label();
9568 statement->gotos.label = label;
9571 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9573 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9575 return create_invalid_statement();
9578 /* remember the goto's in a list for later checking */
9579 *goto_anchor = &statement->gotos;
9580 goto_anchor = &statement->gotos.next;
9582 expect(';', end_error);
9589 * Parse a continue statement.
9591 static statement_t *parse_continue(void)
9593 if (current_loop == NULL) {
9594 errorf(HERE, "continue statement not within loop");
9597 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9600 expect(';', end_error);
9607 * Parse a break statement.
9609 static statement_t *parse_break(void)
9611 if (current_switch == NULL && current_loop == NULL) {
9612 errorf(HERE, "break statement not within loop or switch");
9615 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9618 expect(';', end_error);
9625 * Parse a __leave statement.
9627 static statement_t *parse_leave_statement(void)
9629 if (current_try == NULL) {
9630 errorf(HERE, "__leave statement not within __try");
9633 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9636 expect(';', end_error);
9643 * Check if a given entity represents a local variable.
9645 static bool is_local_variable(const entity_t *entity)
9647 if (entity->kind != ENTITY_VARIABLE)
9650 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9651 case STORAGE_CLASS_AUTO:
9652 case STORAGE_CLASS_REGISTER: {
9653 const type_t *type = skip_typeref(entity->declaration.type);
9654 if (is_type_function(type)) {
9666 * Check if a given expression represents a local variable.
9668 static bool expression_is_local_variable(const expression_t *expression)
9670 if (expression->base.kind != EXPR_REFERENCE) {
9673 const entity_t *entity = expression->reference.entity;
9674 return is_local_variable(entity);
9678 * Check if a given expression represents a local variable and
9679 * return its declaration then, else return NULL.
9681 entity_t *expression_is_variable(const expression_t *expression)
9683 if (expression->base.kind != EXPR_REFERENCE) {
9686 entity_t *entity = expression->reference.entity;
9687 if (entity->kind != ENTITY_VARIABLE)
9694 * Parse a return statement.
9696 static statement_t *parse_return(void)
9698 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9701 expression_t *return_value = NULL;
9702 if (token.type != ';') {
9703 return_value = parse_expression();
9704 mark_vars_read(return_value, NULL);
9707 const type_t *const func_type = skip_typeref(current_function->base.type);
9708 assert(is_type_function(func_type));
9709 type_t *const return_type = skip_typeref(func_type->function.return_type);
9711 source_position_t const *const pos = &statement->base.source_position;
9712 if (return_value != NULL) {
9713 type_t *return_value_type = skip_typeref(return_value->base.type);
9715 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9716 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9717 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9718 /* Only warn in C mode, because GCC does the same */
9719 if (c_mode & _CXX || strict_mode) {
9721 "'return' with a value, in function returning 'void'");
9723 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9725 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9726 /* Only warn in C mode, because GCC does the same */
9729 "'return' with expression in function returning 'void'");
9731 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9735 assign_error_t error = semantic_assign(return_type, return_value);
9736 report_assign_error(error, return_type, return_value, "'return'",
9739 return_value = create_implicit_cast(return_value, return_type);
9740 /* check for returning address of a local var */
9741 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9742 const expression_t *expression = return_value->unary.value;
9743 if (expression_is_local_variable(expression)) {
9744 warningf(WARN_OTHER, pos, "function returns address of local variable");
9747 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9748 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9749 if (c_mode & _CXX || strict_mode) {
9751 "'return' without value, in function returning non-void");
9753 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9756 statement->returns.value = return_value;
9758 expect(';', end_error);
9765 * Parse a declaration statement.
9767 static statement_t *parse_declaration_statement(void)
9769 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9771 entity_t *before = current_scope->last_entity;
9773 parse_external_declaration();
9775 parse_declaration(record_entity, DECL_FLAGS_NONE);
9778 declaration_statement_t *const decl = &statement->declaration;
9779 entity_t *const begin =
9780 before != NULL ? before->base.next : current_scope->entities;
9781 decl->declarations_begin = begin;
9782 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9788 * Parse an expression statement, ie. expr ';'.
9790 static statement_t *parse_expression_statement(void)
9792 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9794 expression_t *const expr = parse_expression();
9795 statement->expression.expression = expr;
9796 mark_vars_read(expr, ENT_ANY);
9798 expect(';', end_error);
9805 * Parse a microsoft __try { } __finally { } or
9806 * __try{ } __except() { }
9808 static statement_t *parse_ms_try_statment(void)
9810 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9813 PUSH_PARENT(statement);
9815 ms_try_statement_t *rem = current_try;
9816 current_try = &statement->ms_try;
9817 statement->ms_try.try_statement = parse_compound_statement(false);
9822 if (next_if(T___except)) {
9823 expect('(', end_error);
9824 add_anchor_token(')');
9825 expression_t *const expr = parse_expression();
9826 mark_vars_read(expr, NULL);
9827 type_t * type = skip_typeref(expr->base.type);
9828 if (is_type_integer(type)) {
9829 type = promote_integer(type);
9830 } else if (is_type_valid(type)) {
9831 errorf(&expr->base.source_position,
9832 "__expect expression is not an integer, but '%T'", type);
9833 type = type_error_type;
9835 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9836 rem_anchor_token(')');
9837 expect(')', end_error);
9838 statement->ms_try.final_statement = parse_compound_statement(false);
9839 } else if (next_if(T__finally)) {
9840 statement->ms_try.final_statement = parse_compound_statement(false);
9842 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9843 return create_invalid_statement();
9847 return create_invalid_statement();
9850 static statement_t *parse_empty_statement(void)
9852 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9853 statement_t *const statement = create_empty_statement();
9858 static statement_t *parse_local_label_declaration(void)
9860 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9864 entity_t *begin = NULL;
9865 entity_t *end = NULL;
9866 entity_t **anchor = &begin;
9868 if (token.type != T_IDENTIFIER) {
9869 parse_error_expected("while parsing local label declaration",
9870 T_IDENTIFIER, NULL);
9873 symbol_t *symbol = token.symbol;
9874 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9875 if (entity != NULL && entity->base.parent_scope == current_scope) {
9876 source_position_t const *const ppos = &entity->base.source_position;
9877 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9879 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9880 entity->base.parent_scope = current_scope;
9881 entity->base.source_position = token.source_position;
9884 anchor = &entity->base.next;
9887 environment_push(entity);
9890 } while (next_if(','));
9891 expect(';', end_error);
9893 statement->declaration.declarations_begin = begin;
9894 statement->declaration.declarations_end = end;
9898 static void parse_namespace_definition(void)
9902 entity_t *entity = NULL;
9903 symbol_t *symbol = NULL;
9905 if (token.type == T_IDENTIFIER) {
9906 symbol = token.symbol;
9909 entity = get_entity(symbol, NAMESPACE_NORMAL);
9911 && entity->kind != ENTITY_NAMESPACE
9912 && entity->base.parent_scope == current_scope) {
9913 if (is_entity_valid(entity)) {
9914 error_redefined_as_different_kind(&token.source_position,
9915 entity, ENTITY_NAMESPACE);
9921 if (entity == NULL) {
9922 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9923 entity->base.source_position = token.source_position;
9924 entity->base.parent_scope = current_scope;
9927 if (token.type == '=') {
9928 /* TODO: parse namespace alias */
9929 panic("namespace alias definition not supported yet");
9932 environment_push(entity);
9933 append_entity(current_scope, entity);
9935 PUSH_SCOPE(&entity->namespacee.members);
9937 entity_t *old_current_entity = current_entity;
9938 current_entity = entity;
9940 expect('{', end_error);
9942 expect('}', end_error);
9945 assert(current_entity == entity);
9946 current_entity = old_current_entity;
9951 * Parse a statement.
9952 * There's also parse_statement() which additionally checks for
9953 * "statement has no effect" warnings
9955 static statement_t *intern_parse_statement(void)
9957 statement_t *statement = NULL;
9959 /* declaration or statement */
9960 add_anchor_token(';');
9961 switch (token.type) {
9962 case T_IDENTIFIER: {
9963 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9964 if (la1_type == ':') {
9965 statement = parse_label_statement();
9966 } else if (is_typedef_symbol(token.symbol)) {
9967 statement = parse_declaration_statement();
9969 /* it's an identifier, the grammar says this must be an
9970 * expression statement. However it is common that users mistype
9971 * declaration types, so we guess a bit here to improve robustness
9972 * for incorrect programs */
9976 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
9978 statement = parse_expression_statement();
9982 statement = parse_declaration_statement();
9990 case T___extension__: {
9991 /* This can be a prefix to a declaration or an expression statement.
9992 * We simply eat it now and parse the rest with tail recursion. */
9994 statement = intern_parse_statement();
10000 statement = parse_declaration_statement();
10004 statement = parse_local_label_declaration();
10007 case ';': statement = parse_empty_statement(); break;
10008 case '{': statement = parse_compound_statement(false); break;
10009 case T___leave: statement = parse_leave_statement(); break;
10010 case T___try: statement = parse_ms_try_statment(); break;
10011 case T_asm: statement = parse_asm_statement(); break;
10012 case T_break: statement = parse_break(); break;
10013 case T_case: statement = parse_case_statement(); break;
10014 case T_continue: statement = parse_continue(); break;
10015 case T_default: statement = parse_default_statement(); break;
10016 case T_do: statement = parse_do(); break;
10017 case T_for: statement = parse_for(); break;
10018 case T_goto: statement = parse_goto(); break;
10019 case T_if: statement = parse_if(); break;
10020 case T_return: statement = parse_return(); break;
10021 case T_switch: statement = parse_switch(); break;
10022 case T_while: statement = parse_while(); break;
10025 statement = parse_expression_statement();
10029 errorf(HERE, "unexpected token %K while parsing statement", &token);
10030 statement = create_invalid_statement();
10035 rem_anchor_token(';');
10037 assert(statement != NULL
10038 && statement->base.source_position.input_name != NULL);
10044 * parse a statement and emits "statement has no effect" warning if needed
10045 * (This is really a wrapper around intern_parse_statement with check for 1
10046 * single warning. It is needed, because for statement expressions we have
10047 * to avoid the warning on the last statement)
10049 static statement_t *parse_statement(void)
10051 statement_t *statement = intern_parse_statement();
10053 if (statement->kind == STATEMENT_EXPRESSION) {
10054 expression_t *expression = statement->expression.expression;
10055 if (!expression_has_effect(expression)) {
10056 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10064 * Parse a compound statement.
10066 static statement_t *parse_compound_statement(bool inside_expression_statement)
10068 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10070 PUSH_PARENT(statement);
10071 PUSH_SCOPE(&statement->compound.scope);
10074 add_anchor_token('}');
10075 /* tokens, which can start a statement */
10076 /* TODO MS, __builtin_FOO */
10077 add_anchor_token('!');
10078 add_anchor_token('&');
10079 add_anchor_token('(');
10080 add_anchor_token('*');
10081 add_anchor_token('+');
10082 add_anchor_token('-');
10083 add_anchor_token('{');
10084 add_anchor_token('~');
10085 add_anchor_token(T_CHARACTER_CONSTANT);
10086 add_anchor_token(T_COLONCOLON);
10087 add_anchor_token(T_FLOATINGPOINT);
10088 add_anchor_token(T_IDENTIFIER);
10089 add_anchor_token(T_INTEGER);
10090 add_anchor_token(T_MINUSMINUS);
10091 add_anchor_token(T_PLUSPLUS);
10092 add_anchor_token(T_STRING_LITERAL);
10093 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10094 add_anchor_token(T_WIDE_STRING_LITERAL);
10095 add_anchor_token(T__Bool);
10096 add_anchor_token(T__Complex);
10097 add_anchor_token(T__Imaginary);
10098 add_anchor_token(T___FUNCTION__);
10099 add_anchor_token(T___PRETTY_FUNCTION__);
10100 add_anchor_token(T___alignof__);
10101 add_anchor_token(T___attribute__);
10102 add_anchor_token(T___builtin_va_start);
10103 add_anchor_token(T___extension__);
10104 add_anchor_token(T___func__);
10105 add_anchor_token(T___imag__);
10106 add_anchor_token(T___label__);
10107 add_anchor_token(T___real__);
10108 add_anchor_token(T___thread);
10109 add_anchor_token(T_asm);
10110 add_anchor_token(T_auto);
10111 add_anchor_token(T_bool);
10112 add_anchor_token(T_break);
10113 add_anchor_token(T_case);
10114 add_anchor_token(T_char);
10115 add_anchor_token(T_class);
10116 add_anchor_token(T_const);
10117 add_anchor_token(T_const_cast);
10118 add_anchor_token(T_continue);
10119 add_anchor_token(T_default);
10120 add_anchor_token(T_delete);
10121 add_anchor_token(T_double);
10122 add_anchor_token(T_do);
10123 add_anchor_token(T_dynamic_cast);
10124 add_anchor_token(T_enum);
10125 add_anchor_token(T_extern);
10126 add_anchor_token(T_false);
10127 add_anchor_token(T_float);
10128 add_anchor_token(T_for);
10129 add_anchor_token(T_goto);
10130 add_anchor_token(T_if);
10131 add_anchor_token(T_inline);
10132 add_anchor_token(T_int);
10133 add_anchor_token(T_long);
10134 add_anchor_token(T_new);
10135 add_anchor_token(T_operator);
10136 add_anchor_token(T_register);
10137 add_anchor_token(T_reinterpret_cast);
10138 add_anchor_token(T_restrict);
10139 add_anchor_token(T_return);
10140 add_anchor_token(T_short);
10141 add_anchor_token(T_signed);
10142 add_anchor_token(T_sizeof);
10143 add_anchor_token(T_static);
10144 add_anchor_token(T_static_cast);
10145 add_anchor_token(T_struct);
10146 add_anchor_token(T_switch);
10147 add_anchor_token(T_template);
10148 add_anchor_token(T_this);
10149 add_anchor_token(T_throw);
10150 add_anchor_token(T_true);
10151 add_anchor_token(T_try);
10152 add_anchor_token(T_typedef);
10153 add_anchor_token(T_typeid);
10154 add_anchor_token(T_typename);
10155 add_anchor_token(T_typeof);
10156 add_anchor_token(T_union);
10157 add_anchor_token(T_unsigned);
10158 add_anchor_token(T_using);
10159 add_anchor_token(T_void);
10160 add_anchor_token(T_volatile);
10161 add_anchor_token(T_wchar_t);
10162 add_anchor_token(T_while);
10164 statement_t **anchor = &statement->compound.statements;
10165 bool only_decls_so_far = true;
10166 while (token.type != '}') {
10167 if (token.type == T_EOF) {
10168 errorf(&statement->base.source_position,
10169 "EOF while parsing compound statement");
10172 statement_t *sub_statement = intern_parse_statement();
10173 if (is_invalid_statement(sub_statement)) {
10174 /* an error occurred. if we are at an anchor, return */
10180 if (sub_statement->kind != STATEMENT_DECLARATION) {
10181 only_decls_so_far = false;
10182 } else if (!only_decls_so_far) {
10183 source_position_t const *const pos = &sub_statement->base.source_position;
10184 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10187 *anchor = sub_statement;
10189 while (sub_statement->base.next != NULL)
10190 sub_statement = sub_statement->base.next;
10192 anchor = &sub_statement->base.next;
10196 /* look over all statements again to produce no effect warnings */
10197 if (is_warn_on(WARN_UNUSED_VALUE)) {
10198 statement_t *sub_statement = statement->compound.statements;
10199 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10200 if (sub_statement->kind != STATEMENT_EXPRESSION)
10202 /* don't emit a warning for the last expression in an expression
10203 * statement as it has always an effect */
10204 if (inside_expression_statement && sub_statement->base.next == NULL)
10207 expression_t *expression = sub_statement->expression.expression;
10208 if (!expression_has_effect(expression)) {
10209 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10215 rem_anchor_token(T_while);
10216 rem_anchor_token(T_wchar_t);
10217 rem_anchor_token(T_volatile);
10218 rem_anchor_token(T_void);
10219 rem_anchor_token(T_using);
10220 rem_anchor_token(T_unsigned);
10221 rem_anchor_token(T_union);
10222 rem_anchor_token(T_typeof);
10223 rem_anchor_token(T_typename);
10224 rem_anchor_token(T_typeid);
10225 rem_anchor_token(T_typedef);
10226 rem_anchor_token(T_try);
10227 rem_anchor_token(T_true);
10228 rem_anchor_token(T_throw);
10229 rem_anchor_token(T_this);
10230 rem_anchor_token(T_template);
10231 rem_anchor_token(T_switch);
10232 rem_anchor_token(T_struct);
10233 rem_anchor_token(T_static_cast);
10234 rem_anchor_token(T_static);
10235 rem_anchor_token(T_sizeof);
10236 rem_anchor_token(T_signed);
10237 rem_anchor_token(T_short);
10238 rem_anchor_token(T_return);
10239 rem_anchor_token(T_restrict);
10240 rem_anchor_token(T_reinterpret_cast);
10241 rem_anchor_token(T_register);
10242 rem_anchor_token(T_operator);
10243 rem_anchor_token(T_new);
10244 rem_anchor_token(T_long);
10245 rem_anchor_token(T_int);
10246 rem_anchor_token(T_inline);
10247 rem_anchor_token(T_if);
10248 rem_anchor_token(T_goto);
10249 rem_anchor_token(T_for);
10250 rem_anchor_token(T_float);
10251 rem_anchor_token(T_false);
10252 rem_anchor_token(T_extern);
10253 rem_anchor_token(T_enum);
10254 rem_anchor_token(T_dynamic_cast);
10255 rem_anchor_token(T_do);
10256 rem_anchor_token(T_double);
10257 rem_anchor_token(T_delete);
10258 rem_anchor_token(T_default);
10259 rem_anchor_token(T_continue);
10260 rem_anchor_token(T_const_cast);
10261 rem_anchor_token(T_const);
10262 rem_anchor_token(T_class);
10263 rem_anchor_token(T_char);
10264 rem_anchor_token(T_case);
10265 rem_anchor_token(T_break);
10266 rem_anchor_token(T_bool);
10267 rem_anchor_token(T_auto);
10268 rem_anchor_token(T_asm);
10269 rem_anchor_token(T___thread);
10270 rem_anchor_token(T___real__);
10271 rem_anchor_token(T___label__);
10272 rem_anchor_token(T___imag__);
10273 rem_anchor_token(T___func__);
10274 rem_anchor_token(T___extension__);
10275 rem_anchor_token(T___builtin_va_start);
10276 rem_anchor_token(T___attribute__);
10277 rem_anchor_token(T___alignof__);
10278 rem_anchor_token(T___PRETTY_FUNCTION__);
10279 rem_anchor_token(T___FUNCTION__);
10280 rem_anchor_token(T__Imaginary);
10281 rem_anchor_token(T__Complex);
10282 rem_anchor_token(T__Bool);
10283 rem_anchor_token(T_WIDE_STRING_LITERAL);
10284 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10285 rem_anchor_token(T_STRING_LITERAL);
10286 rem_anchor_token(T_PLUSPLUS);
10287 rem_anchor_token(T_MINUSMINUS);
10288 rem_anchor_token(T_INTEGER);
10289 rem_anchor_token(T_IDENTIFIER);
10290 rem_anchor_token(T_FLOATINGPOINT);
10291 rem_anchor_token(T_COLONCOLON);
10292 rem_anchor_token(T_CHARACTER_CONSTANT);
10293 rem_anchor_token('~');
10294 rem_anchor_token('{');
10295 rem_anchor_token('-');
10296 rem_anchor_token('+');
10297 rem_anchor_token('*');
10298 rem_anchor_token('(');
10299 rem_anchor_token('&');
10300 rem_anchor_token('!');
10301 rem_anchor_token('}');
10309 * Check for unused global static functions and variables
10311 static void check_unused_globals(void)
10313 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10316 for (const entity_t *entity = file_scope->entities; entity != NULL;
10317 entity = entity->base.next) {
10318 if (!is_declaration(entity))
10321 const declaration_t *declaration = &entity->declaration;
10322 if (declaration->used ||
10323 declaration->modifiers & DM_UNUSED ||
10324 declaration->modifiers & DM_USED ||
10325 declaration->storage_class != STORAGE_CLASS_STATIC)
10330 if (entity->kind == ENTITY_FUNCTION) {
10331 /* inhibit warning for static inline functions */
10332 if (entity->function.is_inline)
10335 why = WARN_UNUSED_FUNCTION;
10336 s = entity->function.statement != NULL ? "defined" : "declared";
10338 why = WARN_UNUSED_VARIABLE;
10342 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10346 static void parse_global_asm(void)
10348 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10351 expect('(', end_error);
10353 statement->asms.asm_text = parse_string_literals();
10354 statement->base.next = unit->global_asm;
10355 unit->global_asm = statement;
10357 expect(')', end_error);
10358 expect(';', end_error);
10363 static void parse_linkage_specification(void)
10367 source_position_t const pos = *HERE;
10368 char const *const linkage = parse_string_literals().begin;
10370 linkage_kind_t old_linkage = current_linkage;
10371 linkage_kind_t new_linkage;
10372 if (strcmp(linkage, "C") == 0) {
10373 new_linkage = LINKAGE_C;
10374 } else if (strcmp(linkage, "C++") == 0) {
10375 new_linkage = LINKAGE_CXX;
10377 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10378 new_linkage = LINKAGE_INVALID;
10380 current_linkage = new_linkage;
10382 if (next_if('{')) {
10384 expect('}', end_error);
10390 assert(current_linkage == new_linkage);
10391 current_linkage = old_linkage;
10394 static void parse_external(void)
10396 switch (token.type) {
10398 if (look_ahead(1)->type == T_STRING_LITERAL) {
10399 parse_linkage_specification();
10401 DECLARATION_START_NO_EXTERN
10403 case T___extension__:
10404 /* tokens below are for implicit int */
10405 case '&': /* & x; -> int& x; (and error later, because C++ has no
10407 case '*': /* * x; -> int* x; */
10408 case '(': /* (x); -> int (x); */
10410 parse_external_declaration();
10416 parse_global_asm();
10420 parse_namespace_definition();
10424 if (!strict_mode) {
10425 warningf(WARN_OTHER, HERE, "stray ';' outside of function");
10432 errorf(HERE, "stray %K outside of function", &token);
10433 if (token.type == '(' || token.type == '{' || token.type == '[')
10434 eat_until_matching_token(token.type);
10440 static void parse_externals(void)
10442 add_anchor_token('}');
10443 add_anchor_token(T_EOF);
10446 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10447 unsigned char token_anchor_copy[T_LAST_TOKEN];
10448 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10451 while (token.type != T_EOF && token.type != '}') {
10453 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10454 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10456 /* the anchor set and its copy differs */
10457 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10460 if (in_gcc_extension) {
10461 /* an gcc extension scope was not closed */
10462 internal_errorf(HERE, "Leaked __extension__");
10469 rem_anchor_token(T_EOF);
10470 rem_anchor_token('}');
10474 * Parse a translation unit.
10476 static void parse_translation_unit(void)
10478 add_anchor_token(T_EOF);
10483 if (token.type == T_EOF)
10486 errorf(HERE, "stray %K outside of function", &token);
10487 if (token.type == '(' || token.type == '{' || token.type == '[')
10488 eat_until_matching_token(token.type);
10493 void set_default_visibility(elf_visibility_tag_t visibility)
10495 default_visibility = visibility;
10501 * @return the translation unit or NULL if errors occurred.
10503 void start_parsing(void)
10505 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10506 label_stack = NEW_ARR_F(stack_entry_t, 0);
10507 diagnostic_count = 0;
10511 print_to_file(stderr);
10513 assert(unit == NULL);
10514 unit = allocate_ast_zero(sizeof(unit[0]));
10516 assert(file_scope == NULL);
10517 file_scope = &unit->scope;
10519 assert(current_scope == NULL);
10520 scope_push(&unit->scope);
10522 create_gnu_builtins();
10524 create_microsoft_intrinsics();
10527 translation_unit_t *finish_parsing(void)
10529 assert(current_scope == &unit->scope);
10532 assert(file_scope == &unit->scope);
10533 check_unused_globals();
10536 DEL_ARR_F(environment_stack);
10537 DEL_ARR_F(label_stack);
10539 translation_unit_t *result = unit;
10544 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10545 * are given length one. */
10546 static void complete_incomplete_arrays(void)
10548 size_t n = ARR_LEN(incomplete_arrays);
10549 for (size_t i = 0; i != n; ++i) {
10550 declaration_t *const decl = incomplete_arrays[i];
10551 type_t *const type = skip_typeref(decl->type);
10553 if (!is_type_incomplete(type))
10556 source_position_t const *const pos = &decl->base.source_position;
10557 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10559 type_t *const new_type = duplicate_type(type);
10560 new_type->array.size_constant = true;
10561 new_type->array.has_implicit_size = true;
10562 new_type->array.size = 1;
10564 type_t *const result = identify_new_type(new_type);
10566 decl->type = result;
10570 void prepare_main_collect2(entity_t *entity)
10572 // create call to __main
10573 symbol_t *symbol = symbol_table_insert("__main");
10574 entity_t *subsubmain_ent
10575 = create_implicit_function(symbol, &builtin_source_position);
10577 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10578 type_t *ftype = subsubmain_ent->declaration.type;
10579 ref->base.source_position = builtin_source_position;
10580 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10581 ref->reference.entity = subsubmain_ent;
10583 expression_t *call = allocate_expression_zero(EXPR_CALL);
10584 call->base.source_position = builtin_source_position;
10585 call->base.type = type_void;
10586 call->call.function = ref;
10588 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10589 expr_statement->base.source_position = builtin_source_position;
10590 expr_statement->expression.expression = call;
10592 statement_t *statement = entity->function.statement;
10593 assert(statement->kind == STATEMENT_COMPOUND);
10594 compound_statement_t *compounds = &statement->compound;
10596 expr_statement->base.next = compounds->statements;
10597 compounds->statements = expr_statement;
10602 lookahead_bufpos = 0;
10603 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10606 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10607 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10608 parse_translation_unit();
10609 complete_incomplete_arrays();
10610 DEL_ARR_F(incomplete_arrays);
10611 incomplete_arrays = NULL;
10615 * Initialize the parser.
10617 void init_parser(void)
10619 sym_anonymous = symbol_table_insert("<anonymous>");
10621 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10623 init_expression_parsers();
10624 obstack_init(&temp_obst);
10628 * Terminate the parser.
10630 void exit_parser(void)
10632 obstack_free(&temp_obst, NULL);