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 entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
113 #define PUSH_PARENT(stmt) \
114 statement_t *const prev_parent = current_parent; \
115 ((void)(current_parent = (stmt)))
116 #define POP_PARENT ((void)(current_parent = prev_parent))
118 /** special symbol used for anonymous entities. */
119 static symbol_t *sym_anonymous = NULL;
121 /** The token anchor set */
122 static unsigned char token_anchor_set[T_LAST_TOKEN];
124 /** The current source position. */
125 #define HERE (&token.source_position)
127 /** true if we are in GCC mode. */
128 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
130 static statement_t *parse_compound_statement(bool inside_expression_statement);
131 static statement_t *parse_statement(void);
133 static expression_t *parse_sub_expression(precedence_t);
134 static expression_t *parse_expression(void);
135 static type_t *parse_typename(void);
136 static void parse_externals(void);
137 static void parse_external(void);
139 static void parse_compound_type_entries(compound_t *compound_declaration);
141 static void check_call_argument(type_t *expected_type,
142 call_argument_t *argument, unsigned pos);
144 typedef enum declarator_flags_t {
146 DECL_MAY_BE_ABSTRACT = 1U << 0,
147 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
148 DECL_IS_PARAMETER = 1U << 2
149 } declarator_flags_t;
151 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
152 declarator_flags_t flags);
154 static void semantic_comparison(binary_expression_t *expression);
156 #define STORAGE_CLASSES \
157 STORAGE_CLASSES_NO_EXTERN \
160 #define STORAGE_CLASSES_NO_EXTERN \
167 #define TYPE_QUALIFIERS \
172 case T__forceinline: \
173 case T___attribute__:
175 #define COMPLEX_SPECIFIERS \
177 #define IMAGINARY_SPECIFIERS \
180 #define TYPE_SPECIFIERS \
182 case T___builtin_va_list: \
207 #define DECLARATION_START \
212 #define DECLARATION_START_NO_EXTERN \
213 STORAGE_CLASSES_NO_EXTERN \
217 #define TYPENAME_START \
221 #define EXPRESSION_START \
230 case T_CHARACTER_CONSTANT: \
231 case T_FLOATINGPOINT: \
235 case T_STRING_LITERAL: \
236 case T_WIDE_CHARACTER_CONSTANT: \
237 case T_WIDE_STRING_LITERAL: \
238 case T___FUNCDNAME__: \
239 case T___FUNCSIG__: \
240 case T___FUNCTION__: \
241 case T___PRETTY_FUNCTION__: \
242 case T___alignof__: \
243 case T___builtin_classify_type: \
244 case T___builtin_constant_p: \
245 case T___builtin_isgreater: \
246 case T___builtin_isgreaterequal: \
247 case T___builtin_isless: \
248 case T___builtin_islessequal: \
249 case T___builtin_islessgreater: \
250 case T___builtin_isunordered: \
251 case T___builtin_offsetof: \
252 case T___builtin_va_arg: \
253 case T___builtin_va_start: \
254 case T___builtin_va_copy: \
265 * Returns the size of a statement node.
267 * @param kind the statement kind
269 static size_t get_statement_struct_size(statement_kind_t kind)
271 static const size_t sizes[] = {
272 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
273 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
274 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
275 [STATEMENT_RETURN] = sizeof(return_statement_t),
276 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
277 [STATEMENT_IF] = sizeof(if_statement_t),
278 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
279 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
280 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
281 [STATEMENT_BREAK] = sizeof(statement_base_t),
282 [STATEMENT_GOTO] = sizeof(goto_statement_t),
283 [STATEMENT_LABEL] = sizeof(label_statement_t),
284 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
285 [STATEMENT_WHILE] = sizeof(while_statement_t),
286 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
287 [STATEMENT_FOR] = sizeof(for_statement_t),
288 [STATEMENT_ASM] = sizeof(asm_statement_t),
289 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
290 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
292 assert(kind < lengthof(sizes));
293 assert(sizes[kind] != 0);
298 * Returns the size of an expression node.
300 * @param kind the expression kind
302 static size_t get_expression_struct_size(expression_kind_t kind)
304 static const size_t sizes[] = {
305 [EXPR_INVALID] = sizeof(expression_base_t),
306 [EXPR_REFERENCE] = sizeof(reference_expression_t),
307 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
308 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
309 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
310 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
311 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
312 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
314 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
315 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
316 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
317 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
318 [EXPR_CALL] = sizeof(call_expression_t),
319 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
320 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
321 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
322 [EXPR_SELECT] = sizeof(select_expression_t),
323 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
324 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
325 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
326 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
327 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
328 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
329 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
330 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
331 [EXPR_VA_START] = sizeof(va_start_expression_t),
332 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
333 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
334 [EXPR_STATEMENT] = sizeof(statement_expression_t),
335 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
337 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
338 return sizes[EXPR_UNARY_FIRST];
340 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
341 return sizes[EXPR_BINARY_FIRST];
343 assert(kind < lengthof(sizes));
344 assert(sizes[kind] != 0);
349 * Allocate a statement node of given kind and initialize all
350 * fields with zero. Sets its source position to the position
351 * of the current token.
353 static statement_t *allocate_statement_zero(statement_kind_t kind)
355 size_t size = get_statement_struct_size(kind);
356 statement_t *res = allocate_ast_zero(size);
358 res->base.kind = kind;
359 res->base.parent = current_parent;
360 res->base.source_position = token.source_position;
365 * Allocate an expression node of given kind and initialize all
368 * @param kind the kind of the expression to allocate
370 static expression_t *allocate_expression_zero(expression_kind_t kind)
372 size_t size = get_expression_struct_size(kind);
373 expression_t *res = allocate_ast_zero(size);
375 res->base.kind = kind;
376 res->base.type = type_error_type;
377 res->base.source_position = token.source_position;
382 * Creates a new invalid expression at the source position
383 * of the current token.
385 static expression_t *create_invalid_expression(void)
387 return allocate_expression_zero(EXPR_INVALID);
391 * Creates a new invalid statement.
393 static statement_t *create_invalid_statement(void)
395 return allocate_statement_zero(STATEMENT_INVALID);
399 * Allocate a new empty statement.
401 static statement_t *create_empty_statement(void)
403 return allocate_statement_zero(STATEMENT_EMPTY);
406 static function_parameter_t *allocate_parameter(type_t *const type)
408 function_parameter_t *const param
409 = obstack_alloc(type_obst, sizeof(*param));
410 memset(param, 0, sizeof(*param));
416 * Returns the size of an initializer node.
418 * @param kind the initializer kind
420 static size_t get_initializer_size(initializer_kind_t kind)
422 static const size_t sizes[] = {
423 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
424 [INITIALIZER_STRING] = sizeof(initializer_string_t),
425 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
426 [INITIALIZER_LIST] = sizeof(initializer_list_t),
427 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
429 assert(kind < lengthof(sizes));
430 assert(sizes[kind] != 0);
435 * Allocate an initializer node of given kind and initialize all
438 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
440 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
447 * Returns the index of the top element of the environment stack.
449 static size_t environment_top(void)
451 return ARR_LEN(environment_stack);
455 * Returns the index of the top element of the global label stack.
457 static size_t label_top(void)
459 return ARR_LEN(label_stack);
463 * Return the next token.
465 static inline void next_token(void)
467 token = lookahead_buffer[lookahead_bufpos];
468 lookahead_buffer[lookahead_bufpos] = lexer_token;
471 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
474 print_token(stderr, &token);
475 fprintf(stderr, "\n");
479 static inline bool next_if(int const type)
481 if (token.type == type) {
490 * Return the next token with a given lookahead.
492 static inline const token_t *look_ahead(size_t num)
494 assert(0 < num && num <= MAX_LOOKAHEAD);
495 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
496 return &lookahead_buffer[pos];
500 * Adds a token type to the token type anchor set (a multi-set).
502 static void add_anchor_token(int token_type)
504 assert(0 <= token_type && token_type < T_LAST_TOKEN);
505 ++token_anchor_set[token_type];
509 * Set the number of tokens types of the given type
510 * to zero and return the old count.
512 static int save_and_reset_anchor_state(int token_type)
514 assert(0 <= token_type && token_type < T_LAST_TOKEN);
515 int count = token_anchor_set[token_type];
516 token_anchor_set[token_type] = 0;
521 * Restore the number of token types to the given count.
523 static void restore_anchor_state(int token_type, int count)
525 assert(0 <= token_type && token_type < T_LAST_TOKEN);
526 token_anchor_set[token_type] = count;
530 * Remove a token type from the token type anchor set (a multi-set).
532 static void rem_anchor_token(int token_type)
534 assert(0 <= token_type && token_type < T_LAST_TOKEN);
535 assert(token_anchor_set[token_type] != 0);
536 --token_anchor_set[token_type];
540 * Return true if the token type of the current token is
543 static bool at_anchor(void)
547 return token_anchor_set[token.type];
551 * Eat tokens until a matching token type is found.
553 static void eat_until_matching_token(int type)
557 case '(': end_token = ')'; break;
558 case '{': end_token = '}'; break;
559 case '[': end_token = ']'; break;
560 default: end_token = type; break;
563 unsigned parenthesis_count = 0;
564 unsigned brace_count = 0;
565 unsigned bracket_count = 0;
566 while (token.type != end_token ||
567 parenthesis_count != 0 ||
569 bracket_count != 0) {
570 switch (token.type) {
572 case '(': ++parenthesis_count; break;
573 case '{': ++brace_count; break;
574 case '[': ++bracket_count; break;
577 if (parenthesis_count > 0)
587 if (bracket_count > 0)
590 if (token.type == end_token &&
591 parenthesis_count == 0 &&
605 * Eat input tokens until an anchor is found.
607 static void eat_until_anchor(void)
609 while (token_anchor_set[token.type] == 0) {
610 if (token.type == '(' || token.type == '{' || token.type == '[')
611 eat_until_matching_token(token.type);
617 * Eat a whole block from input tokens.
619 static void eat_block(void)
621 eat_until_matching_token('{');
625 #define eat(token_type) (assert(token.type == (token_type)), next_token())
628 * Report a parse error because an expected token was not found.
631 #if defined __GNUC__ && __GNUC__ >= 4
632 __attribute__((sentinel))
634 void parse_error_expected(const char *message, ...)
636 if (message != NULL) {
637 errorf(HERE, "%s", message);
640 va_start(ap, message);
641 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
646 * Report an incompatible type.
648 static void type_error_incompatible(const char *msg,
649 const source_position_t *source_position, type_t *type1, type_t *type2)
651 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
656 * Expect the current token is the expected token.
657 * If not, generate an error, eat the current statement,
658 * and goto the end_error label.
660 #define expect(expected, error_label) \
662 if (UNLIKELY(token.type != (expected))) { \
663 parse_error_expected(NULL, (expected), NULL); \
664 add_anchor_token(expected); \
665 eat_until_anchor(); \
666 next_if((expected)); \
667 rem_anchor_token(expected); \
674 * Push a given scope on the scope stack and make it the
677 static scope_t *scope_push(scope_t *new_scope)
679 if (current_scope != NULL) {
680 new_scope->depth = current_scope->depth + 1;
683 scope_t *old_scope = current_scope;
684 current_scope = new_scope;
689 * Pop the current scope from the scope stack.
691 static void scope_pop(scope_t *old_scope)
693 current_scope = old_scope;
697 * Search an entity by its symbol in a given namespace.
699 static entity_t *get_entity(const symbol_t *const symbol,
700 namespace_tag_t namespc)
702 entity_t *entity = symbol->entity;
703 for (; entity != NULL; entity = entity->base.symbol_next) {
704 if (entity->base.namespc == namespc)
711 /* §6.2.3:1 24) There is only one name space for tags even though three are
713 static entity_t *get_tag(symbol_t const *const symbol,
714 entity_kind_tag_t const kind)
716 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
717 if (entity != NULL && entity->kind != kind) {
719 "'%Y' defined as wrong kind of tag (previous definition %P)",
720 symbol, &entity->base.source_position);
727 * pushs an entity on the environment stack and links the corresponding symbol
730 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
732 symbol_t *symbol = entity->base.symbol;
733 entity_namespace_t namespc = entity->base.namespc;
734 assert(namespc != NAMESPACE_INVALID);
736 /* replace/add entity into entity list of the symbol */
739 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
744 /* replace an entry? */
745 if (iter->base.namespc == namespc) {
746 entity->base.symbol_next = iter->base.symbol_next;
752 /* remember old declaration */
754 entry.symbol = symbol;
755 entry.old_entity = iter;
756 entry.namespc = namespc;
757 ARR_APP1(stack_entry_t, *stack_ptr, entry);
761 * Push an entity on the environment stack.
763 static void environment_push(entity_t *entity)
765 assert(entity->base.source_position.input_name != NULL);
766 assert(entity->base.parent_scope != NULL);
767 stack_push(&environment_stack, entity);
771 * Push a declaration on the global label stack.
773 * @param declaration the declaration
775 static void label_push(entity_t *label)
777 /* we abuse the parameters scope as parent for the labels */
778 label->base.parent_scope = ¤t_function->parameters;
779 stack_push(&label_stack, label);
783 * pops symbols from the environment stack until @p new_top is the top element
785 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
787 stack_entry_t *stack = *stack_ptr;
788 size_t top = ARR_LEN(stack);
791 assert(new_top <= top);
795 for (i = top; i > new_top; --i) {
796 stack_entry_t *entry = &stack[i - 1];
798 entity_t *old_entity = entry->old_entity;
799 symbol_t *symbol = entry->symbol;
800 entity_namespace_t namespc = entry->namespc;
802 /* replace with old_entity/remove */
805 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
807 assert(iter != NULL);
808 /* replace an entry? */
809 if (iter->base.namespc == namespc)
813 /* restore definition from outer scopes (if there was one) */
814 if (old_entity != NULL) {
815 old_entity->base.symbol_next = iter->base.symbol_next;
816 *anchor = old_entity;
818 /* remove entry from list */
819 *anchor = iter->base.symbol_next;
823 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
827 * Pop all entries from the environment stack until the new_top
830 * @param new_top the new stack top
832 static void environment_pop_to(size_t new_top)
834 stack_pop_to(&environment_stack, new_top);
838 * Pop all entries from the global label stack until the new_top
841 * @param new_top the new stack top
843 static void label_pop_to(size_t new_top)
845 stack_pop_to(&label_stack, new_top);
848 static int get_akind_rank(atomic_type_kind_t akind)
854 * Return the type rank for an atomic type.
856 static int get_rank(const type_t *type)
858 assert(!is_typeref(type));
859 if (type->kind == TYPE_ENUM)
860 return get_akind_rank(type->enumt.akind);
862 assert(type->kind == TYPE_ATOMIC);
863 return get_akind_rank(type->atomic.akind);
867 * §6.3.1.1:2 Do integer promotion for a given type.
869 * @param type the type to promote
870 * @return the promoted type
872 static type_t *promote_integer(type_t *type)
874 if (type->kind == TYPE_BITFIELD)
875 type = type->bitfield.base_type;
877 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
884 * Create a cast expression.
886 * @param expression the expression to cast
887 * @param dest_type the destination type
889 static expression_t *create_cast_expression(expression_t *expression,
892 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
894 cast->unary.value = expression;
895 cast->base.type = dest_type;
901 * Check if a given expression represents a null pointer constant.
903 * @param expression the expression to check
905 static bool is_null_pointer_constant(const expression_t *expression)
907 /* skip void* cast */
908 if (expression->kind == EXPR_UNARY_CAST ||
909 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
910 type_t *const type = skip_typeref(expression->base.type);
911 if (types_compatible(type, type_void_ptr))
912 expression = expression->unary.value;
915 type_t *const type = skip_typeref(expression->base.type);
917 is_type_integer(type) &&
918 is_constant_expression(expression) &&
919 !fold_constant_to_bool(expression);
923 * Create an implicit cast expression.
925 * @param expression the expression to cast
926 * @param dest_type the destination type
928 static expression_t *create_implicit_cast(expression_t *expression,
931 type_t *const source_type = expression->base.type;
933 if (source_type == dest_type)
936 return create_cast_expression(expression, dest_type);
939 typedef enum assign_error_t {
941 ASSIGN_ERROR_INCOMPATIBLE,
942 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
943 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
944 ASSIGN_WARNING_POINTER_FROM_INT,
945 ASSIGN_WARNING_INT_FROM_POINTER
948 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
949 const expression_t *const right,
951 const source_position_t *source_position)
953 type_t *const orig_type_right = right->base.type;
954 type_t *const type_left = skip_typeref(orig_type_left);
955 type_t *const type_right = skip_typeref(orig_type_right);
960 case ASSIGN_ERROR_INCOMPATIBLE:
961 errorf(source_position,
962 "destination type '%T' in %s is incompatible with type '%T'",
963 orig_type_left, context, orig_type_right);
966 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
968 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
969 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
971 /* the left type has all qualifiers from the right type */
972 unsigned missing_qualifiers
973 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
974 warningf(source_position,
975 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
976 orig_type_left, context, orig_type_right, missing_qualifiers);
981 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
983 warningf(source_position,
984 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
985 orig_type_left, context, right, orig_type_right);
989 case ASSIGN_WARNING_POINTER_FROM_INT:
991 warningf(source_position,
992 "%s makes pointer '%T' from integer '%T' without a cast",
993 context, orig_type_left, orig_type_right);
997 case ASSIGN_WARNING_INT_FROM_POINTER:
999 warningf(source_position,
1000 "%s makes integer '%T' from pointer '%T' without a cast",
1001 context, orig_type_left, orig_type_right);
1006 panic("invalid error value");
1010 /** Implements the rules from §6.5.16.1 */
1011 static assign_error_t semantic_assign(type_t *orig_type_left,
1012 const expression_t *const right)
1014 type_t *const orig_type_right = right->base.type;
1015 type_t *const type_left = skip_typeref(orig_type_left);
1016 type_t *const type_right = skip_typeref(orig_type_right);
1018 if (is_type_pointer(type_left)) {
1019 if (is_null_pointer_constant(right)) {
1020 return ASSIGN_SUCCESS;
1021 } else if (is_type_pointer(type_right)) {
1022 type_t *points_to_left
1023 = skip_typeref(type_left->pointer.points_to);
1024 type_t *points_to_right
1025 = skip_typeref(type_right->pointer.points_to);
1026 assign_error_t res = ASSIGN_SUCCESS;
1028 /* the left type has all qualifiers from the right type */
1029 unsigned missing_qualifiers
1030 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1031 if (missing_qualifiers != 0) {
1032 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1035 points_to_left = get_unqualified_type(points_to_left);
1036 points_to_right = get_unqualified_type(points_to_right);
1038 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1041 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1042 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1043 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1046 if (!types_compatible(points_to_left, points_to_right)) {
1047 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1051 } else if (is_type_integer(type_right)) {
1052 return ASSIGN_WARNING_POINTER_FROM_INT;
1054 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1055 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1056 && is_type_pointer(type_right))) {
1057 return ASSIGN_SUCCESS;
1058 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1059 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1060 type_t *const unqual_type_left = get_unqualified_type(type_left);
1061 type_t *const unqual_type_right = get_unqualified_type(type_right);
1062 if (types_compatible(unqual_type_left, unqual_type_right)) {
1063 return ASSIGN_SUCCESS;
1065 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1066 return ASSIGN_WARNING_INT_FROM_POINTER;
1069 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1070 return ASSIGN_SUCCESS;
1072 return ASSIGN_ERROR_INCOMPATIBLE;
1075 static expression_t *parse_constant_expression(void)
1077 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1079 if (!is_constant_expression(result)) {
1080 errorf(&result->base.source_position,
1081 "expression '%E' is not constant", result);
1087 static expression_t *parse_assignment_expression(void)
1089 return parse_sub_expression(PREC_ASSIGNMENT);
1092 static void warn_string_concat(const source_position_t *pos)
1094 if (warning.traditional) {
1095 warningf(pos, "traditional C rejects string constant concatenation");
1099 static string_t parse_string_literals(void)
1101 assert(token.type == T_STRING_LITERAL);
1102 string_t result = token.literal;
1106 while (token.type == T_STRING_LITERAL) {
1107 warn_string_concat(&token.source_position);
1108 result = concat_strings(&result, &token.literal);
1116 * compare two string, ignoring double underscores on the second.
1118 static int strcmp_underscore(const char *s1, const char *s2)
1120 if (s2[0] == '_' && s2[1] == '_') {
1121 size_t len2 = strlen(s2);
1122 size_t len1 = strlen(s1);
1123 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1124 return strncmp(s1, s2+2, len2-4);
1128 return strcmp(s1, s2);
1131 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1133 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1134 attribute->kind = kind;
1139 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1142 * __attribute__ ( ( attribute-list ) )
1146 * attribute_list , attrib
1151 * any-word ( identifier )
1152 * any-word ( identifier , nonempty-expr-list )
1153 * any-word ( expr-list )
1155 * where the "identifier" must not be declared as a type, and
1156 * "any-word" may be any identifier (including one declared as a
1157 * type), a reserved word storage class specifier, type specifier or
1158 * type qualifier. ??? This still leaves out most reserved keywords
1159 * (following the old parser), shouldn't we include them, and why not
1160 * allow identifiers declared as types to start the arguments?
1162 * Matze: this all looks confusing and little systematic, so we're even less
1163 * strict and parse any list of things which are identifiers or
1164 * (assignment-)expressions.
1166 static attribute_argument_t *parse_attribute_arguments(void)
1168 attribute_argument_t *first = NULL;
1169 attribute_argument_t **anchor = &first;
1170 if (token.type != ')') do {
1171 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1173 /* is it an identifier */
1174 if (token.type == T_IDENTIFIER
1175 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1176 symbol_t *symbol = token.symbol;
1177 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1178 argument->v.symbol = symbol;
1181 /* must be an expression */
1182 expression_t *expression = parse_assignment_expression();
1184 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1185 argument->v.expression = expression;
1188 /* append argument */
1190 anchor = &argument->next;
1191 } while (next_if(','));
1192 expect(')', end_error);
1201 static attribute_t *parse_attribute_asm(void)
1205 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1207 expect('(', end_error);
1208 attribute->a.arguments = parse_attribute_arguments();
1215 static symbol_t *get_symbol_from_token(void)
1217 switch(token.type) {
1219 return token.symbol;
1248 /* maybe we need more tokens ... add them on demand */
1249 return get_token_symbol(&token);
1255 static attribute_t *parse_attribute_gnu_single(void)
1257 /* parse "any-word" */
1258 symbol_t *symbol = get_symbol_from_token();
1259 if (symbol == NULL) {
1260 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1264 const char *name = symbol->string;
1267 attribute_kind_t kind;
1268 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1269 const char *attribute_name = get_attribute_name(kind);
1270 if (attribute_name != NULL
1271 && strcmp_underscore(attribute_name, name) == 0)
1275 if (kind >= ATTRIBUTE_GNU_LAST) {
1276 if (warning.attribute) {
1277 warningf(HERE, "unknown attribute '%s' ignored", name);
1279 /* TODO: we should still save the attribute in the list... */
1280 kind = ATTRIBUTE_UNKNOWN;
1283 attribute_t *attribute = allocate_attribute_zero(kind);
1285 /* parse arguments */
1287 attribute->a.arguments = parse_attribute_arguments();
1295 static attribute_t *parse_attribute_gnu(void)
1297 attribute_t *first = NULL;
1298 attribute_t **anchor = &first;
1300 eat(T___attribute__);
1301 expect('(', end_error);
1302 expect('(', end_error);
1304 if (token.type != ')') do {
1305 attribute_t *attribute = parse_attribute_gnu_single();
1306 if (attribute == NULL)
1309 *anchor = attribute;
1310 anchor = &attribute->next;
1311 } while (next_if(','));
1312 expect(')', end_error);
1313 expect(')', end_error);
1319 /** Parse attributes. */
1320 static attribute_t *parse_attributes(attribute_t *first)
1322 attribute_t **anchor = &first;
1324 while (*anchor != NULL)
1325 anchor = &(*anchor)->next;
1327 attribute_t *attribute;
1328 switch (token.type) {
1329 case T___attribute__:
1330 attribute = parse_attribute_gnu();
1334 attribute = parse_attribute_asm();
1339 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1344 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1347 case T__forceinline:
1349 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1354 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1359 /* TODO record modifier */
1361 warningf(HERE, "Ignoring declaration modifier %K", &token);
1362 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1369 *anchor = attribute;
1370 anchor = &attribute->next;
1374 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1376 static entity_t *determine_lhs_ent(expression_t *const expr,
1379 switch (expr->kind) {
1380 case EXPR_REFERENCE: {
1381 entity_t *const entity = expr->reference.entity;
1382 /* we should only find variables as lvalues... */
1383 if (entity->base.kind != ENTITY_VARIABLE
1384 && entity->base.kind != ENTITY_PARAMETER)
1390 case EXPR_ARRAY_ACCESS: {
1391 expression_t *const ref = expr->array_access.array_ref;
1392 entity_t * ent = NULL;
1393 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1394 ent = determine_lhs_ent(ref, lhs_ent);
1397 mark_vars_read(expr->select.compound, lhs_ent);
1399 mark_vars_read(expr->array_access.index, lhs_ent);
1404 if (is_type_compound(skip_typeref(expr->base.type))) {
1405 return determine_lhs_ent(expr->select.compound, lhs_ent);
1407 mark_vars_read(expr->select.compound, lhs_ent);
1412 case EXPR_UNARY_DEREFERENCE: {
1413 expression_t *const val = expr->unary.value;
1414 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1416 return determine_lhs_ent(val->unary.value, lhs_ent);
1418 mark_vars_read(val, NULL);
1424 mark_vars_read(expr, NULL);
1429 #define ENT_ANY ((entity_t*)-1)
1432 * Mark declarations, which are read. This is used to detect variables, which
1436 * x is not marked as "read", because it is only read to calculate its own new
1440 * x and y are not detected as "not read", because multiple variables are
1443 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1445 switch (expr->kind) {
1446 case EXPR_REFERENCE: {
1447 entity_t *const entity = expr->reference.entity;
1448 if (entity->kind != ENTITY_VARIABLE
1449 && entity->kind != ENTITY_PARAMETER)
1452 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1453 if (entity->kind == ENTITY_VARIABLE) {
1454 entity->variable.read = true;
1456 entity->parameter.read = true;
1463 // TODO respect pure/const
1464 mark_vars_read(expr->call.function, NULL);
1465 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1466 mark_vars_read(arg->expression, NULL);
1470 case EXPR_CONDITIONAL:
1471 // TODO lhs_decl should depend on whether true/false have an effect
1472 mark_vars_read(expr->conditional.condition, NULL);
1473 if (expr->conditional.true_expression != NULL)
1474 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1475 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1479 if (lhs_ent == ENT_ANY
1480 && !is_type_compound(skip_typeref(expr->base.type)))
1482 mark_vars_read(expr->select.compound, lhs_ent);
1485 case EXPR_ARRAY_ACCESS: {
1486 expression_t *const ref = expr->array_access.array_ref;
1487 mark_vars_read(ref, lhs_ent);
1488 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1489 mark_vars_read(expr->array_access.index, lhs_ent);
1494 mark_vars_read(expr->va_arge.ap, lhs_ent);
1498 mark_vars_read(expr->va_copye.src, lhs_ent);
1501 case EXPR_UNARY_CAST:
1502 /* Special case: Use void cast to mark a variable as "read" */
1503 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1508 case EXPR_UNARY_THROW:
1509 if (expr->unary.value == NULL)
1512 case EXPR_UNARY_DEREFERENCE:
1513 case EXPR_UNARY_DELETE:
1514 case EXPR_UNARY_DELETE_ARRAY:
1515 if (lhs_ent == ENT_ANY)
1519 case EXPR_UNARY_NEGATE:
1520 case EXPR_UNARY_PLUS:
1521 case EXPR_UNARY_BITWISE_NEGATE:
1522 case EXPR_UNARY_NOT:
1523 case EXPR_UNARY_TAKE_ADDRESS:
1524 case EXPR_UNARY_POSTFIX_INCREMENT:
1525 case EXPR_UNARY_POSTFIX_DECREMENT:
1526 case EXPR_UNARY_PREFIX_INCREMENT:
1527 case EXPR_UNARY_PREFIX_DECREMENT:
1528 case EXPR_UNARY_CAST_IMPLICIT:
1529 case EXPR_UNARY_ASSUME:
1531 mark_vars_read(expr->unary.value, lhs_ent);
1534 case EXPR_BINARY_ADD:
1535 case EXPR_BINARY_SUB:
1536 case EXPR_BINARY_MUL:
1537 case EXPR_BINARY_DIV:
1538 case EXPR_BINARY_MOD:
1539 case EXPR_BINARY_EQUAL:
1540 case EXPR_BINARY_NOTEQUAL:
1541 case EXPR_BINARY_LESS:
1542 case EXPR_BINARY_LESSEQUAL:
1543 case EXPR_BINARY_GREATER:
1544 case EXPR_BINARY_GREATEREQUAL:
1545 case EXPR_BINARY_BITWISE_AND:
1546 case EXPR_BINARY_BITWISE_OR:
1547 case EXPR_BINARY_BITWISE_XOR:
1548 case EXPR_BINARY_LOGICAL_AND:
1549 case EXPR_BINARY_LOGICAL_OR:
1550 case EXPR_BINARY_SHIFTLEFT:
1551 case EXPR_BINARY_SHIFTRIGHT:
1552 case EXPR_BINARY_COMMA:
1553 case EXPR_BINARY_ISGREATER:
1554 case EXPR_BINARY_ISGREATEREQUAL:
1555 case EXPR_BINARY_ISLESS:
1556 case EXPR_BINARY_ISLESSEQUAL:
1557 case EXPR_BINARY_ISLESSGREATER:
1558 case EXPR_BINARY_ISUNORDERED:
1559 mark_vars_read(expr->binary.left, lhs_ent);
1560 mark_vars_read(expr->binary.right, lhs_ent);
1563 case EXPR_BINARY_ASSIGN:
1564 case EXPR_BINARY_MUL_ASSIGN:
1565 case EXPR_BINARY_DIV_ASSIGN:
1566 case EXPR_BINARY_MOD_ASSIGN:
1567 case EXPR_BINARY_ADD_ASSIGN:
1568 case EXPR_BINARY_SUB_ASSIGN:
1569 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1570 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1571 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1572 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1573 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1574 if (lhs_ent == ENT_ANY)
1576 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1577 mark_vars_read(expr->binary.right, lhs_ent);
1582 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1588 case EXPR_STRING_LITERAL:
1589 case EXPR_WIDE_STRING_LITERAL:
1590 case EXPR_COMPOUND_LITERAL: // TODO init?
1592 case EXPR_CLASSIFY_TYPE:
1595 case EXPR_BUILTIN_CONSTANT_P:
1596 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1598 case EXPR_STATEMENT: // TODO
1599 case EXPR_LABEL_ADDRESS:
1600 case EXPR_REFERENCE_ENUM_VALUE:
1604 panic("unhandled expression");
1607 static designator_t *parse_designation(void)
1609 designator_t *result = NULL;
1610 designator_t **anchor = &result;
1613 designator_t *designator;
1614 switch (token.type) {
1616 designator = allocate_ast_zero(sizeof(designator[0]));
1617 designator->source_position = token.source_position;
1619 add_anchor_token(']');
1620 designator->array_index = parse_constant_expression();
1621 rem_anchor_token(']');
1622 expect(']', end_error);
1625 designator = allocate_ast_zero(sizeof(designator[0]));
1626 designator->source_position = token.source_position;
1628 if (token.type != T_IDENTIFIER) {
1629 parse_error_expected("while parsing designator",
1630 T_IDENTIFIER, NULL);
1633 designator->symbol = token.symbol;
1637 expect('=', end_error);
1641 assert(designator != NULL);
1642 *anchor = designator;
1643 anchor = &designator->next;
1649 static initializer_t *initializer_from_string(array_type_t *const type,
1650 const string_t *const string)
1652 /* TODO: check len vs. size of array type */
1655 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1656 initializer->string.string = *string;
1661 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1662 const string_t *const string)
1664 /* TODO: check len vs. size of array type */
1667 initializer_t *const initializer =
1668 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1669 initializer->wide_string.string = *string;
1675 * Build an initializer from a given expression.
1677 static initializer_t *initializer_from_expression(type_t *orig_type,
1678 expression_t *expression)
1680 /* TODO check that expression is a constant expression */
1682 /* §6.7.8.14/15 char array may be initialized by string literals */
1683 type_t *type = skip_typeref(orig_type);
1684 type_t *expr_type_orig = expression->base.type;
1685 type_t *expr_type = skip_typeref(expr_type_orig);
1687 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1688 array_type_t *const array_type = &type->array;
1689 type_t *const element_type = skip_typeref(array_type->element_type);
1691 if (element_type->kind == TYPE_ATOMIC) {
1692 atomic_type_kind_t akind = element_type->atomic.akind;
1693 switch (expression->kind) {
1694 case EXPR_STRING_LITERAL:
1695 if (akind == ATOMIC_TYPE_CHAR
1696 || akind == ATOMIC_TYPE_SCHAR
1697 || akind == ATOMIC_TYPE_UCHAR) {
1698 return initializer_from_string(array_type,
1699 &expression->string_literal.value);
1703 case EXPR_WIDE_STRING_LITERAL: {
1704 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1705 if (get_unqualified_type(element_type) == bare_wchar_type) {
1706 return initializer_from_wide_string(array_type,
1707 &expression->string_literal.value);
1718 assign_error_t error = semantic_assign(type, expression);
1719 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1721 report_assign_error(error, type, expression, "initializer",
1722 &expression->base.source_position);
1724 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1725 result->value.value = create_implicit_cast(expression, type);
1731 * Checks if a given expression can be used as an constant initializer.
1733 static bool is_initializer_constant(const expression_t *expression)
1735 return is_constant_expression(expression)
1736 || is_address_constant(expression);
1740 * Parses an scalar initializer.
1742 * §6.7.8.11; eat {} without warning
1744 static initializer_t *parse_scalar_initializer(type_t *type,
1745 bool must_be_constant)
1747 /* there might be extra {} hierarchies */
1751 warningf(HERE, "extra curly braces around scalar initializer");
1754 } while (next_if('{'));
1757 expression_t *expression = parse_assignment_expression();
1758 mark_vars_read(expression, NULL);
1759 if (must_be_constant && !is_initializer_constant(expression)) {
1760 errorf(&expression->base.source_position,
1761 "initialisation expression '%E' is not constant",
1765 initializer_t *initializer = initializer_from_expression(type, expression);
1767 if (initializer == NULL) {
1768 errorf(&expression->base.source_position,
1769 "expression '%E' (type '%T') doesn't match expected type '%T'",
1770 expression, expression->base.type, type);
1775 bool additional_warning_displayed = false;
1776 while (braces > 0) {
1778 if (token.type != '}') {
1779 if (!additional_warning_displayed && warning.other) {
1780 warningf(HERE, "additional elements in scalar initializer");
1781 additional_warning_displayed = true;
1792 * An entry in the type path.
1794 typedef struct type_path_entry_t type_path_entry_t;
1795 struct type_path_entry_t {
1796 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1798 size_t index; /**< For array types: the current index. */
1799 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1804 * A type path expression a position inside compound or array types.
1806 typedef struct type_path_t type_path_t;
1807 struct type_path_t {
1808 type_path_entry_t *path; /**< An flexible array containing the current path. */
1809 type_t *top_type; /**< type of the element the path points */
1810 size_t max_index; /**< largest index in outermost array */
1814 * Prints a type path for debugging.
1816 static __attribute__((unused)) void debug_print_type_path(
1817 const type_path_t *path)
1819 size_t len = ARR_LEN(path->path);
1821 for (size_t i = 0; i < len; ++i) {
1822 const type_path_entry_t *entry = & path->path[i];
1824 type_t *type = skip_typeref(entry->type);
1825 if (is_type_compound(type)) {
1826 /* in gcc mode structs can have no members */
1827 if (entry->v.compound_entry == NULL) {
1831 fprintf(stderr, ".%s",
1832 entry->v.compound_entry->base.symbol->string);
1833 } else if (is_type_array(type)) {
1834 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1836 fprintf(stderr, "-INVALID-");
1839 if (path->top_type != NULL) {
1840 fprintf(stderr, " (");
1841 print_type(path->top_type);
1842 fprintf(stderr, ")");
1847 * Return the top type path entry, ie. in a path
1848 * (type).a.b returns the b.
1850 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1852 size_t len = ARR_LEN(path->path);
1854 return &path->path[len-1];
1858 * Enlarge the type path by an (empty) element.
1860 static type_path_entry_t *append_to_type_path(type_path_t *path)
1862 size_t len = ARR_LEN(path->path);
1863 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1865 type_path_entry_t *result = & path->path[len];
1866 memset(result, 0, sizeof(result[0]));
1871 * Descending into a sub-type. Enter the scope of the current top_type.
1873 static void descend_into_subtype(type_path_t *path)
1875 type_t *orig_top_type = path->top_type;
1876 type_t *top_type = skip_typeref(orig_top_type);
1878 type_path_entry_t *top = append_to_type_path(path);
1879 top->type = top_type;
1881 if (is_type_compound(top_type)) {
1882 compound_t *compound = top_type->compound.compound;
1883 entity_t *entry = compound->members.entities;
1885 if (entry != NULL) {
1886 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1887 top->v.compound_entry = &entry->declaration;
1888 path->top_type = entry->declaration.type;
1890 path->top_type = NULL;
1892 } else if (is_type_array(top_type)) {
1894 path->top_type = top_type->array.element_type;
1896 assert(!is_type_valid(top_type));
1901 * Pop an entry from the given type path, ie. returning from
1902 * (type).a.b to (type).a
1904 static void ascend_from_subtype(type_path_t *path)
1906 type_path_entry_t *top = get_type_path_top(path);
1908 path->top_type = top->type;
1910 size_t len = ARR_LEN(path->path);
1911 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1915 * Pop entries from the given type path until the given
1916 * path level is reached.
1918 static void ascend_to(type_path_t *path, size_t top_path_level)
1920 size_t len = ARR_LEN(path->path);
1922 while (len > top_path_level) {
1923 ascend_from_subtype(path);
1924 len = ARR_LEN(path->path);
1928 static bool walk_designator(type_path_t *path, const designator_t *designator,
1929 bool used_in_offsetof)
1931 for (; designator != NULL; designator = designator->next) {
1932 type_path_entry_t *top = get_type_path_top(path);
1933 type_t *orig_type = top->type;
1935 type_t *type = skip_typeref(orig_type);
1937 if (designator->symbol != NULL) {
1938 symbol_t *symbol = designator->symbol;
1939 if (!is_type_compound(type)) {
1940 if (is_type_valid(type)) {
1941 errorf(&designator->source_position,
1942 "'.%Y' designator used for non-compound type '%T'",
1946 top->type = type_error_type;
1947 top->v.compound_entry = NULL;
1948 orig_type = type_error_type;
1950 compound_t *compound = type->compound.compound;
1951 entity_t *iter = compound->members.entities;
1952 for (; iter != NULL; iter = iter->base.next) {
1953 if (iter->base.symbol == symbol) {
1958 errorf(&designator->source_position,
1959 "'%T' has no member named '%Y'", orig_type, symbol);
1962 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1963 if (used_in_offsetof) {
1964 type_t *real_type = skip_typeref(iter->declaration.type);
1965 if (real_type->kind == TYPE_BITFIELD) {
1966 errorf(&designator->source_position,
1967 "offsetof designator '%Y' may not specify bitfield",
1973 top->type = orig_type;
1974 top->v.compound_entry = &iter->declaration;
1975 orig_type = iter->declaration.type;
1978 expression_t *array_index = designator->array_index;
1979 assert(designator->array_index != NULL);
1981 if (!is_type_array(type)) {
1982 if (is_type_valid(type)) {
1983 errorf(&designator->source_position,
1984 "[%E] designator used for non-array type '%T'",
1985 array_index, orig_type);
1990 long index = fold_constant_to_int(array_index);
1991 if (!used_in_offsetof) {
1993 errorf(&designator->source_position,
1994 "array index [%E] must be positive", array_index);
1995 } else if (type->array.size_constant) {
1996 long array_size = type->array.size;
1997 if (index >= array_size) {
1998 errorf(&designator->source_position,
1999 "designator [%E] (%d) exceeds array size %d",
2000 array_index, index, array_size);
2005 top->type = orig_type;
2006 top->v.index = (size_t) index;
2007 orig_type = type->array.element_type;
2009 path->top_type = orig_type;
2011 if (designator->next != NULL) {
2012 descend_into_subtype(path);
2021 static void advance_current_object(type_path_t *path, size_t top_path_level)
2023 type_path_entry_t *top = get_type_path_top(path);
2025 type_t *type = skip_typeref(top->type);
2026 if (is_type_union(type)) {
2027 /* in unions only the first element is initialized */
2028 top->v.compound_entry = NULL;
2029 } else if (is_type_struct(type)) {
2030 declaration_t *entry = top->v.compound_entry;
2032 entity_t *next_entity = entry->base.next;
2033 if (next_entity != NULL) {
2034 assert(is_declaration(next_entity));
2035 entry = &next_entity->declaration;
2040 top->v.compound_entry = entry;
2041 if (entry != NULL) {
2042 path->top_type = entry->type;
2045 } else if (is_type_array(type)) {
2046 assert(is_type_array(type));
2050 if (!type->array.size_constant || top->v.index < type->array.size) {
2054 assert(!is_type_valid(type));
2058 /* we're past the last member of the current sub-aggregate, try if we
2059 * can ascend in the type hierarchy and continue with another subobject */
2060 size_t len = ARR_LEN(path->path);
2062 if (len > top_path_level) {
2063 ascend_from_subtype(path);
2064 advance_current_object(path, top_path_level);
2066 path->top_type = NULL;
2071 * skip any {...} blocks until a closing bracket is reached.
2073 static void skip_initializers(void)
2077 while (token.type != '}') {
2078 if (token.type == T_EOF)
2080 if (token.type == '{') {
2088 static initializer_t *create_empty_initializer(void)
2090 static initializer_t empty_initializer
2091 = { .list = { { INITIALIZER_LIST }, 0 } };
2092 return &empty_initializer;
2096 * Parse a part of an initialiser for a struct or union,
2098 static initializer_t *parse_sub_initializer(type_path_t *path,
2099 type_t *outer_type, size_t top_path_level,
2100 parse_initializer_env_t *env)
2102 if (token.type == '}') {
2103 /* empty initializer */
2104 return create_empty_initializer();
2107 type_t *orig_type = path->top_type;
2108 type_t *type = NULL;
2110 if (orig_type == NULL) {
2111 /* We are initializing an empty compound. */
2113 type = skip_typeref(orig_type);
2116 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2119 designator_t *designator = NULL;
2120 if (token.type == '.' || token.type == '[') {
2121 designator = parse_designation();
2122 goto finish_designator;
2123 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2124 /* GNU-style designator ("identifier: value") */
2125 designator = allocate_ast_zero(sizeof(designator[0]));
2126 designator->source_position = token.source_position;
2127 designator->symbol = token.symbol;
2132 /* reset path to toplevel, evaluate designator from there */
2133 ascend_to(path, top_path_level);
2134 if (!walk_designator(path, designator, false)) {
2135 /* can't continue after designation error */
2139 initializer_t *designator_initializer
2140 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2141 designator_initializer->designator.designator = designator;
2142 ARR_APP1(initializer_t*, initializers, designator_initializer);
2144 orig_type = path->top_type;
2145 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2150 if (token.type == '{') {
2151 if (type != NULL && is_type_scalar(type)) {
2152 sub = parse_scalar_initializer(type, env->must_be_constant);
2156 if (env->entity != NULL) {
2158 "extra brace group at end of initializer for '%Y'",
2159 env->entity->base.symbol);
2161 errorf(HERE, "extra brace group at end of initializer");
2164 descend_into_subtype(path);
2166 add_anchor_token('}');
2167 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2169 rem_anchor_token('}');
2172 ascend_from_subtype(path);
2173 expect('}', end_error);
2175 expect('}', end_error);
2176 goto error_parse_next;
2180 /* must be an expression */
2181 expression_t *expression = parse_assignment_expression();
2182 mark_vars_read(expression, NULL);
2184 if (env->must_be_constant && !is_initializer_constant(expression)) {
2185 errorf(&expression->base.source_position,
2186 "Initialisation expression '%E' is not constant",
2191 /* we are already outside, ... */
2192 if (outer_type == NULL)
2193 goto error_parse_next;
2194 type_t *const outer_type_skip = skip_typeref(outer_type);
2195 if (is_type_compound(outer_type_skip) &&
2196 !outer_type_skip->compound.compound->complete) {
2197 goto error_parse_next;
2202 /* handle { "string" } special case */
2203 if ((expression->kind == EXPR_STRING_LITERAL
2204 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2205 && outer_type != NULL) {
2206 sub = initializer_from_expression(outer_type, expression);
2209 if (token.type != '}' && warning.other) {
2210 warningf(HERE, "excessive elements in initializer for type '%T'",
2213 /* TODO: eat , ... */
2218 /* descend into subtypes until expression matches type */
2220 orig_type = path->top_type;
2221 type = skip_typeref(orig_type);
2223 sub = initializer_from_expression(orig_type, expression);
2227 if (!is_type_valid(type)) {
2230 if (is_type_scalar(type)) {
2231 errorf(&expression->base.source_position,
2232 "expression '%E' doesn't match expected type '%T'",
2233 expression, orig_type);
2237 descend_into_subtype(path);
2241 /* update largest index of top array */
2242 const type_path_entry_t *first = &path->path[0];
2243 type_t *first_type = first->type;
2244 first_type = skip_typeref(first_type);
2245 if (is_type_array(first_type)) {
2246 size_t index = first->v.index;
2247 if (index > path->max_index)
2248 path->max_index = index;
2252 /* append to initializers list */
2253 ARR_APP1(initializer_t*, initializers, sub);
2256 if (warning.other) {
2257 if (env->entity != NULL) {
2258 warningf(HERE, "excess elements in initializer for '%Y'",
2259 env->entity->base.symbol);
2261 warningf(HERE, "excess elements in initializer");
2267 if (token.type == '}') {
2270 expect(',', end_error);
2271 if (token.type == '}') {
2276 /* advance to the next declaration if we are not at the end */
2277 advance_current_object(path, top_path_level);
2278 orig_type = path->top_type;
2279 if (orig_type != NULL)
2280 type = skip_typeref(orig_type);
2286 size_t len = ARR_LEN(initializers);
2287 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2288 initializer_t *result = allocate_ast_zero(size);
2289 result->kind = INITIALIZER_LIST;
2290 result->list.len = len;
2291 memcpy(&result->list.initializers, initializers,
2292 len * sizeof(initializers[0]));
2294 DEL_ARR_F(initializers);
2295 ascend_to(path, top_path_level+1);
2300 skip_initializers();
2301 DEL_ARR_F(initializers);
2302 ascend_to(path, top_path_level+1);
2306 static expression_t *make_size_literal(size_t value)
2308 expression_t *literal = allocate_ast_zero(EXPR_LITERAL_INTEGER);
2309 literal->base.type = type_size_t;
2312 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2313 literal->literal.value = make_string(buf);
2319 * Parses an initializer. Parsers either a compound literal
2320 * (env->declaration == NULL) or an initializer of a declaration.
2322 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2324 type_t *type = skip_typeref(env->type);
2325 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2326 initializer_t *result;
2328 if (is_type_scalar(type)) {
2329 result = parse_scalar_initializer(type, env->must_be_constant);
2330 } else if (token.type == '{') {
2334 memset(&path, 0, sizeof(path));
2335 path.top_type = env->type;
2336 path.path = NEW_ARR_F(type_path_entry_t, 0);
2338 descend_into_subtype(&path);
2340 add_anchor_token('}');
2341 result = parse_sub_initializer(&path, env->type, 1, env);
2342 rem_anchor_token('}');
2344 max_index = path.max_index;
2345 DEL_ARR_F(path.path);
2347 expect('}', end_error);
2349 /* parse_scalar_initializer() also works in this case: we simply
2350 * have an expression without {} around it */
2351 result = parse_scalar_initializer(type, env->must_be_constant);
2354 /* §6.7.8:22 array initializers for arrays with unknown size determine
2355 * the array type size */
2356 if (is_type_array(type) && type->array.size_expression == NULL
2357 && result != NULL) {
2359 switch (result->kind) {
2360 case INITIALIZER_LIST:
2361 assert(max_index != 0xdeadbeaf);
2362 size = max_index + 1;
2365 case INITIALIZER_STRING:
2366 size = result->string.string.size;
2369 case INITIALIZER_WIDE_STRING:
2370 size = result->wide_string.string.size;
2373 case INITIALIZER_DESIGNATOR:
2374 case INITIALIZER_VALUE:
2375 /* can happen for parse errors */
2380 internal_errorf(HERE, "invalid initializer type");
2383 type_t *new_type = duplicate_type(type);
2385 new_type->array.size_expression = make_size_literal(size);
2386 new_type->array.size_constant = true;
2387 new_type->array.has_implicit_size = true;
2388 new_type->array.size = size;
2389 env->type = new_type;
2397 static void append_entity(scope_t *scope, entity_t *entity)
2399 if (scope->last_entity != NULL) {
2400 scope->last_entity->base.next = entity;
2402 scope->entities = entity;
2404 entity->base.parent_entity = current_entity;
2405 scope->last_entity = entity;
2409 static compound_t *parse_compound_type_specifier(bool is_struct)
2411 eat(is_struct ? T_struct : T_union);
2413 symbol_t *symbol = NULL;
2414 compound_t *compound = NULL;
2415 attribute_t *attributes = NULL;
2417 if (token.type == T___attribute__) {
2418 attributes = parse_attributes(NULL);
2421 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2422 if (token.type == T_IDENTIFIER) {
2423 /* the compound has a name, check if we have seen it already */
2424 symbol = token.symbol;
2427 entity_t *entity = get_tag(symbol, kind);
2428 if (entity != NULL) {
2429 compound = &entity->compound;
2430 if (compound->base.parent_scope != current_scope &&
2431 (token.type == '{' || token.type == ';')) {
2432 /* we're in an inner scope and have a definition. Shadow
2433 * existing definition in outer scope */
2435 } else if (compound->complete && token.type == '{') {
2436 assert(symbol != NULL);
2437 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2438 is_struct ? "struct" : "union", symbol,
2439 &compound->base.source_position);
2440 /* clear members in the hope to avoid further errors */
2441 compound->members.entities = NULL;
2444 } else if (token.type != '{') {
2446 parse_error_expected("while parsing struct type specifier",
2447 T_IDENTIFIER, '{', NULL);
2449 parse_error_expected("while parsing union type specifier",
2450 T_IDENTIFIER, '{', NULL);
2456 if (compound == NULL) {
2457 entity_t *entity = allocate_entity_zero(kind);
2458 compound = &entity->compound;
2460 compound->alignment = 1;
2461 compound->base.namespc = NAMESPACE_TAG;
2462 compound->base.source_position = token.source_position;
2463 compound->base.symbol = symbol;
2464 compound->base.parent_scope = current_scope;
2465 if (symbol != NULL) {
2466 environment_push(entity);
2468 append_entity(current_scope, entity);
2471 if (token.type == '{') {
2472 parse_compound_type_entries(compound);
2474 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2475 if (symbol == NULL) {
2476 assert(anonymous_entity == NULL);
2477 anonymous_entity = (entity_t*)compound;
2481 if (attributes != NULL) {
2482 handle_entity_attributes(attributes, (entity_t*) compound);
2488 static void parse_enum_entries(type_t *const enum_type)
2492 if (token.type == '}') {
2493 errorf(HERE, "empty enum not allowed");
2498 add_anchor_token('}');
2500 if (token.type != T_IDENTIFIER) {
2501 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2503 rem_anchor_token('}');
2507 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2508 entity->enum_value.enum_type = enum_type;
2509 entity->base.symbol = token.symbol;
2510 entity->base.source_position = token.source_position;
2514 expression_t *value = parse_constant_expression();
2516 value = create_implicit_cast(value, enum_type);
2517 entity->enum_value.value = value;
2522 record_entity(entity, false);
2523 } while (next_if(',') && token.type != '}');
2524 rem_anchor_token('}');
2526 expect('}', end_error);
2532 static type_t *parse_enum_specifier(void)
2538 switch (token.type) {
2540 symbol = token.symbol;
2543 entity = get_tag(symbol, ENTITY_ENUM);
2544 if (entity != NULL) {
2545 if (entity->base.parent_scope != current_scope &&
2546 (token.type == '{' || token.type == ';')) {
2547 /* we're in an inner scope and have a definition. Shadow
2548 * existing definition in outer scope */
2550 } else if (entity->enume.complete && token.type == '{') {
2551 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2552 symbol, &entity->base.source_position);
2563 parse_error_expected("while parsing enum type specifier",
2564 T_IDENTIFIER, '{', NULL);
2568 if (entity == NULL) {
2569 entity = allocate_entity_zero(ENTITY_ENUM);
2570 entity->base.namespc = NAMESPACE_TAG;
2571 entity->base.source_position = token.source_position;
2572 entity->base.symbol = symbol;
2573 entity->base.parent_scope = current_scope;
2576 type_t *const type = allocate_type_zero(TYPE_ENUM);
2577 type->enumt.enume = &entity->enume;
2578 type->enumt.akind = ATOMIC_TYPE_INT;
2580 if (token.type == '{') {
2581 if (symbol != NULL) {
2582 environment_push(entity);
2584 append_entity(current_scope, entity);
2585 entity->enume.complete = true;
2587 parse_enum_entries(type);
2588 parse_attributes(NULL);
2590 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2591 if (symbol == NULL) {
2592 assert(anonymous_entity == NULL);
2593 anonymous_entity = entity;
2595 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2596 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2604 * if a symbol is a typedef to another type, return true
2606 static bool is_typedef_symbol(symbol_t *symbol)
2608 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2609 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2612 static type_t *parse_typeof(void)
2618 expect('(', end_error);
2619 add_anchor_token(')');
2621 expression_t *expression = NULL;
2623 bool old_type_prop = in_type_prop;
2624 bool old_gcc_extension = in_gcc_extension;
2625 in_type_prop = true;
2627 while (next_if(T___extension__)) {
2628 /* This can be a prefix to a typename or an expression. */
2629 in_gcc_extension = true;
2631 switch (token.type) {
2633 if (is_typedef_symbol(token.symbol)) {
2634 type = parse_typename();
2636 expression = parse_expression();
2637 type = revert_automatic_type_conversion(expression);
2642 type = parse_typename();
2646 expression = parse_expression();
2647 type = expression->base.type;
2650 in_type_prop = old_type_prop;
2651 in_gcc_extension = old_gcc_extension;
2653 rem_anchor_token(')');
2654 expect(')', end_error);
2656 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2657 typeof_type->typeoft.expression = expression;
2658 typeof_type->typeoft.typeof_type = type;
2665 typedef enum specifiers_t {
2666 SPECIFIER_SIGNED = 1 << 0,
2667 SPECIFIER_UNSIGNED = 1 << 1,
2668 SPECIFIER_LONG = 1 << 2,
2669 SPECIFIER_INT = 1 << 3,
2670 SPECIFIER_DOUBLE = 1 << 4,
2671 SPECIFIER_CHAR = 1 << 5,
2672 SPECIFIER_WCHAR_T = 1 << 6,
2673 SPECIFIER_SHORT = 1 << 7,
2674 SPECIFIER_LONG_LONG = 1 << 8,
2675 SPECIFIER_FLOAT = 1 << 9,
2676 SPECIFIER_BOOL = 1 << 10,
2677 SPECIFIER_VOID = 1 << 11,
2678 SPECIFIER_INT8 = 1 << 12,
2679 SPECIFIER_INT16 = 1 << 13,
2680 SPECIFIER_INT32 = 1 << 14,
2681 SPECIFIER_INT64 = 1 << 15,
2682 SPECIFIER_INT128 = 1 << 16,
2683 SPECIFIER_COMPLEX = 1 << 17,
2684 SPECIFIER_IMAGINARY = 1 << 18,
2687 static type_t *create_builtin_type(symbol_t *const symbol,
2688 type_t *const real_type)
2690 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2691 type->builtin.symbol = symbol;
2692 type->builtin.real_type = real_type;
2693 return identify_new_type(type);
2696 static type_t *get_typedef_type(symbol_t *symbol)
2698 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2699 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2702 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2703 type->typedeft.typedefe = &entity->typedefe;
2708 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2710 expect('(', end_error);
2712 attribute_property_argument_t *property
2713 = allocate_ast_zero(sizeof(*property));
2716 if (token.type != T_IDENTIFIER) {
2717 parse_error_expected("while parsing property declspec",
2718 T_IDENTIFIER, NULL);
2723 symbol_t *symbol = token.symbol;
2725 if (strcmp(symbol->string, "put") == 0) {
2727 } else if (strcmp(symbol->string, "get") == 0) {
2730 errorf(HERE, "expected put or get in property declspec");
2733 expect('=', end_error);
2734 if (token.type != T_IDENTIFIER) {
2735 parse_error_expected("while parsing property declspec",
2736 T_IDENTIFIER, NULL);
2740 property->put_symbol = token.symbol;
2742 property->get_symbol = token.symbol;
2745 } while (next_if(','));
2747 attribute->a.property = property;
2749 expect(')', end_error);
2755 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2757 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2758 if (next_if(T_restrict)) {
2759 kind = ATTRIBUTE_MS_RESTRICT;
2760 } else if (token.type == T_IDENTIFIER) {
2761 const char *name = token.symbol->string;
2763 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2765 const char *attribute_name = get_attribute_name(k);
2766 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2772 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2773 warningf(HERE, "unknown __declspec '%s' ignored", name);
2776 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2780 attribute_t *attribute = allocate_attribute_zero(kind);
2782 if (kind == ATTRIBUTE_MS_PROPERTY) {
2783 return parse_attribute_ms_property(attribute);
2786 /* parse arguments */
2788 attribute->a.arguments = parse_attribute_arguments();
2793 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2797 expect('(', end_error);
2802 add_anchor_token(')');
2804 attribute_t **anchor = &first;
2806 while (*anchor != NULL)
2807 anchor = &(*anchor)->next;
2809 attribute_t *attribute
2810 = parse_microsoft_extended_decl_modifier_single();
2811 if (attribute == NULL)
2814 *anchor = attribute;
2815 anchor = &attribute->next;
2816 } while (next_if(','));
2818 rem_anchor_token(')');
2819 expect(')', end_error);
2823 rem_anchor_token(')');
2827 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2829 entity_t *entity = allocate_entity_zero(kind);
2830 entity->base.source_position = *HERE;
2831 entity->base.symbol = symbol;
2832 if (is_declaration(entity)) {
2833 entity->declaration.type = type_error_type;
2834 entity->declaration.implicit = true;
2835 } else if (kind == ENTITY_TYPEDEF) {
2836 entity->typedefe.type = type_error_type;
2837 entity->typedefe.builtin = true;
2839 if (kind != ENTITY_COMPOUND_MEMBER)
2840 record_entity(entity, false);
2844 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2846 type_t *type = NULL;
2847 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2848 unsigned type_specifiers = 0;
2849 bool newtype = false;
2850 bool saw_error = false;
2851 bool old_gcc_extension = in_gcc_extension;
2853 specifiers->source_position = token.source_position;
2856 specifiers->attributes = parse_attributes(specifiers->attributes);
2858 switch (token.type) {
2860 #define MATCH_STORAGE_CLASS(token, class) \
2862 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2863 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2865 specifiers->storage_class = class; \
2866 if (specifiers->thread_local) \
2867 goto check_thread_storage_class; \
2871 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2872 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2873 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2874 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2875 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2878 specifiers->attributes
2879 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2883 if (specifiers->thread_local) {
2884 errorf(HERE, "duplicate '__thread'");
2886 specifiers->thread_local = true;
2887 check_thread_storage_class:
2888 switch (specifiers->storage_class) {
2889 case STORAGE_CLASS_EXTERN:
2890 case STORAGE_CLASS_NONE:
2891 case STORAGE_CLASS_STATIC:
2895 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
2896 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2897 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
2898 wrong_thread_stoarge_class:
2899 errorf(HERE, "'__thread' used with '%s'", wrong);
2906 /* type qualifiers */
2907 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2909 qualifiers |= qualifier; \
2913 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2914 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2915 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2916 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2917 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2918 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2919 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2920 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2922 case T___extension__:
2924 in_gcc_extension = true;
2927 /* type specifiers */
2928 #define MATCH_SPECIFIER(token, specifier, name) \
2930 if (type_specifiers & specifier) { \
2931 errorf(HERE, "multiple " name " type specifiers given"); \
2933 type_specifiers |= specifier; \
2938 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2939 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2940 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2941 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2942 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2943 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2944 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2945 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2946 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2947 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2948 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2949 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2950 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2951 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2952 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2953 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2954 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2955 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2959 specifiers->is_inline = true;
2963 case T__forceinline:
2965 specifiers->modifiers |= DM_FORCEINLINE;
2970 if (type_specifiers & SPECIFIER_LONG_LONG) {
2971 errorf(HERE, "multiple type specifiers given");
2972 } else if (type_specifiers & SPECIFIER_LONG) {
2973 type_specifiers |= SPECIFIER_LONG_LONG;
2975 type_specifiers |= SPECIFIER_LONG;
2980 #define CHECK_DOUBLE_TYPE() \
2981 if ( type != NULL) \
2982 errorf(HERE, "multiple data types in declaration specifiers");
2985 CHECK_DOUBLE_TYPE();
2986 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2988 type->compound.compound = parse_compound_type_specifier(true);
2991 CHECK_DOUBLE_TYPE();
2992 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2993 type->compound.compound = parse_compound_type_specifier(false);
2996 CHECK_DOUBLE_TYPE();
2997 type = parse_enum_specifier();
3000 CHECK_DOUBLE_TYPE();
3001 type = parse_typeof();
3003 case T___builtin_va_list:
3004 CHECK_DOUBLE_TYPE();
3005 type = duplicate_type(type_valist);
3009 case T_IDENTIFIER: {
3010 /* only parse identifier if we haven't found a type yet */
3011 if (type != NULL || type_specifiers != 0) {
3012 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3013 * declaration, so it doesn't generate errors about expecting '(' or
3015 switch (look_ahead(1)->type) {
3022 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3026 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3031 goto finish_specifiers;
3035 type_t *const typedef_type = get_typedef_type(token.symbol);
3036 if (typedef_type == NULL) {
3037 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3038 * declaration, so it doesn't generate 'implicit int' followed by more
3039 * errors later on. */
3040 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3046 errorf(HERE, "%K does not name a type", &token);
3049 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3051 type = allocate_type_zero(TYPE_TYPEDEF);
3052 type->typedeft.typedefe = &entity->typedefe;
3056 if (la1_type == '&' || la1_type == '*')
3057 goto finish_specifiers;
3062 goto finish_specifiers;
3067 type = typedef_type;
3071 /* function specifier */
3073 goto finish_specifiers;
3078 specifiers->attributes = parse_attributes(specifiers->attributes);
3080 in_gcc_extension = old_gcc_extension;
3082 if (type == NULL || (saw_error && type_specifiers != 0)) {
3083 atomic_type_kind_t atomic_type;
3085 /* match valid basic types */
3086 switch (type_specifiers) {
3087 case SPECIFIER_VOID:
3088 atomic_type = ATOMIC_TYPE_VOID;
3090 case SPECIFIER_WCHAR_T:
3091 atomic_type = ATOMIC_TYPE_WCHAR_T;
3093 case SPECIFIER_CHAR:
3094 atomic_type = ATOMIC_TYPE_CHAR;
3096 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3097 atomic_type = ATOMIC_TYPE_SCHAR;
3099 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3100 atomic_type = ATOMIC_TYPE_UCHAR;
3102 case SPECIFIER_SHORT:
3103 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3104 case SPECIFIER_SHORT | SPECIFIER_INT:
3105 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3106 atomic_type = ATOMIC_TYPE_SHORT;
3108 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3109 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3110 atomic_type = ATOMIC_TYPE_USHORT;
3113 case SPECIFIER_SIGNED:
3114 case SPECIFIER_SIGNED | SPECIFIER_INT:
3115 atomic_type = ATOMIC_TYPE_INT;
3117 case SPECIFIER_UNSIGNED:
3118 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3119 atomic_type = ATOMIC_TYPE_UINT;
3121 case SPECIFIER_LONG:
3122 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3123 case SPECIFIER_LONG | SPECIFIER_INT:
3124 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3125 atomic_type = ATOMIC_TYPE_LONG;
3127 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3128 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3129 atomic_type = ATOMIC_TYPE_ULONG;
3132 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3133 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3134 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3135 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3137 atomic_type = ATOMIC_TYPE_LONGLONG;
3138 goto warn_about_long_long;
3140 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3141 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3143 atomic_type = ATOMIC_TYPE_ULONGLONG;
3144 warn_about_long_long:
3145 if (warning.long_long) {
3146 warningf(&specifiers->source_position,
3147 "ISO C90 does not support 'long long'");
3151 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3152 atomic_type = unsigned_int8_type_kind;
3155 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3156 atomic_type = unsigned_int16_type_kind;
3159 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3160 atomic_type = unsigned_int32_type_kind;
3163 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3164 atomic_type = unsigned_int64_type_kind;
3167 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3168 atomic_type = unsigned_int128_type_kind;
3171 case SPECIFIER_INT8:
3172 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3173 atomic_type = int8_type_kind;
3176 case SPECIFIER_INT16:
3177 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3178 atomic_type = int16_type_kind;
3181 case SPECIFIER_INT32:
3182 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3183 atomic_type = int32_type_kind;
3186 case SPECIFIER_INT64:
3187 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3188 atomic_type = int64_type_kind;
3191 case SPECIFIER_INT128:
3192 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3193 atomic_type = int128_type_kind;
3196 case SPECIFIER_FLOAT:
3197 atomic_type = ATOMIC_TYPE_FLOAT;
3199 case SPECIFIER_DOUBLE:
3200 atomic_type = ATOMIC_TYPE_DOUBLE;
3202 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3203 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3205 case SPECIFIER_BOOL:
3206 atomic_type = ATOMIC_TYPE_BOOL;
3208 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3209 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3210 atomic_type = ATOMIC_TYPE_FLOAT;
3212 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3213 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3214 atomic_type = ATOMIC_TYPE_DOUBLE;
3216 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3217 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3218 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3221 /* invalid specifier combination, give an error message */
3222 if (type_specifiers == 0) {
3226 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3227 if (!(c_mode & _CXX) && !strict_mode) {
3228 if (warning.implicit_int) {
3229 warningf(HERE, "no type specifiers in declaration, using 'int'");
3231 atomic_type = ATOMIC_TYPE_INT;
3234 errorf(HERE, "no type specifiers given in declaration");
3236 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3237 (type_specifiers & SPECIFIER_UNSIGNED)) {
3238 errorf(HERE, "signed and unsigned specifiers given");
3239 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3240 errorf(HERE, "only integer types can be signed or unsigned");
3242 errorf(HERE, "multiple datatypes in declaration");
3247 if (type_specifiers & SPECIFIER_COMPLEX) {
3248 type = allocate_type_zero(TYPE_COMPLEX);
3249 type->complex.akind = atomic_type;
3250 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3251 type = allocate_type_zero(TYPE_IMAGINARY);
3252 type->imaginary.akind = atomic_type;
3254 type = allocate_type_zero(TYPE_ATOMIC);
3255 type->atomic.akind = atomic_type;
3258 } else if (type_specifiers != 0) {
3259 errorf(HERE, "multiple datatypes in declaration");
3262 /* FIXME: check type qualifiers here */
3263 type->base.qualifiers = qualifiers;
3266 type = identify_new_type(type);
3268 type = typehash_insert(type);
3271 if (specifiers->attributes != NULL)
3272 type = handle_type_attributes(specifiers->attributes, type);
3273 specifiers->type = type;
3277 specifiers->type = type_error_type;
3280 static type_qualifiers_t parse_type_qualifiers(void)
3282 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3285 switch (token.type) {
3286 /* type qualifiers */
3287 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3288 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3289 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3290 /* microsoft extended type modifiers */
3291 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3292 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3293 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3294 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3295 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3304 * Parses an K&R identifier list
3306 static void parse_identifier_list(scope_t *scope)
3309 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3310 entity->base.source_position = token.source_position;
3311 entity->base.namespc = NAMESPACE_NORMAL;
3312 entity->base.symbol = token.symbol;
3313 /* a K&R parameter has no type, yet */
3317 append_entity(scope, entity);
3318 } while (next_if(',') && token.type == T_IDENTIFIER);
3321 static entity_t *parse_parameter(void)
3323 declaration_specifiers_t specifiers;
3324 memset(&specifiers, 0, sizeof(specifiers));
3326 parse_declaration_specifiers(&specifiers);
3328 entity_t *entity = parse_declarator(&specifiers,
3329 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3330 anonymous_entity = NULL;
3334 static void semantic_parameter_incomplete(const entity_t *entity)
3336 assert(entity->kind == ENTITY_PARAMETER);
3338 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3339 * list in a function declarator that is part of a
3340 * definition of that function shall not have
3341 * incomplete type. */
3342 type_t *type = skip_typeref(entity->declaration.type);
3343 if (is_type_incomplete(type)) {
3344 errorf(&entity->base.source_position,
3345 "parameter '%#T' has incomplete type",
3346 entity->declaration.type, entity->base.symbol);
3350 static bool has_parameters(void)
3352 /* func(void) is not a parameter */
3353 if (token.type == T_IDENTIFIER) {
3354 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3357 if (entity->kind != ENTITY_TYPEDEF)
3359 if (skip_typeref(entity->typedefe.type) != type_void)
3361 } else if (token.type != T_void) {
3364 if (look_ahead(1)->type != ')')
3371 * Parses function type parameters (and optionally creates variable_t entities
3372 * for them in a scope)
3374 static void parse_parameters(function_type_t *type, scope_t *scope)
3377 add_anchor_token(')');
3378 int saved_comma_state = save_and_reset_anchor_state(',');
3380 if (token.type == T_IDENTIFIER &&
3381 !is_typedef_symbol(token.symbol)) {
3382 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3383 if (la1_type == ',' || la1_type == ')') {
3384 type->kr_style_parameters = true;
3385 parse_identifier_list(scope);
3386 goto parameters_finished;
3390 if (token.type == ')') {
3391 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3392 if (!(c_mode & _CXX))
3393 type->unspecified_parameters = true;
3394 goto parameters_finished;
3397 if (has_parameters()) {
3398 function_parameter_t **anchor = &type->parameters;
3400 switch (token.type) {
3403 type->variadic = true;
3404 goto parameters_finished;
3407 case T___extension__:
3410 entity_t *entity = parse_parameter();
3411 if (entity->kind == ENTITY_TYPEDEF) {
3412 errorf(&entity->base.source_position,
3413 "typedef not allowed as function parameter");
3416 assert(is_declaration(entity));
3418 semantic_parameter_incomplete(entity);
3420 function_parameter_t *const parameter =
3421 allocate_parameter(entity->declaration.type);
3423 if (scope != NULL) {
3424 append_entity(scope, entity);
3427 *anchor = parameter;
3428 anchor = ¶meter->next;
3433 goto parameters_finished;
3435 } while (next_if(','));
3439 parameters_finished:
3440 rem_anchor_token(')');
3441 expect(')', end_error);
3444 restore_anchor_state(',', saved_comma_state);
3447 typedef enum construct_type_kind_t {
3450 CONSTRUCT_REFERENCE,
3453 } construct_type_kind_t;
3455 typedef union construct_type_t construct_type_t;
3457 typedef struct construct_type_base_t {
3458 construct_type_kind_t kind;
3459 construct_type_t *next;
3460 } construct_type_base_t;
3462 typedef struct parsed_pointer_t {
3463 construct_type_base_t base;
3464 type_qualifiers_t type_qualifiers;
3465 variable_t *base_variable; /**< MS __based extension. */
3468 typedef struct parsed_reference_t {
3469 construct_type_base_t base;
3470 } parsed_reference_t;
3472 typedef struct construct_function_type_t {
3473 construct_type_base_t base;
3474 type_t *function_type;
3475 } construct_function_type_t;
3477 typedef struct parsed_array_t {
3478 construct_type_base_t base;
3479 type_qualifiers_t type_qualifiers;
3485 union construct_type_t {
3486 construct_type_kind_t kind;
3487 construct_type_base_t base;
3488 parsed_pointer_t pointer;
3489 parsed_reference_t reference;
3490 construct_function_type_t function;
3491 parsed_array_t array;
3494 static construct_type_t *parse_pointer_declarator(void)
3498 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3499 memset(pointer, 0, sizeof(pointer[0]));
3500 pointer->base.kind = CONSTRUCT_POINTER;
3501 pointer->type_qualifiers = parse_type_qualifiers();
3502 //pointer->base_variable = base_variable;
3504 return (construct_type_t*) pointer;
3507 static construct_type_t *parse_reference_declarator(void)
3511 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3512 parsed_reference_t *reference = &cons->reference;
3513 memset(reference, 0, sizeof(*reference));
3514 cons->kind = CONSTRUCT_REFERENCE;
3519 static construct_type_t *parse_array_declarator(void)
3522 add_anchor_token(']');
3524 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3525 parsed_array_t *array = &cons->array;
3526 memset(array, 0, sizeof(*array));
3527 cons->kind = CONSTRUCT_ARRAY;
3529 if (next_if(T_static))
3530 array->is_static = true;
3532 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3533 if (type_qualifiers != 0 && next_if(T_static))
3534 array->is_static = true;
3535 array->type_qualifiers = type_qualifiers;
3537 if (token.type == '*' && look_ahead(1)->type == ']') {
3538 array->is_variable = true;
3540 } else if (token.type != ']') {
3541 expression_t *const size = parse_assignment_expression();
3543 /* §6.7.5.2:1 Array size must have integer type */
3544 type_t *const orig_type = size->base.type;
3545 type_t *const type = skip_typeref(orig_type);
3546 if (!is_type_integer(type) && is_type_valid(type)) {
3547 errorf(&size->base.source_position,
3548 "array size '%E' must have integer type but has type '%T'",
3553 mark_vars_read(size, NULL);
3556 rem_anchor_token(']');
3557 expect(']', end_error);
3563 static construct_type_t *parse_function_declarator(scope_t *scope)
3565 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3566 function_type_t *ftype = &type->function;
3568 ftype->linkage = current_linkage;
3569 ftype->calling_convention = CC_DEFAULT;
3571 parse_parameters(ftype, scope);
3573 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3574 construct_function_type_t *function = &cons->function;
3575 memset(function, 0, sizeof(*function));
3576 cons->kind = CONSTRUCT_FUNCTION;
3577 function->function_type = type;
3582 typedef struct parse_declarator_env_t {
3583 bool may_be_abstract : 1;
3584 bool must_be_abstract : 1;
3585 decl_modifiers_t modifiers;
3587 source_position_t source_position;
3589 attribute_t *attributes;
3590 } parse_declarator_env_t;
3592 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3594 /* construct a single linked list of construct_type_t's which describe
3595 * how to construct the final declarator type */
3596 construct_type_t *first = NULL;
3597 construct_type_t **anchor = &first;
3599 env->attributes = parse_attributes(env->attributes);
3602 construct_type_t *type;
3603 //variable_t *based = NULL; /* MS __based extension */
3604 switch (token.type) {
3606 if (!(c_mode & _CXX))
3607 errorf(HERE, "references are only available for C++");
3608 type = parse_reference_declarator();
3612 panic("based not supported anymore");
3617 type = parse_pointer_declarator();
3621 goto ptr_operator_end;
3625 anchor = &type->base.next;
3627 /* TODO: find out if this is correct */
3628 env->attributes = parse_attributes(env->attributes);
3632 construct_type_t *inner_types = NULL;
3634 switch (token.type) {
3636 if (env->must_be_abstract) {
3637 errorf(HERE, "no identifier expected in typename");
3639 env->symbol = token.symbol;
3640 env->source_position = token.source_position;
3645 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3646 * interpreted as ``function with no parameter specification'', rather
3647 * than redundant parentheses around the omitted identifier. */
3648 if (look_ahead(1)->type != ')') {
3650 add_anchor_token(')');
3651 inner_types = parse_inner_declarator(env);
3652 if (inner_types != NULL) {
3653 /* All later declarators only modify the return type */
3654 env->must_be_abstract = true;
3656 rem_anchor_token(')');
3657 expect(')', end_error);
3661 if (env->may_be_abstract)
3663 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3668 construct_type_t **const p = anchor;
3671 construct_type_t *type;
3672 switch (token.type) {
3674 scope_t *scope = NULL;
3675 if (!env->must_be_abstract) {
3676 scope = &env->parameters;
3679 type = parse_function_declarator(scope);
3683 type = parse_array_declarator();
3686 goto declarator_finished;
3689 /* insert in the middle of the list (at p) */
3690 type->base.next = *p;
3693 anchor = &type->base.next;
3696 declarator_finished:
3697 /* append inner_types at the end of the list, we don't to set anchor anymore
3698 * as it's not needed anymore */
3699 *anchor = inner_types;
3706 static type_t *construct_declarator_type(construct_type_t *construct_list,
3709 construct_type_t *iter = construct_list;
3710 for (; iter != NULL; iter = iter->base.next) {
3711 switch (iter->kind) {
3712 case CONSTRUCT_INVALID:
3714 case CONSTRUCT_FUNCTION: {
3715 construct_function_type_t *function = &iter->function;
3716 type_t *function_type = function->function_type;
3718 function_type->function.return_type = type;
3720 type_t *skipped_return_type = skip_typeref(type);
3722 if (is_type_function(skipped_return_type)) {
3723 errorf(HERE, "function returning function is not allowed");
3724 } else if (is_type_array(skipped_return_type)) {
3725 errorf(HERE, "function returning array is not allowed");
3727 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3729 "type qualifiers in return type of function type are meaningless");
3733 /* The function type was constructed earlier. Freeing it here will
3734 * destroy other types. */
3735 type = typehash_insert(function_type);
3739 case CONSTRUCT_POINTER: {
3740 if (is_type_reference(skip_typeref(type)))
3741 errorf(HERE, "cannot declare a pointer to reference");
3743 parsed_pointer_t *pointer = &iter->pointer;
3744 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3748 case CONSTRUCT_REFERENCE:
3749 if (is_type_reference(skip_typeref(type)))
3750 errorf(HERE, "cannot declare a reference to reference");
3752 type = make_reference_type(type);
3755 case CONSTRUCT_ARRAY: {
3756 if (is_type_reference(skip_typeref(type)))
3757 errorf(HERE, "cannot declare an array of references");
3759 parsed_array_t *array = &iter->array;
3760 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3762 expression_t *size_expression = array->size;
3763 if (size_expression != NULL) {
3765 = create_implicit_cast(size_expression, type_size_t);
3768 array_type->base.qualifiers = array->type_qualifiers;
3769 array_type->array.element_type = type;
3770 array_type->array.is_static = array->is_static;
3771 array_type->array.is_variable = array->is_variable;
3772 array_type->array.size_expression = size_expression;
3774 if (size_expression != NULL) {
3775 if (is_constant_expression(size_expression)) {
3777 = fold_constant_to_int(size_expression);
3778 array_type->array.size = size;
3779 array_type->array.size_constant = true;
3780 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3781 * have a value greater than zero. */
3783 if (size < 0 || !GNU_MODE) {
3784 errorf(&size_expression->base.source_position,
3785 "size of array must be greater than zero");
3786 } else if (warning.other) {
3787 warningf(&size_expression->base.source_position,
3788 "zero length arrays are a GCC extension");
3792 array_type->array.is_vla = true;
3796 type_t *skipped_type = skip_typeref(type);
3798 if (is_type_incomplete(skipped_type)) {
3799 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3800 } else if (is_type_function(skipped_type)) {
3801 errorf(HERE, "array of functions is not allowed");
3803 type = identify_new_type(array_type);
3807 internal_errorf(HERE, "invalid type construction found");
3813 static type_t *automatic_type_conversion(type_t *orig_type);
3815 static type_t *semantic_parameter(const source_position_t *pos,
3817 const declaration_specifiers_t *specifiers,
3820 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3821 * shall be adjusted to ``qualified pointer to type'',
3823 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3824 * type'' shall be adjusted to ``pointer to function
3825 * returning type'', as in 6.3.2.1. */
3826 type = automatic_type_conversion(type);
3828 if (specifiers->is_inline && is_type_valid(type)) {
3829 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3832 /* §6.9.1:6 The declarations in the declaration list shall contain
3833 * no storage-class specifier other than register and no
3834 * initializations. */
3835 if (specifiers->thread_local || (
3836 specifiers->storage_class != STORAGE_CLASS_NONE &&
3837 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3839 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3842 /* delay test for incomplete type, because we might have (void)
3843 * which is legal but incomplete... */
3848 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3849 declarator_flags_t flags)
3851 parse_declarator_env_t env;
3852 memset(&env, 0, sizeof(env));
3853 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3855 construct_type_t *construct_type = parse_inner_declarator(&env);
3857 construct_declarator_type(construct_type, specifiers->type);
3858 type_t *type = skip_typeref(orig_type);
3860 if (construct_type != NULL) {
3861 obstack_free(&temp_obst, construct_type);
3864 attribute_t *attributes = parse_attributes(env.attributes);
3865 /* append (shared) specifier attribute behind attributes of this
3867 attribute_t **anchor = &attributes;
3868 while (*anchor != NULL)
3869 anchor = &(*anchor)->next;
3870 *anchor = specifiers->attributes;
3873 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3874 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3875 entity->base.symbol = env.symbol;
3876 entity->base.source_position = env.source_position;
3877 entity->typedefe.type = orig_type;
3879 if (anonymous_entity != NULL) {
3880 if (is_type_compound(type)) {
3881 assert(anonymous_entity->compound.alias == NULL);
3882 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3883 anonymous_entity->kind == ENTITY_UNION);
3884 anonymous_entity->compound.alias = entity;
3885 anonymous_entity = NULL;
3886 } else if (is_type_enum(type)) {
3887 assert(anonymous_entity->enume.alias == NULL);
3888 assert(anonymous_entity->kind == ENTITY_ENUM);
3889 anonymous_entity->enume.alias = entity;
3890 anonymous_entity = NULL;
3894 /* create a declaration type entity */
3895 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3896 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3898 if (env.symbol != NULL) {
3899 if (specifiers->is_inline && is_type_valid(type)) {
3900 errorf(&env.source_position,
3901 "compound member '%Y' declared 'inline'", env.symbol);
3904 if (specifiers->thread_local ||
3905 specifiers->storage_class != STORAGE_CLASS_NONE) {
3906 errorf(&env.source_position,
3907 "compound member '%Y' must have no storage class",
3911 } else if (flags & DECL_IS_PARAMETER) {
3912 orig_type = semantic_parameter(&env.source_position, orig_type,
3913 specifiers, env.symbol);
3915 entity = allocate_entity_zero(ENTITY_PARAMETER);
3916 } else if (is_type_function(type)) {
3917 entity = allocate_entity_zero(ENTITY_FUNCTION);
3919 entity->function.is_inline = specifiers->is_inline;
3920 entity->function.parameters = env.parameters;
3922 if (env.symbol != NULL) {
3923 /* this needs fixes for C++ */
3924 bool in_function_scope = current_function != NULL;
3926 if (specifiers->thread_local || (
3927 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3928 specifiers->storage_class != STORAGE_CLASS_NONE &&
3929 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3931 errorf(&env.source_position,
3932 "invalid storage class for function '%Y'", env.symbol);
3936 entity = allocate_entity_zero(ENTITY_VARIABLE);
3938 entity->variable.thread_local = specifiers->thread_local;
3940 if (env.symbol != NULL) {
3941 if (specifiers->is_inline && is_type_valid(type)) {
3942 errorf(&env.source_position,
3943 "variable '%Y' declared 'inline'", env.symbol);
3946 bool invalid_storage_class = false;
3947 if (current_scope == file_scope) {
3948 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3949 specifiers->storage_class != STORAGE_CLASS_NONE &&
3950 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3951 invalid_storage_class = true;
3954 if (specifiers->thread_local &&
3955 specifiers->storage_class == STORAGE_CLASS_NONE) {
3956 invalid_storage_class = true;
3959 if (invalid_storage_class) {
3960 errorf(&env.source_position,
3961 "invalid storage class for variable '%Y'", env.symbol);
3966 if (env.symbol != NULL) {
3967 entity->base.symbol = env.symbol;
3968 entity->base.source_position = env.source_position;
3970 entity->base.source_position = specifiers->source_position;
3972 entity->base.namespc = NAMESPACE_NORMAL;
3973 entity->declaration.type = orig_type;
3974 entity->declaration.alignment = get_type_alignment(orig_type);
3975 entity->declaration.modifiers = env.modifiers;
3976 entity->declaration.attributes = attributes;
3978 storage_class_t storage_class = specifiers->storage_class;
3979 entity->declaration.declared_storage_class = storage_class;
3981 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3982 storage_class = STORAGE_CLASS_AUTO;
3983 entity->declaration.storage_class = storage_class;
3986 if (attributes != NULL) {
3987 handle_entity_attributes(attributes, entity);
3993 static type_t *parse_abstract_declarator(type_t *base_type)
3995 parse_declarator_env_t env;
3996 memset(&env, 0, sizeof(env));
3997 env.may_be_abstract = true;
3998 env.must_be_abstract = true;
4000 construct_type_t *construct_type = parse_inner_declarator(&env);
4002 type_t *result = construct_declarator_type(construct_type, base_type);
4003 if (construct_type != NULL) {
4004 obstack_free(&temp_obst, construct_type);
4006 result = handle_type_attributes(env.attributes, result);
4012 * Check if the declaration of main is suspicious. main should be a
4013 * function with external linkage, returning int, taking either zero
4014 * arguments, two, or three arguments of appropriate types, ie.
4016 * int main([ int argc, char **argv [, char **env ] ]).
4018 * @param decl the declaration to check
4019 * @param type the function type of the declaration
4021 static void check_main(const entity_t *entity)
4023 const source_position_t *pos = &entity->base.source_position;
4024 if (entity->kind != ENTITY_FUNCTION) {
4025 warningf(pos, "'main' is not a function");
4029 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4030 warningf(pos, "'main' is normally a non-static function");
4033 type_t *type = skip_typeref(entity->declaration.type);
4034 assert(is_type_function(type));
4036 function_type_t *func_type = &type->function;
4037 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4038 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4039 func_type->return_type);
4041 const function_parameter_t *parm = func_type->parameters;
4043 type_t *const first_type = parm->type;
4044 if (!types_compatible(skip_typeref(first_type), type_int)) {
4046 "first argument of 'main' should be 'int', but is '%T'",
4051 type_t *const second_type = parm->type;
4052 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4053 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4057 type_t *const third_type = parm->type;
4058 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4059 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4063 goto warn_arg_count;
4067 warningf(pos, "'main' takes only zero, two or three arguments");
4073 * Check if a symbol is the equal to "main".
4075 static bool is_sym_main(const symbol_t *const sym)
4077 return strcmp(sym->string, "main") == 0;
4080 static void error_redefined_as_different_kind(const source_position_t *pos,
4081 const entity_t *old, entity_kind_t new_kind)
4083 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4084 get_entity_kind_name(old->kind), old->base.symbol,
4085 get_entity_kind_name(new_kind), &old->base.source_position);
4088 static bool is_error_entity(entity_t *const ent)
4090 if (is_declaration(ent)) {
4091 return is_type_valid(skip_typeref(ent->declaration.type));
4092 } else if (ent->kind == ENTITY_TYPEDEF) {
4093 return is_type_valid(skip_typeref(ent->typedefe.type));
4098 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4100 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4101 if (attributes_equal(tattr, attr))
4108 * test wether new_list contains any attributes not included in old_list
4110 static bool has_new_attributes(const attribute_t *old_list,
4111 const attribute_t *new_list)
4113 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4114 if (!contains_attribute(old_list, attr))
4121 * Merge in attributes from an attribute list (probably from a previous
4122 * declaration with the same name). Warning: destroys the old structure
4123 * of the attribute list - don't reuse attributes after this call.
4125 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4128 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4130 if (contains_attribute(decl->attributes, attr))
4133 /* move attribute to new declarations attributes list */
4134 attr->next = decl->attributes;
4135 decl->attributes = attr;
4140 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4141 * for various problems that occur for multiple definitions
4143 entity_t *record_entity(entity_t *entity, const bool is_definition)
4145 const symbol_t *const symbol = entity->base.symbol;
4146 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4147 const source_position_t *pos = &entity->base.source_position;
4149 /* can happen in error cases */
4153 entity_t *const previous_entity = get_entity(symbol, namespc);
4154 /* pushing the same entity twice will break the stack structure */
4155 assert(previous_entity != entity);
4157 if (entity->kind == ENTITY_FUNCTION) {
4158 type_t *const orig_type = entity->declaration.type;
4159 type_t *const type = skip_typeref(orig_type);
4161 assert(is_type_function(type));
4162 if (type->function.unspecified_parameters &&
4163 warning.strict_prototypes &&
4164 previous_entity == NULL) {
4165 warningf(pos, "function declaration '%#T' is not a prototype",
4169 if (warning.main && current_scope == file_scope
4170 && is_sym_main(symbol)) {
4175 if (is_declaration(entity) &&
4176 warning.nested_externs &&
4177 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4178 current_scope != file_scope) {
4179 warningf(pos, "nested extern declaration of '%#T'",
4180 entity->declaration.type, symbol);
4183 if (previous_entity != NULL) {
4184 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4185 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4186 assert(previous_entity->kind == ENTITY_PARAMETER);
4188 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4189 entity->declaration.type, symbol,
4190 previous_entity->declaration.type, symbol,
4191 &previous_entity->base.source_position);
4195 if (previous_entity->base.parent_scope == current_scope) {
4196 if (previous_entity->kind != entity->kind) {
4197 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4198 error_redefined_as_different_kind(pos, previous_entity,
4203 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4204 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4205 symbol, &previous_entity->base.source_position);
4208 if (previous_entity->kind == ENTITY_TYPEDEF) {
4209 /* TODO: C++ allows this for exactly the same type */
4210 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4211 symbol, &previous_entity->base.source_position);
4215 /* at this point we should have only VARIABLES or FUNCTIONS */
4216 assert(is_declaration(previous_entity) && is_declaration(entity));
4218 declaration_t *const prev_decl = &previous_entity->declaration;
4219 declaration_t *const decl = &entity->declaration;
4221 /* can happen for K&R style declarations */
4222 if (prev_decl->type == NULL &&
4223 previous_entity->kind == ENTITY_PARAMETER &&
4224 entity->kind == ENTITY_PARAMETER) {
4225 prev_decl->type = decl->type;
4226 prev_decl->storage_class = decl->storage_class;
4227 prev_decl->declared_storage_class = decl->declared_storage_class;
4228 prev_decl->modifiers = decl->modifiers;
4229 return previous_entity;
4232 type_t *const orig_type = decl->type;
4233 assert(orig_type != NULL);
4234 type_t *const type = skip_typeref(orig_type);
4235 type_t *const prev_type = skip_typeref(prev_decl->type);
4237 if (!types_compatible(type, prev_type)) {
4239 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4240 orig_type, symbol, prev_decl->type, symbol,
4241 &previous_entity->base.source_position);
4243 unsigned old_storage_class = prev_decl->storage_class;
4245 if (warning.redundant_decls &&
4248 !(prev_decl->modifiers & DM_USED) &&
4249 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4250 warningf(&previous_entity->base.source_position,
4251 "unnecessary static forward declaration for '%#T'",
4252 prev_decl->type, symbol);
4255 storage_class_t new_storage_class = decl->storage_class;
4257 /* pretend no storage class means extern for function
4258 * declarations (except if the previous declaration is neither
4259 * none nor extern) */
4260 if (entity->kind == ENTITY_FUNCTION) {
4261 /* the previous declaration could have unspecified parameters or
4262 * be a typedef, so use the new type */
4263 if (prev_type->function.unspecified_parameters || is_definition)
4264 prev_decl->type = type;
4266 switch (old_storage_class) {
4267 case STORAGE_CLASS_NONE:
4268 old_storage_class = STORAGE_CLASS_EXTERN;
4271 case STORAGE_CLASS_EXTERN:
4272 if (is_definition) {
4273 if (warning.missing_prototypes &&
4274 prev_type->function.unspecified_parameters &&
4275 !is_sym_main(symbol)) {
4276 warningf(pos, "no previous prototype for '%#T'",
4279 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4280 new_storage_class = STORAGE_CLASS_EXTERN;
4287 } else if (is_type_incomplete(prev_type)) {
4288 prev_decl->type = type;
4291 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4292 new_storage_class == STORAGE_CLASS_EXTERN) {
4294 warn_redundant_declaration: ;
4296 = has_new_attributes(prev_decl->attributes,
4298 if (has_new_attrs) {
4299 merge_in_attributes(decl, prev_decl->attributes);
4300 } else if (!is_definition &&
4301 warning.redundant_decls &&
4302 is_type_valid(prev_type) &&
4303 strcmp(previous_entity->base.source_position.input_name,
4304 "<builtin>") != 0) {
4306 "redundant declaration for '%Y' (declared %P)",
4307 symbol, &previous_entity->base.source_position);
4309 } else if (current_function == NULL) {
4310 if (old_storage_class != STORAGE_CLASS_STATIC &&
4311 new_storage_class == STORAGE_CLASS_STATIC) {
4313 "static declaration of '%Y' follows non-static declaration (declared %P)",
4314 symbol, &previous_entity->base.source_position);
4315 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4316 prev_decl->storage_class = STORAGE_CLASS_NONE;
4317 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4319 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4321 goto error_redeclaration;
4322 goto warn_redundant_declaration;
4324 } else if (is_type_valid(prev_type)) {
4325 if (old_storage_class == new_storage_class) {
4326 error_redeclaration:
4327 errorf(pos, "redeclaration of '%Y' (declared %P)",
4328 symbol, &previous_entity->base.source_position);
4331 "redeclaration of '%Y' with different linkage (declared %P)",
4332 symbol, &previous_entity->base.source_position);
4337 prev_decl->modifiers |= decl->modifiers;
4338 if (entity->kind == ENTITY_FUNCTION) {
4339 previous_entity->function.is_inline |= entity->function.is_inline;
4341 return previous_entity;
4344 if (warning.shadow) {
4345 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4346 get_entity_kind_name(entity->kind), symbol,
4347 get_entity_kind_name(previous_entity->kind),
4348 &previous_entity->base.source_position);
4352 if (entity->kind == ENTITY_FUNCTION) {
4353 if (is_definition &&
4354 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4355 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4356 warningf(pos, "no previous prototype for '%#T'",
4357 entity->declaration.type, symbol);
4358 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4359 warningf(pos, "no previous declaration for '%#T'",
4360 entity->declaration.type, symbol);
4363 } else if (warning.missing_declarations &&
4364 entity->kind == ENTITY_VARIABLE &&
4365 current_scope == file_scope) {
4366 declaration_t *declaration = &entity->declaration;
4367 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4368 warningf(pos, "no previous declaration for '%#T'",
4369 declaration->type, symbol);
4374 assert(entity->base.parent_scope == NULL);
4375 assert(current_scope != NULL);
4377 entity->base.parent_scope = current_scope;
4378 entity->base.namespc = NAMESPACE_NORMAL;
4379 environment_push(entity);
4380 append_entity(current_scope, entity);
4385 static void parser_error_multiple_definition(entity_t *entity,
4386 const source_position_t *source_position)
4388 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4389 entity->base.symbol, &entity->base.source_position);
4392 static bool is_declaration_specifier(const token_t *token,
4393 bool only_specifiers_qualifiers)
4395 switch (token->type) {
4400 return is_typedef_symbol(token->symbol);
4402 case T___extension__:
4404 return !only_specifiers_qualifiers;
4411 static void parse_init_declarator_rest(entity_t *entity)
4413 assert(is_declaration(entity));
4414 declaration_t *const declaration = &entity->declaration;
4418 type_t *orig_type = declaration->type;
4419 type_t *type = skip_typeref(orig_type);
4421 if (entity->kind == ENTITY_VARIABLE
4422 && entity->variable.initializer != NULL) {
4423 parser_error_multiple_definition(entity, HERE);
4426 bool must_be_constant = false;
4427 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4428 entity->base.parent_scope == file_scope) {
4429 must_be_constant = true;
4432 if (is_type_function(type)) {
4433 errorf(&entity->base.source_position,
4434 "function '%#T' is initialized like a variable",
4435 orig_type, entity->base.symbol);
4436 orig_type = type_error_type;
4439 parse_initializer_env_t env;
4440 env.type = orig_type;
4441 env.must_be_constant = must_be_constant;
4442 env.entity = entity;
4443 current_init_decl = entity;
4445 initializer_t *initializer = parse_initializer(&env);
4446 current_init_decl = NULL;
4448 if (entity->kind == ENTITY_VARIABLE) {
4449 /* §6.7.5:22 array initializers for arrays with unknown size
4450 * determine the array type size */
4451 declaration->type = env.type;
4452 entity->variable.initializer = initializer;
4456 /* parse rest of a declaration without any declarator */
4457 static void parse_anonymous_declaration_rest(
4458 const declaration_specifiers_t *specifiers)
4461 anonymous_entity = NULL;
4463 if (warning.other) {
4464 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4465 specifiers->thread_local) {
4466 warningf(&specifiers->source_position,
4467 "useless storage class in empty declaration");
4470 type_t *type = specifiers->type;
4471 switch (type->kind) {
4472 case TYPE_COMPOUND_STRUCT:
4473 case TYPE_COMPOUND_UNION: {
4474 if (type->compound.compound->base.symbol == NULL) {
4475 warningf(&specifiers->source_position,
4476 "unnamed struct/union that defines no instances");
4485 warningf(&specifiers->source_position, "empty declaration");
4491 static void check_variable_type_complete(entity_t *ent)
4493 if (ent->kind != ENTITY_VARIABLE)
4496 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4497 * type for the object shall be complete [...] */
4498 declaration_t *decl = &ent->declaration;
4499 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4500 decl->storage_class == STORAGE_CLASS_STATIC)
4503 type_t *const orig_type = decl->type;
4504 type_t *const type = skip_typeref(orig_type);
4505 if (!is_type_incomplete(type))
4508 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4509 * are given length one. */
4510 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4511 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4515 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4516 orig_type, ent->base.symbol);
4520 static void parse_declaration_rest(entity_t *ndeclaration,
4521 const declaration_specifiers_t *specifiers,
4522 parsed_declaration_func finished_declaration,
4523 declarator_flags_t flags)
4525 add_anchor_token(';');
4526 add_anchor_token(',');
4528 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4530 if (token.type == '=') {
4531 parse_init_declarator_rest(entity);
4532 } else if (entity->kind == ENTITY_VARIABLE) {
4533 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4534 * [...] where the extern specifier is explicitly used. */
4535 declaration_t *decl = &entity->declaration;
4536 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4537 type_t *type = decl->type;
4538 if (is_type_reference(skip_typeref(type))) {
4539 errorf(&entity->base.source_position,
4540 "reference '%#T' must be initialized",
4541 type, entity->base.symbol);
4546 check_variable_type_complete(entity);
4551 add_anchor_token('=');
4552 ndeclaration = parse_declarator(specifiers, flags);
4553 rem_anchor_token('=');
4555 expect(';', end_error);
4558 anonymous_entity = NULL;
4559 rem_anchor_token(';');
4560 rem_anchor_token(',');
4563 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4565 symbol_t *symbol = entity->base.symbol;
4566 if (symbol == NULL) {
4567 errorf(HERE, "anonymous declaration not valid as function parameter");
4571 assert(entity->base.namespc == NAMESPACE_NORMAL);
4572 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4573 if (previous_entity == NULL
4574 || previous_entity->base.parent_scope != current_scope) {
4575 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4580 if (is_definition) {
4581 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4584 return record_entity(entity, false);
4587 static void parse_declaration(parsed_declaration_func finished_declaration,
4588 declarator_flags_t flags)
4590 declaration_specifiers_t specifiers;
4591 memset(&specifiers, 0, sizeof(specifiers));
4593 add_anchor_token(';');
4594 parse_declaration_specifiers(&specifiers);
4595 rem_anchor_token(';');
4597 if (token.type == ';') {
4598 parse_anonymous_declaration_rest(&specifiers);
4600 entity_t *entity = parse_declarator(&specifiers, flags);
4601 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4606 static type_t *get_default_promoted_type(type_t *orig_type)
4608 type_t *result = orig_type;
4610 type_t *type = skip_typeref(orig_type);
4611 if (is_type_integer(type)) {
4612 result = promote_integer(type);
4613 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4614 result = type_double;
4620 static void parse_kr_declaration_list(entity_t *entity)
4622 if (entity->kind != ENTITY_FUNCTION)
4625 type_t *type = skip_typeref(entity->declaration.type);
4626 assert(is_type_function(type));
4627 if (!type->function.kr_style_parameters)
4630 add_anchor_token('{');
4632 /* push function parameters */
4633 size_t const top = environment_top();
4634 scope_t *old_scope = scope_push(&entity->function.parameters);
4636 entity_t *parameter = entity->function.parameters.entities;
4637 for ( ; parameter != NULL; parameter = parameter->base.next) {
4638 assert(parameter->base.parent_scope == NULL);
4639 parameter->base.parent_scope = current_scope;
4640 environment_push(parameter);
4643 /* parse declaration list */
4645 switch (token.type) {
4647 case T___extension__:
4648 /* This covers symbols, which are no type, too, and results in
4649 * better error messages. The typical cases are misspelled type
4650 * names and missing includes. */
4652 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4660 /* pop function parameters */
4661 assert(current_scope == &entity->function.parameters);
4662 scope_pop(old_scope);
4663 environment_pop_to(top);
4665 /* update function type */
4666 type_t *new_type = duplicate_type(type);
4668 function_parameter_t *parameters = NULL;
4669 function_parameter_t **anchor = ¶meters;
4671 /* did we have an earlier prototype? */
4672 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4673 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4676 function_parameter_t *proto_parameter = NULL;
4677 if (proto_type != NULL) {
4678 type_t *proto_type_type = proto_type->declaration.type;
4679 proto_parameter = proto_type_type->function.parameters;
4680 /* If a K&R function definition has a variadic prototype earlier, then
4681 * make the function definition variadic, too. This should conform to
4682 * §6.7.5.3:15 and §6.9.1:8. */
4683 new_type->function.variadic = proto_type_type->function.variadic;
4685 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4687 new_type->function.unspecified_parameters = true;
4690 bool need_incompatible_warning = false;
4691 parameter = entity->function.parameters.entities;
4692 for (; parameter != NULL; parameter = parameter->base.next,
4694 proto_parameter == NULL ? NULL : proto_parameter->next) {
4695 if (parameter->kind != ENTITY_PARAMETER)
4698 type_t *parameter_type = parameter->declaration.type;
4699 if (parameter_type == NULL) {
4701 errorf(HERE, "no type specified for function parameter '%Y'",
4702 parameter->base.symbol);
4703 parameter_type = type_error_type;
4705 if (warning.implicit_int) {
4706 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4707 parameter->base.symbol);
4709 parameter_type = type_int;
4711 parameter->declaration.type = parameter_type;
4714 semantic_parameter_incomplete(parameter);
4716 /* we need the default promoted types for the function type */
4717 type_t *not_promoted = parameter_type;
4718 parameter_type = get_default_promoted_type(parameter_type);
4720 /* gcc special: if the type of the prototype matches the unpromoted
4721 * type don't promote */
4722 if (!strict_mode && proto_parameter != NULL) {
4723 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4724 type_t *promo_skip = skip_typeref(parameter_type);
4725 type_t *param_skip = skip_typeref(not_promoted);
4726 if (!types_compatible(proto_p_type, promo_skip)
4727 && types_compatible(proto_p_type, param_skip)) {
4729 need_incompatible_warning = true;
4730 parameter_type = not_promoted;
4733 function_parameter_t *const parameter
4734 = allocate_parameter(parameter_type);
4736 *anchor = parameter;
4737 anchor = ¶meter->next;
4740 new_type->function.parameters = parameters;
4741 new_type = identify_new_type(new_type);
4743 if (warning.other && need_incompatible_warning) {
4744 type_t *proto_type_type = proto_type->declaration.type;
4746 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4747 proto_type_type, proto_type->base.symbol,
4748 new_type, entity->base.symbol,
4749 &proto_type->base.source_position);
4752 entity->declaration.type = new_type;
4754 rem_anchor_token('{');
4757 static bool first_err = true;
4760 * When called with first_err set, prints the name of the current function,
4763 static void print_in_function(void)
4767 diagnosticf("%s: In function '%Y':\n",
4768 current_function->base.base.source_position.input_name,
4769 current_function->base.base.symbol);
4774 * Check if all labels are defined in the current function.
4775 * Check if all labels are used in the current function.
4777 static void check_labels(void)
4779 for (const goto_statement_t *goto_statement = goto_first;
4780 goto_statement != NULL;
4781 goto_statement = goto_statement->next) {
4782 /* skip computed gotos */
4783 if (goto_statement->expression != NULL)
4786 label_t *label = goto_statement->label;
4789 if (label->base.source_position.input_name == NULL) {
4790 print_in_function();
4791 errorf(&goto_statement->base.source_position,
4792 "label '%Y' used but not defined", label->base.symbol);
4796 if (warning.unused_label) {
4797 for (const label_statement_t *label_statement = label_first;
4798 label_statement != NULL;
4799 label_statement = label_statement->next) {
4800 label_t *label = label_statement->label;
4802 if (! label->used) {
4803 print_in_function();
4804 warningf(&label_statement->base.source_position,
4805 "label '%Y' defined but not used", label->base.symbol);
4811 static void warn_unused_entity(entity_t *entity, entity_t *last)
4813 entity_t const *const end = last != NULL ? last->base.next : NULL;
4814 for (; entity != end; entity = entity->base.next) {
4815 if (!is_declaration(entity))
4818 declaration_t *declaration = &entity->declaration;
4819 if (declaration->implicit)
4822 if (!declaration->used) {
4823 print_in_function();
4824 const char *what = get_entity_kind_name(entity->kind);
4825 warningf(&entity->base.source_position, "%s '%Y' is unused",
4826 what, entity->base.symbol);
4827 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4828 print_in_function();
4829 const char *what = get_entity_kind_name(entity->kind);
4830 warningf(&entity->base.source_position, "%s '%Y' is never read",
4831 what, entity->base.symbol);
4836 static void check_unused_variables(statement_t *const stmt, void *const env)
4840 switch (stmt->kind) {
4841 case STATEMENT_DECLARATION: {
4842 declaration_statement_t const *const decls = &stmt->declaration;
4843 warn_unused_entity(decls->declarations_begin,
4844 decls->declarations_end);
4849 warn_unused_entity(stmt->fors.scope.entities, NULL);
4858 * Check declarations of current_function for unused entities.
4860 static void check_declarations(void)
4862 if (warning.unused_parameter) {
4863 const scope_t *scope = ¤t_function->parameters;
4865 /* do not issue unused warnings for main */
4866 if (!is_sym_main(current_function->base.base.symbol)) {
4867 warn_unused_entity(scope->entities, NULL);
4870 if (warning.unused_variable) {
4871 walk_statements(current_function->statement, check_unused_variables,
4876 static int determine_truth(expression_t const* const cond)
4879 !is_constant_expression(cond) ? 0 :
4880 fold_constant_to_bool(cond) ? 1 :
4884 static void check_reachable(statement_t *);
4885 static bool reaches_end;
4887 static bool expression_returns(expression_t const *const expr)
4889 switch (expr->kind) {
4891 expression_t const *const func = expr->call.function;
4892 if (func->kind == EXPR_REFERENCE) {
4893 entity_t *entity = func->reference.entity;
4894 if (entity->kind == ENTITY_FUNCTION
4895 && entity->declaration.modifiers & DM_NORETURN)
4899 if (!expression_returns(func))
4902 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4903 if (!expression_returns(arg->expression))
4910 case EXPR_REFERENCE:
4911 case EXPR_REFERENCE_ENUM_VALUE:
4913 case EXPR_STRING_LITERAL:
4914 case EXPR_WIDE_STRING_LITERAL:
4915 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4916 case EXPR_LABEL_ADDRESS:
4917 case EXPR_CLASSIFY_TYPE:
4918 case EXPR_SIZEOF: // TODO handle obscure VLA case
4921 case EXPR_BUILTIN_CONSTANT_P:
4922 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4927 case EXPR_STATEMENT: {
4928 bool old_reaches_end = reaches_end;
4929 reaches_end = false;
4930 check_reachable(expr->statement.statement);
4931 bool returns = reaches_end;
4932 reaches_end = old_reaches_end;
4936 case EXPR_CONDITIONAL:
4937 // TODO handle constant expression
4939 if (!expression_returns(expr->conditional.condition))
4942 if (expr->conditional.true_expression != NULL
4943 && expression_returns(expr->conditional.true_expression))
4946 return expression_returns(expr->conditional.false_expression);
4949 return expression_returns(expr->select.compound);
4951 case EXPR_ARRAY_ACCESS:
4953 expression_returns(expr->array_access.array_ref) &&
4954 expression_returns(expr->array_access.index);
4957 return expression_returns(expr->va_starte.ap);
4960 return expression_returns(expr->va_arge.ap);
4963 return expression_returns(expr->va_copye.src);
4965 EXPR_UNARY_CASES_MANDATORY
4966 return expression_returns(expr->unary.value);
4968 case EXPR_UNARY_THROW:
4972 // TODO handle constant lhs of && and ||
4974 expression_returns(expr->binary.left) &&
4975 expression_returns(expr->binary.right);
4981 panic("unhandled expression");
4984 static bool initializer_returns(initializer_t const *const init)
4986 switch (init->kind) {
4987 case INITIALIZER_VALUE:
4988 return expression_returns(init->value.value);
4990 case INITIALIZER_LIST: {
4991 initializer_t * const* i = init->list.initializers;
4992 initializer_t * const* const end = i + init->list.len;
4993 bool returns = true;
4994 for (; i != end; ++i) {
4995 if (!initializer_returns(*i))
5001 case INITIALIZER_STRING:
5002 case INITIALIZER_WIDE_STRING:
5003 case INITIALIZER_DESIGNATOR: // designators have no payload
5006 panic("unhandled initializer");
5009 static bool noreturn_candidate;
5011 static void check_reachable(statement_t *const stmt)
5013 if (stmt->base.reachable)
5015 if (stmt->kind != STATEMENT_DO_WHILE)
5016 stmt->base.reachable = true;
5018 statement_t *last = stmt;
5020 switch (stmt->kind) {
5021 case STATEMENT_INVALID:
5022 case STATEMENT_EMPTY:
5024 next = stmt->base.next;
5027 case STATEMENT_DECLARATION: {
5028 declaration_statement_t const *const decl = &stmt->declaration;
5029 entity_t const * ent = decl->declarations_begin;
5030 entity_t const *const last = decl->declarations_end;
5032 for (;; ent = ent->base.next) {
5033 if (ent->kind == ENTITY_VARIABLE &&
5034 ent->variable.initializer != NULL &&
5035 !initializer_returns(ent->variable.initializer)) {
5042 next = stmt->base.next;
5046 case STATEMENT_COMPOUND:
5047 next = stmt->compound.statements;
5049 next = stmt->base.next;
5052 case STATEMENT_RETURN: {
5053 expression_t const *const val = stmt->returns.value;
5054 if (val == NULL || expression_returns(val))
5055 noreturn_candidate = false;
5059 case STATEMENT_IF: {
5060 if_statement_t const *const ifs = &stmt->ifs;
5061 expression_t const *const cond = ifs->condition;
5063 if (!expression_returns(cond))
5066 int const val = determine_truth(cond);
5069 check_reachable(ifs->true_statement);
5074 if (ifs->false_statement != NULL) {
5075 check_reachable(ifs->false_statement);
5079 next = stmt->base.next;
5083 case STATEMENT_SWITCH: {
5084 switch_statement_t const *const switchs = &stmt->switchs;
5085 expression_t const *const expr = switchs->expression;
5087 if (!expression_returns(expr))
5090 if (is_constant_expression(expr)) {
5091 long const val = fold_constant_to_int(expr);
5092 case_label_statement_t * defaults = NULL;
5093 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5094 if (i->expression == NULL) {
5099 if (i->first_case <= val && val <= i->last_case) {
5100 check_reachable((statement_t*)i);
5105 if (defaults != NULL) {
5106 check_reachable((statement_t*)defaults);
5110 bool has_default = false;
5111 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5112 if (i->expression == NULL)
5115 check_reachable((statement_t*)i);
5122 next = stmt->base.next;
5126 case STATEMENT_EXPRESSION: {
5127 /* Check for noreturn function call */
5128 expression_t const *const expr = stmt->expression.expression;
5129 if (!expression_returns(expr))
5132 next = stmt->base.next;
5136 case STATEMENT_CONTINUE:
5137 for (statement_t *parent = stmt;;) {
5138 parent = parent->base.parent;
5139 if (parent == NULL) /* continue not within loop */
5143 switch (parent->kind) {
5144 case STATEMENT_WHILE: goto continue_while;
5145 case STATEMENT_DO_WHILE: goto continue_do_while;
5146 case STATEMENT_FOR: goto continue_for;
5152 case STATEMENT_BREAK:
5153 for (statement_t *parent = stmt;;) {
5154 parent = parent->base.parent;
5155 if (parent == NULL) /* break not within loop/switch */
5158 switch (parent->kind) {
5159 case STATEMENT_SWITCH:
5160 case STATEMENT_WHILE:
5161 case STATEMENT_DO_WHILE:
5164 next = parent->base.next;
5165 goto found_break_parent;
5173 case STATEMENT_GOTO:
5174 if (stmt->gotos.expression) {
5175 if (!expression_returns(stmt->gotos.expression))
5178 statement_t *parent = stmt->base.parent;
5179 if (parent == NULL) /* top level goto */
5183 next = stmt->gotos.label->statement;
5184 if (next == NULL) /* missing label */
5189 case STATEMENT_LABEL:
5190 next = stmt->label.statement;
5193 case STATEMENT_CASE_LABEL:
5194 next = stmt->case_label.statement;
5197 case STATEMENT_WHILE: {
5198 while_statement_t const *const whiles = &stmt->whiles;
5199 expression_t const *const cond = whiles->condition;
5201 if (!expression_returns(cond))
5204 int const val = determine_truth(cond);
5207 check_reachable(whiles->body);
5212 next = stmt->base.next;
5216 case STATEMENT_DO_WHILE:
5217 next = stmt->do_while.body;
5220 case STATEMENT_FOR: {
5221 for_statement_t *const fors = &stmt->fors;
5223 if (fors->condition_reachable)
5225 fors->condition_reachable = true;
5227 expression_t const *const cond = fors->condition;
5232 } else if (expression_returns(cond)) {
5233 val = determine_truth(cond);
5239 check_reachable(fors->body);
5244 next = stmt->base.next;
5248 case STATEMENT_MS_TRY: {
5249 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5250 check_reachable(ms_try->try_statement);
5251 next = ms_try->final_statement;
5255 case STATEMENT_LEAVE: {
5256 statement_t *parent = stmt;
5258 parent = parent->base.parent;
5259 if (parent == NULL) /* __leave not within __try */
5262 if (parent->kind == STATEMENT_MS_TRY) {
5264 next = parent->ms_try.final_statement;
5272 panic("invalid statement kind");
5275 while (next == NULL) {
5276 next = last->base.parent;
5278 noreturn_candidate = false;
5280 type_t *const type = skip_typeref(current_function->base.type);
5281 assert(is_type_function(type));
5282 type_t *const ret = skip_typeref(type->function.return_type);
5283 if (warning.return_type &&
5284 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5285 is_type_valid(ret) &&
5286 !is_sym_main(current_function->base.base.symbol)) {
5287 warningf(&stmt->base.source_position,
5288 "control reaches end of non-void function");
5293 switch (next->kind) {
5294 case STATEMENT_INVALID:
5295 case STATEMENT_EMPTY:
5296 case STATEMENT_DECLARATION:
5297 case STATEMENT_EXPRESSION:
5299 case STATEMENT_RETURN:
5300 case STATEMENT_CONTINUE:
5301 case STATEMENT_BREAK:
5302 case STATEMENT_GOTO:
5303 case STATEMENT_LEAVE:
5304 panic("invalid control flow in function");
5306 case STATEMENT_COMPOUND:
5307 if (next->compound.stmt_expr) {
5313 case STATEMENT_SWITCH:
5314 case STATEMENT_LABEL:
5315 case STATEMENT_CASE_LABEL:
5317 next = next->base.next;
5320 case STATEMENT_WHILE: {
5322 if (next->base.reachable)
5324 next->base.reachable = true;
5326 while_statement_t const *const whiles = &next->whiles;
5327 expression_t const *const cond = whiles->condition;
5329 if (!expression_returns(cond))
5332 int const val = determine_truth(cond);
5335 check_reachable(whiles->body);
5341 next = next->base.next;
5345 case STATEMENT_DO_WHILE: {
5347 if (next->base.reachable)
5349 next->base.reachable = true;
5351 do_while_statement_t const *const dw = &next->do_while;
5352 expression_t const *const cond = dw->condition;
5354 if (!expression_returns(cond))
5357 int const val = determine_truth(cond);
5360 check_reachable(dw->body);
5366 next = next->base.next;
5370 case STATEMENT_FOR: {
5372 for_statement_t *const fors = &next->fors;
5374 fors->step_reachable = true;
5376 if (fors->condition_reachable)
5378 fors->condition_reachable = true;
5380 expression_t const *const cond = fors->condition;
5385 } else if (expression_returns(cond)) {
5386 val = determine_truth(cond);
5392 check_reachable(fors->body);
5398 next = next->base.next;
5402 case STATEMENT_MS_TRY:
5404 next = next->ms_try.final_statement;
5409 check_reachable(next);
5412 static void check_unreachable(statement_t* const stmt, void *const env)
5416 switch (stmt->kind) {
5417 case STATEMENT_DO_WHILE:
5418 if (!stmt->base.reachable) {
5419 expression_t const *const cond = stmt->do_while.condition;
5420 if (determine_truth(cond) >= 0) {
5421 warningf(&cond->base.source_position,
5422 "condition of do-while-loop is unreachable");
5427 case STATEMENT_FOR: {
5428 for_statement_t const* const fors = &stmt->fors;
5430 // if init and step are unreachable, cond is unreachable, too
5431 if (!stmt->base.reachable && !fors->step_reachable) {
5432 warningf(&stmt->base.source_position, "statement is unreachable");
5434 if (!stmt->base.reachable && fors->initialisation != NULL) {
5435 warningf(&fors->initialisation->base.source_position,
5436 "initialisation of for-statement is unreachable");
5439 if (!fors->condition_reachable && fors->condition != NULL) {
5440 warningf(&fors->condition->base.source_position,
5441 "condition of for-statement is unreachable");
5444 if (!fors->step_reachable && fors->step != NULL) {
5445 warningf(&fors->step->base.source_position,
5446 "step of for-statement is unreachable");
5452 case STATEMENT_COMPOUND:
5453 if (stmt->compound.statements != NULL)
5455 goto warn_unreachable;
5457 case STATEMENT_DECLARATION: {
5458 /* Only warn if there is at least one declarator with an initializer.
5459 * This typically occurs in switch statements. */
5460 declaration_statement_t const *const decl = &stmt->declaration;
5461 entity_t const * ent = decl->declarations_begin;
5462 entity_t const *const last = decl->declarations_end;
5464 for (;; ent = ent->base.next) {
5465 if (ent->kind == ENTITY_VARIABLE &&
5466 ent->variable.initializer != NULL) {
5467 goto warn_unreachable;
5477 if (!stmt->base.reachable)
5478 warningf(&stmt->base.source_position, "statement is unreachable");
5483 static void parse_external_declaration(void)
5485 /* function-definitions and declarations both start with declaration
5487 declaration_specifiers_t specifiers;
5488 memset(&specifiers, 0, sizeof(specifiers));
5490 add_anchor_token(';');
5491 parse_declaration_specifiers(&specifiers);
5492 rem_anchor_token(';');
5494 /* must be a declaration */
5495 if (token.type == ';') {
5496 parse_anonymous_declaration_rest(&specifiers);
5500 add_anchor_token(',');
5501 add_anchor_token('=');
5502 add_anchor_token(';');
5503 add_anchor_token('{');
5505 /* declarator is common to both function-definitions and declarations */
5506 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5508 rem_anchor_token('{');
5509 rem_anchor_token(';');
5510 rem_anchor_token('=');
5511 rem_anchor_token(',');
5513 /* must be a declaration */
5514 switch (token.type) {
5518 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5523 /* must be a function definition */
5524 parse_kr_declaration_list(ndeclaration);
5526 if (token.type != '{') {
5527 parse_error_expected("while parsing function definition", '{', NULL);
5528 eat_until_matching_token(';');
5532 assert(is_declaration(ndeclaration));
5533 type_t *const orig_type = ndeclaration->declaration.type;
5534 type_t * type = skip_typeref(orig_type);
5536 if (!is_type_function(type)) {
5537 if (is_type_valid(type)) {
5538 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5539 type, ndeclaration->base.symbol);
5543 } else if (is_typeref(orig_type)) {
5545 errorf(&ndeclaration->base.source_position,
5546 "type of function definition '%#T' is a typedef",
5547 orig_type, ndeclaration->base.symbol);
5550 if (warning.aggregate_return &&
5551 is_type_compound(skip_typeref(type->function.return_type))) {
5552 warningf(HERE, "function '%Y' returns an aggregate",
5553 ndeclaration->base.symbol);
5555 if (warning.traditional && !type->function.unspecified_parameters) {
5556 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5557 ndeclaration->base.symbol);
5559 if (warning.old_style_definition && type->function.unspecified_parameters) {
5560 warningf(HERE, "old-style function definition '%Y'",
5561 ndeclaration->base.symbol);
5564 /* §6.7.5.3:14 a function definition with () means no
5565 * parameters (and not unspecified parameters) */
5566 if (type->function.unspecified_parameters &&
5567 type->function.parameters == NULL) {
5568 type_t *copy = duplicate_type(type);
5569 copy->function.unspecified_parameters = false;
5570 type = identify_new_type(copy);
5572 ndeclaration->declaration.type = type;
5575 entity_t *const entity = record_entity(ndeclaration, true);
5576 assert(entity->kind == ENTITY_FUNCTION);
5577 assert(ndeclaration->kind == ENTITY_FUNCTION);
5579 function_t *function = &entity->function;
5580 if (ndeclaration != entity) {
5581 function->parameters = ndeclaration->function.parameters;
5583 assert(is_declaration(entity));
5584 type = skip_typeref(entity->declaration.type);
5586 /* push function parameters and switch scope */
5587 size_t const top = environment_top();
5588 scope_t *old_scope = scope_push(&function->parameters);
5590 entity_t *parameter = function->parameters.entities;
5591 for (; parameter != NULL; parameter = parameter->base.next) {
5592 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5593 parameter->base.parent_scope = current_scope;
5595 assert(parameter->base.parent_scope == NULL
5596 || parameter->base.parent_scope == current_scope);
5597 parameter->base.parent_scope = current_scope;
5598 if (parameter->base.symbol == NULL) {
5599 errorf(¶meter->base.source_position, "parameter name omitted");
5602 environment_push(parameter);
5605 if (function->statement != NULL) {
5606 parser_error_multiple_definition(entity, HERE);
5609 /* parse function body */
5610 int label_stack_top = label_top();
5611 function_t *old_current_function = current_function;
5612 entity_t *old_current_entity = current_entity;
5613 current_function = function;
5614 current_entity = (entity_t*) function;
5615 current_parent = NULL;
5618 goto_anchor = &goto_first;
5620 label_anchor = &label_first;
5622 statement_t *const body = parse_compound_statement(false);
5623 function->statement = body;
5626 check_declarations();
5627 if (warning.return_type ||
5628 warning.unreachable_code ||
5629 (warning.missing_noreturn
5630 && !(function->base.modifiers & DM_NORETURN))) {
5631 noreturn_candidate = true;
5632 check_reachable(body);
5633 if (warning.unreachable_code)
5634 walk_statements(body, check_unreachable, NULL);
5635 if (warning.missing_noreturn &&
5636 noreturn_candidate &&
5637 !(function->base.modifiers & DM_NORETURN)) {
5638 warningf(&body->base.source_position,
5639 "function '%#T' is candidate for attribute 'noreturn'",
5640 type, entity->base.symbol);
5644 assert(current_parent == NULL);
5645 assert(current_function == function);
5646 assert(current_entity == (entity_t*) function);
5647 current_entity = old_current_entity;
5648 current_function = old_current_function;
5649 label_pop_to(label_stack_top);
5652 assert(current_scope == &function->parameters);
5653 scope_pop(old_scope);
5654 environment_pop_to(top);
5657 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5658 source_position_t *source_position,
5659 const symbol_t *symbol)
5661 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5663 type->bitfield.base_type = base_type;
5664 type->bitfield.size_expression = size;
5667 type_t *skipped_type = skip_typeref(base_type);
5668 if (!is_type_integer(skipped_type)) {
5669 errorf(HERE, "bitfield base type '%T' is not an integer type",
5673 bit_size = get_type_size(base_type) * 8;
5676 if (is_constant_expression(size)) {
5677 long v = fold_constant_to_int(size);
5678 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5681 errorf(source_position, "negative width in bit-field '%Y'",
5683 } else if (v == 0 && symbol != NULL) {
5684 errorf(source_position, "zero width for bit-field '%Y'",
5686 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5687 errorf(source_position, "width of '%Y' exceeds its type",
5690 type->bitfield.bit_size = v;
5697 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5699 entity_t *iter = compound->members.entities;
5700 for (; iter != NULL; iter = iter->base.next) {
5701 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5704 if (iter->base.symbol == symbol) {
5706 } else if (iter->base.symbol == NULL) {
5707 /* search in anonymous structs and unions */
5708 type_t *type = skip_typeref(iter->declaration.type);
5709 if (is_type_compound(type)) {
5710 if (find_compound_entry(type->compound.compound, symbol)
5721 static void check_deprecated(const source_position_t *source_position,
5722 const entity_t *entity)
5724 if (!warning.deprecated_declarations)
5726 if (!is_declaration(entity))
5728 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5731 char const *const prefix = get_entity_kind_name(entity->kind);
5732 const char *deprecated_string
5733 = get_deprecated_string(entity->declaration.attributes);
5734 if (deprecated_string != NULL) {
5735 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5736 prefix, entity->base.symbol, &entity->base.source_position,
5739 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5740 entity->base.symbol, &entity->base.source_position);
5745 static expression_t *create_select(const source_position_t *pos,
5747 type_qualifiers_t qualifiers,
5750 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5752 check_deprecated(pos, entry);
5754 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5755 select->select.compound = addr;
5756 select->select.compound_entry = entry;
5758 type_t *entry_type = entry->declaration.type;
5759 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5761 /* we always do the auto-type conversions; the & and sizeof parser contains
5762 * code to revert this! */
5763 select->base.type = automatic_type_conversion(res_type);
5764 if (res_type->kind == TYPE_BITFIELD) {
5765 select->base.type = res_type->bitfield.base_type;
5772 * Find entry with symbol in compound. Search anonymous structs and unions and
5773 * creates implicit select expressions for them.
5774 * Returns the adress for the innermost compound.
5776 static expression_t *find_create_select(const source_position_t *pos,
5778 type_qualifiers_t qualifiers,
5779 compound_t *compound, symbol_t *symbol)
5781 entity_t *iter = compound->members.entities;
5782 for (; iter != NULL; iter = iter->base.next) {
5783 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5786 symbol_t *iter_symbol = iter->base.symbol;
5787 if (iter_symbol == NULL) {
5788 type_t *type = iter->declaration.type;
5789 if (type->kind != TYPE_COMPOUND_STRUCT
5790 && type->kind != TYPE_COMPOUND_UNION)
5793 compound_t *sub_compound = type->compound.compound;
5795 if (find_compound_entry(sub_compound, symbol) == NULL)
5798 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5799 sub_addr->base.source_position = *pos;
5800 sub_addr->select.implicit = true;
5801 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5805 if (iter_symbol == symbol) {
5806 return create_select(pos, addr, qualifiers, iter);
5813 static void parse_compound_declarators(compound_t *compound,
5814 const declaration_specifiers_t *specifiers)
5819 if (token.type == ':') {
5820 source_position_t source_position = *HERE;
5823 type_t *base_type = specifiers->type;
5824 expression_t *size = parse_constant_expression();
5826 type_t *type = make_bitfield_type(base_type, size,
5827 &source_position, NULL);
5829 attribute_t *attributes = parse_attributes(NULL);
5830 attribute_t **anchor = &attributes;
5831 while (*anchor != NULL)
5832 anchor = &(*anchor)->next;
5833 *anchor = specifiers->attributes;
5835 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5836 entity->base.namespc = NAMESPACE_NORMAL;
5837 entity->base.source_position = source_position;
5838 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5839 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5840 entity->declaration.type = type;
5841 entity->declaration.attributes = attributes;
5843 if (attributes != NULL) {
5844 handle_entity_attributes(attributes, entity);
5846 append_entity(&compound->members, entity);
5848 entity = parse_declarator(specifiers,
5849 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5850 if (entity->kind == ENTITY_TYPEDEF) {
5851 errorf(&entity->base.source_position,
5852 "typedef not allowed as compound member");
5854 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5856 /* make sure we don't define a symbol multiple times */
5857 symbol_t *symbol = entity->base.symbol;
5858 if (symbol != NULL) {
5859 entity_t *prev = find_compound_entry(compound, symbol);
5861 errorf(&entity->base.source_position,
5862 "multiple declarations of symbol '%Y' (declared %P)",
5863 symbol, &prev->base.source_position);
5867 if (token.type == ':') {
5868 source_position_t source_position = *HERE;
5870 expression_t *size = parse_constant_expression();
5872 type_t *type = entity->declaration.type;
5873 type_t *bitfield_type = make_bitfield_type(type, size,
5874 &source_position, entity->base.symbol);
5876 attribute_t *attributes = parse_attributes(NULL);
5877 entity->declaration.type = bitfield_type;
5878 handle_entity_attributes(attributes, entity);
5880 type_t *orig_type = entity->declaration.type;
5881 type_t *type = skip_typeref(orig_type);
5882 if (is_type_function(type)) {
5883 errorf(&entity->base.source_position,
5884 "compound member '%Y' must not have function type '%T'",
5885 entity->base.symbol, orig_type);
5886 } else if (is_type_incomplete(type)) {
5887 /* §6.7.2.1:16 flexible array member */
5888 if (!is_type_array(type) ||
5889 token.type != ';' ||
5890 look_ahead(1)->type != '}') {
5891 errorf(&entity->base.source_position,
5892 "compound member '%Y' has incomplete type '%T'",
5893 entity->base.symbol, orig_type);
5898 append_entity(&compound->members, entity);
5901 } while (next_if(','));
5902 expect(';', end_error);
5905 anonymous_entity = NULL;
5908 static void parse_compound_type_entries(compound_t *compound)
5911 add_anchor_token('}');
5913 while (token.type != '}') {
5914 if (token.type == T_EOF) {
5915 errorf(HERE, "EOF while parsing struct");
5918 declaration_specifiers_t specifiers;
5919 memset(&specifiers, 0, sizeof(specifiers));
5920 parse_declaration_specifiers(&specifiers);
5922 parse_compound_declarators(compound, &specifiers);
5924 rem_anchor_token('}');
5928 compound->complete = true;
5931 static type_t *parse_typename(void)
5933 declaration_specifiers_t specifiers;
5934 memset(&specifiers, 0, sizeof(specifiers));
5935 parse_declaration_specifiers(&specifiers);
5936 if (specifiers.storage_class != STORAGE_CLASS_NONE
5937 || specifiers.thread_local) {
5938 /* TODO: improve error message, user does probably not know what a
5939 * storage class is...
5941 errorf(HERE, "typename may not have a storage class");
5944 type_t *result = parse_abstract_declarator(specifiers.type);
5952 typedef expression_t* (*parse_expression_function)(void);
5953 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5955 typedef struct expression_parser_function_t expression_parser_function_t;
5956 struct expression_parser_function_t {
5957 parse_expression_function parser;
5958 precedence_t infix_precedence;
5959 parse_expression_infix_function infix_parser;
5962 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5965 * Prints an error message if an expression was expected but not read
5967 static expression_t *expected_expression_error(void)
5969 /* skip the error message if the error token was read */
5970 if (token.type != T_ERROR) {
5971 errorf(HERE, "expected expression, got token %K", &token);
5975 return create_invalid_expression();
5978 static type_t *get_string_type(void)
5980 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
5983 static type_t *get_wide_string_type(void)
5985 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5989 * Parse a string constant.
5991 static expression_t *parse_string_literal(void)
5993 source_position_t begin = token.source_position;
5994 string_t res = token.literal;
5995 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5998 while (token.type == T_STRING_LITERAL
5999 || token.type == T_WIDE_STRING_LITERAL) {
6000 warn_string_concat(&token.source_position);
6001 res = concat_strings(&res, &token.literal);
6003 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6006 expression_t *literal;
6008 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6009 literal->base.type = get_wide_string_type();
6011 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6012 literal->base.type = get_string_type();
6014 literal->base.source_position = begin;
6015 literal->literal.value = res;
6021 * Parse a boolean constant.
6023 static expression_t *parse_boolean_literal(bool value)
6025 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6026 literal->base.source_position = token.source_position;
6027 literal->base.type = type_bool;
6028 literal->literal.value.begin = value ? "true" : "false";
6029 literal->literal.value.size = value ? 4 : 5;
6035 static void warn_traditional_suffix(void)
6037 if (!warning.traditional)
6039 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6043 static void check_integer_suffix(void)
6045 symbol_t *suffix = token.symbol;
6049 bool not_traditional = false;
6050 const char *c = suffix->string;
6051 if (*c == 'l' || *c == 'L') {
6054 not_traditional = true;
6056 if (*c == 'u' || *c == 'U') {
6059 } else if (*c == 'u' || *c == 'U') {
6060 not_traditional = true;
6063 } else if (*c == 'u' || *c == 'U') {
6064 not_traditional = true;
6066 if (*c == 'l' || *c == 'L') {
6074 errorf(&token.source_position,
6075 "invalid suffix '%s' on integer constant", suffix->string);
6076 } else if (not_traditional) {
6077 warn_traditional_suffix();
6081 static type_t *check_floatingpoint_suffix(void)
6083 symbol_t *suffix = token.symbol;
6084 type_t *type = type_double;
6088 bool not_traditional = false;
6089 const char *c = suffix->string;
6090 if (*c == 'f' || *c == 'F') {
6093 } else if (*c == 'l' || *c == 'L') {
6095 type = type_long_double;
6098 errorf(&token.source_position,
6099 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6100 } else if (not_traditional) {
6101 warn_traditional_suffix();
6108 * Parse an integer constant.
6110 static expression_t *parse_number_literal(void)
6112 expression_kind_t kind;
6115 switch (token.type) {
6117 kind = EXPR_LITERAL_INTEGER;
6118 check_integer_suffix();
6120 case T_INTEGER_OCTAL:
6121 kind = EXPR_LITERAL_INTEGER_OCTAL;
6122 check_integer_suffix();
6124 case T_INTEGER_HEXADECIMAL:
6125 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6126 check_integer_suffix();
6128 case T_FLOATINGPOINT:
6129 kind = EXPR_LITERAL_FLOATINGPOINT;
6130 type = check_floatingpoint_suffix();
6132 case T_FLOATINGPOINT_HEXADECIMAL:
6133 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6134 type = check_floatingpoint_suffix();
6137 panic("unexpected token type in parse_number_literal");
6140 expression_t *literal = allocate_expression_zero(kind);
6141 literal->base.source_position = token.source_position;
6142 literal->base.type = type;
6143 literal->literal.value = token.literal;
6144 literal->literal.suffix = token.symbol;
6147 /* integer type depends on the size of the number and the size
6148 * representable by the types. The backend/codegeneration has to determine
6151 determine_literal_type(&literal->literal);
6156 * Parse a character constant.
6158 static expression_t *parse_character_constant(void)
6160 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6161 literal->base.source_position = token.source_position;
6162 literal->base.type = c_mode & _CXX ? type_char : type_int;
6163 literal->literal.value = token.literal;
6165 size_t len = literal->literal.value.size;
6167 if (!GNU_MODE && !(c_mode & _C99)) {
6168 errorf(HERE, "more than 1 character in character constant");
6169 } else if (warning.multichar) {
6170 literal->base.type = type_int;
6171 warningf(HERE, "multi-character character constant");
6180 * Parse a wide character constant.
6182 static expression_t *parse_wide_character_constant(void)
6184 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6185 literal->base.source_position = token.source_position;
6186 literal->base.type = type_int;
6187 literal->literal.value = token.literal;
6189 size_t len = wstrlen(&literal->literal.value);
6191 warningf(HERE, "multi-character character constant");
6198 static entity_t *create_implicit_function(symbol_t *symbol,
6199 const source_position_t *source_position)
6201 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6202 ntype->function.return_type = type_int;
6203 ntype->function.unspecified_parameters = true;
6204 ntype->function.linkage = LINKAGE_C;
6205 type_t *type = identify_new_type(ntype);
6207 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6208 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6209 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6210 entity->declaration.type = type;
6211 entity->declaration.implicit = true;
6212 entity->base.symbol = symbol;
6213 entity->base.source_position = *source_position;
6215 if (current_scope != NULL) {
6216 bool strict_prototypes_old = warning.strict_prototypes;
6217 warning.strict_prototypes = false;
6218 record_entity(entity, false);
6219 warning.strict_prototypes = strict_prototypes_old;
6226 * Performs automatic type cast as described in §6.3.2.1.
6228 * @param orig_type the original type
6230 static type_t *automatic_type_conversion(type_t *orig_type)
6232 type_t *type = skip_typeref(orig_type);
6233 if (is_type_array(type)) {
6234 array_type_t *array_type = &type->array;
6235 type_t *element_type = array_type->element_type;
6236 unsigned qualifiers = array_type->base.qualifiers;
6238 return make_pointer_type(element_type, qualifiers);
6241 if (is_type_function(type)) {
6242 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6249 * reverts the automatic casts of array to pointer types and function
6250 * to function-pointer types as defined §6.3.2.1
6252 type_t *revert_automatic_type_conversion(const expression_t *expression)
6254 switch (expression->kind) {
6255 case EXPR_REFERENCE: {
6256 entity_t *entity = expression->reference.entity;
6257 if (is_declaration(entity)) {
6258 return entity->declaration.type;
6259 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6260 return entity->enum_value.enum_type;
6262 panic("no declaration or enum in reference");
6267 entity_t *entity = expression->select.compound_entry;
6268 assert(is_declaration(entity));
6269 type_t *type = entity->declaration.type;
6270 return get_qualified_type(type,
6271 expression->base.type->base.qualifiers);
6274 case EXPR_UNARY_DEREFERENCE: {
6275 const expression_t *const value = expression->unary.value;
6276 type_t *const type = skip_typeref(value->base.type);
6277 if (!is_type_pointer(type))
6278 return type_error_type;
6279 return type->pointer.points_to;
6282 case EXPR_ARRAY_ACCESS: {
6283 const expression_t *array_ref = expression->array_access.array_ref;
6284 type_t *type_left = skip_typeref(array_ref->base.type);
6285 if (!is_type_pointer(type_left))
6286 return type_error_type;
6287 return type_left->pointer.points_to;
6290 case EXPR_STRING_LITERAL: {
6291 size_t size = expression->string_literal.value.size;
6292 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6295 case EXPR_WIDE_STRING_LITERAL: {
6296 size_t size = wstrlen(&expression->string_literal.value);
6297 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6300 case EXPR_COMPOUND_LITERAL:
6301 return expression->compound_literal.type;
6306 return expression->base.type;
6310 * Find an entity matching a symbol in a scope.
6311 * Uses current scope if scope is NULL
6313 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6314 namespace_tag_t namespc)
6316 if (scope == NULL) {
6317 return get_entity(symbol, namespc);
6320 /* we should optimize here, if scope grows above a certain size we should
6321 construct a hashmap here... */
6322 entity_t *entity = scope->entities;
6323 for ( ; entity != NULL; entity = entity->base.next) {
6324 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6331 static entity_t *parse_qualified_identifier(void)
6333 /* namespace containing the symbol */
6335 source_position_t pos;
6336 const scope_t *lookup_scope = NULL;
6338 if (next_if(T_COLONCOLON))
6339 lookup_scope = &unit->scope;
6343 if (token.type != T_IDENTIFIER) {
6344 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6345 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6347 symbol = token.symbol;
6352 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6354 if (!next_if(T_COLONCOLON))
6357 switch (entity->kind) {
6358 case ENTITY_NAMESPACE:
6359 lookup_scope = &entity->namespacee.members;
6364 lookup_scope = &entity->compound.members;
6367 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6368 symbol, get_entity_kind_name(entity->kind));
6373 if (entity == NULL) {
6374 if (!strict_mode && token.type == '(') {
6375 /* an implicitly declared function */
6376 if (warning.error_implicit_function_declaration) {
6377 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6378 } else if (warning.implicit_function_declaration) {
6379 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6382 entity = create_implicit_function(symbol, &pos);
6384 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6385 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6392 /* skip further qualifications */
6393 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6395 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6398 static expression_t *parse_reference(void)
6400 entity_t *entity = parse_qualified_identifier();
6403 if (is_declaration(entity)) {
6404 orig_type = entity->declaration.type;
6405 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6406 orig_type = entity->enum_value.enum_type;
6408 panic("expected declaration or enum value in reference");
6411 /* we always do the auto-type conversions; the & and sizeof parser contains
6412 * code to revert this! */
6413 type_t *type = automatic_type_conversion(orig_type);
6415 expression_kind_t kind = EXPR_REFERENCE;
6416 if (entity->kind == ENTITY_ENUM_VALUE)
6417 kind = EXPR_REFERENCE_ENUM_VALUE;
6419 expression_t *expression = allocate_expression_zero(kind);
6420 expression->reference.entity = entity;
6421 expression->base.type = type;
6423 /* this declaration is used */
6424 if (is_declaration(entity)) {
6425 entity->declaration.used = true;
6428 if (entity->base.parent_scope != file_scope
6429 && (current_function != NULL
6430 && entity->base.parent_scope->depth < current_function->parameters.depth)
6431 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6432 if (entity->kind == ENTITY_VARIABLE) {
6433 /* access of a variable from an outer function */
6434 entity->variable.address_taken = true;
6435 } else if (entity->kind == ENTITY_PARAMETER) {
6436 entity->parameter.address_taken = true;
6438 current_function->need_closure = true;
6441 check_deprecated(HERE, entity);
6443 if (warning.init_self && entity == current_init_decl && !in_type_prop
6444 && entity->kind == ENTITY_VARIABLE) {
6445 current_init_decl = NULL;
6446 warningf(HERE, "variable '%#T' is initialized by itself",
6447 entity->declaration.type, entity->base.symbol);
6453 static bool semantic_cast(expression_t *cast)
6455 expression_t *expression = cast->unary.value;
6456 type_t *orig_dest_type = cast->base.type;
6457 type_t *orig_type_right = expression->base.type;
6458 type_t const *dst_type = skip_typeref(orig_dest_type);
6459 type_t const *src_type = skip_typeref(orig_type_right);
6460 source_position_t const *pos = &cast->base.source_position;
6462 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6463 if (dst_type == type_void)
6466 /* only integer and pointer can be casted to pointer */
6467 if (is_type_pointer(dst_type) &&
6468 !is_type_pointer(src_type) &&
6469 !is_type_integer(src_type) &&
6470 is_type_valid(src_type)) {
6471 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6475 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6476 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6480 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6481 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6485 if (warning.cast_qual &&
6486 is_type_pointer(src_type) &&
6487 is_type_pointer(dst_type)) {
6488 type_t *src = skip_typeref(src_type->pointer.points_to);
6489 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6490 unsigned missing_qualifiers =
6491 src->base.qualifiers & ~dst->base.qualifiers;
6492 if (missing_qualifiers != 0) {
6494 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6495 missing_qualifiers, orig_type_right);
6501 static expression_t *parse_compound_literal(type_t *type)
6503 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6505 parse_initializer_env_t env;
6508 env.must_be_constant = false;
6509 initializer_t *initializer = parse_initializer(&env);
6512 expression->compound_literal.initializer = initializer;
6513 expression->compound_literal.type = type;
6514 expression->base.type = automatic_type_conversion(type);
6520 * Parse a cast expression.
6522 static expression_t *parse_cast(void)
6524 add_anchor_token(')');
6526 source_position_t source_position = token.source_position;
6528 type_t *type = parse_typename();
6530 rem_anchor_token(')');
6531 expect(')', end_error);
6533 if (token.type == '{') {
6534 return parse_compound_literal(type);
6537 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6538 cast->base.source_position = source_position;
6540 expression_t *value = parse_sub_expression(PREC_CAST);
6541 cast->base.type = type;
6542 cast->unary.value = value;
6544 if (! semantic_cast(cast)) {
6545 /* TODO: record the error in the AST. else it is impossible to detect it */
6550 return create_invalid_expression();
6554 * Parse a statement expression.
6556 static expression_t *parse_statement_expression(void)
6558 add_anchor_token(')');
6560 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6562 statement_t *statement = parse_compound_statement(true);
6563 statement->compound.stmt_expr = true;
6564 expression->statement.statement = statement;
6566 /* find last statement and use its type */
6567 type_t *type = type_void;
6568 const statement_t *stmt = statement->compound.statements;
6570 while (stmt->base.next != NULL)
6571 stmt = stmt->base.next;
6573 if (stmt->kind == STATEMENT_EXPRESSION) {
6574 type = stmt->expression.expression->base.type;
6576 } else if (warning.other) {
6577 warningf(&expression->base.source_position, "empty statement expression ({})");
6579 expression->base.type = type;
6581 rem_anchor_token(')');
6582 expect(')', end_error);
6589 * Parse a parenthesized expression.
6591 static expression_t *parse_parenthesized_expression(void)
6595 switch (token.type) {
6597 /* gcc extension: a statement expression */
6598 return parse_statement_expression();
6602 return parse_cast();
6604 if (is_typedef_symbol(token.symbol)) {
6605 return parse_cast();
6609 add_anchor_token(')');
6610 expression_t *result = parse_expression();
6611 result->base.parenthesized = true;
6612 rem_anchor_token(')');
6613 expect(')', end_error);
6619 static expression_t *parse_function_keyword(void)
6623 if (current_function == NULL) {
6624 errorf(HERE, "'__func__' used outside of a function");
6627 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6628 expression->base.type = type_char_ptr;
6629 expression->funcname.kind = FUNCNAME_FUNCTION;
6636 static expression_t *parse_pretty_function_keyword(void)
6638 if (current_function == NULL) {
6639 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6642 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6643 expression->base.type = type_char_ptr;
6644 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6646 eat(T___PRETTY_FUNCTION__);
6651 static expression_t *parse_funcsig_keyword(void)
6653 if (current_function == NULL) {
6654 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6657 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6658 expression->base.type = type_char_ptr;
6659 expression->funcname.kind = FUNCNAME_FUNCSIG;
6666 static expression_t *parse_funcdname_keyword(void)
6668 if (current_function == NULL) {
6669 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6672 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6673 expression->base.type = type_char_ptr;
6674 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6676 eat(T___FUNCDNAME__);
6681 static designator_t *parse_designator(void)
6683 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6684 result->source_position = *HERE;
6686 if (token.type != T_IDENTIFIER) {
6687 parse_error_expected("while parsing member designator",
6688 T_IDENTIFIER, NULL);
6691 result->symbol = token.symbol;
6694 designator_t *last_designator = result;
6697 if (token.type != T_IDENTIFIER) {
6698 parse_error_expected("while parsing member designator",
6699 T_IDENTIFIER, NULL);
6702 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6703 designator->source_position = *HERE;
6704 designator->symbol = token.symbol;
6707 last_designator->next = designator;
6708 last_designator = designator;
6712 add_anchor_token(']');
6713 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6714 designator->source_position = *HERE;
6715 designator->array_index = parse_expression();
6716 rem_anchor_token(']');
6717 expect(']', end_error);
6718 if (designator->array_index == NULL) {
6722 last_designator->next = designator;
6723 last_designator = designator;
6735 * Parse the __builtin_offsetof() expression.
6737 static expression_t *parse_offsetof(void)
6739 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6740 expression->base.type = type_size_t;
6742 eat(T___builtin_offsetof);
6744 expect('(', end_error);
6745 add_anchor_token(',');
6746 type_t *type = parse_typename();
6747 rem_anchor_token(',');
6748 expect(',', end_error);
6749 add_anchor_token(')');
6750 designator_t *designator = parse_designator();
6751 rem_anchor_token(')');
6752 expect(')', end_error);
6754 expression->offsetofe.type = type;
6755 expression->offsetofe.designator = designator;
6758 memset(&path, 0, sizeof(path));
6759 path.top_type = type;
6760 path.path = NEW_ARR_F(type_path_entry_t, 0);
6762 descend_into_subtype(&path);
6764 if (!walk_designator(&path, designator, true)) {
6765 return create_invalid_expression();
6768 DEL_ARR_F(path.path);
6772 return create_invalid_expression();
6776 * Parses a _builtin_va_start() expression.
6778 static expression_t *parse_va_start(void)
6780 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6782 eat(T___builtin_va_start);
6784 expect('(', end_error);
6785 add_anchor_token(',');
6786 expression->va_starte.ap = parse_assignment_expression();
6787 rem_anchor_token(',');
6788 expect(',', end_error);
6789 expression_t *const expr = parse_assignment_expression();
6790 if (expr->kind == EXPR_REFERENCE) {
6791 entity_t *const entity = expr->reference.entity;
6792 if (!current_function->base.type->function.variadic) {
6793 errorf(&expr->base.source_position,
6794 "'va_start' used in non-variadic function");
6795 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6796 entity->base.next != NULL ||
6797 entity->kind != ENTITY_PARAMETER) {
6798 errorf(&expr->base.source_position,
6799 "second argument of 'va_start' must be last parameter of the current function");
6801 expression->va_starte.parameter = &entity->variable;
6803 expect(')', end_error);
6806 expect(')', end_error);
6808 return create_invalid_expression();
6812 * Parses a __builtin_va_arg() expression.
6814 static expression_t *parse_va_arg(void)
6816 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6818 eat(T___builtin_va_arg);
6820 expect('(', end_error);
6822 ap.expression = parse_assignment_expression();
6823 expression->va_arge.ap = ap.expression;
6824 check_call_argument(type_valist, &ap, 1);
6826 expect(',', end_error);
6827 expression->base.type = parse_typename();
6828 expect(')', end_error);
6832 return create_invalid_expression();
6836 * Parses a __builtin_va_copy() expression.
6838 static expression_t *parse_va_copy(void)
6840 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6842 eat(T___builtin_va_copy);
6844 expect('(', end_error);
6845 expression_t *dst = parse_assignment_expression();
6846 assign_error_t error = semantic_assign(type_valist, dst);
6847 report_assign_error(error, type_valist, dst, "call argument 1",
6848 &dst->base.source_position);
6849 expression->va_copye.dst = dst;
6851 expect(',', end_error);
6853 call_argument_t src;
6854 src.expression = parse_assignment_expression();
6855 check_call_argument(type_valist, &src, 2);
6856 expression->va_copye.src = src.expression;
6857 expect(')', end_error);
6861 return create_invalid_expression();
6865 * Parses a __builtin_constant_p() expression.
6867 static expression_t *parse_builtin_constant(void)
6869 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6871 eat(T___builtin_constant_p);
6873 expect('(', end_error);
6874 add_anchor_token(')');
6875 expression->builtin_constant.value = parse_assignment_expression();
6876 rem_anchor_token(')');
6877 expect(')', end_error);
6878 expression->base.type = type_int;
6882 return create_invalid_expression();
6886 * Parses a __builtin_types_compatible_p() expression.
6888 static expression_t *parse_builtin_types_compatible(void)
6890 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6892 eat(T___builtin_types_compatible_p);
6894 expect('(', end_error);
6895 add_anchor_token(')');
6896 add_anchor_token(',');
6897 expression->builtin_types_compatible.left = parse_typename();
6898 rem_anchor_token(',');
6899 expect(',', end_error);
6900 expression->builtin_types_compatible.right = parse_typename();
6901 rem_anchor_token(')');
6902 expect(')', end_error);
6903 expression->base.type = type_int;
6907 return create_invalid_expression();
6911 * Parses a __builtin_is_*() compare expression.
6913 static expression_t *parse_compare_builtin(void)
6915 expression_t *expression;
6917 switch (token.type) {
6918 case T___builtin_isgreater:
6919 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6921 case T___builtin_isgreaterequal:
6922 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6924 case T___builtin_isless:
6925 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6927 case T___builtin_islessequal:
6928 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6930 case T___builtin_islessgreater:
6931 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6933 case T___builtin_isunordered:
6934 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6937 internal_errorf(HERE, "invalid compare builtin found");
6939 expression->base.source_position = *HERE;
6942 expect('(', end_error);
6943 expression->binary.left = parse_assignment_expression();
6944 expect(',', end_error);
6945 expression->binary.right = parse_assignment_expression();
6946 expect(')', end_error);
6948 type_t *const orig_type_left = expression->binary.left->base.type;
6949 type_t *const orig_type_right = expression->binary.right->base.type;
6951 type_t *const type_left = skip_typeref(orig_type_left);
6952 type_t *const type_right = skip_typeref(orig_type_right);
6953 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6954 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6955 type_error_incompatible("invalid operands in comparison",
6956 &expression->base.source_position, orig_type_left, orig_type_right);
6959 semantic_comparison(&expression->binary);
6964 return create_invalid_expression();
6968 * Parses a MS assume() expression.
6970 static expression_t *parse_assume(void)
6972 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6976 expect('(', end_error);
6977 add_anchor_token(')');
6978 expression->unary.value = parse_assignment_expression();
6979 rem_anchor_token(')');
6980 expect(')', end_error);
6982 expression->base.type = type_void;
6985 return create_invalid_expression();
6989 * Return the declaration for a given label symbol or create a new one.
6991 * @param symbol the symbol of the label
6993 static label_t *get_label(symbol_t *symbol)
6996 assert(current_function != NULL);
6998 label = get_entity(symbol, NAMESPACE_LABEL);
6999 /* if we found a local label, we already created the declaration */
7000 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7001 if (label->base.parent_scope != current_scope) {
7002 assert(label->base.parent_scope->depth < current_scope->depth);
7003 current_function->goto_to_outer = true;
7005 return &label->label;
7008 label = get_entity(symbol, NAMESPACE_LABEL);
7009 /* if we found a label in the same function, then we already created the
7012 && label->base.parent_scope == ¤t_function->parameters) {
7013 return &label->label;
7016 /* otherwise we need to create a new one */
7017 label = allocate_entity_zero(ENTITY_LABEL);
7018 label->base.namespc = NAMESPACE_LABEL;
7019 label->base.symbol = symbol;
7023 return &label->label;
7027 * Parses a GNU && label address expression.
7029 static expression_t *parse_label_address(void)
7031 source_position_t source_position = token.source_position;
7033 if (token.type != T_IDENTIFIER) {
7034 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7037 symbol_t *symbol = token.symbol;
7040 label_t *label = get_label(symbol);
7042 label->address_taken = true;
7044 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7045 expression->base.source_position = source_position;
7047 /* label address is threaten as a void pointer */
7048 expression->base.type = type_void_ptr;
7049 expression->label_address.label = label;
7052 return create_invalid_expression();
7056 * Parse a microsoft __noop expression.
7058 static expression_t *parse_noop_expression(void)
7060 /* the result is a (int)0 */
7061 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7062 literal->base.type = type_int;
7063 literal->base.source_position = token.source_position;
7064 literal->literal.value.begin = "__noop";
7065 literal->literal.value.size = 6;
7069 if (token.type == '(') {
7070 /* parse arguments */
7072 add_anchor_token(')');
7073 add_anchor_token(',');
7075 if (token.type != ')') do {
7076 (void)parse_assignment_expression();
7077 } while (next_if(','));
7079 rem_anchor_token(',');
7080 rem_anchor_token(')');
7081 expect(')', end_error);
7088 * Parses a primary expression.
7090 static expression_t *parse_primary_expression(void)
7092 switch (token.type) {
7093 case T_false: return parse_boolean_literal(false);
7094 case T_true: return parse_boolean_literal(true);
7096 case T_INTEGER_OCTAL:
7097 case T_INTEGER_HEXADECIMAL:
7098 case T_FLOATINGPOINT:
7099 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7100 case T_CHARACTER_CONSTANT: return parse_character_constant();
7101 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7102 case T_STRING_LITERAL:
7103 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7104 case T___FUNCTION__:
7105 case T___func__: return parse_function_keyword();
7106 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7107 case T___FUNCSIG__: return parse_funcsig_keyword();
7108 case T___FUNCDNAME__: return parse_funcdname_keyword();
7109 case T___builtin_offsetof: return parse_offsetof();
7110 case T___builtin_va_start: return parse_va_start();
7111 case T___builtin_va_arg: return parse_va_arg();
7112 case T___builtin_va_copy: return parse_va_copy();
7113 case T___builtin_isgreater:
7114 case T___builtin_isgreaterequal:
7115 case T___builtin_isless:
7116 case T___builtin_islessequal:
7117 case T___builtin_islessgreater:
7118 case T___builtin_isunordered: return parse_compare_builtin();
7119 case T___builtin_constant_p: return parse_builtin_constant();
7120 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7121 case T__assume: return parse_assume();
7124 return parse_label_address();
7127 case '(': return parse_parenthesized_expression();
7128 case T___noop: return parse_noop_expression();
7130 /* Gracefully handle type names while parsing expressions. */
7132 return parse_reference();
7134 if (!is_typedef_symbol(token.symbol)) {
7135 return parse_reference();
7139 source_position_t const pos = *HERE;
7140 type_t const *const type = parse_typename();
7141 errorf(&pos, "encountered type '%T' while parsing expression", type);
7142 return create_invalid_expression();
7146 errorf(HERE, "unexpected token %K, expected an expression", &token);
7147 return create_invalid_expression();
7151 * Check if the expression has the character type and issue a warning then.
7153 static void check_for_char_index_type(const expression_t *expression)
7155 type_t *const type = expression->base.type;
7156 const type_t *const base_type = skip_typeref(type);
7158 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7159 warning.char_subscripts) {
7160 warningf(&expression->base.source_position,
7161 "array subscript has type '%T'", type);
7165 static expression_t *parse_array_expression(expression_t *left)
7167 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7170 add_anchor_token(']');
7172 expression_t *inside = parse_expression();
7174 type_t *const orig_type_left = left->base.type;
7175 type_t *const orig_type_inside = inside->base.type;
7177 type_t *const type_left = skip_typeref(orig_type_left);
7178 type_t *const type_inside = skip_typeref(orig_type_inside);
7180 type_t *return_type;
7181 array_access_expression_t *array_access = &expression->array_access;
7182 if (is_type_pointer(type_left)) {
7183 return_type = type_left->pointer.points_to;
7184 array_access->array_ref = left;
7185 array_access->index = inside;
7186 check_for_char_index_type(inside);
7187 } else if (is_type_pointer(type_inside)) {
7188 return_type = type_inside->pointer.points_to;
7189 array_access->array_ref = inside;
7190 array_access->index = left;
7191 array_access->flipped = true;
7192 check_for_char_index_type(left);
7194 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7196 "array access on object with non-pointer types '%T', '%T'",
7197 orig_type_left, orig_type_inside);
7199 return_type = type_error_type;
7200 array_access->array_ref = left;
7201 array_access->index = inside;
7204 expression->base.type = automatic_type_conversion(return_type);
7206 rem_anchor_token(']');
7207 expect(']', end_error);
7212 static expression_t *parse_typeprop(expression_kind_t const kind)
7214 expression_t *tp_expression = allocate_expression_zero(kind);
7215 tp_expression->base.type = type_size_t;
7217 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7219 /* we only refer to a type property, mark this case */
7220 bool old = in_type_prop;
7221 in_type_prop = true;
7224 expression_t *expression;
7225 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7227 add_anchor_token(')');
7228 orig_type = parse_typename();
7229 rem_anchor_token(')');
7230 expect(')', end_error);
7232 if (token.type == '{') {
7233 /* It was not sizeof(type) after all. It is sizeof of an expression
7234 * starting with a compound literal */
7235 expression = parse_compound_literal(orig_type);
7236 goto typeprop_expression;
7239 expression = parse_sub_expression(PREC_UNARY);
7241 typeprop_expression:
7242 tp_expression->typeprop.tp_expression = expression;
7244 orig_type = revert_automatic_type_conversion(expression);
7245 expression->base.type = orig_type;
7248 tp_expression->typeprop.type = orig_type;
7249 type_t const* const type = skip_typeref(orig_type);
7250 char const* const wrong_type =
7251 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7252 is_type_incomplete(type) ? "incomplete" :
7253 type->kind == TYPE_FUNCTION ? "function designator" :
7254 type->kind == TYPE_BITFIELD ? "bitfield" :
7256 if (wrong_type != NULL) {
7257 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7258 errorf(&tp_expression->base.source_position,
7259 "operand of %s expression must not be of %s type '%T'",
7260 what, wrong_type, orig_type);
7265 return tp_expression;
7268 static expression_t *parse_sizeof(void)
7270 return parse_typeprop(EXPR_SIZEOF);
7273 static expression_t *parse_alignof(void)
7275 return parse_typeprop(EXPR_ALIGNOF);
7278 static expression_t *parse_select_expression(expression_t *addr)
7280 assert(token.type == '.' || token.type == T_MINUSGREATER);
7281 bool select_left_arrow = (token.type == T_MINUSGREATER);
7284 if (token.type != T_IDENTIFIER) {
7285 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7286 return create_invalid_expression();
7288 symbol_t *symbol = token.symbol;
7291 type_t *const orig_type = addr->base.type;
7292 type_t *const type = skip_typeref(orig_type);
7295 bool saw_error = false;
7296 if (is_type_pointer(type)) {
7297 if (!select_left_arrow) {
7299 "request for member '%Y' in something not a struct or union, but '%T'",
7303 type_left = skip_typeref(type->pointer.points_to);
7305 if (select_left_arrow && is_type_valid(type)) {
7306 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7312 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7313 type_left->kind != TYPE_COMPOUND_UNION) {
7315 if (is_type_valid(type_left) && !saw_error) {
7317 "request for member '%Y' in something not a struct or union, but '%T'",
7320 return create_invalid_expression();
7323 compound_t *compound = type_left->compound.compound;
7324 if (!compound->complete) {
7325 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7327 return create_invalid_expression();
7330 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7331 expression_t *result
7332 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7334 if (result == NULL) {
7335 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7336 return create_invalid_expression();
7342 static void check_call_argument(type_t *expected_type,
7343 call_argument_t *argument, unsigned pos)
7345 type_t *expected_type_skip = skip_typeref(expected_type);
7346 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7347 expression_t *arg_expr = argument->expression;
7348 type_t *arg_type = skip_typeref(arg_expr->base.type);
7350 /* handle transparent union gnu extension */
7351 if (is_type_union(expected_type_skip)
7352 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7353 compound_t *union_decl = expected_type_skip->compound.compound;
7354 type_t *best_type = NULL;
7355 entity_t *entry = union_decl->members.entities;
7356 for ( ; entry != NULL; entry = entry->base.next) {
7357 assert(is_declaration(entry));
7358 type_t *decl_type = entry->declaration.type;
7359 error = semantic_assign(decl_type, arg_expr);
7360 if (error == ASSIGN_ERROR_INCOMPATIBLE
7361 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7364 if (error == ASSIGN_SUCCESS) {
7365 best_type = decl_type;
7366 } else if (best_type == NULL) {
7367 best_type = decl_type;
7371 if (best_type != NULL) {
7372 expected_type = best_type;
7376 error = semantic_assign(expected_type, arg_expr);
7377 argument->expression = create_implicit_cast(arg_expr, expected_type);
7379 if (error != ASSIGN_SUCCESS) {
7380 /* report exact scope in error messages (like "in argument 3") */
7382 snprintf(buf, sizeof(buf), "call argument %u", pos);
7383 report_assign_error(error, expected_type, arg_expr, buf,
7384 &arg_expr->base.source_position);
7385 } else if (warning.traditional || warning.conversion) {
7386 type_t *const promoted_type = get_default_promoted_type(arg_type);
7387 if (!types_compatible(expected_type_skip, promoted_type) &&
7388 !types_compatible(expected_type_skip, type_void_ptr) &&
7389 !types_compatible(type_void_ptr, promoted_type)) {
7390 /* Deliberately show the skipped types in this warning */
7391 warningf(&arg_expr->base.source_position,
7392 "passing call argument %u as '%T' rather than '%T' due to prototype",
7393 pos, expected_type_skip, promoted_type);
7399 * Handle the semantic restrictions of builtin calls
7401 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7402 switch (call->function->reference.entity->function.btk) {
7403 case bk_gnu_builtin_return_address:
7404 case bk_gnu_builtin_frame_address: {
7405 /* argument must be constant */
7406 call_argument_t *argument = call->arguments;
7408 if (! is_constant_expression(argument->expression)) {
7409 errorf(&call->base.source_position,
7410 "argument of '%Y' must be a constant expression",
7411 call->function->reference.entity->base.symbol);
7415 case bk_gnu_builtin_prefetch: {
7416 /* second and third argument must be constant if existent */
7417 call_argument_t *rw = call->arguments->next;
7418 call_argument_t *locality = NULL;
7421 if (! is_constant_expression(rw->expression)) {
7422 errorf(&call->base.source_position,
7423 "second argument of '%Y' must be a constant expression",
7424 call->function->reference.entity->base.symbol);
7426 locality = rw->next;
7428 if (locality != NULL) {
7429 if (! is_constant_expression(locality->expression)) {
7430 errorf(&call->base.source_position,
7431 "third argument of '%Y' must be a constant expression",
7432 call->function->reference.entity->base.symbol);
7434 locality = rw->next;
7444 * Parse a call expression, ie. expression '( ... )'.
7446 * @param expression the function address
7448 static expression_t *parse_call_expression(expression_t *expression)
7450 expression_t *result = allocate_expression_zero(EXPR_CALL);
7451 call_expression_t *call = &result->call;
7452 call->function = expression;
7454 type_t *const orig_type = expression->base.type;
7455 type_t *const type = skip_typeref(orig_type);
7457 function_type_t *function_type = NULL;
7458 if (is_type_pointer(type)) {
7459 type_t *const to_type = skip_typeref(type->pointer.points_to);
7461 if (is_type_function(to_type)) {
7462 function_type = &to_type->function;
7463 call->base.type = function_type->return_type;
7467 if (function_type == NULL && is_type_valid(type)) {
7469 "called object '%E' (type '%T') is not a pointer to a function",
7470 expression, orig_type);
7473 /* parse arguments */
7475 add_anchor_token(')');
7476 add_anchor_token(',');
7478 if (token.type != ')') {
7479 call_argument_t **anchor = &call->arguments;
7481 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7482 argument->expression = parse_assignment_expression();
7485 anchor = &argument->next;
7486 } while (next_if(','));
7488 rem_anchor_token(',');
7489 rem_anchor_token(')');
7490 expect(')', end_error);
7492 if (function_type == NULL)
7495 /* check type and count of call arguments */
7496 function_parameter_t *parameter = function_type->parameters;
7497 call_argument_t *argument = call->arguments;
7498 if (!function_type->unspecified_parameters) {
7499 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7500 parameter = parameter->next, argument = argument->next) {
7501 check_call_argument(parameter->type, argument, ++pos);
7504 if (parameter != NULL) {
7505 errorf(HERE, "too few arguments to function '%E'", expression);
7506 } else if (argument != NULL && !function_type->variadic) {
7507 errorf(HERE, "too many arguments to function '%E'", expression);
7511 /* do default promotion for other arguments */
7512 for (; argument != NULL; argument = argument->next) {
7513 type_t *type = argument->expression->base.type;
7515 type = get_default_promoted_type(type);
7517 argument->expression
7518 = create_implicit_cast(argument->expression, type);
7521 check_format(&result->call);
7523 if (warning.aggregate_return &&
7524 is_type_compound(skip_typeref(function_type->return_type))) {
7525 warningf(&result->base.source_position,
7526 "function call has aggregate value");
7529 if (call->function->kind == EXPR_REFERENCE) {
7530 reference_expression_t *reference = &call->function->reference;
7531 if (reference->entity->kind == ENTITY_FUNCTION &&
7532 reference->entity->function.btk != bk_none)
7533 handle_builtin_argument_restrictions(call);
7540 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7542 static bool same_compound_type(const type_t *type1, const type_t *type2)
7545 is_type_compound(type1) &&
7546 type1->kind == type2->kind &&
7547 type1->compound.compound == type2->compound.compound;
7550 static expression_t const *get_reference_address(expression_t const *expr)
7552 bool regular_take_address = true;
7554 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7555 expr = expr->unary.value;
7557 regular_take_address = false;
7560 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7563 expr = expr->unary.value;
7566 if (expr->kind != EXPR_REFERENCE)
7569 /* special case for functions which are automatically converted to a
7570 * pointer to function without an extra TAKE_ADDRESS operation */
7571 if (!regular_take_address &&
7572 expr->reference.entity->kind != ENTITY_FUNCTION) {
7579 static void warn_reference_address_as_bool(expression_t const* expr)
7581 if (!warning.address)
7584 expr = get_reference_address(expr);
7586 warningf(&expr->base.source_position,
7587 "the address of '%Y' will always evaluate as 'true'",
7588 expr->reference.entity->base.symbol);
7592 static void warn_assignment_in_condition(const expression_t *const expr)
7594 if (!warning.parentheses)
7596 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7598 if (expr->base.parenthesized)
7600 warningf(&expr->base.source_position,
7601 "suggest parentheses around assignment used as truth value");
7604 static void semantic_condition(expression_t const *const expr,
7605 char const *const context)
7607 type_t *const type = skip_typeref(expr->base.type);
7608 if (is_type_scalar(type)) {
7609 warn_reference_address_as_bool(expr);
7610 warn_assignment_in_condition(expr);
7611 } else if (is_type_valid(type)) {
7612 errorf(&expr->base.source_position,
7613 "%s must have scalar type", context);
7618 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7620 * @param expression the conditional expression
7622 static expression_t *parse_conditional_expression(expression_t *expression)
7624 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7626 conditional_expression_t *conditional = &result->conditional;
7627 conditional->condition = expression;
7630 add_anchor_token(':');
7632 /* §6.5.15:2 The first operand shall have scalar type. */
7633 semantic_condition(expression, "condition of conditional operator");
7635 expression_t *true_expression = expression;
7636 bool gnu_cond = false;
7637 if (GNU_MODE && token.type == ':') {
7640 true_expression = parse_expression();
7642 rem_anchor_token(':');
7643 expect(':', end_error);
7645 expression_t *false_expression =
7646 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7648 type_t *const orig_true_type = true_expression->base.type;
7649 type_t *const orig_false_type = false_expression->base.type;
7650 type_t *const true_type = skip_typeref(orig_true_type);
7651 type_t *const false_type = skip_typeref(orig_false_type);
7654 type_t *result_type;
7655 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7656 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7657 /* ISO/IEC 14882:1998(E) §5.16:2 */
7658 if (true_expression->kind == EXPR_UNARY_THROW) {
7659 result_type = false_type;
7660 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7661 result_type = true_type;
7663 if (warning.other && (
7664 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7665 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7667 warningf(&conditional->base.source_position,
7668 "ISO C forbids conditional expression with only one void side");
7670 result_type = type_void;
7672 } else if (is_type_arithmetic(true_type)
7673 && is_type_arithmetic(false_type)) {
7674 result_type = semantic_arithmetic(true_type, false_type);
7676 true_expression = create_implicit_cast(true_expression, result_type);
7677 false_expression = create_implicit_cast(false_expression, result_type);
7679 conditional->true_expression = true_expression;
7680 conditional->false_expression = false_expression;
7681 conditional->base.type = result_type;
7682 } else if (same_compound_type(true_type, false_type)) {
7683 /* just take 1 of the 2 types */
7684 result_type = true_type;
7685 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7686 type_t *pointer_type;
7688 expression_t *other_expression;
7689 if (is_type_pointer(true_type) &&
7690 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7691 pointer_type = true_type;
7692 other_type = false_type;
7693 other_expression = false_expression;
7695 pointer_type = false_type;
7696 other_type = true_type;
7697 other_expression = true_expression;
7700 if (is_null_pointer_constant(other_expression)) {
7701 result_type = pointer_type;
7702 } else if (is_type_pointer(other_type)) {
7703 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7704 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7707 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7708 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7710 } else if (types_compatible(get_unqualified_type(to1),
7711 get_unqualified_type(to2))) {
7714 if (warning.other) {
7715 warningf(&conditional->base.source_position,
7716 "pointer types '%T' and '%T' in conditional expression are incompatible",
7717 true_type, false_type);
7722 type_t *const type =
7723 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7724 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7725 } else if (is_type_integer(other_type)) {
7726 if (warning.other) {
7727 warningf(&conditional->base.source_position,
7728 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7730 result_type = pointer_type;
7732 if (is_type_valid(other_type)) {
7733 type_error_incompatible("while parsing conditional",
7734 &expression->base.source_position, true_type, false_type);
7736 result_type = type_error_type;
7739 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7740 type_error_incompatible("while parsing conditional",
7741 &conditional->base.source_position, true_type,
7744 result_type = type_error_type;
7747 conditional->true_expression
7748 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7749 conditional->false_expression
7750 = create_implicit_cast(false_expression, result_type);
7751 conditional->base.type = result_type;
7756 * Parse an extension expression.
7758 static expression_t *parse_extension(void)
7760 eat(T___extension__);
7762 bool old_gcc_extension = in_gcc_extension;
7763 in_gcc_extension = true;
7764 expression_t *expression = parse_sub_expression(PREC_UNARY);
7765 in_gcc_extension = old_gcc_extension;
7770 * Parse a __builtin_classify_type() expression.
7772 static expression_t *parse_builtin_classify_type(void)
7774 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7775 result->base.type = type_int;
7777 eat(T___builtin_classify_type);
7779 expect('(', end_error);
7780 add_anchor_token(')');
7781 expression_t *expression = parse_expression();
7782 rem_anchor_token(')');
7783 expect(')', end_error);
7784 result->classify_type.type_expression = expression;
7788 return create_invalid_expression();
7792 * Parse a delete expression
7793 * ISO/IEC 14882:1998(E) §5.3.5
7795 static expression_t *parse_delete(void)
7797 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7798 result->base.type = type_void;
7803 result->kind = EXPR_UNARY_DELETE_ARRAY;
7804 expect(']', end_error);
7808 expression_t *const value = parse_sub_expression(PREC_CAST);
7809 result->unary.value = value;
7811 type_t *const type = skip_typeref(value->base.type);
7812 if (!is_type_pointer(type)) {
7813 if (is_type_valid(type)) {
7814 errorf(&value->base.source_position,
7815 "operand of delete must have pointer type");
7817 } else if (warning.other &&
7818 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7819 warningf(&value->base.source_position,
7820 "deleting 'void*' is undefined");
7827 * Parse a throw expression
7828 * ISO/IEC 14882:1998(E) §15:1
7830 static expression_t *parse_throw(void)
7832 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7833 result->base.type = type_void;
7837 expression_t *value = NULL;
7838 switch (token.type) {
7840 value = parse_assignment_expression();
7841 /* ISO/IEC 14882:1998(E) §15.1:3 */
7842 type_t *const orig_type = value->base.type;
7843 type_t *const type = skip_typeref(orig_type);
7844 if (is_type_incomplete(type)) {
7845 errorf(&value->base.source_position,
7846 "cannot throw object of incomplete type '%T'", orig_type);
7847 } else if (is_type_pointer(type)) {
7848 type_t *const points_to = skip_typeref(type->pointer.points_to);
7849 if (is_type_incomplete(points_to) &&
7850 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7851 errorf(&value->base.source_position,
7852 "cannot throw pointer to incomplete type '%T'", orig_type);
7860 result->unary.value = value;
7865 static bool check_pointer_arithmetic(const source_position_t *source_position,
7866 type_t *pointer_type,
7867 type_t *orig_pointer_type)
7869 type_t *points_to = pointer_type->pointer.points_to;
7870 points_to = skip_typeref(points_to);
7872 if (is_type_incomplete(points_to)) {
7873 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7874 errorf(source_position,
7875 "arithmetic with pointer to incomplete type '%T' not allowed",
7878 } else if (warning.pointer_arith) {
7879 warningf(source_position,
7880 "pointer of type '%T' used in arithmetic",
7883 } else if (is_type_function(points_to)) {
7885 errorf(source_position,
7886 "arithmetic with pointer to function type '%T' not allowed",
7889 } else if (warning.pointer_arith) {
7890 warningf(source_position,
7891 "pointer to a function '%T' used in arithmetic",
7898 static bool is_lvalue(const expression_t *expression)
7900 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7901 switch (expression->kind) {
7902 case EXPR_ARRAY_ACCESS:
7903 case EXPR_COMPOUND_LITERAL:
7904 case EXPR_REFERENCE:
7906 case EXPR_UNARY_DEREFERENCE:
7910 type_t *type = skip_typeref(expression->base.type);
7912 /* ISO/IEC 14882:1998(E) §3.10:3 */
7913 is_type_reference(type) ||
7914 /* Claim it is an lvalue, if the type is invalid. There was a parse
7915 * error before, which maybe prevented properly recognizing it as
7917 !is_type_valid(type);
7922 static void semantic_incdec(unary_expression_t *expression)
7924 type_t *const orig_type = expression->value->base.type;
7925 type_t *const type = skip_typeref(orig_type);
7926 if (is_type_pointer(type)) {
7927 if (!check_pointer_arithmetic(&expression->base.source_position,
7931 } else if (!is_type_real(type) && is_type_valid(type)) {
7932 /* TODO: improve error message */
7933 errorf(&expression->base.source_position,
7934 "operation needs an arithmetic or pointer type");
7937 if (!is_lvalue(expression->value)) {
7938 /* TODO: improve error message */
7939 errorf(&expression->base.source_position, "lvalue required as operand");
7941 expression->base.type = orig_type;
7944 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7946 type_t *const orig_type = expression->value->base.type;
7947 type_t *const type = skip_typeref(orig_type);
7948 if (!is_type_arithmetic(type)) {
7949 if (is_type_valid(type)) {
7950 /* TODO: improve error message */
7951 errorf(&expression->base.source_position,
7952 "operation needs an arithmetic type");
7957 expression->base.type = orig_type;
7960 static void semantic_unexpr_plus(unary_expression_t *expression)
7962 semantic_unexpr_arithmetic(expression);
7963 if (warning.traditional)
7964 warningf(&expression->base.source_position,
7965 "traditional C rejects the unary plus operator");
7968 static void semantic_not(unary_expression_t *expression)
7970 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7971 semantic_condition(expression->value, "operand of !");
7972 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7975 static void semantic_unexpr_integer(unary_expression_t *expression)
7977 type_t *const orig_type = expression->value->base.type;
7978 type_t *const type = skip_typeref(orig_type);
7979 if (!is_type_integer(type)) {
7980 if (is_type_valid(type)) {
7981 errorf(&expression->base.source_position,
7982 "operand of ~ must be of integer type");
7987 expression->base.type = orig_type;
7990 static void semantic_dereference(unary_expression_t *expression)
7992 type_t *const orig_type = expression->value->base.type;
7993 type_t *const type = skip_typeref(orig_type);
7994 if (!is_type_pointer(type)) {
7995 if (is_type_valid(type)) {
7996 errorf(&expression->base.source_position,
7997 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8002 type_t *result_type = type->pointer.points_to;
8003 result_type = automatic_type_conversion(result_type);
8004 expression->base.type = result_type;
8008 * Record that an address is taken (expression represents an lvalue).
8010 * @param expression the expression
8011 * @param may_be_register if true, the expression might be an register
8013 static void set_address_taken(expression_t *expression, bool may_be_register)
8015 if (expression->kind != EXPR_REFERENCE)
8018 entity_t *const entity = expression->reference.entity;
8020 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8023 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8024 && !may_be_register) {
8025 errorf(&expression->base.source_position,
8026 "address of register %s '%Y' requested",
8027 get_entity_kind_name(entity->kind), entity->base.symbol);
8030 if (entity->kind == ENTITY_VARIABLE) {
8031 entity->variable.address_taken = true;
8033 assert(entity->kind == ENTITY_PARAMETER);
8034 entity->parameter.address_taken = true;
8039 * Check the semantic of the address taken expression.
8041 static void semantic_take_addr(unary_expression_t *expression)
8043 expression_t *value = expression->value;
8044 value->base.type = revert_automatic_type_conversion(value);
8046 type_t *orig_type = value->base.type;
8047 type_t *type = skip_typeref(orig_type);
8048 if (!is_type_valid(type))
8052 if (!is_lvalue(value)) {
8053 errorf(&expression->base.source_position, "'&' requires an lvalue");
8055 if (type->kind == TYPE_BITFIELD) {
8056 errorf(&expression->base.source_position,
8057 "'&' not allowed on object with bitfield type '%T'",
8061 set_address_taken(value, false);
8063 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8066 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8067 static expression_t *parse_##unexpression_type(void) \
8069 expression_t *unary_expression \
8070 = allocate_expression_zero(unexpression_type); \
8072 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8074 sfunc(&unary_expression->unary); \
8076 return unary_expression; \
8079 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8080 semantic_unexpr_arithmetic)
8081 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8082 semantic_unexpr_plus)
8083 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8085 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8086 semantic_dereference)
8087 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8089 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8090 semantic_unexpr_integer)
8091 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8093 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8096 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8098 static expression_t *parse_##unexpression_type(expression_t *left) \
8100 expression_t *unary_expression \
8101 = allocate_expression_zero(unexpression_type); \
8103 unary_expression->unary.value = left; \
8105 sfunc(&unary_expression->unary); \
8107 return unary_expression; \
8110 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8111 EXPR_UNARY_POSTFIX_INCREMENT,
8113 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8114 EXPR_UNARY_POSTFIX_DECREMENT,
8117 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8119 /* TODO: handle complex + imaginary types */
8121 type_left = get_unqualified_type(type_left);
8122 type_right = get_unqualified_type(type_right);
8124 /* §6.3.1.8 Usual arithmetic conversions */
8125 if (type_left == type_long_double || type_right == type_long_double) {
8126 return type_long_double;
8127 } else if (type_left == type_double || type_right == type_double) {
8129 } else if (type_left == type_float || type_right == type_float) {
8133 type_left = promote_integer(type_left);
8134 type_right = promote_integer(type_right);
8136 if (type_left == type_right)
8139 bool const signed_left = is_type_signed(type_left);
8140 bool const signed_right = is_type_signed(type_right);
8141 int const rank_left = get_rank(type_left);
8142 int const rank_right = get_rank(type_right);
8144 if (signed_left == signed_right)
8145 return rank_left >= rank_right ? type_left : type_right;
8154 u_rank = rank_right;
8155 u_type = type_right;
8157 s_rank = rank_right;
8158 s_type = type_right;
8163 if (u_rank >= s_rank)
8166 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8168 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8169 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8173 case ATOMIC_TYPE_INT: return type_unsigned_int;
8174 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8175 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8177 default: panic("invalid atomic type");
8182 * Check the semantic restrictions for a binary expression.
8184 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8186 expression_t *const left = expression->left;
8187 expression_t *const right = expression->right;
8188 type_t *const orig_type_left = left->base.type;
8189 type_t *const orig_type_right = right->base.type;
8190 type_t *const type_left = skip_typeref(orig_type_left);
8191 type_t *const type_right = skip_typeref(orig_type_right);
8193 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8194 /* TODO: improve error message */
8195 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8196 errorf(&expression->base.source_position,
8197 "operation needs arithmetic types");
8202 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8203 expression->left = create_implicit_cast(left, arithmetic_type);
8204 expression->right = create_implicit_cast(right, arithmetic_type);
8205 expression->base.type = arithmetic_type;
8208 static void warn_div_by_zero(binary_expression_t const *const expression)
8210 if (!warning.div_by_zero ||
8211 !is_type_integer(expression->base.type))
8214 expression_t const *const right = expression->right;
8215 /* The type of the right operand can be different for /= */
8216 if (is_type_integer(right->base.type) &&
8217 is_constant_expression(right) &&
8218 !fold_constant_to_bool(right)) {
8219 warningf(&expression->base.source_position, "division by zero");
8224 * Check the semantic restrictions for a div/mod expression.
8226 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8228 semantic_binexpr_arithmetic(expression);
8229 warn_div_by_zero(expression);
8232 static void warn_addsub_in_shift(const expression_t *const expr)
8234 if (expr->base.parenthesized)
8238 switch (expr->kind) {
8239 case EXPR_BINARY_ADD: op = '+'; break;
8240 case EXPR_BINARY_SUB: op = '-'; break;
8244 warningf(&expr->base.source_position,
8245 "suggest parentheses around '%c' inside shift", op);
8248 static bool semantic_shift(binary_expression_t *expression)
8250 expression_t *const left = expression->left;
8251 expression_t *const right = expression->right;
8252 type_t *const orig_type_left = left->base.type;
8253 type_t *const orig_type_right = right->base.type;
8254 type_t * type_left = skip_typeref(orig_type_left);
8255 type_t * type_right = skip_typeref(orig_type_right);
8257 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8258 /* TODO: improve error message */
8259 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8260 errorf(&expression->base.source_position,
8261 "operands of shift operation must have integer types");
8266 type_left = promote_integer(type_left);
8268 if (is_constant_expression(right)) {
8269 long count = fold_constant_to_int(right);
8271 warningf(&right->base.source_position,
8272 "shift count must be non-negative");
8273 } else if ((unsigned long)count >=
8274 get_atomic_type_size(type_left->atomic.akind) * 8) {
8275 warningf(&right->base.source_position,
8276 "shift count must be less than type width");
8280 type_right = promote_integer(type_right);
8281 expression->right = create_implicit_cast(right, type_right);
8286 static void semantic_shift_op(binary_expression_t *expression)
8288 expression_t *const left = expression->left;
8289 expression_t *const right = expression->right;
8291 if (!semantic_shift(expression))
8294 if (warning.parentheses) {
8295 warn_addsub_in_shift(left);
8296 warn_addsub_in_shift(right);
8299 type_t *const orig_type_left = left->base.type;
8300 type_t * type_left = skip_typeref(orig_type_left);
8302 type_left = promote_integer(type_left);
8303 expression->left = create_implicit_cast(left, type_left);
8304 expression->base.type = type_left;
8307 static void semantic_add(binary_expression_t *expression)
8309 expression_t *const left = expression->left;
8310 expression_t *const right = expression->right;
8311 type_t *const orig_type_left = left->base.type;
8312 type_t *const orig_type_right = right->base.type;
8313 type_t *const type_left = skip_typeref(orig_type_left);
8314 type_t *const type_right = skip_typeref(orig_type_right);
8317 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8318 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8319 expression->left = create_implicit_cast(left, arithmetic_type);
8320 expression->right = create_implicit_cast(right, arithmetic_type);
8321 expression->base.type = arithmetic_type;
8322 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8323 check_pointer_arithmetic(&expression->base.source_position,
8324 type_left, orig_type_left);
8325 expression->base.type = type_left;
8326 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8327 check_pointer_arithmetic(&expression->base.source_position,
8328 type_right, orig_type_right);
8329 expression->base.type = type_right;
8330 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8331 errorf(&expression->base.source_position,
8332 "invalid operands to binary + ('%T', '%T')",
8333 orig_type_left, orig_type_right);
8337 static void semantic_sub(binary_expression_t *expression)
8339 expression_t *const left = expression->left;
8340 expression_t *const right = expression->right;
8341 type_t *const orig_type_left = left->base.type;
8342 type_t *const orig_type_right = right->base.type;
8343 type_t *const type_left = skip_typeref(orig_type_left);
8344 type_t *const type_right = skip_typeref(orig_type_right);
8345 source_position_t const *const pos = &expression->base.source_position;
8348 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8349 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8350 expression->left = create_implicit_cast(left, arithmetic_type);
8351 expression->right = create_implicit_cast(right, arithmetic_type);
8352 expression->base.type = arithmetic_type;
8353 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8354 check_pointer_arithmetic(&expression->base.source_position,
8355 type_left, orig_type_left);
8356 expression->base.type = type_left;
8357 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8358 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8359 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8360 if (!types_compatible(unqual_left, unqual_right)) {
8362 "subtracting pointers to incompatible types '%T' and '%T'",
8363 orig_type_left, orig_type_right);
8364 } else if (!is_type_object(unqual_left)) {
8365 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8366 errorf(pos, "subtracting pointers to non-object types '%T'",
8368 } else if (warning.other) {
8369 warningf(pos, "subtracting pointers to void");
8372 expression->base.type = type_ptrdiff_t;
8373 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8374 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8375 orig_type_left, orig_type_right);
8379 static void warn_string_literal_address(expression_t const* expr)
8381 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8382 expr = expr->unary.value;
8383 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8385 expr = expr->unary.value;
8388 if (expr->kind == EXPR_STRING_LITERAL
8389 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8390 warningf(&expr->base.source_position,
8391 "comparison with string literal results in unspecified behaviour");
8395 static void warn_comparison_in_comparison(const expression_t *const expr)
8397 if (expr->base.parenthesized)
8399 switch (expr->base.kind) {
8400 case EXPR_BINARY_LESS:
8401 case EXPR_BINARY_GREATER:
8402 case EXPR_BINARY_LESSEQUAL:
8403 case EXPR_BINARY_GREATEREQUAL:
8404 case EXPR_BINARY_NOTEQUAL:
8405 case EXPR_BINARY_EQUAL:
8406 warningf(&expr->base.source_position,
8407 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8414 static bool maybe_negative(expression_t const *const expr)
8417 !is_constant_expression(expr) ||
8418 fold_constant_to_int(expr) < 0;
8422 * Check the semantics of comparison expressions.
8424 * @param expression The expression to check.
8426 static void semantic_comparison(binary_expression_t *expression)
8428 expression_t *left = expression->left;
8429 expression_t *right = expression->right;
8431 if (warning.address) {
8432 warn_string_literal_address(left);
8433 warn_string_literal_address(right);
8435 expression_t const* const func_left = get_reference_address(left);
8436 if (func_left != NULL && is_null_pointer_constant(right)) {
8437 warningf(&expression->base.source_position,
8438 "the address of '%Y' will never be NULL",
8439 func_left->reference.entity->base.symbol);
8442 expression_t const* const func_right = get_reference_address(right);
8443 if (func_right != NULL && is_null_pointer_constant(right)) {
8444 warningf(&expression->base.source_position,
8445 "the address of '%Y' will never be NULL",
8446 func_right->reference.entity->base.symbol);
8450 if (warning.parentheses) {
8451 warn_comparison_in_comparison(left);
8452 warn_comparison_in_comparison(right);
8455 type_t *orig_type_left = left->base.type;
8456 type_t *orig_type_right = right->base.type;
8457 type_t *type_left = skip_typeref(orig_type_left);
8458 type_t *type_right = skip_typeref(orig_type_right);
8460 /* TODO non-arithmetic types */
8461 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8462 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8464 /* test for signed vs unsigned compares */
8465 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8466 bool const signed_left = is_type_signed(type_left);
8467 bool const signed_right = is_type_signed(type_right);
8468 if (signed_left != signed_right) {
8469 /* FIXME long long needs better const folding magic */
8470 /* TODO check whether constant value can be represented by other type */
8471 if ((signed_left && maybe_negative(left)) ||
8472 (signed_right && maybe_negative(right))) {
8473 warningf(&expression->base.source_position,
8474 "comparison between signed and unsigned");
8479 expression->left = create_implicit_cast(left, arithmetic_type);
8480 expression->right = create_implicit_cast(right, arithmetic_type);
8481 expression->base.type = arithmetic_type;
8482 if (warning.float_equal &&
8483 (expression->base.kind == EXPR_BINARY_EQUAL ||
8484 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8485 is_type_float(arithmetic_type)) {
8486 warningf(&expression->base.source_position,
8487 "comparing floating point with == or != is unsafe");
8489 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8490 /* TODO check compatibility */
8491 } else if (is_type_pointer(type_left)) {
8492 expression->right = create_implicit_cast(right, type_left);
8493 } else if (is_type_pointer(type_right)) {
8494 expression->left = create_implicit_cast(left, type_right);
8495 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8496 type_error_incompatible("invalid operands in comparison",
8497 &expression->base.source_position,
8498 type_left, type_right);
8500 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8504 * Checks if a compound type has constant fields.
8506 static bool has_const_fields(const compound_type_t *type)
8508 compound_t *compound = type->compound;
8509 entity_t *entry = compound->members.entities;
8511 for (; entry != NULL; entry = entry->base.next) {
8512 if (!is_declaration(entry))
8515 const type_t *decl_type = skip_typeref(entry->declaration.type);
8516 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8523 static bool is_valid_assignment_lhs(expression_t const* const left)
8525 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8526 type_t *const type_left = skip_typeref(orig_type_left);
8528 if (!is_lvalue(left)) {
8529 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8534 if (left->kind == EXPR_REFERENCE
8535 && left->reference.entity->kind == ENTITY_FUNCTION) {
8536 errorf(HERE, "cannot assign to function '%E'", left);
8540 if (is_type_array(type_left)) {
8541 errorf(HERE, "cannot assign to array '%E'", left);
8544 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8545 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8549 if (is_type_incomplete(type_left)) {
8550 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8551 left, orig_type_left);
8554 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8555 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8556 left, orig_type_left);
8563 static void semantic_arithmetic_assign(binary_expression_t *expression)
8565 expression_t *left = expression->left;
8566 expression_t *right = expression->right;
8567 type_t *orig_type_left = left->base.type;
8568 type_t *orig_type_right = right->base.type;
8570 if (!is_valid_assignment_lhs(left))
8573 type_t *type_left = skip_typeref(orig_type_left);
8574 type_t *type_right = skip_typeref(orig_type_right);
8576 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8577 /* TODO: improve error message */
8578 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8579 errorf(&expression->base.source_position,
8580 "operation needs arithmetic types");
8585 /* combined instructions are tricky. We can't create an implicit cast on
8586 * the left side, because we need the uncasted form for the store.
8587 * The ast2firm pass has to know that left_type must be right_type
8588 * for the arithmetic operation and create a cast by itself */
8589 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8590 expression->right = create_implicit_cast(right, arithmetic_type);
8591 expression->base.type = type_left;
8594 static void semantic_divmod_assign(binary_expression_t *expression)
8596 semantic_arithmetic_assign(expression);
8597 warn_div_by_zero(expression);
8600 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8602 expression_t *const left = expression->left;
8603 expression_t *const right = expression->right;
8604 type_t *const orig_type_left = left->base.type;
8605 type_t *const orig_type_right = right->base.type;
8606 type_t *const type_left = skip_typeref(orig_type_left);
8607 type_t *const type_right = skip_typeref(orig_type_right);
8609 if (!is_valid_assignment_lhs(left))
8612 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8613 /* combined instructions are tricky. We can't create an implicit cast on
8614 * the left side, because we need the uncasted form for the store.
8615 * The ast2firm pass has to know that left_type must be right_type
8616 * for the arithmetic operation and create a cast by itself */
8617 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8618 expression->right = create_implicit_cast(right, arithmetic_type);
8619 expression->base.type = type_left;
8620 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8621 check_pointer_arithmetic(&expression->base.source_position,
8622 type_left, orig_type_left);
8623 expression->base.type = type_left;
8624 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8625 errorf(&expression->base.source_position,
8626 "incompatible types '%T' and '%T' in assignment",
8627 orig_type_left, orig_type_right);
8631 static void semantic_integer_assign(binary_expression_t *expression)
8633 expression_t *left = expression->left;
8634 expression_t *right = expression->right;
8635 type_t *orig_type_left = left->base.type;
8636 type_t *orig_type_right = right->base.type;
8638 if (!is_valid_assignment_lhs(left))
8641 type_t *type_left = skip_typeref(orig_type_left);
8642 type_t *type_right = skip_typeref(orig_type_right);
8644 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8645 /* TODO: improve error message */
8646 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8647 errorf(&expression->base.source_position,
8648 "operation needs integer types");
8653 /* combined instructions are tricky. We can't create an implicit cast on
8654 * the left side, because we need the uncasted form for the store.
8655 * The ast2firm pass has to know that left_type must be right_type
8656 * for the arithmetic operation and create a cast by itself */
8657 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8658 expression->right = create_implicit_cast(right, arithmetic_type);
8659 expression->base.type = type_left;
8662 static void semantic_shift_assign(binary_expression_t *expression)
8664 expression_t *left = expression->left;
8666 if (!is_valid_assignment_lhs(left))
8669 if (!semantic_shift(expression))
8672 expression->base.type = skip_typeref(left->base.type);
8675 static void warn_logical_and_within_or(const expression_t *const expr)
8677 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8679 if (expr->base.parenthesized)
8681 warningf(&expr->base.source_position,
8682 "suggest parentheses around && within ||");
8686 * Check the semantic restrictions of a logical expression.
8688 static void semantic_logical_op(binary_expression_t *expression)
8690 /* §6.5.13:2 Each of the operands shall have scalar type.
8691 * §6.5.14:2 Each of the operands shall have scalar type. */
8692 semantic_condition(expression->left, "left operand of logical operator");
8693 semantic_condition(expression->right, "right operand of logical operator");
8694 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8695 warning.parentheses) {
8696 warn_logical_and_within_or(expression->left);
8697 warn_logical_and_within_or(expression->right);
8699 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8703 * Check the semantic restrictions of a binary assign expression.
8705 static void semantic_binexpr_assign(binary_expression_t *expression)
8707 expression_t *left = expression->left;
8708 type_t *orig_type_left = left->base.type;
8710 if (!is_valid_assignment_lhs(left))
8713 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8714 report_assign_error(error, orig_type_left, expression->right,
8715 "assignment", &left->base.source_position);
8716 expression->right = create_implicit_cast(expression->right, orig_type_left);
8717 expression->base.type = orig_type_left;
8721 * Determine if the outermost operation (or parts thereof) of the given
8722 * expression has no effect in order to generate a warning about this fact.
8723 * Therefore in some cases this only examines some of the operands of the
8724 * expression (see comments in the function and examples below).
8726 * f() + 23; // warning, because + has no effect
8727 * x || f(); // no warning, because x controls execution of f()
8728 * x ? y : f(); // warning, because y has no effect
8729 * (void)x; // no warning to be able to suppress the warning
8730 * This function can NOT be used for an "expression has definitely no effect"-
8732 static bool expression_has_effect(const expression_t *const expr)
8734 switch (expr->kind) {
8735 case EXPR_UNKNOWN: break;
8736 case EXPR_INVALID: return true; /* do NOT warn */
8737 case EXPR_REFERENCE: return false;
8738 case EXPR_REFERENCE_ENUM_VALUE: return false;
8739 case EXPR_LABEL_ADDRESS: return false;
8741 /* suppress the warning for microsoft __noop operations */
8742 case EXPR_LITERAL_MS_NOOP: return true;
8743 case EXPR_LITERAL_BOOLEAN:
8744 case EXPR_LITERAL_CHARACTER:
8745 case EXPR_LITERAL_WIDE_CHARACTER:
8746 case EXPR_LITERAL_INTEGER:
8747 case EXPR_LITERAL_INTEGER_OCTAL:
8748 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8749 case EXPR_LITERAL_FLOATINGPOINT:
8750 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8751 case EXPR_STRING_LITERAL: return false;
8752 case EXPR_WIDE_STRING_LITERAL: return false;
8755 const call_expression_t *const call = &expr->call;
8756 if (call->function->kind != EXPR_REFERENCE)
8759 switch (call->function->reference.entity->function.btk) {
8760 /* FIXME: which builtins have no effect? */
8761 default: return true;
8765 /* Generate the warning if either the left or right hand side of a
8766 * conditional expression has no effect */
8767 case EXPR_CONDITIONAL: {
8768 conditional_expression_t const *const cond = &expr->conditional;
8769 expression_t const *const t = cond->true_expression;
8771 (t == NULL || expression_has_effect(t)) &&
8772 expression_has_effect(cond->false_expression);
8775 case EXPR_SELECT: return false;
8776 case EXPR_ARRAY_ACCESS: return false;
8777 case EXPR_SIZEOF: return false;
8778 case EXPR_CLASSIFY_TYPE: return false;
8779 case EXPR_ALIGNOF: return false;
8781 case EXPR_FUNCNAME: return false;
8782 case EXPR_BUILTIN_CONSTANT_P: return false;
8783 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8784 case EXPR_OFFSETOF: return false;
8785 case EXPR_VA_START: return true;
8786 case EXPR_VA_ARG: return true;
8787 case EXPR_VA_COPY: return true;
8788 case EXPR_STATEMENT: return true; // TODO
8789 case EXPR_COMPOUND_LITERAL: return false;
8791 case EXPR_UNARY_NEGATE: return false;
8792 case EXPR_UNARY_PLUS: return false;
8793 case EXPR_UNARY_BITWISE_NEGATE: return false;
8794 case EXPR_UNARY_NOT: return false;
8795 case EXPR_UNARY_DEREFERENCE: return false;
8796 case EXPR_UNARY_TAKE_ADDRESS: return false;
8797 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8798 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8799 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8800 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8802 /* Treat void casts as if they have an effect in order to being able to
8803 * suppress the warning */
8804 case EXPR_UNARY_CAST: {
8805 type_t *const type = skip_typeref(expr->base.type);
8806 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8809 case EXPR_UNARY_CAST_IMPLICIT: return true;
8810 case EXPR_UNARY_ASSUME: return true;
8811 case EXPR_UNARY_DELETE: return true;
8812 case EXPR_UNARY_DELETE_ARRAY: return true;
8813 case EXPR_UNARY_THROW: return true;
8815 case EXPR_BINARY_ADD: return false;
8816 case EXPR_BINARY_SUB: return false;
8817 case EXPR_BINARY_MUL: return false;
8818 case EXPR_BINARY_DIV: return false;
8819 case EXPR_BINARY_MOD: return false;
8820 case EXPR_BINARY_EQUAL: return false;
8821 case EXPR_BINARY_NOTEQUAL: return false;
8822 case EXPR_BINARY_LESS: return false;
8823 case EXPR_BINARY_LESSEQUAL: return false;
8824 case EXPR_BINARY_GREATER: return false;
8825 case EXPR_BINARY_GREATEREQUAL: return false;
8826 case EXPR_BINARY_BITWISE_AND: return false;
8827 case EXPR_BINARY_BITWISE_OR: return false;
8828 case EXPR_BINARY_BITWISE_XOR: return false;
8829 case EXPR_BINARY_SHIFTLEFT: return false;
8830 case EXPR_BINARY_SHIFTRIGHT: return false;
8831 case EXPR_BINARY_ASSIGN: return true;
8832 case EXPR_BINARY_MUL_ASSIGN: return true;
8833 case EXPR_BINARY_DIV_ASSIGN: return true;
8834 case EXPR_BINARY_MOD_ASSIGN: return true;
8835 case EXPR_BINARY_ADD_ASSIGN: return true;
8836 case EXPR_BINARY_SUB_ASSIGN: return true;
8837 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8838 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8839 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8840 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8841 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8843 /* Only examine the right hand side of && and ||, because the left hand
8844 * side already has the effect of controlling the execution of the right
8846 case EXPR_BINARY_LOGICAL_AND:
8847 case EXPR_BINARY_LOGICAL_OR:
8848 /* Only examine the right hand side of a comma expression, because the left
8849 * hand side has a separate warning */
8850 case EXPR_BINARY_COMMA:
8851 return expression_has_effect(expr->binary.right);
8853 case EXPR_BINARY_ISGREATER: return false;
8854 case EXPR_BINARY_ISGREATEREQUAL: return false;
8855 case EXPR_BINARY_ISLESS: return false;
8856 case EXPR_BINARY_ISLESSEQUAL: return false;
8857 case EXPR_BINARY_ISLESSGREATER: return false;
8858 case EXPR_BINARY_ISUNORDERED: return false;
8861 internal_errorf(HERE, "unexpected expression");
8864 static void semantic_comma(binary_expression_t *expression)
8866 if (warning.unused_value) {
8867 const expression_t *const left = expression->left;
8868 if (!expression_has_effect(left)) {
8869 warningf(&left->base.source_position,
8870 "left-hand operand of comma expression has no effect");
8873 expression->base.type = expression->right->base.type;
8877 * @param prec_r precedence of the right operand
8879 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8880 static expression_t *parse_##binexpression_type(expression_t *left) \
8882 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8883 binexpr->binary.left = left; \
8886 expression_t *right = parse_sub_expression(prec_r); \
8888 binexpr->binary.right = right; \
8889 sfunc(&binexpr->binary); \
8894 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8895 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8896 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8897 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8898 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8899 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8900 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8901 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8902 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8903 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8904 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8905 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8906 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8907 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8908 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8909 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8910 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8911 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8912 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8913 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8914 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8915 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8916 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8917 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8918 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8919 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8920 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8921 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8922 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8923 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8926 static expression_t *parse_sub_expression(precedence_t precedence)
8928 if (token.type < 0) {
8929 return expected_expression_error();
8932 expression_parser_function_t *parser
8933 = &expression_parsers[token.type];
8934 source_position_t source_position = token.source_position;
8937 if (parser->parser != NULL) {
8938 left = parser->parser();
8940 left = parse_primary_expression();
8942 assert(left != NULL);
8943 left->base.source_position = source_position;
8946 if (token.type < 0) {
8947 return expected_expression_error();
8950 parser = &expression_parsers[token.type];
8951 if (parser->infix_parser == NULL)
8953 if (parser->infix_precedence < precedence)
8956 left = parser->infix_parser(left);
8958 assert(left != NULL);
8959 assert(left->kind != EXPR_UNKNOWN);
8960 left->base.source_position = source_position;
8967 * Parse an expression.
8969 static expression_t *parse_expression(void)
8971 return parse_sub_expression(PREC_EXPRESSION);
8975 * Register a parser for a prefix-like operator.
8977 * @param parser the parser function
8978 * @param token_type the token type of the prefix token
8980 static void register_expression_parser(parse_expression_function parser,
8983 expression_parser_function_t *entry = &expression_parsers[token_type];
8985 if (entry->parser != NULL) {
8986 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8987 panic("trying to register multiple expression parsers for a token");
8989 entry->parser = parser;
8993 * Register a parser for an infix operator with given precedence.
8995 * @param parser the parser function
8996 * @param token_type the token type of the infix operator
8997 * @param precedence the precedence of the operator
8999 static void register_infix_parser(parse_expression_infix_function parser,
9000 int token_type, precedence_t precedence)
9002 expression_parser_function_t *entry = &expression_parsers[token_type];
9004 if (entry->infix_parser != NULL) {
9005 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9006 panic("trying to register multiple infix expression parsers for a "
9009 entry->infix_parser = parser;
9010 entry->infix_precedence = precedence;
9014 * Initialize the expression parsers.
9016 static void init_expression_parsers(void)
9018 memset(&expression_parsers, 0, sizeof(expression_parsers));
9020 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9021 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9022 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9023 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9024 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9025 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9026 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9027 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9028 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9029 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9030 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9031 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9032 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9033 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9034 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9035 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9036 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9037 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9038 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9039 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9040 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9041 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9042 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9043 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9044 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9045 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9046 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9047 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9048 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9049 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9050 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9051 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9052 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9053 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9054 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9055 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9056 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9058 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9059 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9060 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9061 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9062 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9063 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9064 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9065 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9066 register_expression_parser(parse_sizeof, T_sizeof);
9067 register_expression_parser(parse_alignof, T___alignof__);
9068 register_expression_parser(parse_extension, T___extension__);
9069 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9070 register_expression_parser(parse_delete, T_delete);
9071 register_expression_parser(parse_throw, T_throw);
9075 * Parse a asm statement arguments specification.
9077 static asm_argument_t *parse_asm_arguments(bool is_out)
9079 asm_argument_t *result = NULL;
9080 asm_argument_t **anchor = &result;
9082 while (token.type == T_STRING_LITERAL || token.type == '[') {
9083 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9084 memset(argument, 0, sizeof(argument[0]));
9087 if (token.type != T_IDENTIFIER) {
9088 parse_error_expected("while parsing asm argument",
9089 T_IDENTIFIER, NULL);
9092 argument->symbol = token.symbol;
9094 expect(']', end_error);
9097 argument->constraints = parse_string_literals();
9098 expect('(', end_error);
9099 add_anchor_token(')');
9100 expression_t *expression = parse_expression();
9101 rem_anchor_token(')');
9103 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9104 * change size or type representation (e.g. int -> long is ok, but
9105 * int -> float is not) */
9106 if (expression->kind == EXPR_UNARY_CAST) {
9107 type_t *const type = expression->base.type;
9108 type_kind_t const kind = type->kind;
9109 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9112 if (kind == TYPE_ATOMIC) {
9113 atomic_type_kind_t const akind = type->atomic.akind;
9114 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9115 size = get_atomic_type_size(akind);
9117 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9118 size = get_atomic_type_size(get_intptr_kind());
9122 expression_t *const value = expression->unary.value;
9123 type_t *const value_type = value->base.type;
9124 type_kind_t const value_kind = value_type->kind;
9126 unsigned value_flags;
9127 unsigned value_size;
9128 if (value_kind == TYPE_ATOMIC) {
9129 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9130 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9131 value_size = get_atomic_type_size(value_akind);
9132 } else if (value_kind == TYPE_POINTER) {
9133 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9134 value_size = get_atomic_type_size(get_intptr_kind());
9139 if (value_flags != flags || value_size != size)
9143 } while (expression->kind == EXPR_UNARY_CAST);
9147 if (!is_lvalue(expression)) {
9148 errorf(&expression->base.source_position,
9149 "asm output argument is not an lvalue");
9152 if (argument->constraints.begin[0] == '+')
9153 mark_vars_read(expression, NULL);
9155 mark_vars_read(expression, NULL);
9157 argument->expression = expression;
9158 expect(')', end_error);
9160 set_address_taken(expression, true);
9163 anchor = &argument->next;
9175 * Parse a asm statement clobber specification.
9177 static asm_clobber_t *parse_asm_clobbers(void)
9179 asm_clobber_t *result = NULL;
9180 asm_clobber_t **anchor = &result;
9182 while (token.type == T_STRING_LITERAL) {
9183 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9184 clobber->clobber = parse_string_literals();
9187 anchor = &clobber->next;
9197 * Parse an asm statement.
9199 static statement_t *parse_asm_statement(void)
9201 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9202 asm_statement_t *asm_statement = &statement->asms;
9206 if (next_if(T_volatile))
9207 asm_statement->is_volatile = true;
9209 expect('(', end_error);
9210 add_anchor_token(')');
9211 add_anchor_token(':');
9212 asm_statement->asm_text = parse_string_literals();
9214 if (!next_if(':')) {
9215 rem_anchor_token(':');
9219 asm_statement->outputs = parse_asm_arguments(true);
9220 if (!next_if(':')) {
9221 rem_anchor_token(':');
9225 asm_statement->inputs = parse_asm_arguments(false);
9226 if (!next_if(':')) {
9227 rem_anchor_token(':');
9230 rem_anchor_token(':');
9232 asm_statement->clobbers = parse_asm_clobbers();
9235 rem_anchor_token(')');
9236 expect(')', end_error);
9237 expect(';', end_error);
9239 if (asm_statement->outputs == NULL) {
9240 /* GCC: An 'asm' instruction without any output operands will be treated
9241 * identically to a volatile 'asm' instruction. */
9242 asm_statement->is_volatile = true;
9247 return create_invalid_statement();
9251 * Parse a case statement.
9253 static statement_t *parse_case_statement(void)
9255 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9256 source_position_t *const pos = &statement->base.source_position;
9260 expression_t *const expression = parse_expression();
9261 statement->case_label.expression = expression;
9262 if (!is_constant_expression(expression)) {
9263 /* This check does not prevent the error message in all cases of an
9264 * prior error while parsing the expression. At least it catches the
9265 * common case of a mistyped enum entry. */
9266 if (is_type_valid(skip_typeref(expression->base.type))) {
9267 errorf(pos, "case label does not reduce to an integer constant");
9269 statement->case_label.is_bad = true;
9271 long const val = fold_constant_to_int(expression);
9272 statement->case_label.first_case = val;
9273 statement->case_label.last_case = val;
9277 if (next_if(T_DOTDOTDOT)) {
9278 expression_t *const end_range = parse_expression();
9279 statement->case_label.end_range = end_range;
9280 if (!is_constant_expression(end_range)) {
9281 /* This check does not prevent the error message in all cases of an
9282 * prior error while parsing the expression. At least it catches the
9283 * common case of a mistyped enum entry. */
9284 if (is_type_valid(skip_typeref(end_range->base.type))) {
9285 errorf(pos, "case range does not reduce to an integer constant");
9287 statement->case_label.is_bad = true;
9289 long const val = fold_constant_to_int(end_range);
9290 statement->case_label.last_case = val;
9292 if (warning.other && val < statement->case_label.first_case) {
9293 statement->case_label.is_empty_range = true;
9294 warningf(pos, "empty range specified");
9300 PUSH_PARENT(statement);
9302 expect(':', end_error);
9305 if (current_switch != NULL) {
9306 if (! statement->case_label.is_bad) {
9307 /* Check for duplicate case values */
9308 case_label_statement_t *c = &statement->case_label;
9309 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9310 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9313 if (c->last_case < l->first_case || c->first_case > l->last_case)
9316 errorf(pos, "duplicate case value (previously used %P)",
9317 &l->base.source_position);
9321 /* link all cases into the switch statement */
9322 if (current_switch->last_case == NULL) {
9323 current_switch->first_case = &statement->case_label;
9325 current_switch->last_case->next = &statement->case_label;
9327 current_switch->last_case = &statement->case_label;
9329 errorf(pos, "case label not within a switch statement");
9332 statement_t *const inner_stmt = parse_statement();
9333 statement->case_label.statement = inner_stmt;
9334 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9335 errorf(&inner_stmt->base.source_position, "declaration after case label");
9343 * Parse a default statement.
9345 static statement_t *parse_default_statement(void)
9347 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9351 PUSH_PARENT(statement);
9353 expect(':', end_error);
9354 if (current_switch != NULL) {
9355 const case_label_statement_t *def_label = current_switch->default_label;
9356 if (def_label != NULL) {
9357 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9358 &def_label->base.source_position);
9360 current_switch->default_label = &statement->case_label;
9362 /* link all cases into the switch statement */
9363 if (current_switch->last_case == NULL) {
9364 current_switch->first_case = &statement->case_label;
9366 current_switch->last_case->next = &statement->case_label;
9368 current_switch->last_case = &statement->case_label;
9371 errorf(&statement->base.source_position,
9372 "'default' label not within a switch statement");
9375 statement_t *const inner_stmt = parse_statement();
9376 statement->case_label.statement = inner_stmt;
9377 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9378 errorf(&inner_stmt->base.source_position, "declaration after default label");
9385 return create_invalid_statement();
9389 * Parse a label statement.
9391 static statement_t *parse_label_statement(void)
9393 assert(token.type == T_IDENTIFIER);
9394 symbol_t *symbol = token.symbol;
9395 label_t *label = get_label(symbol);
9397 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9398 statement->label.label = label;
9402 PUSH_PARENT(statement);
9404 /* if statement is already set then the label is defined twice,
9405 * otherwise it was just mentioned in a goto/local label declaration so far
9407 if (label->statement != NULL) {
9408 errorf(HERE, "duplicate label '%Y' (declared %P)",
9409 symbol, &label->base.source_position);
9411 label->base.source_position = token.source_position;
9412 label->statement = statement;
9417 if (token.type == '}') {
9418 /* TODO only warn? */
9419 if (warning.other && false) {
9420 warningf(HERE, "label at end of compound statement");
9421 statement->label.statement = create_empty_statement();
9423 errorf(HERE, "label at end of compound statement");
9424 statement->label.statement = create_invalid_statement();
9426 } else if (token.type == ';') {
9427 /* Eat an empty statement here, to avoid the warning about an empty
9428 * statement after a label. label:; is commonly used to have a label
9429 * before a closing brace. */
9430 statement->label.statement = create_empty_statement();
9433 statement_t *const inner_stmt = parse_statement();
9434 statement->label.statement = inner_stmt;
9435 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9436 errorf(&inner_stmt->base.source_position, "declaration after label");
9440 /* remember the labels in a list for later checking */
9441 *label_anchor = &statement->label;
9442 label_anchor = &statement->label.next;
9449 * Parse an if statement.
9451 static statement_t *parse_if(void)
9453 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9457 PUSH_PARENT(statement);
9459 add_anchor_token('{');
9461 expect('(', end_error);
9462 add_anchor_token(')');
9463 expression_t *const expr = parse_expression();
9464 statement->ifs.condition = expr;
9465 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9467 semantic_condition(expr, "condition of 'if'-statment");
9468 mark_vars_read(expr, NULL);
9469 rem_anchor_token(')');
9470 expect(')', end_error);
9473 rem_anchor_token('{');
9475 add_anchor_token(T_else);
9476 statement_t *const true_stmt = parse_statement();
9477 statement->ifs.true_statement = true_stmt;
9478 rem_anchor_token(T_else);
9480 if (next_if(T_else)) {
9481 statement->ifs.false_statement = parse_statement();
9482 } else if (warning.parentheses &&
9483 true_stmt->kind == STATEMENT_IF &&
9484 true_stmt->ifs.false_statement != NULL) {
9485 warningf(&true_stmt->base.source_position,
9486 "suggest explicit braces to avoid ambiguous 'else'");
9494 * Check that all enums are handled in a switch.
9496 * @param statement the switch statement to check
9498 static void check_enum_cases(const switch_statement_t *statement)
9500 const type_t *type = skip_typeref(statement->expression->base.type);
9501 if (! is_type_enum(type))
9503 const enum_type_t *enumt = &type->enumt;
9505 /* if we have a default, no warnings */
9506 if (statement->default_label != NULL)
9509 /* FIXME: calculation of value should be done while parsing */
9510 /* TODO: quadratic algorithm here. Change to an n log n one */
9511 long last_value = -1;
9512 const entity_t *entry = enumt->enume->base.next;
9513 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9514 entry = entry->base.next) {
9515 const expression_t *expression = entry->enum_value.value;
9516 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9518 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9519 if (l->expression == NULL)
9521 if (l->first_case <= value && value <= l->last_case) {
9527 warningf(&statement->base.source_position,
9528 "enumeration value '%Y' not handled in switch",
9529 entry->base.symbol);
9536 * Parse a switch statement.
9538 static statement_t *parse_switch(void)
9540 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9544 PUSH_PARENT(statement);
9546 expect('(', end_error);
9547 add_anchor_token(')');
9548 expression_t *const expr = parse_expression();
9549 mark_vars_read(expr, NULL);
9550 type_t * type = skip_typeref(expr->base.type);
9551 if (is_type_integer(type)) {
9552 type = promote_integer(type);
9553 if (warning.traditional) {
9554 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9555 warningf(&expr->base.source_position,
9556 "'%T' switch expression not converted to '%T' in ISO C",
9560 } else if (is_type_valid(type)) {
9561 errorf(&expr->base.source_position,
9562 "switch quantity is not an integer, but '%T'", type);
9563 type = type_error_type;
9565 statement->switchs.expression = create_implicit_cast(expr, type);
9566 expect(')', end_error);
9567 rem_anchor_token(')');
9569 switch_statement_t *rem = current_switch;
9570 current_switch = &statement->switchs;
9571 statement->switchs.body = parse_statement();
9572 current_switch = rem;
9574 if (warning.switch_default &&
9575 statement->switchs.default_label == NULL) {
9576 warningf(&statement->base.source_position, "switch has no default case");
9578 if (warning.switch_enum)
9579 check_enum_cases(&statement->switchs);
9585 return create_invalid_statement();
9588 static statement_t *parse_loop_body(statement_t *const loop)
9590 statement_t *const rem = current_loop;
9591 current_loop = loop;
9593 statement_t *const body = parse_statement();
9600 * Parse a while statement.
9602 static statement_t *parse_while(void)
9604 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9608 PUSH_PARENT(statement);
9610 expect('(', end_error);
9611 add_anchor_token(')');
9612 expression_t *const cond = parse_expression();
9613 statement->whiles.condition = cond;
9614 /* §6.8.5:2 The controlling expression of an iteration statement shall
9615 * have scalar type. */
9616 semantic_condition(cond, "condition of 'while'-statement");
9617 mark_vars_read(cond, NULL);
9618 rem_anchor_token(')');
9619 expect(')', end_error);
9621 statement->whiles.body = parse_loop_body(statement);
9627 return create_invalid_statement();
9631 * Parse a do statement.
9633 static statement_t *parse_do(void)
9635 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9639 PUSH_PARENT(statement);
9641 add_anchor_token(T_while);
9642 statement->do_while.body = parse_loop_body(statement);
9643 rem_anchor_token(T_while);
9645 expect(T_while, end_error);
9646 expect('(', end_error);
9647 add_anchor_token(')');
9648 expression_t *const cond = parse_expression();
9649 statement->do_while.condition = cond;
9650 /* §6.8.5:2 The controlling expression of an iteration statement shall
9651 * have scalar type. */
9652 semantic_condition(cond, "condition of 'do-while'-statement");
9653 mark_vars_read(cond, NULL);
9654 rem_anchor_token(')');
9655 expect(')', end_error);
9656 expect(';', end_error);
9662 return create_invalid_statement();
9666 * Parse a for statement.
9668 static statement_t *parse_for(void)
9670 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9674 expect('(', end_error1);
9675 add_anchor_token(')');
9677 PUSH_PARENT(statement);
9679 size_t const top = environment_top();
9680 scope_t *old_scope = scope_push(&statement->fors.scope);
9682 bool old_gcc_extension = in_gcc_extension;
9683 while (next_if(T___extension__)) {
9684 in_gcc_extension = true;
9688 } else if (is_declaration_specifier(&token, false)) {
9689 parse_declaration(record_entity, DECL_FLAGS_NONE);
9691 add_anchor_token(';');
9692 expression_t *const init = parse_expression();
9693 statement->fors.initialisation = init;
9694 mark_vars_read(init, ENT_ANY);
9695 if (warning.unused_value && !expression_has_effect(init)) {
9696 warningf(&init->base.source_position,
9697 "initialisation of 'for'-statement has no effect");
9699 rem_anchor_token(';');
9700 expect(';', end_error2);
9702 in_gcc_extension = old_gcc_extension;
9704 if (token.type != ';') {
9705 add_anchor_token(';');
9706 expression_t *const cond = parse_expression();
9707 statement->fors.condition = cond;
9708 /* §6.8.5:2 The controlling expression of an iteration statement
9709 * shall have scalar type. */
9710 semantic_condition(cond, "condition of 'for'-statement");
9711 mark_vars_read(cond, NULL);
9712 rem_anchor_token(';');
9714 expect(';', end_error2);
9715 if (token.type != ')') {
9716 expression_t *const step = parse_expression();
9717 statement->fors.step = step;
9718 mark_vars_read(step, ENT_ANY);
9719 if (warning.unused_value && !expression_has_effect(step)) {
9720 warningf(&step->base.source_position,
9721 "step of 'for'-statement has no effect");
9724 expect(')', end_error2);
9725 rem_anchor_token(')');
9726 statement->fors.body = parse_loop_body(statement);
9728 assert(current_scope == &statement->fors.scope);
9729 scope_pop(old_scope);
9730 environment_pop_to(top);
9737 rem_anchor_token(')');
9738 assert(current_scope == &statement->fors.scope);
9739 scope_pop(old_scope);
9740 environment_pop_to(top);
9744 return create_invalid_statement();
9748 * Parse a goto statement.
9750 static statement_t *parse_goto(void)
9752 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9755 if (GNU_MODE && next_if('*')) {
9756 expression_t *expression = parse_expression();
9757 mark_vars_read(expression, NULL);
9759 /* Argh: although documentation says the expression must be of type void*,
9760 * gcc accepts anything that can be casted into void* without error */
9761 type_t *type = expression->base.type;
9763 if (type != type_error_type) {
9764 if (!is_type_pointer(type) && !is_type_integer(type)) {
9765 errorf(&expression->base.source_position,
9766 "cannot convert to a pointer type");
9767 } else if (warning.other && type != type_void_ptr) {
9768 warningf(&expression->base.source_position,
9769 "type of computed goto expression should be 'void*' not '%T'", type);
9771 expression = create_implicit_cast(expression, type_void_ptr);
9774 statement->gotos.expression = expression;
9775 } else if (token.type == T_IDENTIFIER) {
9776 symbol_t *symbol = token.symbol;
9778 statement->gotos.label = get_label(symbol);
9781 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9783 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9788 /* remember the goto's in a list for later checking */
9789 *goto_anchor = &statement->gotos;
9790 goto_anchor = &statement->gotos.next;
9792 expect(';', end_error);
9796 return create_invalid_statement();
9800 * Parse a continue statement.
9802 static statement_t *parse_continue(void)
9804 if (current_loop == NULL) {
9805 errorf(HERE, "continue statement not within loop");
9808 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9811 expect(';', end_error);
9818 * Parse a break statement.
9820 static statement_t *parse_break(void)
9822 if (current_switch == NULL && current_loop == NULL) {
9823 errorf(HERE, "break statement not within loop or switch");
9826 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9829 expect(';', end_error);
9836 * Parse a __leave statement.
9838 static statement_t *parse_leave_statement(void)
9840 if (current_try == NULL) {
9841 errorf(HERE, "__leave statement not within __try");
9844 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9847 expect(';', end_error);
9854 * Check if a given entity represents a local variable.
9856 static bool is_local_variable(const entity_t *entity)
9858 if (entity->kind != ENTITY_VARIABLE)
9861 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9862 case STORAGE_CLASS_AUTO:
9863 case STORAGE_CLASS_REGISTER: {
9864 const type_t *type = skip_typeref(entity->declaration.type);
9865 if (is_type_function(type)) {
9877 * Check if a given expression represents a local variable.
9879 static bool expression_is_local_variable(const expression_t *expression)
9881 if (expression->base.kind != EXPR_REFERENCE) {
9884 const entity_t *entity = expression->reference.entity;
9885 return is_local_variable(entity);
9889 * Check if a given expression represents a local variable and
9890 * return its declaration then, else return NULL.
9892 entity_t *expression_is_variable(const expression_t *expression)
9894 if (expression->base.kind != EXPR_REFERENCE) {
9897 entity_t *entity = expression->reference.entity;
9898 if (entity->kind != ENTITY_VARIABLE)
9905 * Parse a return statement.
9907 static statement_t *parse_return(void)
9911 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9913 expression_t *return_value = NULL;
9914 if (token.type != ';') {
9915 return_value = parse_expression();
9916 mark_vars_read(return_value, NULL);
9919 const type_t *const func_type = skip_typeref(current_function->base.type);
9920 assert(is_type_function(func_type));
9921 type_t *const return_type = skip_typeref(func_type->function.return_type);
9923 source_position_t const *const pos = &statement->base.source_position;
9924 if (return_value != NULL) {
9925 type_t *return_value_type = skip_typeref(return_value->base.type);
9927 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9928 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9929 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9930 /* Only warn in C mode, because GCC does the same */
9931 if (c_mode & _CXX || strict_mode) {
9933 "'return' with a value, in function returning 'void'");
9934 } else if (warning.other) {
9936 "'return' with a value, in function returning 'void'");
9938 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9939 /* Only warn in C mode, because GCC does the same */
9942 "'return' with expression in function returning 'void'");
9943 } else if (warning.other) {
9945 "'return' with expression in function returning 'void'");
9949 assign_error_t error = semantic_assign(return_type, return_value);
9950 report_assign_error(error, return_type, return_value, "'return'",
9953 return_value = create_implicit_cast(return_value, return_type);
9954 /* check for returning address of a local var */
9955 if (warning.other && return_value != NULL
9956 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9957 const expression_t *expression = return_value->unary.value;
9958 if (expression_is_local_variable(expression)) {
9959 warningf(pos, "function returns address of local variable");
9962 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9963 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9964 if (c_mode & _CXX || strict_mode) {
9966 "'return' without value, in function returning non-void");
9969 "'return' without value, in function returning non-void");
9972 statement->returns.value = return_value;
9974 expect(';', end_error);
9981 * Parse a declaration statement.
9983 static statement_t *parse_declaration_statement(void)
9985 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9987 entity_t *before = current_scope->last_entity;
9989 parse_external_declaration();
9991 parse_declaration(record_entity, DECL_FLAGS_NONE);
9994 declaration_statement_t *const decl = &statement->declaration;
9995 entity_t *const begin =
9996 before != NULL ? before->base.next : current_scope->entities;
9997 decl->declarations_begin = begin;
9998 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10004 * Parse an expression statement, ie. expr ';'.
10006 static statement_t *parse_expression_statement(void)
10008 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10010 expression_t *const expr = parse_expression();
10011 statement->expression.expression = expr;
10012 mark_vars_read(expr, ENT_ANY);
10014 expect(';', end_error);
10021 * Parse a microsoft __try { } __finally { } or
10022 * __try{ } __except() { }
10024 static statement_t *parse_ms_try_statment(void)
10026 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10029 PUSH_PARENT(statement);
10031 ms_try_statement_t *rem = current_try;
10032 current_try = &statement->ms_try;
10033 statement->ms_try.try_statement = parse_compound_statement(false);
10038 if (next_if(T___except)) {
10039 expect('(', end_error);
10040 add_anchor_token(')');
10041 expression_t *const expr = parse_expression();
10042 mark_vars_read(expr, NULL);
10043 type_t * type = skip_typeref(expr->base.type);
10044 if (is_type_integer(type)) {
10045 type = promote_integer(type);
10046 } else if (is_type_valid(type)) {
10047 errorf(&expr->base.source_position,
10048 "__expect expression is not an integer, but '%T'", type);
10049 type = type_error_type;
10051 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10052 rem_anchor_token(')');
10053 expect(')', end_error);
10054 statement->ms_try.final_statement = parse_compound_statement(false);
10055 } else if (next_if(T__finally)) {
10056 statement->ms_try.final_statement = parse_compound_statement(false);
10058 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10059 return create_invalid_statement();
10063 return create_invalid_statement();
10066 static statement_t *parse_empty_statement(void)
10068 if (warning.empty_statement) {
10069 warningf(HERE, "statement is empty");
10071 statement_t *const statement = create_empty_statement();
10076 static statement_t *parse_local_label_declaration(void)
10078 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10082 entity_t *begin = NULL, *end = NULL;
10085 if (token.type != T_IDENTIFIER) {
10086 parse_error_expected("while parsing local label declaration",
10087 T_IDENTIFIER, NULL);
10090 symbol_t *symbol = token.symbol;
10091 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10092 if (entity != NULL && entity->base.parent_scope == current_scope) {
10093 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10094 symbol, &entity->base.source_position);
10096 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10098 entity->base.parent_scope = current_scope;
10099 entity->base.namespc = NAMESPACE_LABEL;
10100 entity->base.source_position = token.source_position;
10101 entity->base.symbol = symbol;
10104 end->base.next = entity;
10109 environment_push(entity);
10112 } while (next_if(','));
10115 statement->declaration.declarations_begin = begin;
10116 statement->declaration.declarations_end = end;
10120 static void parse_namespace_definition(void)
10124 entity_t *entity = NULL;
10125 symbol_t *symbol = NULL;
10127 if (token.type == T_IDENTIFIER) {
10128 symbol = token.symbol;
10131 entity = get_entity(symbol, NAMESPACE_NORMAL);
10133 && entity->kind != ENTITY_NAMESPACE
10134 && entity->base.parent_scope == current_scope) {
10135 if (!is_error_entity(entity)) {
10136 error_redefined_as_different_kind(&token.source_position,
10137 entity, ENTITY_NAMESPACE);
10143 if (entity == NULL) {
10144 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10145 entity->base.symbol = symbol;
10146 entity->base.source_position = token.source_position;
10147 entity->base.namespc = NAMESPACE_NORMAL;
10148 entity->base.parent_scope = current_scope;
10151 if (token.type == '=') {
10152 /* TODO: parse namespace alias */
10153 panic("namespace alias definition not supported yet");
10156 environment_push(entity);
10157 append_entity(current_scope, entity);
10159 size_t const top = environment_top();
10160 scope_t *old_scope = scope_push(&entity->namespacee.members);
10162 entity_t *old_current_entity = current_entity;
10163 current_entity = entity;
10165 expect('{', end_error);
10167 expect('}', end_error);
10170 assert(current_scope == &entity->namespacee.members);
10171 assert(current_entity == entity);
10172 current_entity = old_current_entity;
10173 scope_pop(old_scope);
10174 environment_pop_to(top);
10178 * Parse a statement.
10179 * There's also parse_statement() which additionally checks for
10180 * "statement has no effect" warnings
10182 static statement_t *intern_parse_statement(void)
10184 statement_t *statement = NULL;
10186 /* declaration or statement */
10187 add_anchor_token(';');
10188 switch (token.type) {
10189 case T_IDENTIFIER: {
10190 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10191 if (la1_type == ':') {
10192 statement = parse_label_statement();
10193 } else if (is_typedef_symbol(token.symbol)) {
10194 statement = parse_declaration_statement();
10196 /* it's an identifier, the grammar says this must be an
10197 * expression statement. However it is common that users mistype
10198 * declaration types, so we guess a bit here to improve robustness
10199 * for incorrect programs */
10200 switch (la1_type) {
10203 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL)
10204 goto expression_statment;
10209 statement = parse_declaration_statement();
10213 expression_statment:
10214 statement = parse_expression_statement();
10221 case T___extension__:
10222 /* This can be a prefix to a declaration or an expression statement.
10223 * We simply eat it now and parse the rest with tail recursion. */
10224 while (next_if(T___extension__)) {}
10225 bool old_gcc_extension = in_gcc_extension;
10226 in_gcc_extension = true;
10227 statement = intern_parse_statement();
10228 in_gcc_extension = old_gcc_extension;
10232 statement = parse_declaration_statement();
10236 statement = parse_local_label_declaration();
10239 case ';': statement = parse_empty_statement(); break;
10240 case '{': statement = parse_compound_statement(false); break;
10241 case T___leave: statement = parse_leave_statement(); break;
10242 case T___try: statement = parse_ms_try_statment(); break;
10243 case T_asm: statement = parse_asm_statement(); break;
10244 case T_break: statement = parse_break(); break;
10245 case T_case: statement = parse_case_statement(); break;
10246 case T_continue: statement = parse_continue(); break;
10247 case T_default: statement = parse_default_statement(); break;
10248 case T_do: statement = parse_do(); break;
10249 case T_for: statement = parse_for(); break;
10250 case T_goto: statement = parse_goto(); break;
10251 case T_if: statement = parse_if(); break;
10252 case T_return: statement = parse_return(); break;
10253 case T_switch: statement = parse_switch(); break;
10254 case T_while: statement = parse_while(); break;
10257 statement = parse_expression_statement();
10261 errorf(HERE, "unexpected token %K while parsing statement", &token);
10262 statement = create_invalid_statement();
10267 rem_anchor_token(';');
10269 assert(statement != NULL
10270 && statement->base.source_position.input_name != NULL);
10276 * parse a statement and emits "statement has no effect" warning if needed
10277 * (This is really a wrapper around intern_parse_statement with check for 1
10278 * single warning. It is needed, because for statement expressions we have
10279 * to avoid the warning on the last statement)
10281 static statement_t *parse_statement(void)
10283 statement_t *statement = intern_parse_statement();
10285 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10286 expression_t *expression = statement->expression.expression;
10287 if (!expression_has_effect(expression)) {
10288 warningf(&expression->base.source_position,
10289 "statement has no effect");
10297 * Parse a compound statement.
10299 static statement_t *parse_compound_statement(bool inside_expression_statement)
10301 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10303 PUSH_PARENT(statement);
10306 add_anchor_token('}');
10307 /* tokens, which can start a statement */
10308 /* TODO MS, __builtin_FOO */
10309 add_anchor_token('!');
10310 add_anchor_token('&');
10311 add_anchor_token('(');
10312 add_anchor_token('*');
10313 add_anchor_token('+');
10314 add_anchor_token('-');
10315 add_anchor_token('{');
10316 add_anchor_token('~');
10317 add_anchor_token(T_CHARACTER_CONSTANT);
10318 add_anchor_token(T_COLONCOLON);
10319 add_anchor_token(T_FLOATINGPOINT);
10320 add_anchor_token(T_IDENTIFIER);
10321 add_anchor_token(T_INTEGER);
10322 add_anchor_token(T_MINUSMINUS);
10323 add_anchor_token(T_PLUSPLUS);
10324 add_anchor_token(T_STRING_LITERAL);
10325 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10326 add_anchor_token(T_WIDE_STRING_LITERAL);
10327 add_anchor_token(T__Bool);
10328 add_anchor_token(T__Complex);
10329 add_anchor_token(T__Imaginary);
10330 add_anchor_token(T___FUNCTION__);
10331 add_anchor_token(T___PRETTY_FUNCTION__);
10332 add_anchor_token(T___alignof__);
10333 add_anchor_token(T___attribute__);
10334 add_anchor_token(T___builtin_va_start);
10335 add_anchor_token(T___extension__);
10336 add_anchor_token(T___func__);
10337 add_anchor_token(T___imag__);
10338 add_anchor_token(T___label__);
10339 add_anchor_token(T___real__);
10340 add_anchor_token(T___thread);
10341 add_anchor_token(T_asm);
10342 add_anchor_token(T_auto);
10343 add_anchor_token(T_bool);
10344 add_anchor_token(T_break);
10345 add_anchor_token(T_case);
10346 add_anchor_token(T_char);
10347 add_anchor_token(T_class);
10348 add_anchor_token(T_const);
10349 add_anchor_token(T_const_cast);
10350 add_anchor_token(T_continue);
10351 add_anchor_token(T_default);
10352 add_anchor_token(T_delete);
10353 add_anchor_token(T_double);
10354 add_anchor_token(T_do);
10355 add_anchor_token(T_dynamic_cast);
10356 add_anchor_token(T_enum);
10357 add_anchor_token(T_extern);
10358 add_anchor_token(T_false);
10359 add_anchor_token(T_float);
10360 add_anchor_token(T_for);
10361 add_anchor_token(T_goto);
10362 add_anchor_token(T_if);
10363 add_anchor_token(T_inline);
10364 add_anchor_token(T_int);
10365 add_anchor_token(T_long);
10366 add_anchor_token(T_new);
10367 add_anchor_token(T_operator);
10368 add_anchor_token(T_register);
10369 add_anchor_token(T_reinterpret_cast);
10370 add_anchor_token(T_restrict);
10371 add_anchor_token(T_return);
10372 add_anchor_token(T_short);
10373 add_anchor_token(T_signed);
10374 add_anchor_token(T_sizeof);
10375 add_anchor_token(T_static);
10376 add_anchor_token(T_static_cast);
10377 add_anchor_token(T_struct);
10378 add_anchor_token(T_switch);
10379 add_anchor_token(T_template);
10380 add_anchor_token(T_this);
10381 add_anchor_token(T_throw);
10382 add_anchor_token(T_true);
10383 add_anchor_token(T_try);
10384 add_anchor_token(T_typedef);
10385 add_anchor_token(T_typeid);
10386 add_anchor_token(T_typename);
10387 add_anchor_token(T_typeof);
10388 add_anchor_token(T_union);
10389 add_anchor_token(T_unsigned);
10390 add_anchor_token(T_using);
10391 add_anchor_token(T_void);
10392 add_anchor_token(T_volatile);
10393 add_anchor_token(T_wchar_t);
10394 add_anchor_token(T_while);
10396 size_t const top = environment_top();
10397 scope_t *old_scope = scope_push(&statement->compound.scope);
10399 statement_t **anchor = &statement->compound.statements;
10400 bool only_decls_so_far = true;
10401 while (token.type != '}') {
10402 if (token.type == T_EOF) {
10403 errorf(&statement->base.source_position,
10404 "EOF while parsing compound statement");
10407 statement_t *sub_statement = intern_parse_statement();
10408 if (is_invalid_statement(sub_statement)) {
10409 /* an error occurred. if we are at an anchor, return */
10415 if (warning.declaration_after_statement) {
10416 if (sub_statement->kind != STATEMENT_DECLARATION) {
10417 only_decls_so_far = false;
10418 } else if (!only_decls_so_far) {
10419 warningf(&sub_statement->base.source_position,
10420 "ISO C90 forbids mixed declarations and code");
10424 *anchor = sub_statement;
10426 while (sub_statement->base.next != NULL)
10427 sub_statement = sub_statement->base.next;
10429 anchor = &sub_statement->base.next;
10433 /* look over all statements again to produce no effect warnings */
10434 if (warning.unused_value) {
10435 statement_t *sub_statement = statement->compound.statements;
10436 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10437 if (sub_statement->kind != STATEMENT_EXPRESSION)
10439 /* don't emit a warning for the last expression in an expression
10440 * statement as it has always an effect */
10441 if (inside_expression_statement && sub_statement->base.next == NULL)
10444 expression_t *expression = sub_statement->expression.expression;
10445 if (!expression_has_effect(expression)) {
10446 warningf(&expression->base.source_position,
10447 "statement has no effect");
10453 rem_anchor_token(T_while);
10454 rem_anchor_token(T_wchar_t);
10455 rem_anchor_token(T_volatile);
10456 rem_anchor_token(T_void);
10457 rem_anchor_token(T_using);
10458 rem_anchor_token(T_unsigned);
10459 rem_anchor_token(T_union);
10460 rem_anchor_token(T_typeof);
10461 rem_anchor_token(T_typename);
10462 rem_anchor_token(T_typeid);
10463 rem_anchor_token(T_typedef);
10464 rem_anchor_token(T_try);
10465 rem_anchor_token(T_true);
10466 rem_anchor_token(T_throw);
10467 rem_anchor_token(T_this);
10468 rem_anchor_token(T_template);
10469 rem_anchor_token(T_switch);
10470 rem_anchor_token(T_struct);
10471 rem_anchor_token(T_static_cast);
10472 rem_anchor_token(T_static);
10473 rem_anchor_token(T_sizeof);
10474 rem_anchor_token(T_signed);
10475 rem_anchor_token(T_short);
10476 rem_anchor_token(T_return);
10477 rem_anchor_token(T_restrict);
10478 rem_anchor_token(T_reinterpret_cast);
10479 rem_anchor_token(T_register);
10480 rem_anchor_token(T_operator);
10481 rem_anchor_token(T_new);
10482 rem_anchor_token(T_long);
10483 rem_anchor_token(T_int);
10484 rem_anchor_token(T_inline);
10485 rem_anchor_token(T_if);
10486 rem_anchor_token(T_goto);
10487 rem_anchor_token(T_for);
10488 rem_anchor_token(T_float);
10489 rem_anchor_token(T_false);
10490 rem_anchor_token(T_extern);
10491 rem_anchor_token(T_enum);
10492 rem_anchor_token(T_dynamic_cast);
10493 rem_anchor_token(T_do);
10494 rem_anchor_token(T_double);
10495 rem_anchor_token(T_delete);
10496 rem_anchor_token(T_default);
10497 rem_anchor_token(T_continue);
10498 rem_anchor_token(T_const_cast);
10499 rem_anchor_token(T_const);
10500 rem_anchor_token(T_class);
10501 rem_anchor_token(T_char);
10502 rem_anchor_token(T_case);
10503 rem_anchor_token(T_break);
10504 rem_anchor_token(T_bool);
10505 rem_anchor_token(T_auto);
10506 rem_anchor_token(T_asm);
10507 rem_anchor_token(T___thread);
10508 rem_anchor_token(T___real__);
10509 rem_anchor_token(T___label__);
10510 rem_anchor_token(T___imag__);
10511 rem_anchor_token(T___func__);
10512 rem_anchor_token(T___extension__);
10513 rem_anchor_token(T___builtin_va_start);
10514 rem_anchor_token(T___attribute__);
10515 rem_anchor_token(T___alignof__);
10516 rem_anchor_token(T___PRETTY_FUNCTION__);
10517 rem_anchor_token(T___FUNCTION__);
10518 rem_anchor_token(T__Imaginary);
10519 rem_anchor_token(T__Complex);
10520 rem_anchor_token(T__Bool);
10521 rem_anchor_token(T_WIDE_STRING_LITERAL);
10522 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10523 rem_anchor_token(T_STRING_LITERAL);
10524 rem_anchor_token(T_PLUSPLUS);
10525 rem_anchor_token(T_MINUSMINUS);
10526 rem_anchor_token(T_INTEGER);
10527 rem_anchor_token(T_IDENTIFIER);
10528 rem_anchor_token(T_FLOATINGPOINT);
10529 rem_anchor_token(T_COLONCOLON);
10530 rem_anchor_token(T_CHARACTER_CONSTANT);
10531 rem_anchor_token('~');
10532 rem_anchor_token('{');
10533 rem_anchor_token('-');
10534 rem_anchor_token('+');
10535 rem_anchor_token('*');
10536 rem_anchor_token('(');
10537 rem_anchor_token('&');
10538 rem_anchor_token('!');
10539 rem_anchor_token('}');
10540 assert(current_scope == &statement->compound.scope);
10541 scope_pop(old_scope);
10542 environment_pop_to(top);
10549 * Check for unused global static functions and variables
10551 static void check_unused_globals(void)
10553 if (!warning.unused_function && !warning.unused_variable)
10556 for (const entity_t *entity = file_scope->entities; entity != NULL;
10557 entity = entity->base.next) {
10558 if (!is_declaration(entity))
10561 const declaration_t *declaration = &entity->declaration;
10562 if (declaration->used ||
10563 declaration->modifiers & DM_UNUSED ||
10564 declaration->modifiers & DM_USED ||
10565 declaration->storage_class != STORAGE_CLASS_STATIC)
10568 type_t *const type = declaration->type;
10570 if (entity->kind == ENTITY_FUNCTION) {
10571 /* inhibit warning for static inline functions */
10572 if (entity->function.is_inline)
10575 s = entity->function.statement != NULL ? "defined" : "declared";
10580 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10581 type, declaration->base.symbol, s);
10585 static void parse_global_asm(void)
10587 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10590 expect('(', end_error);
10592 statement->asms.asm_text = parse_string_literals();
10593 statement->base.next = unit->global_asm;
10594 unit->global_asm = statement;
10596 expect(')', end_error);
10597 expect(';', end_error);
10602 static void parse_linkage_specification(void)
10605 assert(token.type == T_STRING_LITERAL);
10607 const char *linkage = parse_string_literals().begin;
10609 linkage_kind_t old_linkage = current_linkage;
10610 linkage_kind_t new_linkage;
10611 if (strcmp(linkage, "C") == 0) {
10612 new_linkage = LINKAGE_C;
10613 } else if (strcmp(linkage, "C++") == 0) {
10614 new_linkage = LINKAGE_CXX;
10616 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10617 new_linkage = LINKAGE_INVALID;
10619 current_linkage = new_linkage;
10621 if (next_if('{')) {
10623 expect('}', end_error);
10629 assert(current_linkage == new_linkage);
10630 current_linkage = old_linkage;
10633 static void parse_external(void)
10635 switch (token.type) {
10636 DECLARATION_START_NO_EXTERN
10638 case T___extension__:
10639 /* tokens below are for implicit int */
10640 case '&': /* & x; -> int& x; (and error later, because C++ has no
10642 case '*': /* * x; -> int* x; */
10643 case '(': /* (x); -> int (x); */
10644 parse_external_declaration();
10648 if (look_ahead(1)->type == T_STRING_LITERAL) {
10649 parse_linkage_specification();
10651 parse_external_declaration();
10656 parse_global_asm();
10660 parse_namespace_definition();
10664 if (!strict_mode) {
10666 warningf(HERE, "stray ';' outside of function");
10673 errorf(HERE, "stray %K outside of function", &token);
10674 if (token.type == '(' || token.type == '{' || token.type == '[')
10675 eat_until_matching_token(token.type);
10681 static void parse_externals(void)
10683 add_anchor_token('}');
10684 add_anchor_token(T_EOF);
10687 unsigned char token_anchor_copy[T_LAST_TOKEN];
10688 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10691 while (token.type != T_EOF && token.type != '}') {
10693 bool anchor_leak = false;
10694 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10695 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10697 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10698 anchor_leak = true;
10701 if (in_gcc_extension) {
10702 errorf(HERE, "Leaked __extension__");
10703 anchor_leak = true;
10713 rem_anchor_token(T_EOF);
10714 rem_anchor_token('}');
10718 * Parse a translation unit.
10720 static void parse_translation_unit(void)
10722 add_anchor_token(T_EOF);
10727 if (token.type == T_EOF)
10730 errorf(HERE, "stray %K outside of function", &token);
10731 if (token.type == '(' || token.type == '{' || token.type == '[')
10732 eat_until_matching_token(token.type);
10740 * @return the translation unit or NULL if errors occurred.
10742 void start_parsing(void)
10744 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10745 label_stack = NEW_ARR_F(stack_entry_t, 0);
10746 diagnostic_count = 0;
10750 print_to_file(stderr);
10752 assert(unit == NULL);
10753 unit = allocate_ast_zero(sizeof(unit[0]));
10755 assert(file_scope == NULL);
10756 file_scope = &unit->scope;
10758 assert(current_scope == NULL);
10759 scope_push(&unit->scope);
10761 create_gnu_builtins();
10763 create_microsoft_intrinsics();
10766 translation_unit_t *finish_parsing(void)
10768 assert(current_scope == &unit->scope);
10771 assert(file_scope == &unit->scope);
10772 check_unused_globals();
10775 DEL_ARR_F(environment_stack);
10776 DEL_ARR_F(label_stack);
10778 translation_unit_t *result = unit;
10783 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10784 * are given length one. */
10785 static void complete_incomplete_arrays(void)
10787 size_t n = ARR_LEN(incomplete_arrays);
10788 for (size_t i = 0; i != n; ++i) {
10789 declaration_t *const decl = incomplete_arrays[i];
10790 type_t *const orig_type = decl->type;
10791 type_t *const type = skip_typeref(orig_type);
10793 if (!is_type_incomplete(type))
10796 if (warning.other) {
10797 warningf(&decl->base.source_position,
10798 "array '%#T' assumed to have one element",
10799 orig_type, decl->base.symbol);
10802 type_t *const new_type = duplicate_type(type);
10803 new_type->array.size_constant = true;
10804 new_type->array.has_implicit_size = true;
10805 new_type->array.size = 1;
10807 type_t *const result = identify_new_type(new_type);
10809 decl->type = result;
10813 void prepare_main_collect2(entity_t *entity)
10815 // create call to __main
10816 symbol_t *symbol = symbol_table_insert("__main");
10817 entity_t *subsubmain_ent
10818 = create_implicit_function(symbol, &builtin_source_position);
10820 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10821 type_t *ftype = subsubmain_ent->declaration.type;
10822 ref->base.source_position = builtin_source_position;
10823 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10824 ref->reference.entity = subsubmain_ent;
10826 expression_t *call = allocate_expression_zero(EXPR_CALL);
10827 call->base.source_position = builtin_source_position;
10828 call->base.type = type_void;
10829 call->call.function = ref;
10831 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10832 expr_statement->base.source_position = builtin_source_position;
10833 expr_statement->expression.expression = call;
10835 statement_t *statement = entity->function.statement;
10836 assert(statement->kind == STATEMENT_COMPOUND);
10837 compound_statement_t *compounds = &statement->compound;
10839 expr_statement->base.next = compounds->statements;
10840 compounds->statements = expr_statement;
10845 lookahead_bufpos = 0;
10846 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10849 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10850 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10851 parse_translation_unit();
10852 complete_incomplete_arrays();
10853 DEL_ARR_F(incomplete_arrays);
10854 incomplete_arrays = NULL;
10858 * Initialize the parser.
10860 void init_parser(void)
10862 sym_anonymous = symbol_table_insert("<anonymous>");
10864 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10866 init_expression_parsers();
10867 obstack_init(&temp_obst);
10869 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10870 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10874 * Terminate the parser.
10876 void exit_parser(void)
10878 obstack_free(&temp_obst, NULL);