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_subexpression(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: \
232 case T_FLOATINGPOINT_HEXADECIMAL: \
234 case T_INTEGER_HEXADECIMAL: \
235 case T_INTEGER_OCTAL: \
238 case T_STRING_LITERAL: \
239 case T_WIDE_CHARACTER_CONSTANT: \
240 case T_WIDE_STRING_LITERAL: \
241 case T___FUNCDNAME__: \
242 case T___FUNCSIG__: \
243 case T___FUNCTION__: \
244 case T___PRETTY_FUNCTION__: \
245 case T___alignof__: \
246 case T___builtin_classify_type: \
247 case T___builtin_constant_p: \
248 case T___builtin_isgreater: \
249 case T___builtin_isgreaterequal: \
250 case T___builtin_isless: \
251 case T___builtin_islessequal: \
252 case T___builtin_islessgreater: \
253 case T___builtin_isunordered: \
254 case T___builtin_offsetof: \
255 case T___builtin_va_arg: \
256 case T___builtin_va_copy: \
257 case T___builtin_va_start: \
268 * Returns the size of a statement node.
270 * @param kind the statement kind
272 static size_t get_statement_struct_size(statement_kind_t kind)
274 static const size_t sizes[] = {
275 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
276 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
277 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
278 [STATEMENT_RETURN] = sizeof(return_statement_t),
279 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
280 [STATEMENT_IF] = sizeof(if_statement_t),
281 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
282 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
283 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
284 [STATEMENT_BREAK] = sizeof(statement_base_t),
285 [STATEMENT_GOTO] = sizeof(goto_statement_t),
286 [STATEMENT_LABEL] = sizeof(label_statement_t),
287 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
288 [STATEMENT_WHILE] = sizeof(while_statement_t),
289 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
290 [STATEMENT_FOR] = sizeof(for_statement_t),
291 [STATEMENT_ASM] = sizeof(asm_statement_t),
292 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
293 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
295 assert(kind < lengthof(sizes));
296 assert(sizes[kind] != 0);
301 * Returns the size of an expression node.
303 * @param kind the expression kind
305 static size_t get_expression_struct_size(expression_kind_t kind)
307 static const size_t sizes[] = {
308 [EXPR_INVALID] = sizeof(expression_base_t),
309 [EXPR_REFERENCE] = sizeof(reference_expression_t),
310 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
311 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
312 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
314 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
316 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
317 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
318 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
319 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
320 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
321 [EXPR_CALL] = sizeof(call_expression_t),
322 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
323 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
324 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
325 [EXPR_SELECT] = sizeof(select_expression_t),
326 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
327 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
328 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
329 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
330 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
331 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
332 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
333 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
334 [EXPR_VA_START] = sizeof(va_start_expression_t),
335 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
336 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
337 [EXPR_STATEMENT] = sizeof(statement_expression_t),
338 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
340 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
341 return sizes[EXPR_UNARY_FIRST];
343 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
344 return sizes[EXPR_BINARY_FIRST];
346 assert(kind < lengthof(sizes));
347 assert(sizes[kind] != 0);
352 * Allocate a statement node of given kind and initialize all
353 * fields with zero. Sets its source position to the position
354 * of the current token.
356 static statement_t *allocate_statement_zero(statement_kind_t kind)
358 size_t size = get_statement_struct_size(kind);
359 statement_t *res = allocate_ast_zero(size);
361 res->base.kind = kind;
362 res->base.parent = current_parent;
363 res->base.source_position = token.source_position;
368 * Allocate an expression node of given kind and initialize all
371 * @param kind the kind of the expression to allocate
373 static expression_t *allocate_expression_zero(expression_kind_t kind)
375 size_t size = get_expression_struct_size(kind);
376 expression_t *res = allocate_ast_zero(size);
378 res->base.kind = kind;
379 res->base.type = type_error_type;
380 res->base.source_position = token.source_position;
385 * Creates a new invalid expression at the source position
386 * of the current token.
388 static expression_t *create_invalid_expression(void)
390 return allocate_expression_zero(EXPR_INVALID);
394 * Creates a new invalid statement.
396 static statement_t *create_invalid_statement(void)
398 return allocate_statement_zero(STATEMENT_INVALID);
402 * Allocate a new empty statement.
404 static statement_t *create_empty_statement(void)
406 return allocate_statement_zero(STATEMENT_EMPTY);
409 static function_parameter_t *allocate_parameter(type_t *const type)
411 function_parameter_t *const param
412 = obstack_alloc(type_obst, sizeof(*param));
413 memset(param, 0, sizeof(*param));
419 * Returns the size of an initializer node.
421 * @param kind the initializer kind
423 static size_t get_initializer_size(initializer_kind_t kind)
425 static const size_t sizes[] = {
426 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
427 [INITIALIZER_STRING] = sizeof(initializer_string_t),
428 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
429 [INITIALIZER_LIST] = sizeof(initializer_list_t),
430 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
432 assert(kind < lengthof(sizes));
433 assert(sizes[kind] != 0);
438 * Allocate an initializer node of given kind and initialize all
441 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
443 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
450 * Returns the index of the top element of the environment stack.
452 static size_t environment_top(void)
454 return ARR_LEN(environment_stack);
458 * Returns the index of the top element of the global label stack.
460 static size_t label_top(void)
462 return ARR_LEN(label_stack);
466 * Return the next token.
468 static inline void next_token(void)
470 token = lookahead_buffer[lookahead_bufpos];
471 lookahead_buffer[lookahead_bufpos] = lexer_token;
474 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
477 print_token(stderr, &token);
478 fprintf(stderr, "\n");
482 static inline bool next_if(int const type)
484 if (token.type == type) {
493 * Return the next token with a given lookahead.
495 static inline const token_t *look_ahead(size_t num)
497 assert(0 < num && num <= MAX_LOOKAHEAD);
498 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
499 return &lookahead_buffer[pos];
503 * Adds a token type to the token type anchor set (a multi-set).
505 static void add_anchor_token(int token_type)
507 assert(0 <= token_type && token_type < T_LAST_TOKEN);
508 ++token_anchor_set[token_type];
512 * Set the number of tokens types of the given type
513 * to zero and return the old count.
515 static int save_and_reset_anchor_state(int token_type)
517 assert(0 <= token_type && token_type < T_LAST_TOKEN);
518 int count = token_anchor_set[token_type];
519 token_anchor_set[token_type] = 0;
524 * Restore the number of token types to the given count.
526 static void restore_anchor_state(int token_type, int count)
528 assert(0 <= token_type && token_type < T_LAST_TOKEN);
529 token_anchor_set[token_type] = count;
533 * Remove a token type from the token type anchor set (a multi-set).
535 static void rem_anchor_token(int token_type)
537 assert(0 <= token_type && token_type < T_LAST_TOKEN);
538 assert(token_anchor_set[token_type] != 0);
539 --token_anchor_set[token_type];
543 * Return true if the token type of the current token is
546 static bool at_anchor(void)
550 return token_anchor_set[token.type];
554 * Eat tokens until a matching token type is found.
556 static void eat_until_matching_token(int type)
560 case '(': end_token = ')'; break;
561 case '{': end_token = '}'; break;
562 case '[': end_token = ']'; break;
563 default: end_token = type; break;
566 unsigned parenthesis_count = 0;
567 unsigned brace_count = 0;
568 unsigned bracket_count = 0;
569 while (token.type != end_token ||
570 parenthesis_count != 0 ||
572 bracket_count != 0) {
573 switch (token.type) {
575 case '(': ++parenthesis_count; break;
576 case '{': ++brace_count; break;
577 case '[': ++bracket_count; break;
580 if (parenthesis_count > 0)
590 if (bracket_count > 0)
593 if (token.type == end_token &&
594 parenthesis_count == 0 &&
608 * Eat input tokens until an anchor is found.
610 static void eat_until_anchor(void)
612 while (token_anchor_set[token.type] == 0) {
613 if (token.type == '(' || token.type == '{' || token.type == '[')
614 eat_until_matching_token(token.type);
620 * Eat a whole block from input tokens.
622 static void eat_block(void)
624 eat_until_matching_token('{');
628 #define eat(token_type) (assert(token.type == (token_type)), next_token())
631 * Report a parse error because an expected token was not found.
634 #if defined __GNUC__ && __GNUC__ >= 4
635 __attribute__((sentinel))
637 void parse_error_expected(const char *message, ...)
639 if (message != NULL) {
640 errorf(HERE, "%s", message);
643 va_start(ap, message);
644 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
649 * Report an incompatible type.
651 static void type_error_incompatible(const char *msg,
652 const source_position_t *source_position, type_t *type1, type_t *type2)
654 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
659 * Expect the current token is the expected token.
660 * If not, generate an error, eat the current statement,
661 * and goto the error_label label.
663 #define expect(expected, error_label) \
665 if (UNLIKELY(token.type != (expected))) { \
666 parse_error_expected(NULL, (expected), NULL); \
667 add_anchor_token(expected); \
668 eat_until_anchor(); \
669 next_if((expected)); \
670 rem_anchor_token(expected); \
677 * Push a given scope on the scope stack and make it the
680 static scope_t *scope_push(scope_t *new_scope)
682 if (current_scope != NULL) {
683 new_scope->depth = current_scope->depth + 1;
686 scope_t *old_scope = current_scope;
687 current_scope = new_scope;
692 * Pop the current scope from the scope stack.
694 static void scope_pop(scope_t *old_scope)
696 current_scope = old_scope;
700 * Search an entity by its symbol in a given namespace.
702 static entity_t *get_entity(const symbol_t *const symbol,
703 namespace_tag_t namespc)
705 entity_t *entity = symbol->entity;
706 for (; entity != NULL; entity = entity->base.symbol_next) {
707 if (entity->base.namespc == namespc)
714 /* §6.2.3:1 24) There is only one name space for tags even though three are
716 static entity_t *get_tag(symbol_t const *const symbol,
717 entity_kind_tag_t const kind)
719 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
720 if (entity != NULL && entity->kind != kind) {
722 "'%Y' defined as wrong kind of tag (previous definition %P)",
723 symbol, &entity->base.source_position);
730 * pushs an entity on the environment stack and links the corresponding symbol
733 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
735 symbol_t *symbol = entity->base.symbol;
736 entity_namespace_t namespc = entity->base.namespc;
737 assert(namespc != NAMESPACE_INVALID);
739 /* replace/add entity into entity list of the symbol */
742 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
747 /* replace an entry? */
748 if (iter->base.namespc == namespc) {
749 entity->base.symbol_next = iter->base.symbol_next;
755 /* remember old declaration */
757 entry.symbol = symbol;
758 entry.old_entity = iter;
759 entry.namespc = namespc;
760 ARR_APP1(stack_entry_t, *stack_ptr, entry);
764 * Push an entity on the environment stack.
766 static void environment_push(entity_t *entity)
768 assert(entity->base.source_position.input_name != NULL);
769 assert(entity->base.parent_scope != NULL);
770 stack_push(&environment_stack, entity);
774 * Push a declaration on the global label stack.
776 * @param declaration the declaration
778 static void label_push(entity_t *label)
780 /* we abuse the parameters scope as parent for the labels */
781 label->base.parent_scope = ¤t_function->parameters;
782 stack_push(&label_stack, label);
786 * pops symbols from the environment stack until @p new_top is the top element
788 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
790 stack_entry_t *stack = *stack_ptr;
791 size_t top = ARR_LEN(stack);
794 assert(new_top <= top);
798 for (i = top; i > new_top; --i) {
799 stack_entry_t *entry = &stack[i - 1];
801 entity_t *old_entity = entry->old_entity;
802 symbol_t *symbol = entry->symbol;
803 entity_namespace_t namespc = entry->namespc;
805 /* replace with old_entity/remove */
808 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
810 assert(iter != NULL);
811 /* replace an entry? */
812 if (iter->base.namespc == namespc)
816 /* restore definition from outer scopes (if there was one) */
817 if (old_entity != NULL) {
818 old_entity->base.symbol_next = iter->base.symbol_next;
819 *anchor = old_entity;
821 /* remove entry from list */
822 *anchor = iter->base.symbol_next;
826 ARR_SHRINKLEN(*stack_ptr, new_top);
830 * Pop all entries from the environment stack until the new_top
833 * @param new_top the new stack top
835 static void environment_pop_to(size_t new_top)
837 stack_pop_to(&environment_stack, new_top);
841 * Pop all entries from the global label stack until the new_top
844 * @param new_top the new stack top
846 static void label_pop_to(size_t new_top)
848 stack_pop_to(&label_stack, new_top);
851 static int get_akind_rank(atomic_type_kind_t akind)
857 * Return the type rank for an atomic type.
859 static int get_rank(const type_t *type)
861 assert(!is_typeref(type));
862 if (type->kind == TYPE_ENUM)
863 return get_akind_rank(type->enumt.akind);
865 assert(type->kind == TYPE_ATOMIC);
866 return get_akind_rank(type->atomic.akind);
870 * §6.3.1.1:2 Do integer promotion for a given type.
872 * @param type the type to promote
873 * @return the promoted type
875 static type_t *promote_integer(type_t *type)
877 if (type->kind == TYPE_BITFIELD)
878 type = type->bitfield.base_type;
880 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
887 * Create a cast expression.
889 * @param expression the expression to cast
890 * @param dest_type the destination type
892 static expression_t *create_cast_expression(expression_t *expression,
895 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
897 cast->unary.value = expression;
898 cast->base.type = dest_type;
904 * Check if a given expression represents a null pointer constant.
906 * @param expression the expression to check
908 static bool is_null_pointer_constant(const expression_t *expression)
910 /* skip void* cast */
911 if (expression->kind == EXPR_UNARY_CAST ||
912 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
913 type_t *const type = skip_typeref(expression->base.type);
914 if (types_compatible(type, type_void_ptr))
915 expression = expression->unary.value;
918 type_t *const type = skip_typeref(expression->base.type);
919 if (!is_type_integer(type))
921 switch (is_constant_expression(expression)) {
922 case EXPR_CLASS_ERROR: return true;
923 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
924 default: return false;
929 * Create an implicit cast expression.
931 * @param expression the expression to cast
932 * @param dest_type the destination type
934 static expression_t *create_implicit_cast(expression_t *expression,
937 type_t *const source_type = expression->base.type;
939 if (source_type == dest_type)
942 return create_cast_expression(expression, dest_type);
945 typedef enum assign_error_t {
947 ASSIGN_ERROR_INCOMPATIBLE,
948 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
949 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
950 ASSIGN_WARNING_POINTER_FROM_INT,
951 ASSIGN_WARNING_INT_FROM_POINTER
954 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
955 const expression_t *const right,
957 const source_position_t *source_position)
959 type_t *const orig_type_right = right->base.type;
960 type_t *const type_left = skip_typeref(orig_type_left);
961 type_t *const type_right = skip_typeref(orig_type_right);
966 case ASSIGN_ERROR_INCOMPATIBLE:
967 errorf(source_position,
968 "destination type '%T' in %s is incompatible with type '%T'",
969 orig_type_left, context, orig_type_right);
972 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
974 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
975 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
977 /* the left type has all qualifiers from the right type */
978 unsigned missing_qualifiers
979 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
980 warningf(source_position,
981 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
982 orig_type_left, context, orig_type_right, missing_qualifiers);
987 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
989 warningf(source_position,
990 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
991 orig_type_left, context, right, orig_type_right);
995 case ASSIGN_WARNING_POINTER_FROM_INT:
997 warningf(source_position,
998 "%s makes pointer '%T' from integer '%T' without a cast",
999 context, orig_type_left, orig_type_right);
1003 case ASSIGN_WARNING_INT_FROM_POINTER:
1004 if (warning.other) {
1005 warningf(source_position,
1006 "%s makes integer '%T' from pointer '%T' without a cast",
1007 context, orig_type_left, orig_type_right);
1012 panic("invalid error value");
1016 /** Implements the rules from §6.5.16.1 */
1017 static assign_error_t semantic_assign(type_t *orig_type_left,
1018 const expression_t *const right)
1020 type_t *const orig_type_right = right->base.type;
1021 type_t *const type_left = skip_typeref(orig_type_left);
1022 type_t *const type_right = skip_typeref(orig_type_right);
1024 if (is_type_pointer(type_left)) {
1025 if (is_null_pointer_constant(right)) {
1026 return ASSIGN_SUCCESS;
1027 } else if (is_type_pointer(type_right)) {
1028 type_t *points_to_left
1029 = skip_typeref(type_left->pointer.points_to);
1030 type_t *points_to_right
1031 = skip_typeref(type_right->pointer.points_to);
1032 assign_error_t res = ASSIGN_SUCCESS;
1034 /* the left type has all qualifiers from the right type */
1035 unsigned missing_qualifiers
1036 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1037 if (missing_qualifiers != 0) {
1038 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1041 points_to_left = get_unqualified_type(points_to_left);
1042 points_to_right = get_unqualified_type(points_to_right);
1044 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1047 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1048 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1049 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1052 if (!types_compatible(points_to_left, points_to_right)) {
1053 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1057 } else if (is_type_integer(type_right)) {
1058 return ASSIGN_WARNING_POINTER_FROM_INT;
1060 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1061 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1062 && is_type_pointer(type_right))) {
1063 return ASSIGN_SUCCESS;
1064 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1065 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1066 type_t *const unqual_type_left = get_unqualified_type(type_left);
1067 type_t *const unqual_type_right = get_unqualified_type(type_right);
1068 if (types_compatible(unqual_type_left, unqual_type_right)) {
1069 return ASSIGN_SUCCESS;
1071 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1072 return ASSIGN_WARNING_INT_FROM_POINTER;
1075 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1076 return ASSIGN_SUCCESS;
1078 return ASSIGN_ERROR_INCOMPATIBLE;
1081 static expression_t *parse_constant_expression(void)
1083 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1085 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1086 errorf(&result->base.source_position,
1087 "expression '%E' is not constant", result);
1093 static expression_t *parse_assignment_expression(void)
1095 return parse_subexpression(PREC_ASSIGNMENT);
1098 static void warn_string_concat(const source_position_t *pos)
1100 if (warning.traditional) {
1101 warningf(pos, "traditional C rejects string constant concatenation");
1105 static string_t parse_string_literals(void)
1107 assert(token.type == T_STRING_LITERAL);
1108 string_t result = token.literal;
1112 while (token.type == T_STRING_LITERAL) {
1113 warn_string_concat(&token.source_position);
1114 result = concat_strings(&result, &token.literal);
1122 * compare two string, ignoring double underscores on the second.
1124 static int strcmp_underscore(const char *s1, const char *s2)
1126 if (s2[0] == '_' && s2[1] == '_') {
1127 size_t len2 = strlen(s2);
1128 size_t len1 = strlen(s1);
1129 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1130 return strncmp(s1, s2+2, len2-4);
1134 return strcmp(s1, s2);
1137 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1139 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1140 attribute->kind = kind;
1145 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1148 * __attribute__ ( ( attribute-list ) )
1152 * attribute_list , attrib
1157 * any-word ( identifier )
1158 * any-word ( identifier , nonempty-expr-list )
1159 * any-word ( expr-list )
1161 * where the "identifier" must not be declared as a type, and
1162 * "any-word" may be any identifier (including one declared as a
1163 * type), a reserved word storage class specifier, type specifier or
1164 * type qualifier. ??? This still leaves out most reserved keywords
1165 * (following the old parser), shouldn't we include them, and why not
1166 * allow identifiers declared as types to start the arguments?
1168 * Matze: this all looks confusing and little systematic, so we're even less
1169 * strict and parse any list of things which are identifiers or
1170 * (assignment-)expressions.
1172 static attribute_argument_t *parse_attribute_arguments(void)
1174 attribute_argument_t *first = NULL;
1175 attribute_argument_t **anchor = &first;
1176 if (token.type != ')') do {
1177 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1179 /* is it an identifier */
1180 if (token.type == T_IDENTIFIER
1181 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1182 symbol_t *symbol = token.symbol;
1183 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1184 argument->v.symbol = symbol;
1187 /* must be an expression */
1188 expression_t *expression = parse_assignment_expression();
1190 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1191 argument->v.expression = expression;
1194 /* append argument */
1196 anchor = &argument->next;
1197 } while (next_if(','));
1198 expect(')', end_error);
1207 static attribute_t *parse_attribute_asm(void)
1211 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1213 expect('(', end_error);
1214 attribute->a.arguments = parse_attribute_arguments();
1221 static symbol_t *get_symbol_from_token(void)
1223 switch(token.type) {
1225 return token.symbol;
1254 /* maybe we need more tokens ... add them on demand */
1255 return get_token_symbol(&token);
1261 static attribute_t *parse_attribute_gnu_single(void)
1263 /* parse "any-word" */
1264 symbol_t *symbol = get_symbol_from_token();
1265 if (symbol == NULL) {
1266 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1270 const char *name = symbol->string;
1273 attribute_kind_t kind;
1274 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1275 const char *attribute_name = get_attribute_name(kind);
1276 if (attribute_name != NULL
1277 && strcmp_underscore(attribute_name, name) == 0)
1281 if (kind >= ATTRIBUTE_GNU_LAST) {
1282 if (warning.attribute) {
1283 warningf(HERE, "unknown attribute '%s' ignored", name);
1285 /* TODO: we should still save the attribute in the list... */
1286 kind = ATTRIBUTE_UNKNOWN;
1289 attribute_t *attribute = allocate_attribute_zero(kind);
1291 /* parse arguments */
1293 attribute->a.arguments = parse_attribute_arguments();
1298 static attribute_t *parse_attribute_gnu(void)
1300 attribute_t *first = NULL;
1301 attribute_t **anchor = &first;
1303 eat(T___attribute__);
1304 expect('(', end_error);
1305 expect('(', end_error);
1307 if (token.type != ')') do {
1308 attribute_t *attribute = parse_attribute_gnu_single();
1309 if (attribute == NULL)
1312 *anchor = attribute;
1313 anchor = &attribute->next;
1314 } while (next_if(','));
1315 expect(')', end_error);
1316 expect(')', end_error);
1322 /** Parse attributes. */
1323 static attribute_t *parse_attributes(attribute_t *first)
1325 attribute_t **anchor = &first;
1327 while (*anchor != NULL)
1328 anchor = &(*anchor)->next;
1330 attribute_t *attribute;
1331 switch (token.type) {
1332 case T___attribute__:
1333 attribute = parse_attribute_gnu();
1337 attribute = parse_attribute_asm();
1342 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1347 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1350 case T__forceinline:
1352 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1357 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1362 /* TODO record modifier */
1364 warningf(HERE, "Ignoring declaration modifier %K", &token);
1365 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1372 *anchor = attribute;
1373 anchor = &attribute->next;
1377 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1379 static entity_t *determine_lhs_ent(expression_t *const expr,
1382 switch (expr->kind) {
1383 case EXPR_REFERENCE: {
1384 entity_t *const entity = expr->reference.entity;
1385 /* we should only find variables as lvalues... */
1386 if (entity->base.kind != ENTITY_VARIABLE
1387 && entity->base.kind != ENTITY_PARAMETER)
1393 case EXPR_ARRAY_ACCESS: {
1394 expression_t *const ref = expr->array_access.array_ref;
1395 entity_t * ent = NULL;
1396 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1397 ent = determine_lhs_ent(ref, lhs_ent);
1400 mark_vars_read(expr->select.compound, lhs_ent);
1402 mark_vars_read(expr->array_access.index, lhs_ent);
1407 if (is_type_compound(skip_typeref(expr->base.type))) {
1408 return determine_lhs_ent(expr->select.compound, lhs_ent);
1410 mark_vars_read(expr->select.compound, lhs_ent);
1415 case EXPR_UNARY_DEREFERENCE: {
1416 expression_t *const val = expr->unary.value;
1417 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1419 return determine_lhs_ent(val->unary.value, lhs_ent);
1421 mark_vars_read(val, NULL);
1427 mark_vars_read(expr, NULL);
1432 #define ENT_ANY ((entity_t*)-1)
1435 * Mark declarations, which are read. This is used to detect variables, which
1439 * x is not marked as "read", because it is only read to calculate its own new
1443 * x and y are not detected as "not read", because multiple variables are
1446 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1448 switch (expr->kind) {
1449 case EXPR_REFERENCE: {
1450 entity_t *const entity = expr->reference.entity;
1451 if (entity->kind != ENTITY_VARIABLE
1452 && entity->kind != ENTITY_PARAMETER)
1455 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1456 if (entity->kind == ENTITY_VARIABLE) {
1457 entity->variable.read = true;
1459 entity->parameter.read = true;
1466 // TODO respect pure/const
1467 mark_vars_read(expr->call.function, NULL);
1468 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1469 mark_vars_read(arg->expression, NULL);
1473 case EXPR_CONDITIONAL:
1474 // TODO lhs_decl should depend on whether true/false have an effect
1475 mark_vars_read(expr->conditional.condition, NULL);
1476 if (expr->conditional.true_expression != NULL)
1477 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1478 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1482 if (lhs_ent == ENT_ANY
1483 && !is_type_compound(skip_typeref(expr->base.type)))
1485 mark_vars_read(expr->select.compound, lhs_ent);
1488 case EXPR_ARRAY_ACCESS: {
1489 expression_t *const ref = expr->array_access.array_ref;
1490 mark_vars_read(ref, lhs_ent);
1491 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1492 mark_vars_read(expr->array_access.index, lhs_ent);
1497 mark_vars_read(expr->va_arge.ap, lhs_ent);
1501 mark_vars_read(expr->va_copye.src, lhs_ent);
1504 case EXPR_UNARY_CAST:
1505 /* Special case: Use void cast to mark a variable as "read" */
1506 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1511 case EXPR_UNARY_THROW:
1512 if (expr->unary.value == NULL)
1515 case EXPR_UNARY_DEREFERENCE:
1516 case EXPR_UNARY_DELETE:
1517 case EXPR_UNARY_DELETE_ARRAY:
1518 if (lhs_ent == ENT_ANY)
1522 case EXPR_UNARY_NEGATE:
1523 case EXPR_UNARY_PLUS:
1524 case EXPR_UNARY_BITWISE_NEGATE:
1525 case EXPR_UNARY_NOT:
1526 case EXPR_UNARY_TAKE_ADDRESS:
1527 case EXPR_UNARY_POSTFIX_INCREMENT:
1528 case EXPR_UNARY_POSTFIX_DECREMENT:
1529 case EXPR_UNARY_PREFIX_INCREMENT:
1530 case EXPR_UNARY_PREFIX_DECREMENT:
1531 case EXPR_UNARY_CAST_IMPLICIT:
1532 case EXPR_UNARY_ASSUME:
1534 mark_vars_read(expr->unary.value, lhs_ent);
1537 case EXPR_BINARY_ADD:
1538 case EXPR_BINARY_SUB:
1539 case EXPR_BINARY_MUL:
1540 case EXPR_BINARY_DIV:
1541 case EXPR_BINARY_MOD:
1542 case EXPR_BINARY_EQUAL:
1543 case EXPR_BINARY_NOTEQUAL:
1544 case EXPR_BINARY_LESS:
1545 case EXPR_BINARY_LESSEQUAL:
1546 case EXPR_BINARY_GREATER:
1547 case EXPR_BINARY_GREATEREQUAL:
1548 case EXPR_BINARY_BITWISE_AND:
1549 case EXPR_BINARY_BITWISE_OR:
1550 case EXPR_BINARY_BITWISE_XOR:
1551 case EXPR_BINARY_LOGICAL_AND:
1552 case EXPR_BINARY_LOGICAL_OR:
1553 case EXPR_BINARY_SHIFTLEFT:
1554 case EXPR_BINARY_SHIFTRIGHT:
1555 case EXPR_BINARY_COMMA:
1556 case EXPR_BINARY_ISGREATER:
1557 case EXPR_BINARY_ISGREATEREQUAL:
1558 case EXPR_BINARY_ISLESS:
1559 case EXPR_BINARY_ISLESSEQUAL:
1560 case EXPR_BINARY_ISLESSGREATER:
1561 case EXPR_BINARY_ISUNORDERED:
1562 mark_vars_read(expr->binary.left, lhs_ent);
1563 mark_vars_read(expr->binary.right, lhs_ent);
1566 case EXPR_BINARY_ASSIGN:
1567 case EXPR_BINARY_MUL_ASSIGN:
1568 case EXPR_BINARY_DIV_ASSIGN:
1569 case EXPR_BINARY_MOD_ASSIGN:
1570 case EXPR_BINARY_ADD_ASSIGN:
1571 case EXPR_BINARY_SUB_ASSIGN:
1572 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1573 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1574 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1575 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1576 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1577 if (lhs_ent == ENT_ANY)
1579 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1580 mark_vars_read(expr->binary.right, lhs_ent);
1585 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1591 case EXPR_STRING_LITERAL:
1592 case EXPR_WIDE_STRING_LITERAL:
1593 case EXPR_COMPOUND_LITERAL: // TODO init?
1595 case EXPR_CLASSIFY_TYPE:
1598 case EXPR_BUILTIN_CONSTANT_P:
1599 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1601 case EXPR_STATEMENT: // TODO
1602 case EXPR_LABEL_ADDRESS:
1603 case EXPR_REFERENCE_ENUM_VALUE:
1607 panic("unhandled expression");
1610 static designator_t *parse_designation(void)
1612 designator_t *result = NULL;
1613 designator_t **anchor = &result;
1616 designator_t *designator;
1617 switch (token.type) {
1619 designator = allocate_ast_zero(sizeof(designator[0]));
1620 designator->source_position = token.source_position;
1622 add_anchor_token(']');
1623 designator->array_index = parse_constant_expression();
1624 rem_anchor_token(']');
1625 expect(']', end_error);
1628 designator = allocate_ast_zero(sizeof(designator[0]));
1629 designator->source_position = token.source_position;
1631 if (token.type != T_IDENTIFIER) {
1632 parse_error_expected("while parsing designator",
1633 T_IDENTIFIER, NULL);
1636 designator->symbol = token.symbol;
1640 expect('=', end_error);
1644 assert(designator != NULL);
1645 *anchor = designator;
1646 anchor = &designator->next;
1652 static initializer_t *initializer_from_string(array_type_t *const type,
1653 const string_t *const string)
1655 /* TODO: check len vs. size of array type */
1658 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1659 initializer->string.string = *string;
1664 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1665 const string_t *const string)
1667 /* TODO: check len vs. size of array type */
1670 initializer_t *const initializer =
1671 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1672 initializer->wide_string.string = *string;
1678 * Build an initializer from a given expression.
1680 static initializer_t *initializer_from_expression(type_t *orig_type,
1681 expression_t *expression)
1683 /* TODO check that expression is a constant expression */
1685 /* §6.7.8.14/15 char array may be initialized by string literals */
1686 type_t *type = skip_typeref(orig_type);
1687 type_t *expr_type_orig = expression->base.type;
1688 type_t *expr_type = skip_typeref(expr_type_orig);
1690 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1691 array_type_t *const array_type = &type->array;
1692 type_t *const element_type = skip_typeref(array_type->element_type);
1694 if (element_type->kind == TYPE_ATOMIC) {
1695 atomic_type_kind_t akind = element_type->atomic.akind;
1696 switch (expression->kind) {
1697 case EXPR_STRING_LITERAL:
1698 if (akind == ATOMIC_TYPE_CHAR
1699 || akind == ATOMIC_TYPE_SCHAR
1700 || akind == ATOMIC_TYPE_UCHAR) {
1701 return initializer_from_string(array_type,
1702 &expression->string_literal.value);
1706 case EXPR_WIDE_STRING_LITERAL: {
1707 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1708 if (get_unqualified_type(element_type) == bare_wchar_type) {
1709 return initializer_from_wide_string(array_type,
1710 &expression->string_literal.value);
1721 assign_error_t error = semantic_assign(type, expression);
1722 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1724 report_assign_error(error, type, expression, "initializer",
1725 &expression->base.source_position);
1727 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1728 result->value.value = create_implicit_cast(expression, type);
1734 * Checks if a given expression can be used as an constant initializer.
1736 static bool is_initializer_constant(const expression_t *expression)
1739 is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1740 is_address_constant(expression) != EXPR_CLASS_VARIABLE;
1744 * Parses an scalar initializer.
1746 * §6.7.8.11; eat {} without warning
1748 static initializer_t *parse_scalar_initializer(type_t *type,
1749 bool must_be_constant)
1751 /* there might be extra {} hierarchies */
1755 warningf(HERE, "extra curly braces around scalar initializer");
1758 } while (next_if('{'));
1761 expression_t *expression = parse_assignment_expression();
1762 mark_vars_read(expression, NULL);
1763 if (must_be_constant && !is_initializer_constant(expression)) {
1764 errorf(&expression->base.source_position,
1765 "initialisation expression '%E' is not constant",
1769 initializer_t *initializer = initializer_from_expression(type, expression);
1771 if (initializer == NULL) {
1772 errorf(&expression->base.source_position,
1773 "expression '%E' (type '%T') doesn't match expected type '%T'",
1774 expression, expression->base.type, type);
1779 bool additional_warning_displayed = false;
1780 while (braces > 0) {
1782 if (token.type != '}') {
1783 if (!additional_warning_displayed && warning.other) {
1784 warningf(HERE, "additional elements in scalar initializer");
1785 additional_warning_displayed = true;
1796 * An entry in the type path.
1798 typedef struct type_path_entry_t type_path_entry_t;
1799 struct type_path_entry_t {
1800 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1802 size_t index; /**< For array types: the current index. */
1803 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1808 * A type path expression a position inside compound or array types.
1810 typedef struct type_path_t type_path_t;
1811 struct type_path_t {
1812 type_path_entry_t *path; /**< An flexible array containing the current path. */
1813 type_t *top_type; /**< type of the element the path points */
1814 size_t max_index; /**< largest index in outermost array */
1818 * Prints a type path for debugging.
1820 static __attribute__((unused)) void debug_print_type_path(
1821 const type_path_t *path)
1823 size_t len = ARR_LEN(path->path);
1825 for (size_t i = 0; i < len; ++i) {
1826 const type_path_entry_t *entry = & path->path[i];
1828 type_t *type = skip_typeref(entry->type);
1829 if (is_type_compound(type)) {
1830 /* in gcc mode structs can have no members */
1831 if (entry->v.compound_entry == NULL) {
1835 fprintf(stderr, ".%s",
1836 entry->v.compound_entry->base.symbol->string);
1837 } else if (is_type_array(type)) {
1838 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1840 fprintf(stderr, "-INVALID-");
1843 if (path->top_type != NULL) {
1844 fprintf(stderr, " (");
1845 print_type(path->top_type);
1846 fprintf(stderr, ")");
1851 * Return the top type path entry, ie. in a path
1852 * (type).a.b returns the b.
1854 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1856 size_t len = ARR_LEN(path->path);
1858 return &path->path[len-1];
1862 * Enlarge the type path by an (empty) element.
1864 static type_path_entry_t *append_to_type_path(type_path_t *path)
1866 size_t len = ARR_LEN(path->path);
1867 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1869 type_path_entry_t *result = & path->path[len];
1870 memset(result, 0, sizeof(result[0]));
1875 * Descending into a sub-type. Enter the scope of the current top_type.
1877 static void descend_into_subtype(type_path_t *path)
1879 type_t *orig_top_type = path->top_type;
1880 type_t *top_type = skip_typeref(orig_top_type);
1882 type_path_entry_t *top = append_to_type_path(path);
1883 top->type = top_type;
1885 if (is_type_compound(top_type)) {
1886 compound_t *compound = top_type->compound.compound;
1887 entity_t *entry = compound->members.entities;
1889 if (entry != NULL) {
1890 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1891 top->v.compound_entry = &entry->declaration;
1892 path->top_type = entry->declaration.type;
1894 path->top_type = NULL;
1896 } else if (is_type_array(top_type)) {
1898 path->top_type = top_type->array.element_type;
1900 assert(!is_type_valid(top_type));
1905 * Pop an entry from the given type path, ie. returning from
1906 * (type).a.b to (type).a
1908 static void ascend_from_subtype(type_path_t *path)
1910 type_path_entry_t *top = get_type_path_top(path);
1912 path->top_type = top->type;
1914 size_t len = ARR_LEN(path->path);
1915 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1919 * Pop entries from the given type path until the given
1920 * path level is reached.
1922 static void ascend_to(type_path_t *path, size_t top_path_level)
1924 size_t len = ARR_LEN(path->path);
1926 while (len > top_path_level) {
1927 ascend_from_subtype(path);
1928 len = ARR_LEN(path->path);
1932 static bool walk_designator(type_path_t *path, const designator_t *designator,
1933 bool used_in_offsetof)
1935 for (; designator != NULL; designator = designator->next) {
1936 type_path_entry_t *top = get_type_path_top(path);
1937 type_t *orig_type = top->type;
1939 type_t *type = skip_typeref(orig_type);
1941 if (designator->symbol != NULL) {
1942 symbol_t *symbol = designator->symbol;
1943 if (!is_type_compound(type)) {
1944 if (is_type_valid(type)) {
1945 errorf(&designator->source_position,
1946 "'.%Y' designator used for non-compound type '%T'",
1950 top->type = type_error_type;
1951 top->v.compound_entry = NULL;
1952 orig_type = type_error_type;
1954 compound_t *compound = type->compound.compound;
1955 entity_t *iter = compound->members.entities;
1956 for (; iter != NULL; iter = iter->base.next) {
1957 if (iter->base.symbol == symbol) {
1962 errorf(&designator->source_position,
1963 "'%T' has no member named '%Y'", orig_type, symbol);
1966 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1967 if (used_in_offsetof) {
1968 type_t *real_type = skip_typeref(iter->declaration.type);
1969 if (real_type->kind == TYPE_BITFIELD) {
1970 errorf(&designator->source_position,
1971 "offsetof designator '%Y' must not specify bitfield",
1977 top->type = orig_type;
1978 top->v.compound_entry = &iter->declaration;
1979 orig_type = iter->declaration.type;
1982 expression_t *array_index = designator->array_index;
1983 assert(designator->array_index != NULL);
1985 if (!is_type_array(type)) {
1986 if (is_type_valid(type)) {
1987 errorf(&designator->source_position,
1988 "[%E] designator used for non-array type '%T'",
1989 array_index, orig_type);
1994 long index = fold_constant_to_int(array_index);
1995 if (!used_in_offsetof) {
1997 errorf(&designator->source_position,
1998 "array index [%E] must be positive", array_index);
1999 } else if (type->array.size_constant) {
2000 long array_size = type->array.size;
2001 if (index >= array_size) {
2002 errorf(&designator->source_position,
2003 "designator [%E] (%d) exceeds array size %d",
2004 array_index, index, array_size);
2009 top->type = orig_type;
2010 top->v.index = (size_t) index;
2011 orig_type = type->array.element_type;
2013 path->top_type = orig_type;
2015 if (designator->next != NULL) {
2016 descend_into_subtype(path);
2025 static void advance_current_object(type_path_t *path, size_t top_path_level)
2027 type_path_entry_t *top = get_type_path_top(path);
2029 type_t *type = skip_typeref(top->type);
2030 if (is_type_union(type)) {
2031 /* in unions only the first element is initialized */
2032 top->v.compound_entry = NULL;
2033 } else if (is_type_struct(type)) {
2034 declaration_t *entry = top->v.compound_entry;
2036 entity_t *next_entity = entry->base.next;
2037 if (next_entity != NULL) {
2038 assert(is_declaration(next_entity));
2039 entry = &next_entity->declaration;
2044 top->v.compound_entry = entry;
2045 if (entry != NULL) {
2046 path->top_type = entry->type;
2049 } else if (is_type_array(type)) {
2050 assert(is_type_array(type));
2054 if (!type->array.size_constant || top->v.index < type->array.size) {
2058 assert(!is_type_valid(type));
2062 /* we're past the last member of the current sub-aggregate, try if we
2063 * can ascend in the type hierarchy and continue with another subobject */
2064 size_t len = ARR_LEN(path->path);
2066 if (len > top_path_level) {
2067 ascend_from_subtype(path);
2068 advance_current_object(path, top_path_level);
2070 path->top_type = NULL;
2075 * skip any {...} blocks until a closing bracket is reached.
2077 static void skip_initializers(void)
2081 while (token.type != '}') {
2082 if (token.type == T_EOF)
2084 if (token.type == '{') {
2092 static initializer_t *create_empty_initializer(void)
2094 static initializer_t empty_initializer
2095 = { .list = { { INITIALIZER_LIST }, 0 } };
2096 return &empty_initializer;
2100 * Parse a part of an initialiser for a struct or union,
2102 static initializer_t *parse_sub_initializer(type_path_t *path,
2103 type_t *outer_type, size_t top_path_level,
2104 parse_initializer_env_t *env)
2106 if (token.type == '}') {
2107 /* empty initializer */
2108 return create_empty_initializer();
2111 type_t *orig_type = path->top_type;
2112 type_t *type = NULL;
2114 if (orig_type == NULL) {
2115 /* We are initializing an empty compound. */
2117 type = skip_typeref(orig_type);
2120 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2123 designator_t *designator = NULL;
2124 if (token.type == '.' || token.type == '[') {
2125 designator = parse_designation();
2126 goto finish_designator;
2127 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2128 /* GNU-style designator ("identifier: value") */
2129 designator = allocate_ast_zero(sizeof(designator[0]));
2130 designator->source_position = token.source_position;
2131 designator->symbol = token.symbol;
2136 /* reset path to toplevel, evaluate designator from there */
2137 ascend_to(path, top_path_level);
2138 if (!walk_designator(path, designator, false)) {
2139 /* can't continue after designation error */
2143 initializer_t *designator_initializer
2144 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2145 designator_initializer->designator.designator = designator;
2146 ARR_APP1(initializer_t*, initializers, designator_initializer);
2148 orig_type = path->top_type;
2149 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2154 if (token.type == '{') {
2155 if (type != NULL && is_type_scalar(type)) {
2156 sub = parse_scalar_initializer(type, env->must_be_constant);
2160 if (env->entity != NULL) {
2162 "extra brace group at end of initializer for '%Y'",
2163 env->entity->base.symbol);
2165 errorf(HERE, "extra brace group at end of initializer");
2168 descend_into_subtype(path);
2170 add_anchor_token('}');
2171 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2173 rem_anchor_token('}');
2176 ascend_from_subtype(path);
2177 expect('}', end_error);
2179 expect('}', end_error);
2180 goto error_parse_next;
2184 /* must be an expression */
2185 expression_t *expression = parse_assignment_expression();
2186 mark_vars_read(expression, NULL);
2188 if (env->must_be_constant && !is_initializer_constant(expression)) {
2189 errorf(&expression->base.source_position,
2190 "Initialisation expression '%E' is not constant",
2195 /* we are already outside, ... */
2196 if (outer_type == NULL)
2197 goto error_parse_next;
2198 type_t *const outer_type_skip = skip_typeref(outer_type);
2199 if (is_type_compound(outer_type_skip) &&
2200 !outer_type_skip->compound.compound->complete) {
2201 goto error_parse_next;
2206 /* handle { "string" } special case */
2207 if ((expression->kind == EXPR_STRING_LITERAL
2208 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2209 && outer_type != NULL) {
2210 sub = initializer_from_expression(outer_type, expression);
2213 if (token.type != '}' && warning.other) {
2214 warningf(HERE, "excessive elements in initializer for type '%T'",
2217 /* TODO: eat , ... */
2222 /* descend into subtypes until expression matches type */
2224 orig_type = path->top_type;
2225 type = skip_typeref(orig_type);
2227 sub = initializer_from_expression(orig_type, expression);
2231 if (!is_type_valid(type)) {
2234 if (is_type_scalar(type)) {
2235 errorf(&expression->base.source_position,
2236 "expression '%E' doesn't match expected type '%T'",
2237 expression, orig_type);
2241 descend_into_subtype(path);
2245 /* update largest index of top array */
2246 const type_path_entry_t *first = &path->path[0];
2247 type_t *first_type = first->type;
2248 first_type = skip_typeref(first_type);
2249 if (is_type_array(first_type)) {
2250 size_t index = first->v.index;
2251 if (index > path->max_index)
2252 path->max_index = index;
2256 /* append to initializers list */
2257 ARR_APP1(initializer_t*, initializers, sub);
2260 if (warning.other) {
2261 if (env->entity != NULL) {
2262 warningf(HERE, "excess elements in initializer for '%Y'",
2263 env->entity->base.symbol);
2265 warningf(HERE, "excess elements in initializer");
2271 if (token.type == '}') {
2274 expect(',', end_error);
2275 if (token.type == '}') {
2280 /* advance to the next declaration if we are not at the end */
2281 advance_current_object(path, top_path_level);
2282 orig_type = path->top_type;
2283 if (orig_type != NULL)
2284 type = skip_typeref(orig_type);
2290 size_t len = ARR_LEN(initializers);
2291 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2292 initializer_t *result = allocate_ast_zero(size);
2293 result->kind = INITIALIZER_LIST;
2294 result->list.len = len;
2295 memcpy(&result->list.initializers, initializers,
2296 len * sizeof(initializers[0]));
2298 DEL_ARR_F(initializers);
2299 ascend_to(path, top_path_level+1);
2304 skip_initializers();
2305 DEL_ARR_F(initializers);
2306 ascend_to(path, top_path_level+1);
2310 static expression_t *make_size_literal(size_t value)
2312 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2313 literal->base.type = type_size_t;
2316 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2317 literal->literal.value = make_string(buf);
2323 * Parses an initializer. Parsers either a compound literal
2324 * (env->declaration == NULL) or an initializer of a declaration.
2326 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2328 type_t *type = skip_typeref(env->type);
2329 size_t max_index = 0;
2330 initializer_t *result;
2332 if (is_type_scalar(type)) {
2333 result = parse_scalar_initializer(type, env->must_be_constant);
2334 } else if (token.type == '{') {
2338 memset(&path, 0, sizeof(path));
2339 path.top_type = env->type;
2340 path.path = NEW_ARR_F(type_path_entry_t, 0);
2342 descend_into_subtype(&path);
2344 add_anchor_token('}');
2345 result = parse_sub_initializer(&path, env->type, 1, env);
2346 rem_anchor_token('}');
2348 max_index = path.max_index;
2349 DEL_ARR_F(path.path);
2351 expect('}', end_error);
2353 /* parse_scalar_initializer() also works in this case: we simply
2354 * have an expression without {} around it */
2355 result = parse_scalar_initializer(type, env->must_be_constant);
2358 /* §6.7.8:22 array initializers for arrays with unknown size determine
2359 * the array type size */
2360 if (is_type_array(type) && type->array.size_expression == NULL
2361 && result != NULL) {
2363 switch (result->kind) {
2364 case INITIALIZER_LIST:
2365 assert(max_index != 0xdeadbeaf);
2366 size = max_index + 1;
2369 case INITIALIZER_STRING:
2370 size = result->string.string.size;
2373 case INITIALIZER_WIDE_STRING:
2374 size = result->wide_string.string.size;
2377 case INITIALIZER_DESIGNATOR:
2378 case INITIALIZER_VALUE:
2379 /* can happen for parse errors */
2384 internal_errorf(HERE, "invalid initializer type");
2387 type_t *new_type = duplicate_type(type);
2389 new_type->array.size_expression = make_size_literal(size);
2390 new_type->array.size_constant = true;
2391 new_type->array.has_implicit_size = true;
2392 new_type->array.size = size;
2393 env->type = new_type;
2401 static void append_entity(scope_t *scope, entity_t *entity)
2403 if (scope->last_entity != NULL) {
2404 scope->last_entity->base.next = entity;
2406 scope->entities = entity;
2408 entity->base.parent_entity = current_entity;
2409 scope->last_entity = entity;
2413 static compound_t *parse_compound_type_specifier(bool is_struct)
2415 eat(is_struct ? T_struct : T_union);
2417 symbol_t *symbol = NULL;
2418 compound_t *compound = NULL;
2419 attribute_t *attributes = NULL;
2421 if (token.type == T___attribute__) {
2422 attributes = parse_attributes(NULL);
2425 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2426 if (token.type == T_IDENTIFIER) {
2427 /* the compound has a name, check if we have seen it already */
2428 symbol = token.symbol;
2431 entity_t *entity = get_tag(symbol, kind);
2432 if (entity != NULL) {
2433 compound = &entity->compound;
2434 if (compound->base.parent_scope != current_scope &&
2435 (token.type == '{' || token.type == ';')) {
2436 /* we're in an inner scope and have a definition. Shadow
2437 * existing definition in outer scope */
2439 } else if (compound->complete && token.type == '{') {
2440 assert(symbol != NULL);
2441 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2442 is_struct ? "struct" : "union", symbol,
2443 &compound->base.source_position);
2444 /* clear members in the hope to avoid further errors */
2445 compound->members.entities = NULL;
2448 } else if (token.type != '{') {
2450 parse_error_expected("while parsing struct type specifier",
2451 T_IDENTIFIER, '{', NULL);
2453 parse_error_expected("while parsing union type specifier",
2454 T_IDENTIFIER, '{', NULL);
2460 if (compound == NULL) {
2461 entity_t *entity = allocate_entity_zero(kind);
2462 compound = &entity->compound;
2464 compound->alignment = 1;
2465 compound->base.namespc = NAMESPACE_TAG;
2466 compound->base.source_position = token.source_position;
2467 compound->base.symbol = symbol;
2468 compound->base.parent_scope = current_scope;
2469 if (symbol != NULL) {
2470 environment_push(entity);
2472 append_entity(current_scope, entity);
2475 if (token.type == '{') {
2476 parse_compound_type_entries(compound);
2478 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2479 if (symbol == NULL) {
2480 assert(anonymous_entity == NULL);
2481 anonymous_entity = (entity_t*)compound;
2485 if (attributes != NULL) {
2486 handle_entity_attributes(attributes, (entity_t*) compound);
2492 static void parse_enum_entries(type_t *const enum_type)
2496 if (token.type == '}') {
2497 errorf(HERE, "empty enum not allowed");
2502 add_anchor_token('}');
2504 if (token.type != T_IDENTIFIER) {
2505 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2507 rem_anchor_token('}');
2511 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2512 entity->enum_value.enum_type = enum_type;
2513 entity->base.symbol = token.symbol;
2514 entity->base.source_position = token.source_position;
2518 expression_t *value = parse_constant_expression();
2520 value = create_implicit_cast(value, enum_type);
2521 entity->enum_value.value = value;
2526 record_entity(entity, false);
2527 } while (next_if(',') && token.type != '}');
2528 rem_anchor_token('}');
2530 expect('}', end_error);
2536 static type_t *parse_enum_specifier(void)
2542 switch (token.type) {
2544 symbol = token.symbol;
2547 entity = get_tag(symbol, ENTITY_ENUM);
2548 if (entity != NULL) {
2549 if (entity->base.parent_scope != current_scope &&
2550 (token.type == '{' || token.type == ';')) {
2551 /* we're in an inner scope and have a definition. Shadow
2552 * existing definition in outer scope */
2554 } else if (entity->enume.complete && token.type == '{') {
2555 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2556 symbol, &entity->base.source_position);
2567 parse_error_expected("while parsing enum type specifier",
2568 T_IDENTIFIER, '{', NULL);
2572 if (entity == NULL) {
2573 entity = allocate_entity_zero(ENTITY_ENUM);
2574 entity->base.namespc = NAMESPACE_TAG;
2575 entity->base.source_position = token.source_position;
2576 entity->base.symbol = symbol;
2577 entity->base.parent_scope = current_scope;
2580 type_t *const type = allocate_type_zero(TYPE_ENUM);
2581 type->enumt.enume = &entity->enume;
2582 type->enumt.akind = ATOMIC_TYPE_INT;
2584 if (token.type == '{') {
2585 if (symbol != NULL) {
2586 environment_push(entity);
2588 append_entity(current_scope, entity);
2589 entity->enume.complete = true;
2591 parse_enum_entries(type);
2592 parse_attributes(NULL);
2594 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2595 if (symbol == NULL) {
2596 assert(anonymous_entity == NULL);
2597 anonymous_entity = entity;
2599 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2600 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2608 * if a symbol is a typedef to another type, return true
2610 static bool is_typedef_symbol(symbol_t *symbol)
2612 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2613 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2616 static type_t *parse_typeof(void)
2622 expect('(', end_error);
2623 add_anchor_token(')');
2625 expression_t *expression = NULL;
2627 bool old_type_prop = in_type_prop;
2628 bool old_gcc_extension = in_gcc_extension;
2629 in_type_prop = true;
2631 while (next_if(T___extension__)) {
2632 /* This can be a prefix to a typename or an expression. */
2633 in_gcc_extension = true;
2635 switch (token.type) {
2637 if (is_typedef_symbol(token.symbol)) {
2639 type = parse_typename();
2642 expression = parse_expression();
2643 type = revert_automatic_type_conversion(expression);
2647 in_type_prop = old_type_prop;
2648 in_gcc_extension = old_gcc_extension;
2650 rem_anchor_token(')');
2651 expect(')', end_error);
2653 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2654 typeof_type->typeoft.expression = expression;
2655 typeof_type->typeoft.typeof_type = type;
2662 typedef enum specifiers_t {
2663 SPECIFIER_SIGNED = 1 << 0,
2664 SPECIFIER_UNSIGNED = 1 << 1,
2665 SPECIFIER_LONG = 1 << 2,
2666 SPECIFIER_INT = 1 << 3,
2667 SPECIFIER_DOUBLE = 1 << 4,
2668 SPECIFIER_CHAR = 1 << 5,
2669 SPECIFIER_WCHAR_T = 1 << 6,
2670 SPECIFIER_SHORT = 1 << 7,
2671 SPECIFIER_LONG_LONG = 1 << 8,
2672 SPECIFIER_FLOAT = 1 << 9,
2673 SPECIFIER_BOOL = 1 << 10,
2674 SPECIFIER_VOID = 1 << 11,
2675 SPECIFIER_INT8 = 1 << 12,
2676 SPECIFIER_INT16 = 1 << 13,
2677 SPECIFIER_INT32 = 1 << 14,
2678 SPECIFIER_INT64 = 1 << 15,
2679 SPECIFIER_INT128 = 1 << 16,
2680 SPECIFIER_COMPLEX = 1 << 17,
2681 SPECIFIER_IMAGINARY = 1 << 18,
2684 static type_t *create_builtin_type(symbol_t *const symbol,
2685 type_t *const real_type)
2687 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2688 type->builtin.symbol = symbol;
2689 type->builtin.real_type = real_type;
2690 return identify_new_type(type);
2693 static type_t *get_typedef_type(symbol_t *symbol)
2695 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2696 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2699 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2700 type->typedeft.typedefe = &entity->typedefe;
2705 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2707 expect('(', end_error);
2709 attribute_property_argument_t *property
2710 = allocate_ast_zero(sizeof(*property));
2713 if (token.type != T_IDENTIFIER) {
2714 parse_error_expected("while parsing property declspec",
2715 T_IDENTIFIER, NULL);
2720 symbol_t *symbol = token.symbol;
2722 if (strcmp(symbol->string, "put") == 0) {
2724 } else if (strcmp(symbol->string, "get") == 0) {
2727 errorf(HERE, "expected put or get in property declspec");
2730 expect('=', end_error);
2731 if (token.type != T_IDENTIFIER) {
2732 parse_error_expected("while parsing property declspec",
2733 T_IDENTIFIER, NULL);
2737 property->put_symbol = token.symbol;
2739 property->get_symbol = token.symbol;
2742 } while (next_if(','));
2744 attribute->a.property = property;
2746 expect(')', end_error);
2752 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2754 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2755 if (next_if(T_restrict)) {
2756 kind = ATTRIBUTE_MS_RESTRICT;
2757 } else if (token.type == T_IDENTIFIER) {
2758 const char *name = token.symbol->string;
2760 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2762 const char *attribute_name = get_attribute_name(k);
2763 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2769 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2770 warningf(HERE, "unknown __declspec '%s' ignored", name);
2773 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2777 attribute_t *attribute = allocate_attribute_zero(kind);
2779 if (kind == ATTRIBUTE_MS_PROPERTY) {
2780 return parse_attribute_ms_property(attribute);
2783 /* parse arguments */
2785 attribute->a.arguments = parse_attribute_arguments();
2790 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2794 expect('(', end_error);
2799 add_anchor_token(')');
2801 attribute_t **anchor = &first;
2803 while (*anchor != NULL)
2804 anchor = &(*anchor)->next;
2806 attribute_t *attribute
2807 = parse_microsoft_extended_decl_modifier_single();
2808 if (attribute == NULL)
2811 *anchor = attribute;
2812 anchor = &attribute->next;
2813 } while (next_if(','));
2815 rem_anchor_token(')');
2816 expect(')', end_error);
2820 rem_anchor_token(')');
2824 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2826 entity_t *entity = allocate_entity_zero(kind);
2827 entity->base.source_position = *HERE;
2828 entity->base.symbol = symbol;
2829 if (is_declaration(entity)) {
2830 entity->declaration.type = type_error_type;
2831 entity->declaration.implicit = true;
2832 } else if (kind == ENTITY_TYPEDEF) {
2833 entity->typedefe.type = type_error_type;
2834 entity->typedefe.builtin = true;
2836 if (kind != ENTITY_COMPOUND_MEMBER)
2837 record_entity(entity, false);
2841 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2843 type_t *type = NULL;
2844 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2845 unsigned type_specifiers = 0;
2846 bool newtype = false;
2847 bool saw_error = false;
2848 bool old_gcc_extension = in_gcc_extension;
2850 specifiers->source_position = token.source_position;
2853 specifiers->attributes = parse_attributes(specifiers->attributes);
2855 switch (token.type) {
2857 #define MATCH_STORAGE_CLASS(token, class) \
2859 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2860 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2862 specifiers->storage_class = class; \
2863 if (specifiers->thread_local) \
2864 goto check_thread_storage_class; \
2868 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2869 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2870 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2871 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2872 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2875 specifiers->attributes
2876 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2880 if (specifiers->thread_local) {
2881 errorf(HERE, "duplicate '__thread'");
2883 specifiers->thread_local = true;
2884 check_thread_storage_class:
2885 switch (specifiers->storage_class) {
2886 case STORAGE_CLASS_EXTERN:
2887 case STORAGE_CLASS_NONE:
2888 case STORAGE_CLASS_STATIC:
2892 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2893 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2894 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2895 wrong_thread_storage_class:
2896 errorf(HERE, "'__thread' used with '%s'", wrong);
2903 /* type qualifiers */
2904 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2906 qualifiers |= qualifier; \
2910 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2911 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2912 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2913 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2914 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2915 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2916 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2917 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2919 case T___extension__:
2921 in_gcc_extension = true;
2924 /* type specifiers */
2925 #define MATCH_SPECIFIER(token, specifier, name) \
2927 if (type_specifiers & specifier) { \
2928 errorf(HERE, "multiple " name " type specifiers given"); \
2930 type_specifiers |= specifier; \
2935 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2936 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2937 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2938 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2939 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2940 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2941 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2942 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2943 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2944 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2945 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2946 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2947 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2948 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2949 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2950 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2951 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2952 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2956 specifiers->is_inline = true;
2960 case T__forceinline:
2962 specifiers->modifiers |= DM_FORCEINLINE;
2967 if (type_specifiers & SPECIFIER_LONG_LONG) {
2968 errorf(HERE, "multiple type specifiers given");
2969 } else if (type_specifiers & SPECIFIER_LONG) {
2970 type_specifiers |= SPECIFIER_LONG_LONG;
2972 type_specifiers |= SPECIFIER_LONG;
2977 #define CHECK_DOUBLE_TYPE() \
2978 if ( type != NULL) \
2979 errorf(HERE, "multiple data types in declaration specifiers");
2982 CHECK_DOUBLE_TYPE();
2983 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2985 type->compound.compound = parse_compound_type_specifier(true);
2988 CHECK_DOUBLE_TYPE();
2989 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2990 type->compound.compound = parse_compound_type_specifier(false);
2993 CHECK_DOUBLE_TYPE();
2994 type = parse_enum_specifier();
2997 CHECK_DOUBLE_TYPE();
2998 type = parse_typeof();
3000 case T___builtin_va_list:
3001 CHECK_DOUBLE_TYPE();
3002 type = duplicate_type(type_valist);
3006 case T_IDENTIFIER: {
3007 /* only parse identifier if we haven't found a type yet */
3008 if (type != NULL || type_specifiers != 0) {
3009 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3010 * declaration, so it doesn't generate errors about expecting '(' or
3012 switch (look_ahead(1)->type) {
3019 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3023 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3028 goto finish_specifiers;
3032 type_t *const typedef_type = get_typedef_type(token.symbol);
3033 if (typedef_type == NULL) {
3034 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3035 * declaration, so it doesn't generate 'implicit int' followed by more
3036 * errors later on. */
3037 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3043 errorf(HERE, "%K does not name a type", &token);
3046 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3048 type = allocate_type_zero(TYPE_TYPEDEF);
3049 type->typedeft.typedefe = &entity->typedefe;
3053 if (la1_type == '&' || la1_type == '*')
3054 goto finish_specifiers;
3059 goto finish_specifiers;
3064 type = typedef_type;
3068 /* function specifier */
3070 goto finish_specifiers;
3075 specifiers->attributes = parse_attributes(specifiers->attributes);
3077 in_gcc_extension = old_gcc_extension;
3079 if (type == NULL || (saw_error && type_specifiers != 0)) {
3080 atomic_type_kind_t atomic_type;
3082 /* match valid basic types */
3083 switch (type_specifiers) {
3084 case SPECIFIER_VOID:
3085 atomic_type = ATOMIC_TYPE_VOID;
3087 case SPECIFIER_WCHAR_T:
3088 atomic_type = ATOMIC_TYPE_WCHAR_T;
3090 case SPECIFIER_CHAR:
3091 atomic_type = ATOMIC_TYPE_CHAR;
3093 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3094 atomic_type = ATOMIC_TYPE_SCHAR;
3096 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3097 atomic_type = ATOMIC_TYPE_UCHAR;
3099 case SPECIFIER_SHORT:
3100 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3101 case SPECIFIER_SHORT | SPECIFIER_INT:
3102 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3103 atomic_type = ATOMIC_TYPE_SHORT;
3105 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3106 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3107 atomic_type = ATOMIC_TYPE_USHORT;
3110 case SPECIFIER_SIGNED:
3111 case SPECIFIER_SIGNED | SPECIFIER_INT:
3112 atomic_type = ATOMIC_TYPE_INT;
3114 case SPECIFIER_UNSIGNED:
3115 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3116 atomic_type = ATOMIC_TYPE_UINT;
3118 case SPECIFIER_LONG:
3119 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3120 case SPECIFIER_LONG | SPECIFIER_INT:
3121 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3122 atomic_type = ATOMIC_TYPE_LONG;
3124 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3125 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3126 atomic_type = ATOMIC_TYPE_ULONG;
3129 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3130 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3131 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3132 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3134 atomic_type = ATOMIC_TYPE_LONGLONG;
3135 goto warn_about_long_long;
3137 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3138 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3140 atomic_type = ATOMIC_TYPE_ULONGLONG;
3141 warn_about_long_long:
3142 if (warning.long_long) {
3143 warningf(&specifiers->source_position,
3144 "ISO C90 does not support 'long long'");
3148 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3149 atomic_type = unsigned_int8_type_kind;
3152 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3153 atomic_type = unsigned_int16_type_kind;
3156 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3157 atomic_type = unsigned_int32_type_kind;
3160 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3161 atomic_type = unsigned_int64_type_kind;
3164 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3165 atomic_type = unsigned_int128_type_kind;
3168 case SPECIFIER_INT8:
3169 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3170 atomic_type = int8_type_kind;
3173 case SPECIFIER_INT16:
3174 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3175 atomic_type = int16_type_kind;
3178 case SPECIFIER_INT32:
3179 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3180 atomic_type = int32_type_kind;
3183 case SPECIFIER_INT64:
3184 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3185 atomic_type = int64_type_kind;
3188 case SPECIFIER_INT128:
3189 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3190 atomic_type = int128_type_kind;
3193 case SPECIFIER_FLOAT:
3194 atomic_type = ATOMIC_TYPE_FLOAT;
3196 case SPECIFIER_DOUBLE:
3197 atomic_type = ATOMIC_TYPE_DOUBLE;
3199 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3200 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3202 case SPECIFIER_BOOL:
3203 atomic_type = ATOMIC_TYPE_BOOL;
3205 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3206 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3207 atomic_type = ATOMIC_TYPE_FLOAT;
3209 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3210 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3211 atomic_type = ATOMIC_TYPE_DOUBLE;
3213 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3214 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3215 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3218 /* invalid specifier combination, give an error message */
3219 if (type_specifiers == 0) {
3223 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3224 if (!(c_mode & _CXX) && !strict_mode) {
3225 if (warning.implicit_int) {
3226 warningf(HERE, "no type specifiers in declaration, using 'int'");
3228 atomic_type = ATOMIC_TYPE_INT;
3231 errorf(HERE, "no type specifiers given in declaration");
3233 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3234 (type_specifiers & SPECIFIER_UNSIGNED)) {
3235 errorf(HERE, "signed and unsigned specifiers given");
3236 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3237 errorf(HERE, "only integer types can be signed or unsigned");
3239 errorf(HERE, "multiple datatypes in declaration");
3244 if (type_specifiers & SPECIFIER_COMPLEX) {
3245 type = allocate_type_zero(TYPE_COMPLEX);
3246 type->complex.akind = atomic_type;
3247 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3248 type = allocate_type_zero(TYPE_IMAGINARY);
3249 type->imaginary.akind = atomic_type;
3251 type = allocate_type_zero(TYPE_ATOMIC);
3252 type->atomic.akind = atomic_type;
3255 } else if (type_specifiers != 0) {
3256 errorf(HERE, "multiple datatypes in declaration");
3259 /* FIXME: check type qualifiers here */
3260 type->base.qualifiers = qualifiers;
3263 type = identify_new_type(type);
3265 type = typehash_insert(type);
3268 if (specifiers->attributes != NULL)
3269 type = handle_type_attributes(specifiers->attributes, type);
3270 specifiers->type = type;
3274 specifiers->type = type_error_type;
3277 static type_qualifiers_t parse_type_qualifiers(void)
3279 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3282 switch (token.type) {
3283 /* type qualifiers */
3284 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3285 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3286 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3287 /* microsoft extended type modifiers */
3288 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3289 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3290 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3291 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3292 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3301 * Parses an K&R identifier list
3303 static void parse_identifier_list(scope_t *scope)
3306 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3307 entity->base.source_position = token.source_position;
3308 entity->base.namespc = NAMESPACE_NORMAL;
3309 entity->base.symbol = token.symbol;
3310 /* a K&R parameter has no type, yet */
3314 append_entity(scope, entity);
3315 } while (next_if(',') && token.type == T_IDENTIFIER);
3318 static entity_t *parse_parameter(void)
3320 declaration_specifiers_t specifiers;
3321 memset(&specifiers, 0, sizeof(specifiers));
3323 parse_declaration_specifiers(&specifiers);
3325 entity_t *entity = parse_declarator(&specifiers,
3326 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3327 anonymous_entity = NULL;
3331 static void semantic_parameter_incomplete(const entity_t *entity)
3333 assert(entity->kind == ENTITY_PARAMETER);
3335 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3336 * list in a function declarator that is part of a
3337 * definition of that function shall not have
3338 * incomplete type. */
3339 type_t *type = skip_typeref(entity->declaration.type);
3340 if (is_type_incomplete(type)) {
3341 errorf(&entity->base.source_position,
3342 "parameter '%#T' has incomplete type",
3343 entity->declaration.type, entity->base.symbol);
3347 static bool has_parameters(void)
3349 /* func(void) is not a parameter */
3350 if (token.type == T_IDENTIFIER) {
3351 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3354 if (entity->kind != ENTITY_TYPEDEF)
3356 if (skip_typeref(entity->typedefe.type) != type_void)
3358 } else if (token.type != T_void) {
3361 if (look_ahead(1)->type != ')')
3368 * Parses function type parameters (and optionally creates variable_t entities
3369 * for them in a scope)
3371 static void parse_parameters(function_type_t *type, scope_t *scope)
3374 add_anchor_token(')');
3375 int saved_comma_state = save_and_reset_anchor_state(',');
3377 if (token.type == T_IDENTIFIER &&
3378 !is_typedef_symbol(token.symbol)) {
3379 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3380 if (la1_type == ',' || la1_type == ')') {
3381 type->kr_style_parameters = true;
3382 parse_identifier_list(scope);
3383 goto parameters_finished;
3387 if (token.type == ')') {
3388 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3389 if (!(c_mode & _CXX))
3390 type->unspecified_parameters = true;
3391 goto parameters_finished;
3394 if (has_parameters()) {
3395 function_parameter_t **anchor = &type->parameters;
3397 switch (token.type) {
3400 type->variadic = true;
3401 goto parameters_finished;
3404 case T___extension__:
3407 entity_t *entity = parse_parameter();
3408 if (entity->kind == ENTITY_TYPEDEF) {
3409 errorf(&entity->base.source_position,
3410 "typedef not allowed as function parameter");
3413 assert(is_declaration(entity));
3415 semantic_parameter_incomplete(entity);
3417 function_parameter_t *const parameter =
3418 allocate_parameter(entity->declaration.type);
3420 if (scope != NULL) {
3421 append_entity(scope, entity);
3424 *anchor = parameter;
3425 anchor = ¶meter->next;
3430 goto parameters_finished;
3432 } while (next_if(','));
3436 parameters_finished:
3437 rem_anchor_token(')');
3438 expect(')', end_error);
3441 restore_anchor_state(',', saved_comma_state);
3444 typedef enum construct_type_kind_t {
3447 CONSTRUCT_REFERENCE,
3450 } construct_type_kind_t;
3452 typedef union construct_type_t construct_type_t;
3454 typedef struct construct_type_base_t {
3455 construct_type_kind_t kind;
3456 construct_type_t *next;
3457 } construct_type_base_t;
3459 typedef struct parsed_pointer_t {
3460 construct_type_base_t base;
3461 type_qualifiers_t type_qualifiers;
3462 variable_t *base_variable; /**< MS __based extension. */
3465 typedef struct parsed_reference_t {
3466 construct_type_base_t base;
3467 } parsed_reference_t;
3469 typedef struct construct_function_type_t {
3470 construct_type_base_t base;
3471 type_t *function_type;
3472 } construct_function_type_t;
3474 typedef struct parsed_array_t {
3475 construct_type_base_t base;
3476 type_qualifiers_t type_qualifiers;
3482 union construct_type_t {
3483 construct_type_kind_t kind;
3484 construct_type_base_t base;
3485 parsed_pointer_t pointer;
3486 parsed_reference_t reference;
3487 construct_function_type_t function;
3488 parsed_array_t array;
3491 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3493 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3494 memset(cons, 0, size);
3500 static construct_type_t *parse_pointer_declarator(void)
3504 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3505 cons->pointer.type_qualifiers = parse_type_qualifiers();
3506 //cons->pointer.base_variable = base_variable;
3511 /* ISO/IEC 14882:1998(E) §8.3.2 */
3512 static construct_type_t *parse_reference_declarator(void)
3516 if (!(c_mode & _CXX))
3517 errorf(HERE, "references are only available for C++");
3519 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3525 static construct_type_t *parse_array_declarator(void)
3528 add_anchor_token(']');
3530 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3531 parsed_array_t *const array = &cons->array;
3533 bool is_static = next_if(T_static);
3535 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3538 is_static = next_if(T_static);
3540 array->type_qualifiers = type_qualifiers;
3541 array->is_static = is_static;
3543 expression_t *size = NULL;
3544 if (token.type == '*' && look_ahead(1)->type == ']') {
3545 array->is_variable = true;
3547 } else if (token.type != ']') {
3548 size = parse_assignment_expression();
3550 /* §6.7.5.2:1 Array size must have integer type */
3551 type_t *const orig_type = size->base.type;
3552 type_t *const type = skip_typeref(orig_type);
3553 if (!is_type_integer(type) && is_type_valid(type)) {
3554 errorf(&size->base.source_position,
3555 "array size '%E' must have integer type but has type '%T'",
3560 mark_vars_read(size, NULL);
3563 if (is_static && size == NULL)
3564 errorf(HERE, "static array parameters require a size");
3566 rem_anchor_token(']');
3567 expect(']', end_error);
3574 static construct_type_t *parse_function_declarator(scope_t *scope)
3576 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3577 function_type_t *ftype = &type->function;
3579 ftype->linkage = current_linkage;
3580 ftype->calling_convention = CC_DEFAULT;
3582 parse_parameters(ftype, scope);
3584 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3585 cons->function.function_type = type;
3590 typedef struct parse_declarator_env_t {
3591 bool may_be_abstract : 1;
3592 bool must_be_abstract : 1;
3593 decl_modifiers_t modifiers;
3595 source_position_t source_position;
3597 attribute_t *attributes;
3598 } parse_declarator_env_t;
3601 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3603 /* construct a single linked list of construct_type_t's which describe
3604 * how to construct the final declarator type */
3605 construct_type_t *first = NULL;
3606 construct_type_t **anchor = &first;
3608 env->attributes = parse_attributes(env->attributes);
3611 construct_type_t *type;
3612 //variable_t *based = NULL; /* MS __based extension */
3613 switch (token.type) {
3615 type = parse_reference_declarator();
3619 panic("based not supported anymore");
3624 type = parse_pointer_declarator();
3628 goto ptr_operator_end;
3632 anchor = &type->base.next;
3634 /* TODO: find out if this is correct */
3635 env->attributes = parse_attributes(env->attributes);
3639 construct_type_t *inner_types = NULL;
3641 switch (token.type) {
3643 if (env->must_be_abstract) {
3644 errorf(HERE, "no identifier expected in typename");
3646 env->symbol = token.symbol;
3647 env->source_position = token.source_position;
3652 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3653 * interpreted as ``function with no parameter specification'', rather
3654 * than redundant parentheses around the omitted identifier. */
3655 if (look_ahead(1)->type != ')') {
3657 add_anchor_token(')');
3658 inner_types = parse_inner_declarator(env);
3659 if (inner_types != NULL) {
3660 /* All later declarators only modify the return type */
3661 env->must_be_abstract = true;
3663 rem_anchor_token(')');
3664 expect(')', end_error);
3665 } else if (!env->may_be_abstract) {
3666 errorf(HERE, "declarator must have a name");
3671 if (env->may_be_abstract)
3673 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3679 construct_type_t **const p = anchor;
3682 construct_type_t *type;
3683 switch (token.type) {
3685 scope_t *scope = NULL;
3686 if (!env->must_be_abstract) {
3687 scope = &env->parameters;
3690 type = parse_function_declarator(scope);
3694 type = parse_array_declarator();
3697 goto declarator_finished;
3700 /* insert in the middle of the list (at p) */
3701 type->base.next = *p;
3704 anchor = &type->base.next;
3707 declarator_finished:
3708 /* append inner_types at the end of the list, we don't to set anchor anymore
3709 * as it's not needed anymore */
3710 *anchor = inner_types;
3717 static type_t *construct_declarator_type(construct_type_t *construct_list,
3720 construct_type_t *iter = construct_list;
3721 for (; iter != NULL; iter = iter->base.next) {
3722 switch (iter->kind) {
3723 case CONSTRUCT_INVALID:
3725 case CONSTRUCT_FUNCTION: {
3726 construct_function_type_t *function = &iter->function;
3727 type_t *function_type = function->function_type;
3729 function_type->function.return_type = type;
3731 type_t *skipped_return_type = skip_typeref(type);
3733 if (is_type_function(skipped_return_type)) {
3734 errorf(HERE, "function returning function is not allowed");
3735 } else if (is_type_array(skipped_return_type)) {
3736 errorf(HERE, "function returning array is not allowed");
3738 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3740 "type qualifiers in return type of function type are meaningless");
3744 /* The function type was constructed earlier. Freeing it here will
3745 * destroy other types. */
3746 type = typehash_insert(function_type);
3750 case CONSTRUCT_POINTER: {
3751 if (is_type_reference(skip_typeref(type)))
3752 errorf(HERE, "cannot declare a pointer to reference");
3754 parsed_pointer_t *pointer = &iter->pointer;
3755 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3759 case CONSTRUCT_REFERENCE:
3760 if (is_type_reference(skip_typeref(type)))
3761 errorf(HERE, "cannot declare a reference to reference");
3763 type = make_reference_type(type);
3766 case CONSTRUCT_ARRAY: {
3767 if (is_type_reference(skip_typeref(type)))
3768 errorf(HERE, "cannot declare an array of references");
3770 parsed_array_t *array = &iter->array;
3771 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3773 expression_t *size_expression = array->size;
3774 if (size_expression != NULL) {
3776 = create_implicit_cast(size_expression, type_size_t);
3779 array_type->base.qualifiers = array->type_qualifiers;
3780 array_type->array.element_type = type;
3781 array_type->array.is_static = array->is_static;
3782 array_type->array.is_variable = array->is_variable;
3783 array_type->array.size_expression = size_expression;
3785 if (size_expression != NULL) {
3786 switch (is_constant_expression(size_expression)) {
3787 case EXPR_CLASS_CONSTANT: {
3788 long const size = fold_constant_to_int(size_expression);
3789 array_type->array.size = size;
3790 array_type->array.size_constant = true;
3791 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3792 * have a value greater than zero. */
3794 if (size < 0 || !GNU_MODE) {
3795 errorf(&size_expression->base.source_position,
3796 "size of array must be greater than zero");
3797 } else if (warning.other) {
3798 warningf(&size_expression->base.source_position,
3799 "zero length arrays are a GCC extension");
3805 case EXPR_CLASS_VARIABLE:
3806 array_type->array.is_vla = true;
3809 case EXPR_CLASS_ERROR:
3814 type_t *skipped_type = skip_typeref(type);
3816 if (is_type_incomplete(skipped_type)) {
3817 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3818 } else if (is_type_function(skipped_type)) {
3819 errorf(HERE, "array of functions is not allowed");
3821 type = identify_new_type(array_type);
3825 internal_errorf(HERE, "invalid type construction found");
3831 static type_t *automatic_type_conversion(type_t *orig_type);
3833 static type_t *semantic_parameter(const source_position_t *pos,
3835 const declaration_specifiers_t *specifiers,
3838 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3839 * shall be adjusted to ``qualified pointer to type'',
3841 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3842 * type'' shall be adjusted to ``pointer to function
3843 * returning type'', as in 6.3.2.1. */
3844 type = automatic_type_conversion(type);
3846 if (specifiers->is_inline && is_type_valid(type)) {
3847 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3850 /* §6.9.1:6 The declarations in the declaration list shall contain
3851 * no storage-class specifier other than register and no
3852 * initializations. */
3853 if (specifiers->thread_local || (
3854 specifiers->storage_class != STORAGE_CLASS_NONE &&
3855 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3857 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3860 /* delay test for incomplete type, because we might have (void)
3861 * which is legal but incomplete... */
3866 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3867 declarator_flags_t flags)
3869 parse_declarator_env_t env;
3870 memset(&env, 0, sizeof(env));
3871 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3873 construct_type_t *construct_type = parse_inner_declarator(&env);
3875 construct_declarator_type(construct_type, specifiers->type);
3876 type_t *type = skip_typeref(orig_type);
3878 if (construct_type != NULL) {
3879 obstack_free(&temp_obst, construct_type);
3882 attribute_t *attributes = parse_attributes(env.attributes);
3883 /* append (shared) specifier attribute behind attributes of this
3885 attribute_t **anchor = &attributes;
3886 while (*anchor != NULL)
3887 anchor = &(*anchor)->next;
3888 *anchor = specifiers->attributes;
3891 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3892 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3893 entity->base.symbol = env.symbol;
3894 entity->base.source_position = env.source_position;
3895 entity->typedefe.type = orig_type;
3897 if (anonymous_entity != NULL) {
3898 if (is_type_compound(type)) {
3899 assert(anonymous_entity->compound.alias == NULL);
3900 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3901 anonymous_entity->kind == ENTITY_UNION);
3902 anonymous_entity->compound.alias = entity;
3903 anonymous_entity = NULL;
3904 } else if (is_type_enum(type)) {
3905 assert(anonymous_entity->enume.alias == NULL);
3906 assert(anonymous_entity->kind == ENTITY_ENUM);
3907 anonymous_entity->enume.alias = entity;
3908 anonymous_entity = NULL;
3912 /* create a declaration type entity */
3913 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3914 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3916 if (env.symbol != NULL) {
3917 if (specifiers->is_inline && is_type_valid(type)) {
3918 errorf(&env.source_position,
3919 "compound member '%Y' declared 'inline'", env.symbol);
3922 if (specifiers->thread_local ||
3923 specifiers->storage_class != STORAGE_CLASS_NONE) {
3924 errorf(&env.source_position,
3925 "compound member '%Y' must have no storage class",
3929 } else if (flags & DECL_IS_PARAMETER) {
3930 orig_type = semantic_parameter(&env.source_position, orig_type,
3931 specifiers, env.symbol);
3933 entity = allocate_entity_zero(ENTITY_PARAMETER);
3934 } else if (is_type_function(type)) {
3935 entity = allocate_entity_zero(ENTITY_FUNCTION);
3937 entity->function.is_inline = specifiers->is_inline;
3938 entity->function.parameters = env.parameters;
3940 if (env.symbol != NULL) {
3941 /* this needs fixes for C++ */
3942 bool in_function_scope = current_function != NULL;
3944 if (specifiers->thread_local || (
3945 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3946 specifiers->storage_class != STORAGE_CLASS_NONE &&
3947 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3949 errorf(&env.source_position,
3950 "invalid storage class for function '%Y'", env.symbol);
3954 entity = allocate_entity_zero(ENTITY_VARIABLE);
3956 entity->variable.thread_local = specifiers->thread_local;
3958 if (env.symbol != NULL) {
3959 if (specifiers->is_inline && is_type_valid(type)) {
3960 errorf(&env.source_position,
3961 "variable '%Y' declared 'inline'", env.symbol);
3964 bool invalid_storage_class = false;
3965 if (current_scope == file_scope) {
3966 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3967 specifiers->storage_class != STORAGE_CLASS_NONE &&
3968 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3969 invalid_storage_class = true;
3972 if (specifiers->thread_local &&
3973 specifiers->storage_class == STORAGE_CLASS_NONE) {
3974 invalid_storage_class = true;
3977 if (invalid_storage_class) {
3978 errorf(&env.source_position,
3979 "invalid storage class for variable '%Y'", env.symbol);
3984 if (env.symbol != NULL) {
3985 entity->base.symbol = env.symbol;
3986 entity->base.source_position = env.source_position;
3988 entity->base.source_position = specifiers->source_position;
3990 entity->base.namespc = NAMESPACE_NORMAL;
3991 entity->declaration.type = orig_type;
3992 entity->declaration.alignment = get_type_alignment(orig_type);
3993 entity->declaration.modifiers = env.modifiers;
3994 entity->declaration.attributes = attributes;
3996 storage_class_t storage_class = specifiers->storage_class;
3997 entity->declaration.declared_storage_class = storage_class;
3999 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4000 storage_class = STORAGE_CLASS_AUTO;
4001 entity->declaration.storage_class = storage_class;
4004 if (attributes != NULL) {
4005 handle_entity_attributes(attributes, entity);
4011 static type_t *parse_abstract_declarator(type_t *base_type)
4013 parse_declarator_env_t env;
4014 memset(&env, 0, sizeof(env));
4015 env.may_be_abstract = true;
4016 env.must_be_abstract = true;
4018 construct_type_t *construct_type = parse_inner_declarator(&env);
4020 type_t *result = construct_declarator_type(construct_type, base_type);
4021 if (construct_type != NULL) {
4022 obstack_free(&temp_obst, construct_type);
4024 result = handle_type_attributes(env.attributes, result);
4030 * Check if the declaration of main is suspicious. main should be a
4031 * function with external linkage, returning int, taking either zero
4032 * arguments, two, or three arguments of appropriate types, ie.
4034 * int main([ int argc, char **argv [, char **env ] ]).
4036 * @param decl the declaration to check
4037 * @param type the function type of the declaration
4039 static void check_main(const entity_t *entity)
4041 const source_position_t *pos = &entity->base.source_position;
4042 if (entity->kind != ENTITY_FUNCTION) {
4043 warningf(pos, "'main' is not a function");
4047 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4048 warningf(pos, "'main' is normally a non-static function");
4051 type_t *type = skip_typeref(entity->declaration.type);
4052 assert(is_type_function(type));
4054 function_type_t *func_type = &type->function;
4055 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4056 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4057 func_type->return_type);
4059 const function_parameter_t *parm = func_type->parameters;
4061 type_t *const first_type = parm->type;
4062 if (!types_compatible(skip_typeref(first_type), type_int)) {
4064 "first argument of 'main' should be 'int', but is '%T'",
4069 type_t *const second_type = parm->type;
4070 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4071 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4075 type_t *const third_type = parm->type;
4076 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4077 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4081 goto warn_arg_count;
4085 warningf(pos, "'main' takes only zero, two or three arguments");
4091 * Check if a symbol is the equal to "main".
4093 static bool is_sym_main(const symbol_t *const sym)
4095 return strcmp(sym->string, "main") == 0;
4098 static void error_redefined_as_different_kind(const source_position_t *pos,
4099 const entity_t *old, entity_kind_t new_kind)
4101 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4102 get_entity_kind_name(old->kind), old->base.symbol,
4103 get_entity_kind_name(new_kind), &old->base.source_position);
4106 static bool is_error_entity(entity_t *const ent)
4108 if (is_declaration(ent)) {
4109 return is_type_valid(skip_typeref(ent->declaration.type));
4110 } else if (ent->kind == ENTITY_TYPEDEF) {
4111 return is_type_valid(skip_typeref(ent->typedefe.type));
4116 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4118 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4119 if (attributes_equal(tattr, attr))
4126 * test wether new_list contains any attributes not included in old_list
4128 static bool has_new_attributes(const attribute_t *old_list,
4129 const attribute_t *new_list)
4131 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4132 if (!contains_attribute(old_list, attr))
4139 * Merge in attributes from an attribute list (probably from a previous
4140 * declaration with the same name). Warning: destroys the old structure
4141 * of the attribute list - don't reuse attributes after this call.
4143 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4146 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4148 if (contains_attribute(decl->attributes, attr))
4151 /* move attribute to new declarations attributes list */
4152 attr->next = decl->attributes;
4153 decl->attributes = attr;
4158 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4159 * for various problems that occur for multiple definitions
4161 entity_t *record_entity(entity_t *entity, const bool is_definition)
4163 const symbol_t *const symbol = entity->base.symbol;
4164 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4165 const source_position_t *pos = &entity->base.source_position;
4167 /* can happen in error cases */
4171 entity_t *const previous_entity = get_entity(symbol, namespc);
4172 /* pushing the same entity twice will break the stack structure */
4173 assert(previous_entity != entity);
4175 if (entity->kind == ENTITY_FUNCTION) {
4176 type_t *const orig_type = entity->declaration.type;
4177 type_t *const type = skip_typeref(orig_type);
4179 assert(is_type_function(type));
4180 if (type->function.unspecified_parameters &&
4181 warning.strict_prototypes &&
4182 previous_entity == NULL) {
4183 warningf(pos, "function declaration '%#T' is not a prototype",
4187 if (warning.main && current_scope == file_scope
4188 && is_sym_main(symbol)) {
4193 if (is_declaration(entity) &&
4194 warning.nested_externs &&
4195 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4196 current_scope != file_scope) {
4197 warningf(pos, "nested extern declaration of '%#T'",
4198 entity->declaration.type, symbol);
4201 if (previous_entity != NULL) {
4202 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4203 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4204 assert(previous_entity->kind == ENTITY_PARAMETER);
4206 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4207 entity->declaration.type, symbol,
4208 previous_entity->declaration.type, symbol,
4209 &previous_entity->base.source_position);
4213 if (previous_entity->base.parent_scope == current_scope) {
4214 if (previous_entity->kind != entity->kind) {
4215 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4216 error_redefined_as_different_kind(pos, previous_entity,
4221 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4222 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4223 symbol, &previous_entity->base.source_position);
4226 if (previous_entity->kind == ENTITY_TYPEDEF) {
4227 /* TODO: C++ allows this for exactly the same type */
4228 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4229 symbol, &previous_entity->base.source_position);
4233 /* at this point we should have only VARIABLES or FUNCTIONS */
4234 assert(is_declaration(previous_entity) && is_declaration(entity));
4236 declaration_t *const prev_decl = &previous_entity->declaration;
4237 declaration_t *const decl = &entity->declaration;
4239 /* can happen for K&R style declarations */
4240 if (prev_decl->type == NULL &&
4241 previous_entity->kind == ENTITY_PARAMETER &&
4242 entity->kind == ENTITY_PARAMETER) {
4243 prev_decl->type = decl->type;
4244 prev_decl->storage_class = decl->storage_class;
4245 prev_decl->declared_storage_class = decl->declared_storage_class;
4246 prev_decl->modifiers = decl->modifiers;
4247 return previous_entity;
4250 type_t *const orig_type = decl->type;
4251 assert(orig_type != NULL);
4252 type_t *const type = skip_typeref(orig_type);
4253 type_t *const prev_type = skip_typeref(prev_decl->type);
4255 if (!types_compatible(type, prev_type)) {
4257 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4258 orig_type, symbol, prev_decl->type, symbol,
4259 &previous_entity->base.source_position);
4261 unsigned old_storage_class = prev_decl->storage_class;
4263 if (warning.redundant_decls &&
4266 !(prev_decl->modifiers & DM_USED) &&
4267 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4268 warningf(&previous_entity->base.source_position,
4269 "unnecessary static forward declaration for '%#T'",
4270 prev_decl->type, symbol);
4273 storage_class_t new_storage_class = decl->storage_class;
4275 /* pretend no storage class means extern for function
4276 * declarations (except if the previous declaration is neither
4277 * none nor extern) */
4278 if (entity->kind == ENTITY_FUNCTION) {
4279 /* the previous declaration could have unspecified parameters or
4280 * be a typedef, so use the new type */
4281 if (prev_type->function.unspecified_parameters || is_definition)
4282 prev_decl->type = type;
4284 switch (old_storage_class) {
4285 case STORAGE_CLASS_NONE:
4286 old_storage_class = STORAGE_CLASS_EXTERN;
4289 case STORAGE_CLASS_EXTERN:
4290 if (is_definition) {
4291 if (warning.missing_prototypes &&
4292 prev_type->function.unspecified_parameters &&
4293 !is_sym_main(symbol)) {
4294 warningf(pos, "no previous prototype for '%#T'",
4297 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4298 new_storage_class = STORAGE_CLASS_EXTERN;
4305 } else if (is_type_incomplete(prev_type)) {
4306 prev_decl->type = type;
4309 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4310 new_storage_class == STORAGE_CLASS_EXTERN) {
4312 warn_redundant_declaration: ;
4314 = has_new_attributes(prev_decl->attributes,
4316 if (has_new_attrs) {
4317 merge_in_attributes(decl, prev_decl->attributes);
4318 } else if (!is_definition &&
4319 warning.redundant_decls &&
4320 is_type_valid(prev_type) &&
4321 strcmp(previous_entity->base.source_position.input_name,
4322 "<builtin>") != 0) {
4324 "redundant declaration for '%Y' (declared %P)",
4325 symbol, &previous_entity->base.source_position);
4327 } else if (current_function == NULL) {
4328 if (old_storage_class != STORAGE_CLASS_STATIC &&
4329 new_storage_class == STORAGE_CLASS_STATIC) {
4331 "static declaration of '%Y' follows non-static declaration (declared %P)",
4332 symbol, &previous_entity->base.source_position);
4333 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4334 prev_decl->storage_class = STORAGE_CLASS_NONE;
4335 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4337 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4339 goto error_redeclaration;
4340 goto warn_redundant_declaration;
4342 } else if (is_type_valid(prev_type)) {
4343 if (old_storage_class == new_storage_class) {
4344 error_redeclaration:
4345 errorf(pos, "redeclaration of '%Y' (declared %P)",
4346 symbol, &previous_entity->base.source_position);
4349 "redeclaration of '%Y' with different linkage (declared %P)",
4350 symbol, &previous_entity->base.source_position);
4355 prev_decl->modifiers |= decl->modifiers;
4356 if (entity->kind == ENTITY_FUNCTION) {
4357 previous_entity->function.is_inline |= entity->function.is_inline;
4359 return previous_entity;
4362 if (warning.shadow) {
4363 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4364 get_entity_kind_name(entity->kind), symbol,
4365 get_entity_kind_name(previous_entity->kind),
4366 &previous_entity->base.source_position);
4370 if (entity->kind == ENTITY_FUNCTION) {
4371 if (is_definition &&
4372 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4373 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4374 warningf(pos, "no previous prototype for '%#T'",
4375 entity->declaration.type, symbol);
4376 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4377 warningf(pos, "no previous declaration for '%#T'",
4378 entity->declaration.type, symbol);
4381 } else if (warning.missing_declarations &&
4382 entity->kind == ENTITY_VARIABLE &&
4383 current_scope == file_scope) {
4384 declaration_t *declaration = &entity->declaration;
4385 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4386 warningf(pos, "no previous declaration for '%#T'",
4387 declaration->type, symbol);
4392 assert(entity->base.parent_scope == NULL);
4393 assert(current_scope != NULL);
4395 entity->base.parent_scope = current_scope;
4396 entity->base.namespc = NAMESPACE_NORMAL;
4397 environment_push(entity);
4398 append_entity(current_scope, entity);
4403 static void parser_error_multiple_definition(entity_t *entity,
4404 const source_position_t *source_position)
4406 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4407 entity->base.symbol, &entity->base.source_position);
4410 static bool is_declaration_specifier(const token_t *token,
4411 bool only_specifiers_qualifiers)
4413 switch (token->type) {
4418 return is_typedef_symbol(token->symbol);
4420 case T___extension__:
4422 return !only_specifiers_qualifiers;
4429 static void parse_init_declarator_rest(entity_t *entity)
4431 assert(is_declaration(entity));
4432 declaration_t *const declaration = &entity->declaration;
4436 type_t *orig_type = declaration->type;
4437 type_t *type = skip_typeref(orig_type);
4439 if (entity->kind == ENTITY_VARIABLE
4440 && entity->variable.initializer != NULL) {
4441 parser_error_multiple_definition(entity, HERE);
4444 bool must_be_constant = false;
4445 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4446 entity->base.parent_scope == file_scope) {
4447 must_be_constant = true;
4450 if (is_type_function(type)) {
4451 errorf(&entity->base.source_position,
4452 "function '%#T' is initialized like a variable",
4453 orig_type, entity->base.symbol);
4454 orig_type = type_error_type;
4457 parse_initializer_env_t env;
4458 env.type = orig_type;
4459 env.must_be_constant = must_be_constant;
4460 env.entity = entity;
4461 current_init_decl = entity;
4463 initializer_t *initializer = parse_initializer(&env);
4464 current_init_decl = NULL;
4466 if (entity->kind == ENTITY_VARIABLE) {
4467 /* §6.7.5:22 array initializers for arrays with unknown size
4468 * determine the array type size */
4469 declaration->type = env.type;
4470 entity->variable.initializer = initializer;
4474 /* parse rest of a declaration without any declarator */
4475 static void parse_anonymous_declaration_rest(
4476 const declaration_specifiers_t *specifiers)
4479 anonymous_entity = NULL;
4481 if (warning.other) {
4482 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4483 specifiers->thread_local) {
4484 warningf(&specifiers->source_position,
4485 "useless storage class in empty declaration");
4488 type_t *type = specifiers->type;
4489 switch (type->kind) {
4490 case TYPE_COMPOUND_STRUCT:
4491 case TYPE_COMPOUND_UNION: {
4492 if (type->compound.compound->base.symbol == NULL) {
4493 warningf(&specifiers->source_position,
4494 "unnamed struct/union that defines no instances");
4503 warningf(&specifiers->source_position, "empty declaration");
4509 static void check_variable_type_complete(entity_t *ent)
4511 if (ent->kind != ENTITY_VARIABLE)
4514 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4515 * type for the object shall be complete [...] */
4516 declaration_t *decl = &ent->declaration;
4517 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4518 decl->storage_class == STORAGE_CLASS_STATIC)
4521 type_t *const orig_type = decl->type;
4522 type_t *const type = skip_typeref(orig_type);
4523 if (!is_type_incomplete(type))
4526 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4527 * are given length one. */
4528 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4529 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4533 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4534 orig_type, ent->base.symbol);
4538 static void parse_declaration_rest(entity_t *ndeclaration,
4539 const declaration_specifiers_t *specifiers,
4540 parsed_declaration_func finished_declaration,
4541 declarator_flags_t flags)
4543 add_anchor_token(';');
4544 add_anchor_token(',');
4546 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4548 if (token.type == '=') {
4549 parse_init_declarator_rest(entity);
4550 } else if (entity->kind == ENTITY_VARIABLE) {
4551 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4552 * [...] where the extern specifier is explicitly used. */
4553 declaration_t *decl = &entity->declaration;
4554 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4555 type_t *type = decl->type;
4556 if (is_type_reference(skip_typeref(type))) {
4557 errorf(&entity->base.source_position,
4558 "reference '%#T' must be initialized",
4559 type, entity->base.symbol);
4564 check_variable_type_complete(entity);
4569 add_anchor_token('=');
4570 ndeclaration = parse_declarator(specifiers, flags);
4571 rem_anchor_token('=');
4573 expect(';', end_error);
4576 anonymous_entity = NULL;
4577 rem_anchor_token(';');
4578 rem_anchor_token(',');
4581 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4583 symbol_t *symbol = entity->base.symbol;
4584 if (symbol == NULL) {
4585 errorf(HERE, "anonymous declaration not valid as function parameter");
4589 assert(entity->base.namespc == NAMESPACE_NORMAL);
4590 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4591 if (previous_entity == NULL
4592 || previous_entity->base.parent_scope != current_scope) {
4593 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4598 if (is_definition) {
4599 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4602 return record_entity(entity, false);
4605 static void parse_declaration(parsed_declaration_func finished_declaration,
4606 declarator_flags_t flags)
4608 declaration_specifiers_t specifiers;
4609 memset(&specifiers, 0, sizeof(specifiers));
4611 add_anchor_token(';');
4612 parse_declaration_specifiers(&specifiers);
4613 rem_anchor_token(';');
4615 if (token.type == ';') {
4616 parse_anonymous_declaration_rest(&specifiers);
4618 entity_t *entity = parse_declarator(&specifiers, flags);
4619 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4624 static type_t *get_default_promoted_type(type_t *orig_type)
4626 type_t *result = orig_type;
4628 type_t *type = skip_typeref(orig_type);
4629 if (is_type_integer(type)) {
4630 result = promote_integer(type);
4631 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4632 result = type_double;
4638 static void parse_kr_declaration_list(entity_t *entity)
4640 if (entity->kind != ENTITY_FUNCTION)
4643 type_t *type = skip_typeref(entity->declaration.type);
4644 assert(is_type_function(type));
4645 if (!type->function.kr_style_parameters)
4648 add_anchor_token('{');
4650 /* push function parameters */
4651 size_t const top = environment_top();
4652 scope_t *old_scope = scope_push(&entity->function.parameters);
4654 entity_t *parameter = entity->function.parameters.entities;
4655 for ( ; parameter != NULL; parameter = parameter->base.next) {
4656 assert(parameter->base.parent_scope == NULL);
4657 parameter->base.parent_scope = current_scope;
4658 environment_push(parameter);
4661 /* parse declaration list */
4663 switch (token.type) {
4665 case T___extension__:
4666 /* This covers symbols, which are no type, too, and results in
4667 * better error messages. The typical cases are misspelled type
4668 * names and missing includes. */
4670 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4678 /* pop function parameters */
4679 assert(current_scope == &entity->function.parameters);
4680 scope_pop(old_scope);
4681 environment_pop_to(top);
4683 /* update function type */
4684 type_t *new_type = duplicate_type(type);
4686 function_parameter_t *parameters = NULL;
4687 function_parameter_t **anchor = ¶meters;
4689 /* did we have an earlier prototype? */
4690 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4691 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4694 function_parameter_t *proto_parameter = NULL;
4695 if (proto_type != NULL) {
4696 type_t *proto_type_type = proto_type->declaration.type;
4697 proto_parameter = proto_type_type->function.parameters;
4698 /* If a K&R function definition has a variadic prototype earlier, then
4699 * make the function definition variadic, too. This should conform to
4700 * §6.7.5.3:15 and §6.9.1:8. */
4701 new_type->function.variadic = proto_type_type->function.variadic;
4703 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4705 new_type->function.unspecified_parameters = true;
4708 bool need_incompatible_warning = false;
4709 parameter = entity->function.parameters.entities;
4710 for (; parameter != NULL; parameter = parameter->base.next,
4712 proto_parameter == NULL ? NULL : proto_parameter->next) {
4713 if (parameter->kind != ENTITY_PARAMETER)
4716 type_t *parameter_type = parameter->declaration.type;
4717 if (parameter_type == NULL) {
4719 errorf(HERE, "no type specified for function parameter '%Y'",
4720 parameter->base.symbol);
4721 parameter_type = type_error_type;
4723 if (warning.implicit_int) {
4724 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4725 parameter->base.symbol);
4727 parameter_type = type_int;
4729 parameter->declaration.type = parameter_type;
4732 semantic_parameter_incomplete(parameter);
4734 /* we need the default promoted types for the function type */
4735 type_t *not_promoted = parameter_type;
4736 parameter_type = get_default_promoted_type(parameter_type);
4738 /* gcc special: if the type of the prototype matches the unpromoted
4739 * type don't promote */
4740 if (!strict_mode && proto_parameter != NULL) {
4741 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4742 type_t *promo_skip = skip_typeref(parameter_type);
4743 type_t *param_skip = skip_typeref(not_promoted);
4744 if (!types_compatible(proto_p_type, promo_skip)
4745 && types_compatible(proto_p_type, param_skip)) {
4747 need_incompatible_warning = true;
4748 parameter_type = not_promoted;
4751 function_parameter_t *const parameter
4752 = allocate_parameter(parameter_type);
4754 *anchor = parameter;
4755 anchor = ¶meter->next;
4758 new_type->function.parameters = parameters;
4759 new_type = identify_new_type(new_type);
4761 if (warning.other && need_incompatible_warning) {
4762 type_t *proto_type_type = proto_type->declaration.type;
4764 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4765 proto_type_type, proto_type->base.symbol,
4766 new_type, entity->base.symbol,
4767 &proto_type->base.source_position);
4770 entity->declaration.type = new_type;
4772 rem_anchor_token('{');
4775 static bool first_err = true;
4778 * When called with first_err set, prints the name of the current function,
4781 static void print_in_function(void)
4785 diagnosticf("%s: In function '%Y':\n",
4786 current_function->base.base.source_position.input_name,
4787 current_function->base.base.symbol);
4792 * Check if all labels are defined in the current function.
4793 * Check if all labels are used in the current function.
4795 static void check_labels(void)
4797 for (const goto_statement_t *goto_statement = goto_first;
4798 goto_statement != NULL;
4799 goto_statement = goto_statement->next) {
4800 /* skip computed gotos */
4801 if (goto_statement->expression != NULL)
4804 label_t *label = goto_statement->label;
4807 if (label->base.source_position.input_name == NULL) {
4808 print_in_function();
4809 errorf(&goto_statement->base.source_position,
4810 "label '%Y' used but not defined", label->base.symbol);
4814 if (warning.unused_label) {
4815 for (const label_statement_t *label_statement = label_first;
4816 label_statement != NULL;
4817 label_statement = label_statement->next) {
4818 label_t *label = label_statement->label;
4820 if (! label->used) {
4821 print_in_function();
4822 warningf(&label_statement->base.source_position,
4823 "label '%Y' defined but not used", label->base.symbol);
4829 static void warn_unused_entity(entity_t *entity, entity_t *last)
4831 entity_t const *const end = last != NULL ? last->base.next : NULL;
4832 for (; entity != end; entity = entity->base.next) {
4833 if (!is_declaration(entity))
4836 declaration_t *declaration = &entity->declaration;
4837 if (declaration->implicit)
4840 if (!declaration->used) {
4841 print_in_function();
4842 const char *what = get_entity_kind_name(entity->kind);
4843 warningf(&entity->base.source_position, "%s '%Y' is unused",
4844 what, entity->base.symbol);
4845 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4846 print_in_function();
4847 const char *what = get_entity_kind_name(entity->kind);
4848 warningf(&entity->base.source_position, "%s '%Y' is never read",
4849 what, entity->base.symbol);
4854 static void check_unused_variables(statement_t *const stmt, void *const env)
4858 switch (stmt->kind) {
4859 case STATEMENT_DECLARATION: {
4860 declaration_statement_t const *const decls = &stmt->declaration;
4861 warn_unused_entity(decls->declarations_begin,
4862 decls->declarations_end);
4867 warn_unused_entity(stmt->fors.scope.entities, NULL);
4876 * Check declarations of current_function for unused entities.
4878 static void check_declarations(void)
4880 if (warning.unused_parameter) {
4881 const scope_t *scope = ¤t_function->parameters;
4883 /* do not issue unused warnings for main */
4884 if (!is_sym_main(current_function->base.base.symbol)) {
4885 warn_unused_entity(scope->entities, NULL);
4888 if (warning.unused_variable) {
4889 walk_statements(current_function->statement, check_unused_variables,
4894 static int determine_truth(expression_t const* const cond)
4897 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4898 fold_constant_to_bool(cond) ? 1 :
4902 static void check_reachable(statement_t *);
4903 static bool reaches_end;
4905 static bool expression_returns(expression_t const *const expr)
4907 switch (expr->kind) {
4909 expression_t const *const func = expr->call.function;
4910 if (func->kind == EXPR_REFERENCE) {
4911 entity_t *entity = func->reference.entity;
4912 if (entity->kind == ENTITY_FUNCTION
4913 && entity->declaration.modifiers & DM_NORETURN)
4917 if (!expression_returns(func))
4920 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4921 if (!expression_returns(arg->expression))
4928 case EXPR_REFERENCE:
4929 case EXPR_REFERENCE_ENUM_VALUE:
4931 case EXPR_STRING_LITERAL:
4932 case EXPR_WIDE_STRING_LITERAL:
4933 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4934 case EXPR_LABEL_ADDRESS:
4935 case EXPR_CLASSIFY_TYPE:
4936 case EXPR_SIZEOF: // TODO handle obscure VLA case
4939 case EXPR_BUILTIN_CONSTANT_P:
4940 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4945 case EXPR_STATEMENT: {
4946 bool old_reaches_end = reaches_end;
4947 reaches_end = false;
4948 check_reachable(expr->statement.statement);
4949 bool returns = reaches_end;
4950 reaches_end = old_reaches_end;
4954 case EXPR_CONDITIONAL:
4955 // TODO handle constant expression
4957 if (!expression_returns(expr->conditional.condition))
4960 if (expr->conditional.true_expression != NULL
4961 && expression_returns(expr->conditional.true_expression))
4964 return expression_returns(expr->conditional.false_expression);
4967 return expression_returns(expr->select.compound);
4969 case EXPR_ARRAY_ACCESS:
4971 expression_returns(expr->array_access.array_ref) &&
4972 expression_returns(expr->array_access.index);
4975 return expression_returns(expr->va_starte.ap);
4978 return expression_returns(expr->va_arge.ap);
4981 return expression_returns(expr->va_copye.src);
4983 EXPR_UNARY_CASES_MANDATORY
4984 return expression_returns(expr->unary.value);
4986 case EXPR_UNARY_THROW:
4990 // TODO handle constant lhs of && and ||
4992 expression_returns(expr->binary.left) &&
4993 expression_returns(expr->binary.right);
4999 panic("unhandled expression");
5002 static bool initializer_returns(initializer_t const *const init)
5004 switch (init->kind) {
5005 case INITIALIZER_VALUE:
5006 return expression_returns(init->value.value);
5008 case INITIALIZER_LIST: {
5009 initializer_t * const* i = init->list.initializers;
5010 initializer_t * const* const end = i + init->list.len;
5011 bool returns = true;
5012 for (; i != end; ++i) {
5013 if (!initializer_returns(*i))
5019 case INITIALIZER_STRING:
5020 case INITIALIZER_WIDE_STRING:
5021 case INITIALIZER_DESIGNATOR: // designators have no payload
5024 panic("unhandled initializer");
5027 static bool noreturn_candidate;
5029 static void check_reachable(statement_t *const stmt)
5031 if (stmt->base.reachable)
5033 if (stmt->kind != STATEMENT_DO_WHILE)
5034 stmt->base.reachable = true;
5036 statement_t *last = stmt;
5038 switch (stmt->kind) {
5039 case STATEMENT_INVALID:
5040 case STATEMENT_EMPTY:
5042 next = stmt->base.next;
5045 case STATEMENT_DECLARATION: {
5046 declaration_statement_t const *const decl = &stmt->declaration;
5047 entity_t const * ent = decl->declarations_begin;
5048 entity_t const *const last = decl->declarations_end;
5050 for (;; ent = ent->base.next) {
5051 if (ent->kind == ENTITY_VARIABLE &&
5052 ent->variable.initializer != NULL &&
5053 !initializer_returns(ent->variable.initializer)) {
5060 next = stmt->base.next;
5064 case STATEMENT_COMPOUND:
5065 next = stmt->compound.statements;
5067 next = stmt->base.next;
5070 case STATEMENT_RETURN: {
5071 expression_t const *const val = stmt->returns.value;
5072 if (val == NULL || expression_returns(val))
5073 noreturn_candidate = false;
5077 case STATEMENT_IF: {
5078 if_statement_t const *const ifs = &stmt->ifs;
5079 expression_t const *const cond = ifs->condition;
5081 if (!expression_returns(cond))
5084 int const val = determine_truth(cond);
5087 check_reachable(ifs->true_statement);
5092 if (ifs->false_statement != NULL) {
5093 check_reachable(ifs->false_statement);
5097 next = stmt->base.next;
5101 case STATEMENT_SWITCH: {
5102 switch_statement_t const *const switchs = &stmt->switchs;
5103 expression_t const *const expr = switchs->expression;
5105 if (!expression_returns(expr))
5108 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5109 long const val = fold_constant_to_int(expr);
5110 case_label_statement_t * defaults = NULL;
5111 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5112 if (i->expression == NULL) {
5117 if (i->first_case <= val && val <= i->last_case) {
5118 check_reachable((statement_t*)i);
5123 if (defaults != NULL) {
5124 check_reachable((statement_t*)defaults);
5128 bool has_default = false;
5129 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5130 if (i->expression == NULL)
5133 check_reachable((statement_t*)i);
5140 next = stmt->base.next;
5144 case STATEMENT_EXPRESSION: {
5145 /* Check for noreturn function call */
5146 expression_t const *const expr = stmt->expression.expression;
5147 if (!expression_returns(expr))
5150 next = stmt->base.next;
5154 case STATEMENT_CONTINUE:
5155 for (statement_t *parent = stmt;;) {
5156 parent = parent->base.parent;
5157 if (parent == NULL) /* continue not within loop */
5161 switch (parent->kind) {
5162 case STATEMENT_WHILE: goto continue_while;
5163 case STATEMENT_DO_WHILE: goto continue_do_while;
5164 case STATEMENT_FOR: goto continue_for;
5170 case STATEMENT_BREAK:
5171 for (statement_t *parent = stmt;;) {
5172 parent = parent->base.parent;
5173 if (parent == NULL) /* break not within loop/switch */
5176 switch (parent->kind) {
5177 case STATEMENT_SWITCH:
5178 case STATEMENT_WHILE:
5179 case STATEMENT_DO_WHILE:
5182 next = parent->base.next;
5183 goto found_break_parent;
5191 case STATEMENT_GOTO:
5192 if (stmt->gotos.expression) {
5193 if (!expression_returns(stmt->gotos.expression))
5196 statement_t *parent = stmt->base.parent;
5197 if (parent == NULL) /* top level goto */
5201 next = stmt->gotos.label->statement;
5202 if (next == NULL) /* missing label */
5207 case STATEMENT_LABEL:
5208 next = stmt->label.statement;
5211 case STATEMENT_CASE_LABEL:
5212 next = stmt->case_label.statement;
5215 case STATEMENT_WHILE: {
5216 while_statement_t const *const whiles = &stmt->whiles;
5217 expression_t const *const cond = whiles->condition;
5219 if (!expression_returns(cond))
5222 int const val = determine_truth(cond);
5225 check_reachable(whiles->body);
5230 next = stmt->base.next;
5234 case STATEMENT_DO_WHILE:
5235 next = stmt->do_while.body;
5238 case STATEMENT_FOR: {
5239 for_statement_t *const fors = &stmt->fors;
5241 if (fors->condition_reachable)
5243 fors->condition_reachable = true;
5245 expression_t const *const cond = fors->condition;
5250 } else if (expression_returns(cond)) {
5251 val = determine_truth(cond);
5257 check_reachable(fors->body);
5262 next = stmt->base.next;
5266 case STATEMENT_MS_TRY: {
5267 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5268 check_reachable(ms_try->try_statement);
5269 next = ms_try->final_statement;
5273 case STATEMENT_LEAVE: {
5274 statement_t *parent = stmt;
5276 parent = parent->base.parent;
5277 if (parent == NULL) /* __leave not within __try */
5280 if (parent->kind == STATEMENT_MS_TRY) {
5282 next = parent->ms_try.final_statement;
5290 panic("invalid statement kind");
5293 while (next == NULL) {
5294 next = last->base.parent;
5296 noreturn_candidate = false;
5298 type_t *const type = skip_typeref(current_function->base.type);
5299 assert(is_type_function(type));
5300 type_t *const ret = skip_typeref(type->function.return_type);
5301 if (warning.return_type &&
5302 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5303 is_type_valid(ret) &&
5304 !is_sym_main(current_function->base.base.symbol)) {
5305 warningf(&stmt->base.source_position,
5306 "control reaches end of non-void function");
5311 switch (next->kind) {
5312 case STATEMENT_INVALID:
5313 case STATEMENT_EMPTY:
5314 case STATEMENT_DECLARATION:
5315 case STATEMENT_EXPRESSION:
5317 case STATEMENT_RETURN:
5318 case STATEMENT_CONTINUE:
5319 case STATEMENT_BREAK:
5320 case STATEMENT_GOTO:
5321 case STATEMENT_LEAVE:
5322 panic("invalid control flow in function");
5324 case STATEMENT_COMPOUND:
5325 if (next->compound.stmt_expr) {
5331 case STATEMENT_SWITCH:
5332 case STATEMENT_LABEL:
5333 case STATEMENT_CASE_LABEL:
5335 next = next->base.next;
5338 case STATEMENT_WHILE: {
5340 if (next->base.reachable)
5342 next->base.reachable = true;
5344 while_statement_t const *const whiles = &next->whiles;
5345 expression_t const *const cond = whiles->condition;
5347 if (!expression_returns(cond))
5350 int const val = determine_truth(cond);
5353 check_reachable(whiles->body);
5359 next = next->base.next;
5363 case STATEMENT_DO_WHILE: {
5365 if (next->base.reachable)
5367 next->base.reachable = true;
5369 do_while_statement_t const *const dw = &next->do_while;
5370 expression_t const *const cond = dw->condition;
5372 if (!expression_returns(cond))
5375 int const val = determine_truth(cond);
5378 check_reachable(dw->body);
5384 next = next->base.next;
5388 case STATEMENT_FOR: {
5390 for_statement_t *const fors = &next->fors;
5392 fors->step_reachable = true;
5394 if (fors->condition_reachable)
5396 fors->condition_reachable = true;
5398 expression_t const *const cond = fors->condition;
5403 } else if (expression_returns(cond)) {
5404 val = determine_truth(cond);
5410 check_reachable(fors->body);
5416 next = next->base.next;
5420 case STATEMENT_MS_TRY:
5422 next = next->ms_try.final_statement;
5427 check_reachable(next);
5430 static void check_unreachable(statement_t* const stmt, void *const env)
5434 switch (stmt->kind) {
5435 case STATEMENT_DO_WHILE:
5436 if (!stmt->base.reachable) {
5437 expression_t const *const cond = stmt->do_while.condition;
5438 if (determine_truth(cond) >= 0) {
5439 warningf(&cond->base.source_position,
5440 "condition of do-while-loop is unreachable");
5445 case STATEMENT_FOR: {
5446 for_statement_t const* const fors = &stmt->fors;
5448 // if init and step are unreachable, cond is unreachable, too
5449 if (!stmt->base.reachable && !fors->step_reachable) {
5450 warningf(&stmt->base.source_position, "statement is unreachable");
5452 if (!stmt->base.reachable && fors->initialisation != NULL) {
5453 warningf(&fors->initialisation->base.source_position,
5454 "initialisation of for-statement is unreachable");
5457 if (!fors->condition_reachable && fors->condition != NULL) {
5458 warningf(&fors->condition->base.source_position,
5459 "condition of for-statement is unreachable");
5462 if (!fors->step_reachable && fors->step != NULL) {
5463 warningf(&fors->step->base.source_position,
5464 "step of for-statement is unreachable");
5470 case STATEMENT_COMPOUND:
5471 if (stmt->compound.statements != NULL)
5473 goto warn_unreachable;
5475 case STATEMENT_DECLARATION: {
5476 /* Only warn if there is at least one declarator with an initializer.
5477 * This typically occurs in switch statements. */
5478 declaration_statement_t const *const decl = &stmt->declaration;
5479 entity_t const * ent = decl->declarations_begin;
5480 entity_t const *const last = decl->declarations_end;
5482 for (;; ent = ent->base.next) {
5483 if (ent->kind == ENTITY_VARIABLE &&
5484 ent->variable.initializer != NULL) {
5485 goto warn_unreachable;
5495 if (!stmt->base.reachable)
5496 warningf(&stmt->base.source_position, "statement is unreachable");
5501 static void parse_external_declaration(void)
5503 /* function-definitions and declarations both start with declaration
5505 declaration_specifiers_t specifiers;
5506 memset(&specifiers, 0, sizeof(specifiers));
5508 add_anchor_token(';');
5509 parse_declaration_specifiers(&specifiers);
5510 rem_anchor_token(';');
5512 /* must be a declaration */
5513 if (token.type == ';') {
5514 parse_anonymous_declaration_rest(&specifiers);
5518 add_anchor_token(',');
5519 add_anchor_token('=');
5520 add_anchor_token(';');
5521 add_anchor_token('{');
5523 /* declarator is common to both function-definitions and declarations */
5524 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5526 rem_anchor_token('{');
5527 rem_anchor_token(';');
5528 rem_anchor_token('=');
5529 rem_anchor_token(',');
5531 /* must be a declaration */
5532 switch (token.type) {
5536 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5541 /* must be a function definition */
5542 parse_kr_declaration_list(ndeclaration);
5544 if (token.type != '{') {
5545 parse_error_expected("while parsing function definition", '{', NULL);
5546 eat_until_matching_token(';');
5550 assert(is_declaration(ndeclaration));
5551 type_t *const orig_type = ndeclaration->declaration.type;
5552 type_t * type = skip_typeref(orig_type);
5554 if (!is_type_function(type)) {
5555 if (is_type_valid(type)) {
5556 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5557 type, ndeclaration->base.symbol);
5561 } else if (is_typeref(orig_type)) {
5563 errorf(&ndeclaration->base.source_position,
5564 "type of function definition '%#T' is a typedef",
5565 orig_type, ndeclaration->base.symbol);
5568 if (warning.aggregate_return &&
5569 is_type_compound(skip_typeref(type->function.return_type))) {
5570 warningf(HERE, "function '%Y' returns an aggregate",
5571 ndeclaration->base.symbol);
5573 if (warning.traditional && !type->function.unspecified_parameters) {
5574 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5575 ndeclaration->base.symbol);
5577 if (warning.old_style_definition && type->function.unspecified_parameters) {
5578 warningf(HERE, "old-style function definition '%Y'",
5579 ndeclaration->base.symbol);
5582 /* §6.7.5.3:14 a function definition with () means no
5583 * parameters (and not unspecified parameters) */
5584 if (type->function.unspecified_parameters &&
5585 type->function.parameters == NULL) {
5586 type_t *copy = duplicate_type(type);
5587 copy->function.unspecified_parameters = false;
5588 type = identify_new_type(copy);
5590 ndeclaration->declaration.type = type;
5593 entity_t *const entity = record_entity(ndeclaration, true);
5594 assert(entity->kind == ENTITY_FUNCTION);
5595 assert(ndeclaration->kind == ENTITY_FUNCTION);
5597 function_t *function = &entity->function;
5598 if (ndeclaration != entity) {
5599 function->parameters = ndeclaration->function.parameters;
5601 assert(is_declaration(entity));
5602 type = skip_typeref(entity->declaration.type);
5604 /* push function parameters and switch scope */
5605 size_t const top = environment_top();
5606 scope_t *old_scope = scope_push(&function->parameters);
5608 entity_t *parameter = function->parameters.entities;
5609 for (; parameter != NULL; parameter = parameter->base.next) {
5610 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5611 parameter->base.parent_scope = current_scope;
5613 assert(parameter->base.parent_scope == NULL
5614 || parameter->base.parent_scope == current_scope);
5615 parameter->base.parent_scope = current_scope;
5616 if (parameter->base.symbol == NULL) {
5617 errorf(¶meter->base.source_position, "parameter name omitted");
5620 environment_push(parameter);
5623 if (function->statement != NULL) {
5624 parser_error_multiple_definition(entity, HERE);
5627 /* parse function body */
5628 int label_stack_top = label_top();
5629 function_t *old_current_function = current_function;
5630 entity_t *old_current_entity = current_entity;
5631 current_function = function;
5632 current_entity = (entity_t*) function;
5633 current_parent = NULL;
5636 goto_anchor = &goto_first;
5638 label_anchor = &label_first;
5640 statement_t *const body = parse_compound_statement(false);
5641 function->statement = body;
5644 check_declarations();
5645 if (warning.return_type ||
5646 warning.unreachable_code ||
5647 (warning.missing_noreturn
5648 && !(function->base.modifiers & DM_NORETURN))) {
5649 noreturn_candidate = true;
5650 check_reachable(body);
5651 if (warning.unreachable_code)
5652 walk_statements(body, check_unreachable, NULL);
5653 if (warning.missing_noreturn &&
5654 noreturn_candidate &&
5655 !(function->base.modifiers & DM_NORETURN)) {
5656 warningf(&body->base.source_position,
5657 "function '%#T' is candidate for attribute 'noreturn'",
5658 type, entity->base.symbol);
5662 assert(current_parent == NULL);
5663 assert(current_function == function);
5664 assert(current_entity == (entity_t*) function);
5665 current_entity = old_current_entity;
5666 current_function = old_current_function;
5667 label_pop_to(label_stack_top);
5670 assert(current_scope == &function->parameters);
5671 scope_pop(old_scope);
5672 environment_pop_to(top);
5675 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5676 source_position_t *source_position,
5677 const symbol_t *symbol)
5679 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5681 type->bitfield.base_type = base_type;
5682 type->bitfield.size_expression = size;
5685 type_t *skipped_type = skip_typeref(base_type);
5686 if (!is_type_integer(skipped_type)) {
5687 errorf(HERE, "bitfield base type '%T' is not an integer type",
5691 bit_size = get_type_size(base_type) * 8;
5694 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5695 long v = fold_constant_to_int(size);
5696 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5699 errorf(source_position, "negative width in bit-field '%Y'",
5701 } else if (v == 0 && symbol != NULL) {
5702 errorf(source_position, "zero width for bit-field '%Y'",
5704 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5705 errorf(source_position, "width of '%Y' exceeds its type",
5708 type->bitfield.bit_size = v;
5715 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5717 entity_t *iter = compound->members.entities;
5718 for (; iter != NULL; iter = iter->base.next) {
5719 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5722 if (iter->base.symbol == symbol) {
5724 } else if (iter->base.symbol == NULL) {
5725 /* search in anonymous structs and unions */
5726 type_t *type = skip_typeref(iter->declaration.type);
5727 if (is_type_compound(type)) {
5728 if (find_compound_entry(type->compound.compound, symbol)
5739 static void check_deprecated(const source_position_t *source_position,
5740 const entity_t *entity)
5742 if (!warning.deprecated_declarations)
5744 if (!is_declaration(entity))
5746 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5749 char const *const prefix = get_entity_kind_name(entity->kind);
5750 const char *deprecated_string
5751 = get_deprecated_string(entity->declaration.attributes);
5752 if (deprecated_string != NULL) {
5753 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5754 prefix, entity->base.symbol, &entity->base.source_position,
5757 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5758 entity->base.symbol, &entity->base.source_position);
5763 static expression_t *create_select(const source_position_t *pos,
5765 type_qualifiers_t qualifiers,
5768 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5770 check_deprecated(pos, entry);
5772 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5773 select->select.compound = addr;
5774 select->select.compound_entry = entry;
5776 type_t *entry_type = entry->declaration.type;
5777 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5779 /* we always do the auto-type conversions; the & and sizeof parser contains
5780 * code to revert this! */
5781 select->base.type = automatic_type_conversion(res_type);
5782 if (res_type->kind == TYPE_BITFIELD) {
5783 select->base.type = res_type->bitfield.base_type;
5790 * Find entry with symbol in compound. Search anonymous structs and unions and
5791 * creates implicit select expressions for them.
5792 * Returns the adress for the innermost compound.
5794 static expression_t *find_create_select(const source_position_t *pos,
5796 type_qualifiers_t qualifiers,
5797 compound_t *compound, symbol_t *symbol)
5799 entity_t *iter = compound->members.entities;
5800 for (; iter != NULL; iter = iter->base.next) {
5801 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5804 symbol_t *iter_symbol = iter->base.symbol;
5805 if (iter_symbol == NULL) {
5806 type_t *type = iter->declaration.type;
5807 if (type->kind != TYPE_COMPOUND_STRUCT
5808 && type->kind != TYPE_COMPOUND_UNION)
5811 compound_t *sub_compound = type->compound.compound;
5813 if (find_compound_entry(sub_compound, symbol) == NULL)
5816 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5817 sub_addr->base.source_position = *pos;
5818 sub_addr->select.implicit = true;
5819 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5823 if (iter_symbol == symbol) {
5824 return create_select(pos, addr, qualifiers, iter);
5831 static void parse_compound_declarators(compound_t *compound,
5832 const declaration_specifiers_t *specifiers)
5837 if (token.type == ':') {
5838 source_position_t source_position = *HERE;
5841 type_t *base_type = specifiers->type;
5842 expression_t *size = parse_constant_expression();
5844 type_t *type = make_bitfield_type(base_type, size,
5845 &source_position, NULL);
5847 attribute_t *attributes = parse_attributes(NULL);
5848 attribute_t **anchor = &attributes;
5849 while (*anchor != NULL)
5850 anchor = &(*anchor)->next;
5851 *anchor = specifiers->attributes;
5853 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5854 entity->base.namespc = NAMESPACE_NORMAL;
5855 entity->base.source_position = source_position;
5856 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5857 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5858 entity->declaration.type = type;
5859 entity->declaration.attributes = attributes;
5861 if (attributes != NULL) {
5862 handle_entity_attributes(attributes, entity);
5864 append_entity(&compound->members, entity);
5866 entity = parse_declarator(specifiers,
5867 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5868 if (entity->kind == ENTITY_TYPEDEF) {
5869 errorf(&entity->base.source_position,
5870 "typedef not allowed as compound member");
5872 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5874 /* make sure we don't define a symbol multiple times */
5875 symbol_t *symbol = entity->base.symbol;
5876 if (symbol != NULL) {
5877 entity_t *prev = find_compound_entry(compound, symbol);
5879 errorf(&entity->base.source_position,
5880 "multiple declarations of symbol '%Y' (declared %P)",
5881 symbol, &prev->base.source_position);
5885 if (token.type == ':') {
5886 source_position_t source_position = *HERE;
5888 expression_t *size = parse_constant_expression();
5890 type_t *type = entity->declaration.type;
5891 type_t *bitfield_type = make_bitfield_type(type, size,
5892 &source_position, entity->base.symbol);
5894 attribute_t *attributes = parse_attributes(NULL);
5895 entity->declaration.type = bitfield_type;
5896 handle_entity_attributes(attributes, entity);
5898 type_t *orig_type = entity->declaration.type;
5899 type_t *type = skip_typeref(orig_type);
5900 if (is_type_function(type)) {
5901 errorf(&entity->base.source_position,
5902 "compound member '%Y' must not have function type '%T'",
5903 entity->base.symbol, orig_type);
5904 } else if (is_type_incomplete(type)) {
5905 /* §6.7.2.1:16 flexible array member */
5906 if (!is_type_array(type) ||
5907 token.type != ';' ||
5908 look_ahead(1)->type != '}') {
5909 errorf(&entity->base.source_position,
5910 "compound member '%Y' has incomplete type '%T'",
5911 entity->base.symbol, orig_type);
5916 append_entity(&compound->members, entity);
5919 } while (next_if(','));
5920 expect(';', end_error);
5923 anonymous_entity = NULL;
5926 static void parse_compound_type_entries(compound_t *compound)
5929 add_anchor_token('}');
5931 while (token.type != '}') {
5932 if (token.type == T_EOF) {
5933 errorf(HERE, "EOF while parsing struct");
5936 declaration_specifiers_t specifiers;
5937 memset(&specifiers, 0, sizeof(specifiers));
5938 parse_declaration_specifiers(&specifiers);
5940 parse_compound_declarators(compound, &specifiers);
5942 rem_anchor_token('}');
5946 compound->complete = true;
5949 static type_t *parse_typename(void)
5951 declaration_specifiers_t specifiers;
5952 memset(&specifiers, 0, sizeof(specifiers));
5953 parse_declaration_specifiers(&specifiers);
5954 if (specifiers.storage_class != STORAGE_CLASS_NONE
5955 || specifiers.thread_local) {
5956 /* TODO: improve error message, user does probably not know what a
5957 * storage class is...
5959 errorf(HERE, "typename must not have a storage class");
5962 type_t *result = parse_abstract_declarator(specifiers.type);
5970 typedef expression_t* (*parse_expression_function)(void);
5971 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5973 typedef struct expression_parser_function_t expression_parser_function_t;
5974 struct expression_parser_function_t {
5975 parse_expression_function parser;
5976 precedence_t infix_precedence;
5977 parse_expression_infix_function infix_parser;
5980 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5983 * Prints an error message if an expression was expected but not read
5985 static expression_t *expected_expression_error(void)
5987 /* skip the error message if the error token was read */
5988 if (token.type != T_ERROR) {
5989 errorf(HERE, "expected expression, got token %K", &token);
5993 return create_invalid_expression();
5996 static type_t *get_string_type(void)
5998 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6001 static type_t *get_wide_string_type(void)
6003 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6007 * Parse a string constant.
6009 static expression_t *parse_string_literal(void)
6011 source_position_t begin = token.source_position;
6012 string_t res = token.literal;
6013 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
6016 while (token.type == T_STRING_LITERAL
6017 || token.type == T_WIDE_STRING_LITERAL) {
6018 warn_string_concat(&token.source_position);
6019 res = concat_strings(&res, &token.literal);
6021 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6024 expression_t *literal;
6026 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6027 literal->base.type = get_wide_string_type();
6029 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6030 literal->base.type = get_string_type();
6032 literal->base.source_position = begin;
6033 literal->literal.value = res;
6039 * Parse a boolean constant.
6041 static expression_t *parse_boolean_literal(bool value)
6043 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6044 literal->base.source_position = token.source_position;
6045 literal->base.type = type_bool;
6046 literal->literal.value.begin = value ? "true" : "false";
6047 literal->literal.value.size = value ? 4 : 5;
6053 static void warn_traditional_suffix(void)
6055 if (!warning.traditional)
6057 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6061 static void check_integer_suffix(void)
6063 symbol_t *suffix = token.symbol;
6067 bool not_traditional = false;
6068 const char *c = suffix->string;
6069 if (*c == 'l' || *c == 'L') {
6072 not_traditional = true;
6074 if (*c == 'u' || *c == 'U') {
6077 } else if (*c == 'u' || *c == 'U') {
6078 not_traditional = true;
6081 } else if (*c == 'u' || *c == 'U') {
6082 not_traditional = true;
6084 if (*c == 'l' || *c == 'L') {
6092 errorf(&token.source_position,
6093 "invalid suffix '%s' on integer constant", suffix->string);
6094 } else if (not_traditional) {
6095 warn_traditional_suffix();
6099 static type_t *check_floatingpoint_suffix(void)
6101 symbol_t *suffix = token.symbol;
6102 type_t *type = type_double;
6106 bool not_traditional = false;
6107 const char *c = suffix->string;
6108 if (*c == 'f' || *c == 'F') {
6111 } else if (*c == 'l' || *c == 'L') {
6113 type = type_long_double;
6116 errorf(&token.source_position,
6117 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6118 } else if (not_traditional) {
6119 warn_traditional_suffix();
6126 * Parse an integer constant.
6128 static expression_t *parse_number_literal(void)
6130 expression_kind_t kind;
6133 switch (token.type) {
6135 kind = EXPR_LITERAL_INTEGER;
6136 check_integer_suffix();
6139 case T_INTEGER_OCTAL:
6140 kind = EXPR_LITERAL_INTEGER_OCTAL;
6141 check_integer_suffix();
6144 case T_INTEGER_HEXADECIMAL:
6145 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6146 check_integer_suffix();
6149 case T_FLOATINGPOINT:
6150 kind = EXPR_LITERAL_FLOATINGPOINT;
6151 type = check_floatingpoint_suffix();
6153 case T_FLOATINGPOINT_HEXADECIMAL:
6154 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6155 type = check_floatingpoint_suffix();
6158 panic("unexpected token type in parse_number_literal");
6161 expression_t *literal = allocate_expression_zero(kind);
6162 literal->base.source_position = token.source_position;
6163 literal->base.type = type;
6164 literal->literal.value = token.literal;
6165 literal->literal.suffix = token.symbol;
6168 /* integer type depends on the size of the number and the size
6169 * representable by the types. The backend/codegeneration has to determine
6172 determine_literal_type(&literal->literal);
6177 * Parse a character constant.
6179 static expression_t *parse_character_constant(void)
6181 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6182 literal->base.source_position = token.source_position;
6183 literal->base.type = c_mode & _CXX ? type_char : type_int;
6184 literal->literal.value = token.literal;
6186 size_t len = literal->literal.value.size;
6188 if (!GNU_MODE && !(c_mode & _C99)) {
6189 errorf(HERE, "more than 1 character in character constant");
6190 } else if (warning.multichar) {
6191 literal->base.type = type_int;
6192 warningf(HERE, "multi-character character constant");
6201 * Parse a wide character constant.
6203 static expression_t *parse_wide_character_constant(void)
6205 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6206 literal->base.source_position = token.source_position;
6207 literal->base.type = type_int;
6208 literal->literal.value = token.literal;
6210 size_t len = wstrlen(&literal->literal.value);
6212 warningf(HERE, "multi-character character constant");
6219 static entity_t *create_implicit_function(symbol_t *symbol,
6220 const source_position_t *source_position)
6222 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6223 ntype->function.return_type = type_int;
6224 ntype->function.unspecified_parameters = true;
6225 ntype->function.linkage = LINKAGE_C;
6226 type_t *type = identify_new_type(ntype);
6228 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6229 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6230 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6231 entity->declaration.type = type;
6232 entity->declaration.implicit = true;
6233 entity->base.symbol = symbol;
6234 entity->base.source_position = *source_position;
6236 if (current_scope != NULL) {
6237 bool strict_prototypes_old = warning.strict_prototypes;
6238 warning.strict_prototypes = false;
6239 record_entity(entity, false);
6240 warning.strict_prototypes = strict_prototypes_old;
6247 * Performs automatic type cast as described in §6.3.2.1.
6249 * @param orig_type the original type
6251 static type_t *automatic_type_conversion(type_t *orig_type)
6253 type_t *type = skip_typeref(orig_type);
6254 if (is_type_array(type)) {
6255 array_type_t *array_type = &type->array;
6256 type_t *element_type = array_type->element_type;
6257 unsigned qualifiers = array_type->base.qualifiers;
6259 return make_pointer_type(element_type, qualifiers);
6262 if (is_type_function(type)) {
6263 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6270 * reverts the automatic casts of array to pointer types and function
6271 * to function-pointer types as defined §6.3.2.1
6273 type_t *revert_automatic_type_conversion(const expression_t *expression)
6275 switch (expression->kind) {
6276 case EXPR_REFERENCE: {
6277 entity_t *entity = expression->reference.entity;
6278 if (is_declaration(entity)) {
6279 return entity->declaration.type;
6280 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6281 return entity->enum_value.enum_type;
6283 panic("no declaration or enum in reference");
6288 entity_t *entity = expression->select.compound_entry;
6289 assert(is_declaration(entity));
6290 type_t *type = entity->declaration.type;
6291 return get_qualified_type(type,
6292 expression->base.type->base.qualifiers);
6295 case EXPR_UNARY_DEREFERENCE: {
6296 const expression_t *const value = expression->unary.value;
6297 type_t *const type = skip_typeref(value->base.type);
6298 if (!is_type_pointer(type))
6299 return type_error_type;
6300 return type->pointer.points_to;
6303 case EXPR_ARRAY_ACCESS: {
6304 const expression_t *array_ref = expression->array_access.array_ref;
6305 type_t *type_left = skip_typeref(array_ref->base.type);
6306 if (!is_type_pointer(type_left))
6307 return type_error_type;
6308 return type_left->pointer.points_to;
6311 case EXPR_STRING_LITERAL: {
6312 size_t size = expression->string_literal.value.size;
6313 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6316 case EXPR_WIDE_STRING_LITERAL: {
6317 size_t size = wstrlen(&expression->string_literal.value);
6318 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6321 case EXPR_COMPOUND_LITERAL:
6322 return expression->compound_literal.type;
6327 return expression->base.type;
6331 * Find an entity matching a symbol in a scope.
6332 * Uses current scope if scope is NULL
6334 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6335 namespace_tag_t namespc)
6337 if (scope == NULL) {
6338 return get_entity(symbol, namespc);
6341 /* we should optimize here, if scope grows above a certain size we should
6342 construct a hashmap here... */
6343 entity_t *entity = scope->entities;
6344 for ( ; entity != NULL; entity = entity->base.next) {
6345 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6352 static entity_t *parse_qualified_identifier(void)
6354 /* namespace containing the symbol */
6356 source_position_t pos;
6357 const scope_t *lookup_scope = NULL;
6359 if (next_if(T_COLONCOLON))
6360 lookup_scope = &unit->scope;
6364 if (token.type != T_IDENTIFIER) {
6365 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6366 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6368 symbol = token.symbol;
6373 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6375 if (!next_if(T_COLONCOLON))
6378 switch (entity->kind) {
6379 case ENTITY_NAMESPACE:
6380 lookup_scope = &entity->namespacee.members;
6385 lookup_scope = &entity->compound.members;
6388 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6389 symbol, get_entity_kind_name(entity->kind));
6394 if (entity == NULL) {
6395 if (!strict_mode && token.type == '(') {
6396 /* an implicitly declared function */
6397 if (warning.error_implicit_function_declaration) {
6398 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6399 } else if (warning.implicit_function_declaration) {
6400 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6403 entity = create_implicit_function(symbol, &pos);
6405 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6406 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6413 /* skip further qualifications */
6414 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6416 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6419 static expression_t *parse_reference(void)
6421 entity_t *entity = parse_qualified_identifier();
6424 if (is_declaration(entity)) {
6425 orig_type = entity->declaration.type;
6426 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6427 orig_type = entity->enum_value.enum_type;
6429 panic("expected declaration or enum value in reference");
6432 /* we always do the auto-type conversions; the & and sizeof parser contains
6433 * code to revert this! */
6434 type_t *type = automatic_type_conversion(orig_type);
6436 expression_kind_t kind = EXPR_REFERENCE;
6437 if (entity->kind == ENTITY_ENUM_VALUE)
6438 kind = EXPR_REFERENCE_ENUM_VALUE;
6440 expression_t *expression = allocate_expression_zero(kind);
6441 expression->reference.entity = entity;
6442 expression->base.type = type;
6444 /* this declaration is used */
6445 if (is_declaration(entity)) {
6446 entity->declaration.used = true;
6449 if (entity->base.parent_scope != file_scope
6450 && (current_function != NULL
6451 && entity->base.parent_scope->depth < current_function->parameters.depth)
6452 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6453 if (entity->kind == ENTITY_VARIABLE) {
6454 /* access of a variable from an outer function */
6455 entity->variable.address_taken = true;
6456 } else if (entity->kind == ENTITY_PARAMETER) {
6457 entity->parameter.address_taken = true;
6459 current_function->need_closure = true;
6462 check_deprecated(HERE, entity);
6464 if (warning.init_self && entity == current_init_decl && !in_type_prop
6465 && entity->kind == ENTITY_VARIABLE) {
6466 current_init_decl = NULL;
6467 warningf(HERE, "variable '%#T' is initialized by itself",
6468 entity->declaration.type, entity->base.symbol);
6474 static bool semantic_cast(expression_t *cast)
6476 expression_t *expression = cast->unary.value;
6477 type_t *orig_dest_type = cast->base.type;
6478 type_t *orig_type_right = expression->base.type;
6479 type_t const *dst_type = skip_typeref(orig_dest_type);
6480 type_t const *src_type = skip_typeref(orig_type_right);
6481 source_position_t const *pos = &cast->base.source_position;
6483 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6484 if (dst_type == type_void)
6487 /* only integer and pointer can be casted to pointer */
6488 if (is_type_pointer(dst_type) &&
6489 !is_type_pointer(src_type) &&
6490 !is_type_integer(src_type) &&
6491 is_type_valid(src_type)) {
6492 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6496 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6497 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6501 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6502 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6506 if (warning.cast_qual &&
6507 is_type_pointer(src_type) &&
6508 is_type_pointer(dst_type)) {
6509 type_t *src = skip_typeref(src_type->pointer.points_to);
6510 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6511 unsigned missing_qualifiers =
6512 src->base.qualifiers & ~dst->base.qualifiers;
6513 if (missing_qualifiers != 0) {
6515 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6516 missing_qualifiers, orig_type_right);
6522 static expression_t *parse_compound_literal(type_t *type)
6524 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6526 parse_initializer_env_t env;
6529 env.must_be_constant = false;
6530 initializer_t *initializer = parse_initializer(&env);
6533 expression->compound_literal.initializer = initializer;
6534 expression->compound_literal.type = type;
6535 expression->base.type = automatic_type_conversion(type);
6541 * Parse a cast expression.
6543 static expression_t *parse_cast(void)
6545 add_anchor_token(')');
6547 source_position_t source_position = token.source_position;
6549 type_t *type = parse_typename();
6551 rem_anchor_token(')');
6552 expect(')', end_error);
6554 if (token.type == '{') {
6555 return parse_compound_literal(type);
6558 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6559 cast->base.source_position = source_position;
6561 expression_t *value = parse_subexpression(PREC_CAST);
6562 cast->base.type = type;
6563 cast->unary.value = value;
6565 if (! semantic_cast(cast)) {
6566 /* TODO: record the error in the AST. else it is impossible to detect it */
6571 return create_invalid_expression();
6575 * Parse a statement expression.
6577 static expression_t *parse_statement_expression(void)
6579 add_anchor_token(')');
6581 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6583 statement_t *statement = parse_compound_statement(true);
6584 statement->compound.stmt_expr = true;
6585 expression->statement.statement = statement;
6587 /* find last statement and use its type */
6588 type_t *type = type_void;
6589 const statement_t *stmt = statement->compound.statements;
6591 while (stmt->base.next != NULL)
6592 stmt = stmt->base.next;
6594 if (stmt->kind == STATEMENT_EXPRESSION) {
6595 type = stmt->expression.expression->base.type;
6597 } else if (warning.other) {
6598 warningf(&expression->base.source_position, "empty statement expression ({})");
6600 expression->base.type = type;
6602 rem_anchor_token(')');
6603 expect(')', end_error);
6610 * Parse a parenthesized expression.
6612 static expression_t *parse_parenthesized_expression(void)
6616 switch (token.type) {
6618 /* gcc extension: a statement expression */
6619 return parse_statement_expression();
6623 return parse_cast();
6625 if (is_typedef_symbol(token.symbol)) {
6626 return parse_cast();
6630 add_anchor_token(')');
6631 expression_t *result = parse_expression();
6632 result->base.parenthesized = true;
6633 rem_anchor_token(')');
6634 expect(')', end_error);
6640 static expression_t *parse_function_keyword(void)
6644 if (current_function == NULL) {
6645 errorf(HERE, "'__func__' used outside of a function");
6648 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6649 expression->base.type = type_char_ptr;
6650 expression->funcname.kind = FUNCNAME_FUNCTION;
6657 static expression_t *parse_pretty_function_keyword(void)
6659 if (current_function == NULL) {
6660 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6663 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6664 expression->base.type = type_char_ptr;
6665 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6667 eat(T___PRETTY_FUNCTION__);
6672 static expression_t *parse_funcsig_keyword(void)
6674 if (current_function == NULL) {
6675 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6678 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6679 expression->base.type = type_char_ptr;
6680 expression->funcname.kind = FUNCNAME_FUNCSIG;
6687 static expression_t *parse_funcdname_keyword(void)
6689 if (current_function == NULL) {
6690 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6693 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6694 expression->base.type = type_char_ptr;
6695 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6697 eat(T___FUNCDNAME__);
6702 static designator_t *parse_designator(void)
6704 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6705 result->source_position = *HERE;
6707 if (token.type != T_IDENTIFIER) {
6708 parse_error_expected("while parsing member designator",
6709 T_IDENTIFIER, NULL);
6712 result->symbol = token.symbol;
6715 designator_t *last_designator = result;
6718 if (token.type != T_IDENTIFIER) {
6719 parse_error_expected("while parsing member designator",
6720 T_IDENTIFIER, NULL);
6723 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6724 designator->source_position = *HERE;
6725 designator->symbol = token.symbol;
6728 last_designator->next = designator;
6729 last_designator = designator;
6733 add_anchor_token(']');
6734 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6735 designator->source_position = *HERE;
6736 designator->array_index = parse_expression();
6737 rem_anchor_token(']');
6738 expect(']', end_error);
6739 if (designator->array_index == NULL) {
6743 last_designator->next = designator;
6744 last_designator = designator;
6756 * Parse the __builtin_offsetof() expression.
6758 static expression_t *parse_offsetof(void)
6760 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6761 expression->base.type = type_size_t;
6763 eat(T___builtin_offsetof);
6765 expect('(', end_error);
6766 add_anchor_token(',');
6767 type_t *type = parse_typename();
6768 rem_anchor_token(',');
6769 expect(',', end_error);
6770 add_anchor_token(')');
6771 designator_t *designator = parse_designator();
6772 rem_anchor_token(')');
6773 expect(')', end_error);
6775 expression->offsetofe.type = type;
6776 expression->offsetofe.designator = designator;
6779 memset(&path, 0, sizeof(path));
6780 path.top_type = type;
6781 path.path = NEW_ARR_F(type_path_entry_t, 0);
6783 descend_into_subtype(&path);
6785 if (!walk_designator(&path, designator, true)) {
6786 return create_invalid_expression();
6789 DEL_ARR_F(path.path);
6793 return create_invalid_expression();
6797 * Parses a _builtin_va_start() expression.
6799 static expression_t *parse_va_start(void)
6801 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6803 eat(T___builtin_va_start);
6805 expect('(', end_error);
6806 add_anchor_token(',');
6807 expression->va_starte.ap = parse_assignment_expression();
6808 rem_anchor_token(',');
6809 expect(',', end_error);
6810 expression_t *const expr = parse_assignment_expression();
6811 if (expr->kind == EXPR_REFERENCE) {
6812 entity_t *const entity = expr->reference.entity;
6813 if (!current_function->base.type->function.variadic) {
6814 errorf(&expr->base.source_position,
6815 "'va_start' used in non-variadic function");
6816 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6817 entity->base.next != NULL ||
6818 entity->kind != ENTITY_PARAMETER) {
6819 errorf(&expr->base.source_position,
6820 "second argument of 'va_start' must be last parameter of the current function");
6822 expression->va_starte.parameter = &entity->variable;
6824 expect(')', end_error);
6827 expect(')', end_error);
6829 return create_invalid_expression();
6833 * Parses a __builtin_va_arg() expression.
6835 static expression_t *parse_va_arg(void)
6837 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6839 eat(T___builtin_va_arg);
6841 expect('(', end_error);
6843 ap.expression = parse_assignment_expression();
6844 expression->va_arge.ap = ap.expression;
6845 check_call_argument(type_valist, &ap, 1);
6847 expect(',', end_error);
6848 expression->base.type = parse_typename();
6849 expect(')', end_error);
6853 return create_invalid_expression();
6857 * Parses a __builtin_va_copy() expression.
6859 static expression_t *parse_va_copy(void)
6861 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6863 eat(T___builtin_va_copy);
6865 expect('(', end_error);
6866 expression_t *dst = parse_assignment_expression();
6867 assign_error_t error = semantic_assign(type_valist, dst);
6868 report_assign_error(error, type_valist, dst, "call argument 1",
6869 &dst->base.source_position);
6870 expression->va_copye.dst = dst;
6872 expect(',', end_error);
6874 call_argument_t src;
6875 src.expression = parse_assignment_expression();
6876 check_call_argument(type_valist, &src, 2);
6877 expression->va_copye.src = src.expression;
6878 expect(')', end_error);
6882 return create_invalid_expression();
6886 * Parses a __builtin_constant_p() expression.
6888 static expression_t *parse_builtin_constant(void)
6890 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6892 eat(T___builtin_constant_p);
6894 expect('(', end_error);
6895 add_anchor_token(')');
6896 expression->builtin_constant.value = parse_assignment_expression();
6897 rem_anchor_token(')');
6898 expect(')', end_error);
6899 expression->base.type = type_int;
6903 return create_invalid_expression();
6907 * Parses a __builtin_types_compatible_p() expression.
6909 static expression_t *parse_builtin_types_compatible(void)
6911 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6913 eat(T___builtin_types_compatible_p);
6915 expect('(', end_error);
6916 add_anchor_token(')');
6917 add_anchor_token(',');
6918 expression->builtin_types_compatible.left = parse_typename();
6919 rem_anchor_token(',');
6920 expect(',', end_error);
6921 expression->builtin_types_compatible.right = parse_typename();
6922 rem_anchor_token(')');
6923 expect(')', end_error);
6924 expression->base.type = type_int;
6928 return create_invalid_expression();
6932 * Parses a __builtin_is_*() compare expression.
6934 static expression_t *parse_compare_builtin(void)
6936 expression_t *expression;
6938 switch (token.type) {
6939 case T___builtin_isgreater:
6940 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6942 case T___builtin_isgreaterequal:
6943 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6945 case T___builtin_isless:
6946 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6948 case T___builtin_islessequal:
6949 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6951 case T___builtin_islessgreater:
6952 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6954 case T___builtin_isunordered:
6955 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6958 internal_errorf(HERE, "invalid compare builtin found");
6960 expression->base.source_position = *HERE;
6963 expect('(', end_error);
6964 expression->binary.left = parse_assignment_expression();
6965 expect(',', end_error);
6966 expression->binary.right = parse_assignment_expression();
6967 expect(')', end_error);
6969 type_t *const orig_type_left = expression->binary.left->base.type;
6970 type_t *const orig_type_right = expression->binary.right->base.type;
6972 type_t *const type_left = skip_typeref(orig_type_left);
6973 type_t *const type_right = skip_typeref(orig_type_right);
6974 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6975 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6976 type_error_incompatible("invalid operands in comparison",
6977 &expression->base.source_position, orig_type_left, orig_type_right);
6980 semantic_comparison(&expression->binary);
6985 return create_invalid_expression();
6989 * Parses a MS assume() expression.
6991 static expression_t *parse_assume(void)
6993 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6997 expect('(', end_error);
6998 add_anchor_token(')');
6999 expression->unary.value = parse_assignment_expression();
7000 rem_anchor_token(')');
7001 expect(')', end_error);
7003 expression->base.type = type_void;
7006 return create_invalid_expression();
7010 * Return the declaration for a given label symbol or create a new one.
7012 * @param symbol the symbol of the label
7014 static label_t *get_label(symbol_t *symbol)
7017 assert(current_function != NULL);
7019 label = get_entity(symbol, NAMESPACE_LABEL);
7020 /* if we found a local label, we already created the declaration */
7021 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7022 if (label->base.parent_scope != current_scope) {
7023 assert(label->base.parent_scope->depth < current_scope->depth);
7024 current_function->goto_to_outer = true;
7026 return &label->label;
7029 label = get_entity(symbol, NAMESPACE_LABEL);
7030 /* if we found a label in the same function, then we already created the
7033 && label->base.parent_scope == ¤t_function->parameters) {
7034 return &label->label;
7037 /* otherwise we need to create a new one */
7038 label = allocate_entity_zero(ENTITY_LABEL);
7039 label->base.namespc = NAMESPACE_LABEL;
7040 label->base.symbol = symbol;
7044 return &label->label;
7048 * Parses a GNU && label address expression.
7050 static expression_t *parse_label_address(void)
7052 source_position_t source_position = token.source_position;
7054 if (token.type != T_IDENTIFIER) {
7055 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7058 symbol_t *symbol = token.symbol;
7061 label_t *label = get_label(symbol);
7063 label->address_taken = true;
7065 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7066 expression->base.source_position = source_position;
7068 /* label address is threaten as a void pointer */
7069 expression->base.type = type_void_ptr;
7070 expression->label_address.label = label;
7073 return create_invalid_expression();
7077 * Parse a microsoft __noop expression.
7079 static expression_t *parse_noop_expression(void)
7081 /* the result is a (int)0 */
7082 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7083 literal->base.type = type_int;
7084 literal->base.source_position = token.source_position;
7085 literal->literal.value.begin = "__noop";
7086 literal->literal.value.size = 6;
7090 if (token.type == '(') {
7091 /* parse arguments */
7093 add_anchor_token(')');
7094 add_anchor_token(',');
7096 if (token.type != ')') do {
7097 (void)parse_assignment_expression();
7098 } while (next_if(','));
7100 rem_anchor_token(',');
7101 rem_anchor_token(')');
7102 expect(')', end_error);
7109 * Parses a primary expression.
7111 static expression_t *parse_primary_expression(void)
7113 switch (token.type) {
7114 case T_false: return parse_boolean_literal(false);
7115 case T_true: return parse_boolean_literal(true);
7117 case T_INTEGER_OCTAL:
7118 case T_INTEGER_HEXADECIMAL:
7119 case T_FLOATINGPOINT:
7120 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7121 case T_CHARACTER_CONSTANT: return parse_character_constant();
7122 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7123 case T_STRING_LITERAL:
7124 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7125 case T___FUNCTION__:
7126 case T___func__: return parse_function_keyword();
7127 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7128 case T___FUNCSIG__: return parse_funcsig_keyword();
7129 case T___FUNCDNAME__: return parse_funcdname_keyword();
7130 case T___builtin_offsetof: return parse_offsetof();
7131 case T___builtin_va_start: return parse_va_start();
7132 case T___builtin_va_arg: return parse_va_arg();
7133 case T___builtin_va_copy: return parse_va_copy();
7134 case T___builtin_isgreater:
7135 case T___builtin_isgreaterequal:
7136 case T___builtin_isless:
7137 case T___builtin_islessequal:
7138 case T___builtin_islessgreater:
7139 case T___builtin_isunordered: return parse_compare_builtin();
7140 case T___builtin_constant_p: return parse_builtin_constant();
7141 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7142 case T__assume: return parse_assume();
7145 return parse_label_address();
7148 case '(': return parse_parenthesized_expression();
7149 case T___noop: return parse_noop_expression();
7151 /* Gracefully handle type names while parsing expressions. */
7153 return parse_reference();
7155 if (!is_typedef_symbol(token.symbol)) {
7156 return parse_reference();
7160 source_position_t const pos = *HERE;
7161 type_t const *const type = parse_typename();
7162 errorf(&pos, "encountered type '%T' while parsing expression", type);
7163 return create_invalid_expression();
7167 errorf(HERE, "unexpected token %K, expected an expression", &token);
7169 return create_invalid_expression();
7173 * Check if the expression has the character type and issue a warning then.
7175 static void check_for_char_index_type(const expression_t *expression)
7177 type_t *const type = expression->base.type;
7178 const type_t *const base_type = skip_typeref(type);
7180 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7181 warning.char_subscripts) {
7182 warningf(&expression->base.source_position,
7183 "array subscript has type '%T'", type);
7187 static expression_t *parse_array_expression(expression_t *left)
7189 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7192 add_anchor_token(']');
7194 expression_t *inside = parse_expression();
7196 type_t *const orig_type_left = left->base.type;
7197 type_t *const orig_type_inside = inside->base.type;
7199 type_t *const type_left = skip_typeref(orig_type_left);
7200 type_t *const type_inside = skip_typeref(orig_type_inside);
7202 type_t *return_type;
7203 array_access_expression_t *array_access = &expression->array_access;
7204 if (is_type_pointer(type_left)) {
7205 return_type = type_left->pointer.points_to;
7206 array_access->array_ref = left;
7207 array_access->index = inside;
7208 check_for_char_index_type(inside);
7209 } else if (is_type_pointer(type_inside)) {
7210 return_type = type_inside->pointer.points_to;
7211 array_access->array_ref = inside;
7212 array_access->index = left;
7213 array_access->flipped = true;
7214 check_for_char_index_type(left);
7216 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7218 "array access on object with non-pointer types '%T', '%T'",
7219 orig_type_left, orig_type_inside);
7221 return_type = type_error_type;
7222 array_access->array_ref = left;
7223 array_access->index = inside;
7226 expression->base.type = automatic_type_conversion(return_type);
7228 rem_anchor_token(']');
7229 expect(']', end_error);
7234 static expression_t *parse_typeprop(expression_kind_t const kind)
7236 expression_t *tp_expression = allocate_expression_zero(kind);
7237 tp_expression->base.type = type_size_t;
7239 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7241 /* we only refer to a type property, mark this case */
7242 bool old = in_type_prop;
7243 in_type_prop = true;
7246 expression_t *expression;
7247 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7249 add_anchor_token(')');
7250 orig_type = parse_typename();
7251 rem_anchor_token(')');
7252 expect(')', end_error);
7254 if (token.type == '{') {
7255 /* It was not sizeof(type) after all. It is sizeof of an expression
7256 * starting with a compound literal */
7257 expression = parse_compound_literal(orig_type);
7258 goto typeprop_expression;
7261 expression = parse_subexpression(PREC_UNARY);
7263 typeprop_expression:
7264 tp_expression->typeprop.tp_expression = expression;
7266 orig_type = revert_automatic_type_conversion(expression);
7267 expression->base.type = orig_type;
7270 tp_expression->typeprop.type = orig_type;
7271 type_t const* const type = skip_typeref(orig_type);
7272 char const* const wrong_type =
7273 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7274 is_type_incomplete(type) ? "incomplete" :
7275 type->kind == TYPE_FUNCTION ? "function designator" :
7276 type->kind == TYPE_BITFIELD ? "bitfield" :
7278 if (wrong_type != NULL) {
7279 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7280 errorf(&tp_expression->base.source_position,
7281 "operand of %s expression must not be of %s type '%T'",
7282 what, wrong_type, orig_type);
7287 return tp_expression;
7290 static expression_t *parse_sizeof(void)
7292 return parse_typeprop(EXPR_SIZEOF);
7295 static expression_t *parse_alignof(void)
7297 return parse_typeprop(EXPR_ALIGNOF);
7300 static expression_t *parse_select_expression(expression_t *addr)
7302 assert(token.type == '.' || token.type == T_MINUSGREATER);
7303 bool select_left_arrow = (token.type == T_MINUSGREATER);
7306 if (token.type != T_IDENTIFIER) {
7307 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7308 return create_invalid_expression();
7310 symbol_t *symbol = token.symbol;
7313 type_t *const orig_type = addr->base.type;
7314 type_t *const type = skip_typeref(orig_type);
7317 bool saw_error = false;
7318 if (is_type_pointer(type)) {
7319 if (!select_left_arrow) {
7321 "request for member '%Y' in something not a struct or union, but '%T'",
7325 type_left = skip_typeref(type->pointer.points_to);
7327 if (select_left_arrow && is_type_valid(type)) {
7328 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7334 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7335 type_left->kind != TYPE_COMPOUND_UNION) {
7337 if (is_type_valid(type_left) && !saw_error) {
7339 "request for member '%Y' in something not a struct or union, but '%T'",
7342 return create_invalid_expression();
7345 compound_t *compound = type_left->compound.compound;
7346 if (!compound->complete) {
7347 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7349 return create_invalid_expression();
7352 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7353 expression_t *result
7354 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7356 if (result == NULL) {
7357 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7358 return create_invalid_expression();
7364 static void check_call_argument(type_t *expected_type,
7365 call_argument_t *argument, unsigned pos)
7367 type_t *expected_type_skip = skip_typeref(expected_type);
7368 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7369 expression_t *arg_expr = argument->expression;
7370 type_t *arg_type = skip_typeref(arg_expr->base.type);
7372 /* handle transparent union gnu extension */
7373 if (is_type_union(expected_type_skip)
7374 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7375 compound_t *union_decl = expected_type_skip->compound.compound;
7376 type_t *best_type = NULL;
7377 entity_t *entry = union_decl->members.entities;
7378 for ( ; entry != NULL; entry = entry->base.next) {
7379 assert(is_declaration(entry));
7380 type_t *decl_type = entry->declaration.type;
7381 error = semantic_assign(decl_type, arg_expr);
7382 if (error == ASSIGN_ERROR_INCOMPATIBLE
7383 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7386 if (error == ASSIGN_SUCCESS) {
7387 best_type = decl_type;
7388 } else if (best_type == NULL) {
7389 best_type = decl_type;
7393 if (best_type != NULL) {
7394 expected_type = best_type;
7398 error = semantic_assign(expected_type, arg_expr);
7399 argument->expression = create_implicit_cast(arg_expr, expected_type);
7401 if (error != ASSIGN_SUCCESS) {
7402 /* report exact scope in error messages (like "in argument 3") */
7404 snprintf(buf, sizeof(buf), "call argument %u", pos);
7405 report_assign_error(error, expected_type, arg_expr, buf,
7406 &arg_expr->base.source_position);
7407 } else if (warning.traditional || warning.conversion) {
7408 type_t *const promoted_type = get_default_promoted_type(arg_type);
7409 if (!types_compatible(expected_type_skip, promoted_type) &&
7410 !types_compatible(expected_type_skip, type_void_ptr) &&
7411 !types_compatible(type_void_ptr, promoted_type)) {
7412 /* Deliberately show the skipped types in this warning */
7413 warningf(&arg_expr->base.source_position,
7414 "passing call argument %u as '%T' rather than '%T' due to prototype",
7415 pos, expected_type_skip, promoted_type);
7421 * Handle the semantic restrictions of builtin calls
7423 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7424 switch (call->function->reference.entity->function.btk) {
7425 case bk_gnu_builtin_return_address:
7426 case bk_gnu_builtin_frame_address: {
7427 /* argument must be constant */
7428 call_argument_t *argument = call->arguments;
7430 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7431 errorf(&call->base.source_position,
7432 "argument of '%Y' must be a constant expression",
7433 call->function->reference.entity->base.symbol);
7437 case bk_gnu_builtin_object_size:
7438 if (call->arguments == NULL)
7441 call_argument_t *arg = call->arguments->next;
7442 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7443 errorf(&call->base.source_position,
7444 "second argument of '%Y' must be a constant expression",
7445 call->function->reference.entity->base.symbol);
7448 case bk_gnu_builtin_prefetch:
7449 /* second and third argument must be constant if existent */
7450 if (call->arguments == NULL)
7452 call_argument_t *rw = call->arguments->next;
7453 call_argument_t *locality = NULL;
7456 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7457 errorf(&call->base.source_position,
7458 "second argument of '%Y' must be a constant expression",
7459 call->function->reference.entity->base.symbol);
7461 locality = rw->next;
7463 if (locality != NULL) {
7464 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7465 errorf(&call->base.source_position,
7466 "third argument of '%Y' must be a constant expression",
7467 call->function->reference.entity->base.symbol);
7469 locality = rw->next;
7478 * Parse a call expression, ie. expression '( ... )'.
7480 * @param expression the function address
7482 static expression_t *parse_call_expression(expression_t *expression)
7484 expression_t *result = allocate_expression_zero(EXPR_CALL);
7485 call_expression_t *call = &result->call;
7486 call->function = expression;
7488 type_t *const orig_type = expression->base.type;
7489 type_t *const type = skip_typeref(orig_type);
7491 function_type_t *function_type = NULL;
7492 if (is_type_pointer(type)) {
7493 type_t *const to_type = skip_typeref(type->pointer.points_to);
7495 if (is_type_function(to_type)) {
7496 function_type = &to_type->function;
7497 call->base.type = function_type->return_type;
7501 if (function_type == NULL && is_type_valid(type)) {
7503 "called object '%E' (type '%T') is not a pointer to a function",
7504 expression, orig_type);
7507 /* parse arguments */
7509 add_anchor_token(')');
7510 add_anchor_token(',');
7512 if (token.type != ')') {
7513 call_argument_t **anchor = &call->arguments;
7515 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7516 argument->expression = parse_assignment_expression();
7519 anchor = &argument->next;
7520 } while (next_if(','));
7522 rem_anchor_token(',');
7523 rem_anchor_token(')');
7524 expect(')', end_error);
7526 if (function_type == NULL)
7529 /* check type and count of call arguments */
7530 function_parameter_t *parameter = function_type->parameters;
7531 call_argument_t *argument = call->arguments;
7532 if (!function_type->unspecified_parameters) {
7533 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7534 parameter = parameter->next, argument = argument->next) {
7535 check_call_argument(parameter->type, argument, ++pos);
7538 if (parameter != NULL) {
7539 errorf(HERE, "too few arguments to function '%E'", expression);
7540 } else if (argument != NULL && !function_type->variadic) {
7541 errorf(HERE, "too many arguments to function '%E'", expression);
7545 /* do default promotion for other arguments */
7546 for (; argument != NULL; argument = argument->next) {
7547 type_t *type = argument->expression->base.type;
7548 if (!is_type_object(skip_typeref(type))) {
7549 errorf(&argument->expression->base.source_position,
7550 "call argument '%E' must not be void", argument->expression);
7553 type = get_default_promoted_type(type);
7555 argument->expression
7556 = create_implicit_cast(argument->expression, type);
7559 check_format(&result->call);
7561 if (warning.aggregate_return &&
7562 is_type_compound(skip_typeref(function_type->return_type))) {
7563 warningf(&result->base.source_position,
7564 "function call has aggregate value");
7567 if (call->function->kind == EXPR_REFERENCE) {
7568 reference_expression_t *reference = &call->function->reference;
7569 if (reference->entity->kind == ENTITY_FUNCTION &&
7570 reference->entity->function.btk != bk_none)
7571 handle_builtin_argument_restrictions(call);
7578 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7580 static bool same_compound_type(const type_t *type1, const type_t *type2)
7583 is_type_compound(type1) &&
7584 type1->kind == type2->kind &&
7585 type1->compound.compound == type2->compound.compound;
7588 static expression_t const *get_reference_address(expression_t const *expr)
7590 bool regular_take_address = true;
7592 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7593 expr = expr->unary.value;
7595 regular_take_address = false;
7598 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7601 expr = expr->unary.value;
7604 if (expr->kind != EXPR_REFERENCE)
7607 /* special case for functions which are automatically converted to a
7608 * pointer to function without an extra TAKE_ADDRESS operation */
7609 if (!regular_take_address &&
7610 expr->reference.entity->kind != ENTITY_FUNCTION) {
7617 static void warn_reference_address_as_bool(expression_t const* expr)
7619 if (!warning.address)
7622 expr = get_reference_address(expr);
7624 warningf(&expr->base.source_position,
7625 "the address of '%Y' will always evaluate as 'true'",
7626 expr->reference.entity->base.symbol);
7630 static void warn_assignment_in_condition(const expression_t *const expr)
7632 if (!warning.parentheses)
7634 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7636 if (expr->base.parenthesized)
7638 warningf(&expr->base.source_position,
7639 "suggest parentheses around assignment used as truth value");
7642 static void semantic_condition(expression_t const *const expr,
7643 char const *const context)
7645 type_t *const type = skip_typeref(expr->base.type);
7646 if (is_type_scalar(type)) {
7647 warn_reference_address_as_bool(expr);
7648 warn_assignment_in_condition(expr);
7649 } else if (is_type_valid(type)) {
7650 errorf(&expr->base.source_position,
7651 "%s must have scalar type", context);
7656 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7658 * @param expression the conditional expression
7660 static expression_t *parse_conditional_expression(expression_t *expression)
7662 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7664 conditional_expression_t *conditional = &result->conditional;
7665 conditional->condition = expression;
7668 add_anchor_token(':');
7670 /* §6.5.15:2 The first operand shall have scalar type. */
7671 semantic_condition(expression, "condition of conditional operator");
7673 expression_t *true_expression = expression;
7674 bool gnu_cond = false;
7675 if (GNU_MODE && token.type == ':') {
7678 true_expression = parse_expression();
7680 rem_anchor_token(':');
7681 expect(':', end_error);
7683 expression_t *false_expression =
7684 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7686 type_t *const orig_true_type = true_expression->base.type;
7687 type_t *const orig_false_type = false_expression->base.type;
7688 type_t *const true_type = skip_typeref(orig_true_type);
7689 type_t *const false_type = skip_typeref(orig_false_type);
7692 type_t *result_type;
7693 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7694 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7695 /* ISO/IEC 14882:1998(E) §5.16:2 */
7696 if (true_expression->kind == EXPR_UNARY_THROW) {
7697 result_type = false_type;
7698 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7699 result_type = true_type;
7701 if (warning.other && (
7702 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7703 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7705 warningf(&conditional->base.source_position,
7706 "ISO C forbids conditional expression with only one void side");
7708 result_type = type_void;
7710 } else if (is_type_arithmetic(true_type)
7711 && is_type_arithmetic(false_type)) {
7712 result_type = semantic_arithmetic(true_type, false_type);
7713 } else if (same_compound_type(true_type, false_type)) {
7714 /* just take 1 of the 2 types */
7715 result_type = true_type;
7716 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7717 type_t *pointer_type;
7719 expression_t *other_expression;
7720 if (is_type_pointer(true_type) &&
7721 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7722 pointer_type = true_type;
7723 other_type = false_type;
7724 other_expression = false_expression;
7726 pointer_type = false_type;
7727 other_type = true_type;
7728 other_expression = true_expression;
7731 if (is_null_pointer_constant(other_expression)) {
7732 result_type = pointer_type;
7733 } else if (is_type_pointer(other_type)) {
7734 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7735 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7738 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7739 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7741 } else if (types_compatible(get_unqualified_type(to1),
7742 get_unqualified_type(to2))) {
7745 if (warning.other) {
7746 warningf(&conditional->base.source_position,
7747 "pointer types '%T' and '%T' in conditional expression are incompatible",
7748 true_type, false_type);
7753 type_t *const type =
7754 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7755 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7756 } else if (is_type_integer(other_type)) {
7757 if (warning.other) {
7758 warningf(&conditional->base.source_position,
7759 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7761 result_type = pointer_type;
7763 if (is_type_valid(other_type)) {
7764 type_error_incompatible("while parsing conditional",
7765 &expression->base.source_position, true_type, false_type);
7767 result_type = type_error_type;
7770 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7771 type_error_incompatible("while parsing conditional",
7772 &conditional->base.source_position, true_type,
7775 result_type = type_error_type;
7778 conditional->true_expression
7779 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7780 conditional->false_expression
7781 = create_implicit_cast(false_expression, result_type);
7782 conditional->base.type = result_type;
7787 * Parse an extension expression.
7789 static expression_t *parse_extension(void)
7791 eat(T___extension__);
7793 bool old_gcc_extension = in_gcc_extension;
7794 in_gcc_extension = true;
7795 expression_t *expression = parse_subexpression(PREC_UNARY);
7796 in_gcc_extension = old_gcc_extension;
7801 * Parse a __builtin_classify_type() expression.
7803 static expression_t *parse_builtin_classify_type(void)
7805 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7806 result->base.type = type_int;
7808 eat(T___builtin_classify_type);
7810 expect('(', end_error);
7811 add_anchor_token(')');
7812 expression_t *expression = parse_expression();
7813 rem_anchor_token(')');
7814 expect(')', end_error);
7815 result->classify_type.type_expression = expression;
7819 return create_invalid_expression();
7823 * Parse a delete expression
7824 * ISO/IEC 14882:1998(E) §5.3.5
7826 static expression_t *parse_delete(void)
7828 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7829 result->base.type = type_void;
7834 result->kind = EXPR_UNARY_DELETE_ARRAY;
7835 expect(']', end_error);
7839 expression_t *const value = parse_subexpression(PREC_CAST);
7840 result->unary.value = value;
7842 type_t *const type = skip_typeref(value->base.type);
7843 if (!is_type_pointer(type)) {
7844 if (is_type_valid(type)) {
7845 errorf(&value->base.source_position,
7846 "operand of delete must have pointer type");
7848 } else if (warning.other &&
7849 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7850 warningf(&value->base.source_position,
7851 "deleting 'void*' is undefined");
7858 * Parse a throw expression
7859 * ISO/IEC 14882:1998(E) §15:1
7861 static expression_t *parse_throw(void)
7863 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7864 result->base.type = type_void;
7868 expression_t *value = NULL;
7869 switch (token.type) {
7871 value = parse_assignment_expression();
7872 /* ISO/IEC 14882:1998(E) §15.1:3 */
7873 type_t *const orig_type = value->base.type;
7874 type_t *const type = skip_typeref(orig_type);
7875 if (is_type_incomplete(type)) {
7876 errorf(&value->base.source_position,
7877 "cannot throw object of incomplete type '%T'", orig_type);
7878 } else if (is_type_pointer(type)) {
7879 type_t *const points_to = skip_typeref(type->pointer.points_to);
7880 if (is_type_incomplete(points_to) &&
7881 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7882 errorf(&value->base.source_position,
7883 "cannot throw pointer to incomplete type '%T'", orig_type);
7891 result->unary.value = value;
7896 static bool check_pointer_arithmetic(const source_position_t *source_position,
7897 type_t *pointer_type,
7898 type_t *orig_pointer_type)
7900 type_t *points_to = pointer_type->pointer.points_to;
7901 points_to = skip_typeref(points_to);
7903 if (is_type_incomplete(points_to)) {
7904 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7905 errorf(source_position,
7906 "arithmetic with pointer to incomplete type '%T' not allowed",
7909 } else if (warning.pointer_arith) {
7910 warningf(source_position,
7911 "pointer of type '%T' used in arithmetic",
7914 } else if (is_type_function(points_to)) {
7916 errorf(source_position,
7917 "arithmetic with pointer to function type '%T' not allowed",
7920 } else if (warning.pointer_arith) {
7921 warningf(source_position,
7922 "pointer to a function '%T' used in arithmetic",
7929 static bool is_lvalue(const expression_t *expression)
7931 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7932 switch (expression->kind) {
7933 case EXPR_ARRAY_ACCESS:
7934 case EXPR_COMPOUND_LITERAL:
7935 case EXPR_REFERENCE:
7937 case EXPR_UNARY_DEREFERENCE:
7941 type_t *type = skip_typeref(expression->base.type);
7943 /* ISO/IEC 14882:1998(E) §3.10:3 */
7944 is_type_reference(type) ||
7945 /* Claim it is an lvalue, if the type is invalid. There was a parse
7946 * error before, which maybe prevented properly recognizing it as
7948 !is_type_valid(type);
7953 static void semantic_incdec(unary_expression_t *expression)
7955 type_t *const orig_type = expression->value->base.type;
7956 type_t *const type = skip_typeref(orig_type);
7957 if (is_type_pointer(type)) {
7958 if (!check_pointer_arithmetic(&expression->base.source_position,
7962 } else if (!is_type_real(type) && is_type_valid(type)) {
7963 /* TODO: improve error message */
7964 errorf(&expression->base.source_position,
7965 "operation needs an arithmetic or pointer type");
7968 if (!is_lvalue(expression->value)) {
7969 /* TODO: improve error message */
7970 errorf(&expression->base.source_position, "lvalue required as operand");
7972 expression->base.type = orig_type;
7975 static void semantic_unexpr_arithmetic(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_arithmetic(type)) {
7980 if (is_type_valid(type)) {
7981 /* TODO: improve error message */
7982 errorf(&expression->base.source_position,
7983 "operation needs an arithmetic type");
7988 expression->base.type = orig_type;
7991 static void semantic_unexpr_plus(unary_expression_t *expression)
7993 semantic_unexpr_arithmetic(expression);
7994 if (warning.traditional)
7995 warningf(&expression->base.source_position,
7996 "traditional C rejects the unary plus operator");
7999 static void semantic_not(unary_expression_t *expression)
8001 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8002 semantic_condition(expression->value, "operand of !");
8003 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8006 static void semantic_unexpr_integer(unary_expression_t *expression)
8008 type_t *const orig_type = expression->value->base.type;
8009 type_t *const type = skip_typeref(orig_type);
8010 if (!is_type_integer(type)) {
8011 if (is_type_valid(type)) {
8012 errorf(&expression->base.source_position,
8013 "operand of ~ must be of integer type");
8018 expression->base.type = orig_type;
8021 static void semantic_dereference(unary_expression_t *expression)
8023 type_t *const orig_type = expression->value->base.type;
8024 type_t *const type = skip_typeref(orig_type);
8025 if (!is_type_pointer(type)) {
8026 if (is_type_valid(type)) {
8027 errorf(&expression->base.source_position,
8028 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8033 type_t *result_type = type->pointer.points_to;
8034 result_type = automatic_type_conversion(result_type);
8035 expression->base.type = result_type;
8039 * Record that an address is taken (expression represents an lvalue).
8041 * @param expression the expression
8042 * @param may_be_register if true, the expression might be an register
8044 static void set_address_taken(expression_t *expression, bool may_be_register)
8046 if (expression->kind != EXPR_REFERENCE)
8049 entity_t *const entity = expression->reference.entity;
8051 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8054 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8055 && !may_be_register) {
8056 errorf(&expression->base.source_position,
8057 "address of register %s '%Y' requested",
8058 get_entity_kind_name(entity->kind), entity->base.symbol);
8061 if (entity->kind == ENTITY_VARIABLE) {
8062 entity->variable.address_taken = true;
8064 assert(entity->kind == ENTITY_PARAMETER);
8065 entity->parameter.address_taken = true;
8070 * Check the semantic of the address taken expression.
8072 static void semantic_take_addr(unary_expression_t *expression)
8074 expression_t *value = expression->value;
8075 value->base.type = revert_automatic_type_conversion(value);
8077 type_t *orig_type = value->base.type;
8078 type_t *type = skip_typeref(orig_type);
8079 if (!is_type_valid(type))
8083 if (!is_lvalue(value)) {
8084 errorf(&expression->base.source_position, "'&' requires an lvalue");
8086 if (type->kind == TYPE_BITFIELD) {
8087 errorf(&expression->base.source_position,
8088 "'&' not allowed on object with bitfield type '%T'",
8092 set_address_taken(value, false);
8094 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8097 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8098 static expression_t *parse_##unexpression_type(void) \
8100 expression_t *unary_expression \
8101 = allocate_expression_zero(unexpression_type); \
8103 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8105 sfunc(&unary_expression->unary); \
8107 return unary_expression; \
8110 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8111 semantic_unexpr_arithmetic)
8112 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8113 semantic_unexpr_plus)
8114 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8116 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8117 semantic_dereference)
8118 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8120 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8121 semantic_unexpr_integer)
8122 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8124 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8127 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8129 static expression_t *parse_##unexpression_type(expression_t *left) \
8131 expression_t *unary_expression \
8132 = allocate_expression_zero(unexpression_type); \
8134 unary_expression->unary.value = left; \
8136 sfunc(&unary_expression->unary); \
8138 return unary_expression; \
8141 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8142 EXPR_UNARY_POSTFIX_INCREMENT,
8144 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8145 EXPR_UNARY_POSTFIX_DECREMENT,
8148 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8150 /* TODO: handle complex + imaginary types */
8152 type_left = get_unqualified_type(type_left);
8153 type_right = get_unqualified_type(type_right);
8155 /* §6.3.1.8 Usual arithmetic conversions */
8156 if (type_left == type_long_double || type_right == type_long_double) {
8157 return type_long_double;
8158 } else if (type_left == type_double || type_right == type_double) {
8160 } else if (type_left == type_float || type_right == type_float) {
8164 type_left = promote_integer(type_left);
8165 type_right = promote_integer(type_right);
8167 if (type_left == type_right)
8170 bool const signed_left = is_type_signed(type_left);
8171 bool const signed_right = is_type_signed(type_right);
8172 int const rank_left = get_rank(type_left);
8173 int const rank_right = get_rank(type_right);
8175 if (signed_left == signed_right)
8176 return rank_left >= rank_right ? type_left : type_right;
8185 u_rank = rank_right;
8186 u_type = type_right;
8188 s_rank = rank_right;
8189 s_type = type_right;
8194 if (u_rank >= s_rank)
8197 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8199 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8200 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8204 case ATOMIC_TYPE_INT: return type_unsigned_int;
8205 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8206 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8208 default: panic("invalid atomic type");
8213 * Check the semantic restrictions for a binary expression.
8215 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8217 expression_t *const left = expression->left;
8218 expression_t *const right = expression->right;
8219 type_t *const orig_type_left = left->base.type;
8220 type_t *const orig_type_right = right->base.type;
8221 type_t *const type_left = skip_typeref(orig_type_left);
8222 type_t *const type_right = skip_typeref(orig_type_right);
8224 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8225 /* TODO: improve error message */
8226 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8227 errorf(&expression->base.source_position,
8228 "operation needs arithmetic types");
8233 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8234 expression->left = create_implicit_cast(left, arithmetic_type);
8235 expression->right = create_implicit_cast(right, arithmetic_type);
8236 expression->base.type = arithmetic_type;
8239 static void warn_div_by_zero(binary_expression_t const *const expression)
8241 if (!warning.div_by_zero ||
8242 !is_type_integer(expression->base.type))
8245 expression_t const *const right = expression->right;
8246 /* The type of the right operand can be different for /= */
8247 if (is_type_integer(right->base.type) &&
8248 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8249 !fold_constant_to_bool(right)) {
8250 warningf(&expression->base.source_position, "division by zero");
8255 * Check the semantic restrictions for a div/mod expression.
8257 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8259 semantic_binexpr_arithmetic(expression);
8260 warn_div_by_zero(expression);
8263 static void warn_addsub_in_shift(const expression_t *const expr)
8265 if (expr->base.parenthesized)
8269 switch (expr->kind) {
8270 case EXPR_BINARY_ADD: op = '+'; break;
8271 case EXPR_BINARY_SUB: op = '-'; break;
8275 warningf(&expr->base.source_position,
8276 "suggest parentheses around '%c' inside shift", op);
8279 static bool semantic_shift(binary_expression_t *expression)
8281 expression_t *const left = expression->left;
8282 expression_t *const right = expression->right;
8283 type_t *const orig_type_left = left->base.type;
8284 type_t *const orig_type_right = right->base.type;
8285 type_t * type_left = skip_typeref(orig_type_left);
8286 type_t * type_right = skip_typeref(orig_type_right);
8288 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8289 /* TODO: improve error message */
8290 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8291 errorf(&expression->base.source_position,
8292 "operands of shift operation must have integer types");
8297 type_left = promote_integer(type_left);
8299 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8300 long count = fold_constant_to_int(right);
8302 warningf(&right->base.source_position,
8303 "shift count must be non-negative");
8304 } else if ((unsigned long)count >=
8305 get_atomic_type_size(type_left->atomic.akind) * 8) {
8306 warningf(&right->base.source_position,
8307 "shift count must be less than type width");
8311 type_right = promote_integer(type_right);
8312 expression->right = create_implicit_cast(right, type_right);
8317 static void semantic_shift_op(binary_expression_t *expression)
8319 expression_t *const left = expression->left;
8320 expression_t *const right = expression->right;
8322 if (!semantic_shift(expression))
8325 if (warning.parentheses) {
8326 warn_addsub_in_shift(left);
8327 warn_addsub_in_shift(right);
8330 type_t *const orig_type_left = left->base.type;
8331 type_t * type_left = skip_typeref(orig_type_left);
8333 type_left = promote_integer(type_left);
8334 expression->left = create_implicit_cast(left, type_left);
8335 expression->base.type = type_left;
8338 static void semantic_add(binary_expression_t *expression)
8340 expression_t *const left = expression->left;
8341 expression_t *const right = expression->right;
8342 type_t *const orig_type_left = left->base.type;
8343 type_t *const orig_type_right = right->base.type;
8344 type_t *const type_left = skip_typeref(orig_type_left);
8345 type_t *const type_right = skip_typeref(orig_type_right);
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_right) && is_type_integer(type_left)) {
8358 check_pointer_arithmetic(&expression->base.source_position,
8359 type_right, orig_type_right);
8360 expression->base.type = type_right;
8361 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8362 errorf(&expression->base.source_position,
8363 "invalid operands to binary + ('%T', '%T')",
8364 orig_type_left, orig_type_right);
8368 static void semantic_sub(binary_expression_t *expression)
8370 expression_t *const left = expression->left;
8371 expression_t *const right = expression->right;
8372 type_t *const orig_type_left = left->base.type;
8373 type_t *const orig_type_right = right->base.type;
8374 type_t *const type_left = skip_typeref(orig_type_left);
8375 type_t *const type_right = skip_typeref(orig_type_right);
8376 source_position_t const *const pos = &expression->base.source_position;
8379 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8380 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8381 expression->left = create_implicit_cast(left, arithmetic_type);
8382 expression->right = create_implicit_cast(right, arithmetic_type);
8383 expression->base.type = arithmetic_type;
8384 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8385 check_pointer_arithmetic(&expression->base.source_position,
8386 type_left, orig_type_left);
8387 expression->base.type = type_left;
8388 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8389 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8390 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8391 if (!types_compatible(unqual_left, unqual_right)) {
8393 "subtracting pointers to incompatible types '%T' and '%T'",
8394 orig_type_left, orig_type_right);
8395 } else if (!is_type_object(unqual_left)) {
8396 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8397 errorf(pos, "subtracting pointers to non-object types '%T'",
8399 } else if (warning.other) {
8400 warningf(pos, "subtracting pointers to void");
8403 expression->base.type = type_ptrdiff_t;
8404 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8405 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8406 orig_type_left, orig_type_right);
8410 static void warn_string_literal_address(expression_t const* expr)
8412 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8413 expr = expr->unary.value;
8414 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8416 expr = expr->unary.value;
8419 if (expr->kind == EXPR_STRING_LITERAL
8420 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8421 warningf(&expr->base.source_position,
8422 "comparison with string literal results in unspecified behaviour");
8426 static void warn_comparison_in_comparison(const expression_t *const expr)
8428 if (expr->base.parenthesized)
8430 switch (expr->base.kind) {
8431 case EXPR_BINARY_LESS:
8432 case EXPR_BINARY_GREATER:
8433 case EXPR_BINARY_LESSEQUAL:
8434 case EXPR_BINARY_GREATEREQUAL:
8435 case EXPR_BINARY_NOTEQUAL:
8436 case EXPR_BINARY_EQUAL:
8437 warningf(&expr->base.source_position,
8438 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8445 static bool maybe_negative(expression_t const *const expr)
8447 switch (is_constant_expression(expr)) {
8448 case EXPR_CLASS_ERROR: return false;
8449 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8450 default: return true;
8455 * Check the semantics of comparison expressions.
8457 * @param expression The expression to check.
8459 static void semantic_comparison(binary_expression_t *expression)
8461 expression_t *left = expression->left;
8462 expression_t *right = expression->right;
8464 if (warning.address) {
8465 warn_string_literal_address(left);
8466 warn_string_literal_address(right);
8468 expression_t const* const func_left = get_reference_address(left);
8469 if (func_left != NULL && is_null_pointer_constant(right)) {
8470 warningf(&expression->base.source_position,
8471 "the address of '%Y' will never be NULL",
8472 func_left->reference.entity->base.symbol);
8475 expression_t const* const func_right = get_reference_address(right);
8476 if (func_right != NULL && is_null_pointer_constant(right)) {
8477 warningf(&expression->base.source_position,
8478 "the address of '%Y' will never be NULL",
8479 func_right->reference.entity->base.symbol);
8483 if (warning.parentheses) {
8484 warn_comparison_in_comparison(left);
8485 warn_comparison_in_comparison(right);
8488 type_t *orig_type_left = left->base.type;
8489 type_t *orig_type_right = right->base.type;
8490 type_t *type_left = skip_typeref(orig_type_left);
8491 type_t *type_right = skip_typeref(orig_type_right);
8493 /* TODO non-arithmetic types */
8494 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8495 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8497 /* test for signed vs unsigned compares */
8498 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8499 bool const signed_left = is_type_signed(type_left);
8500 bool const signed_right = is_type_signed(type_right);
8501 if (signed_left != signed_right) {
8502 /* FIXME long long needs better const folding magic */
8503 /* TODO check whether constant value can be represented by other type */
8504 if ((signed_left && maybe_negative(left)) ||
8505 (signed_right && maybe_negative(right))) {
8506 warningf(&expression->base.source_position,
8507 "comparison between signed and unsigned");
8512 expression->left = create_implicit_cast(left, arithmetic_type);
8513 expression->right = create_implicit_cast(right, arithmetic_type);
8514 expression->base.type = arithmetic_type;
8515 if (warning.float_equal &&
8516 (expression->base.kind == EXPR_BINARY_EQUAL ||
8517 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8518 is_type_float(arithmetic_type)) {
8519 warningf(&expression->base.source_position,
8520 "comparing floating point with == or != is unsafe");
8522 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8523 /* TODO check compatibility */
8524 } else if (is_type_pointer(type_left)) {
8525 expression->right = create_implicit_cast(right, type_left);
8526 } else if (is_type_pointer(type_right)) {
8527 expression->left = create_implicit_cast(left, type_right);
8528 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8529 type_error_incompatible("invalid operands in comparison",
8530 &expression->base.source_position,
8531 type_left, type_right);
8533 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8537 * Checks if a compound type has constant fields.
8539 static bool has_const_fields(const compound_type_t *type)
8541 compound_t *compound = type->compound;
8542 entity_t *entry = compound->members.entities;
8544 for (; entry != NULL; entry = entry->base.next) {
8545 if (!is_declaration(entry))
8548 const type_t *decl_type = skip_typeref(entry->declaration.type);
8549 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8556 static bool is_valid_assignment_lhs(expression_t const* const left)
8558 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8559 type_t *const type_left = skip_typeref(orig_type_left);
8561 if (!is_lvalue(left)) {
8562 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8567 if (left->kind == EXPR_REFERENCE
8568 && left->reference.entity->kind == ENTITY_FUNCTION) {
8569 errorf(HERE, "cannot assign to function '%E'", left);
8573 if (is_type_array(type_left)) {
8574 errorf(HERE, "cannot assign to array '%E'", left);
8577 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8578 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8582 if (is_type_incomplete(type_left)) {
8583 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8584 left, orig_type_left);
8587 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8588 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8589 left, orig_type_left);
8596 static void semantic_arithmetic_assign(binary_expression_t *expression)
8598 expression_t *left = expression->left;
8599 expression_t *right = expression->right;
8600 type_t *orig_type_left = left->base.type;
8601 type_t *orig_type_right = right->base.type;
8603 if (!is_valid_assignment_lhs(left))
8606 type_t *type_left = skip_typeref(orig_type_left);
8607 type_t *type_right = skip_typeref(orig_type_right);
8609 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8610 /* TODO: improve error message */
8611 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8612 errorf(&expression->base.source_position,
8613 "operation needs arithmetic types");
8618 /* combined instructions are tricky. We can't create an implicit cast on
8619 * the left side, because we need the uncasted form for the store.
8620 * The ast2firm pass has to know that left_type must be right_type
8621 * for the arithmetic operation and create a cast by itself */
8622 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8623 expression->right = create_implicit_cast(right, arithmetic_type);
8624 expression->base.type = type_left;
8627 static void semantic_divmod_assign(binary_expression_t *expression)
8629 semantic_arithmetic_assign(expression);
8630 warn_div_by_zero(expression);
8633 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8635 expression_t *const left = expression->left;
8636 expression_t *const right = expression->right;
8637 type_t *const orig_type_left = left->base.type;
8638 type_t *const orig_type_right = right->base.type;
8639 type_t *const type_left = skip_typeref(orig_type_left);
8640 type_t *const type_right = skip_typeref(orig_type_right);
8642 if (!is_valid_assignment_lhs(left))
8645 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8646 /* combined instructions are tricky. We can't create an implicit cast on
8647 * the left side, because we need the uncasted form for the store.
8648 * The ast2firm pass has to know that left_type must be right_type
8649 * for the arithmetic operation and create a cast by itself */
8650 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8651 expression->right = create_implicit_cast(right, arithmetic_type);
8652 expression->base.type = type_left;
8653 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8654 check_pointer_arithmetic(&expression->base.source_position,
8655 type_left, orig_type_left);
8656 expression->base.type = type_left;
8657 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8658 errorf(&expression->base.source_position,
8659 "incompatible types '%T' and '%T' in assignment",
8660 orig_type_left, orig_type_right);
8664 static void semantic_integer_assign(binary_expression_t *expression)
8666 expression_t *left = expression->left;
8667 expression_t *right = expression->right;
8668 type_t *orig_type_left = left->base.type;
8669 type_t *orig_type_right = right->base.type;
8671 if (!is_valid_assignment_lhs(left))
8674 type_t *type_left = skip_typeref(orig_type_left);
8675 type_t *type_right = skip_typeref(orig_type_right);
8677 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8678 /* TODO: improve error message */
8679 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8680 errorf(&expression->base.source_position,
8681 "operation needs integer types");
8686 /* combined instructions are tricky. We can't create an implicit cast on
8687 * the left side, because we need the uncasted form for the store.
8688 * The ast2firm pass has to know that left_type must be right_type
8689 * for the arithmetic operation and create a cast by itself */
8690 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8691 expression->right = create_implicit_cast(right, arithmetic_type);
8692 expression->base.type = type_left;
8695 static void semantic_shift_assign(binary_expression_t *expression)
8697 expression_t *left = expression->left;
8699 if (!is_valid_assignment_lhs(left))
8702 if (!semantic_shift(expression))
8705 expression->base.type = skip_typeref(left->base.type);
8708 static void warn_logical_and_within_or(const expression_t *const expr)
8710 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8712 if (expr->base.parenthesized)
8714 warningf(&expr->base.source_position,
8715 "suggest parentheses around && within ||");
8719 * Check the semantic restrictions of a logical expression.
8721 static void semantic_logical_op(binary_expression_t *expression)
8723 /* §6.5.13:2 Each of the operands shall have scalar type.
8724 * §6.5.14:2 Each of the operands shall have scalar type. */
8725 semantic_condition(expression->left, "left operand of logical operator");
8726 semantic_condition(expression->right, "right operand of logical operator");
8727 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8728 warning.parentheses) {
8729 warn_logical_and_within_or(expression->left);
8730 warn_logical_and_within_or(expression->right);
8732 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8736 * Check the semantic restrictions of a binary assign expression.
8738 static void semantic_binexpr_assign(binary_expression_t *expression)
8740 expression_t *left = expression->left;
8741 type_t *orig_type_left = left->base.type;
8743 if (!is_valid_assignment_lhs(left))
8746 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8747 report_assign_error(error, orig_type_left, expression->right,
8748 "assignment", &left->base.source_position);
8749 expression->right = create_implicit_cast(expression->right, orig_type_left);
8750 expression->base.type = orig_type_left;
8754 * Determine if the outermost operation (or parts thereof) of the given
8755 * expression has no effect in order to generate a warning about this fact.
8756 * Therefore in some cases this only examines some of the operands of the
8757 * expression (see comments in the function and examples below).
8759 * f() + 23; // warning, because + has no effect
8760 * x || f(); // no warning, because x controls execution of f()
8761 * x ? y : f(); // warning, because y has no effect
8762 * (void)x; // no warning to be able to suppress the warning
8763 * This function can NOT be used for an "expression has definitely no effect"-
8765 static bool expression_has_effect(const expression_t *const expr)
8767 switch (expr->kind) {
8768 case EXPR_UNKNOWN: break;
8769 case EXPR_INVALID: return true; /* do NOT warn */
8770 case EXPR_REFERENCE: return false;
8771 case EXPR_REFERENCE_ENUM_VALUE: return false;
8772 case EXPR_LABEL_ADDRESS: return false;
8774 /* suppress the warning for microsoft __noop operations */
8775 case EXPR_LITERAL_MS_NOOP: return true;
8776 case EXPR_LITERAL_BOOLEAN:
8777 case EXPR_LITERAL_CHARACTER:
8778 case EXPR_LITERAL_WIDE_CHARACTER:
8779 case EXPR_LITERAL_INTEGER:
8780 case EXPR_LITERAL_INTEGER_OCTAL:
8781 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8782 case EXPR_LITERAL_FLOATINGPOINT:
8783 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8784 case EXPR_STRING_LITERAL: return false;
8785 case EXPR_WIDE_STRING_LITERAL: return false;
8788 const call_expression_t *const call = &expr->call;
8789 if (call->function->kind != EXPR_REFERENCE)
8792 switch (call->function->reference.entity->function.btk) {
8793 /* FIXME: which builtins have no effect? */
8794 default: return true;
8798 /* Generate the warning if either the left or right hand side of a
8799 * conditional expression has no effect */
8800 case EXPR_CONDITIONAL: {
8801 conditional_expression_t const *const cond = &expr->conditional;
8802 expression_t const *const t = cond->true_expression;
8804 (t == NULL || expression_has_effect(t)) &&
8805 expression_has_effect(cond->false_expression);
8808 case EXPR_SELECT: return false;
8809 case EXPR_ARRAY_ACCESS: return false;
8810 case EXPR_SIZEOF: return false;
8811 case EXPR_CLASSIFY_TYPE: return false;
8812 case EXPR_ALIGNOF: return false;
8814 case EXPR_FUNCNAME: return false;
8815 case EXPR_BUILTIN_CONSTANT_P: return false;
8816 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8817 case EXPR_OFFSETOF: return false;
8818 case EXPR_VA_START: return true;
8819 case EXPR_VA_ARG: return true;
8820 case EXPR_VA_COPY: return true;
8821 case EXPR_STATEMENT: return true; // TODO
8822 case EXPR_COMPOUND_LITERAL: return false;
8824 case EXPR_UNARY_NEGATE: return false;
8825 case EXPR_UNARY_PLUS: return false;
8826 case EXPR_UNARY_BITWISE_NEGATE: return false;
8827 case EXPR_UNARY_NOT: return false;
8828 case EXPR_UNARY_DEREFERENCE: return false;
8829 case EXPR_UNARY_TAKE_ADDRESS: return false;
8830 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8831 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8832 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8833 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8835 /* Treat void casts as if they have an effect in order to being able to
8836 * suppress the warning */
8837 case EXPR_UNARY_CAST: {
8838 type_t *const type = skip_typeref(expr->base.type);
8839 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8842 case EXPR_UNARY_CAST_IMPLICIT: return true;
8843 case EXPR_UNARY_ASSUME: return true;
8844 case EXPR_UNARY_DELETE: return true;
8845 case EXPR_UNARY_DELETE_ARRAY: return true;
8846 case EXPR_UNARY_THROW: return true;
8848 case EXPR_BINARY_ADD: return false;
8849 case EXPR_BINARY_SUB: return false;
8850 case EXPR_BINARY_MUL: return false;
8851 case EXPR_BINARY_DIV: return false;
8852 case EXPR_BINARY_MOD: return false;
8853 case EXPR_BINARY_EQUAL: return false;
8854 case EXPR_BINARY_NOTEQUAL: return false;
8855 case EXPR_BINARY_LESS: return false;
8856 case EXPR_BINARY_LESSEQUAL: return false;
8857 case EXPR_BINARY_GREATER: return false;
8858 case EXPR_BINARY_GREATEREQUAL: return false;
8859 case EXPR_BINARY_BITWISE_AND: return false;
8860 case EXPR_BINARY_BITWISE_OR: return false;
8861 case EXPR_BINARY_BITWISE_XOR: return false;
8862 case EXPR_BINARY_SHIFTLEFT: return false;
8863 case EXPR_BINARY_SHIFTRIGHT: return false;
8864 case EXPR_BINARY_ASSIGN: return true;
8865 case EXPR_BINARY_MUL_ASSIGN: return true;
8866 case EXPR_BINARY_DIV_ASSIGN: return true;
8867 case EXPR_BINARY_MOD_ASSIGN: return true;
8868 case EXPR_BINARY_ADD_ASSIGN: return true;
8869 case EXPR_BINARY_SUB_ASSIGN: return true;
8870 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8871 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8872 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8873 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8874 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8876 /* Only examine the right hand side of && and ||, because the left hand
8877 * side already has the effect of controlling the execution of the right
8879 case EXPR_BINARY_LOGICAL_AND:
8880 case EXPR_BINARY_LOGICAL_OR:
8881 /* Only examine the right hand side of a comma expression, because the left
8882 * hand side has a separate warning */
8883 case EXPR_BINARY_COMMA:
8884 return expression_has_effect(expr->binary.right);
8886 case EXPR_BINARY_ISGREATER: return false;
8887 case EXPR_BINARY_ISGREATEREQUAL: return false;
8888 case EXPR_BINARY_ISLESS: return false;
8889 case EXPR_BINARY_ISLESSEQUAL: return false;
8890 case EXPR_BINARY_ISLESSGREATER: return false;
8891 case EXPR_BINARY_ISUNORDERED: return false;
8894 internal_errorf(HERE, "unexpected expression");
8897 static void semantic_comma(binary_expression_t *expression)
8899 if (warning.unused_value) {
8900 const expression_t *const left = expression->left;
8901 if (!expression_has_effect(left)) {
8902 warningf(&left->base.source_position,
8903 "left-hand operand of comma expression has no effect");
8906 expression->base.type = expression->right->base.type;
8910 * @param prec_r precedence of the right operand
8912 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8913 static expression_t *parse_##binexpression_type(expression_t *left) \
8915 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8916 binexpr->binary.left = left; \
8919 expression_t *right = parse_subexpression(prec_r); \
8921 binexpr->binary.right = right; \
8922 sfunc(&binexpr->binary); \
8927 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8928 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8929 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8930 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8931 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8932 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8933 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8934 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8935 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8936 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8937 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8938 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8939 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8940 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8941 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8942 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8943 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8944 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8945 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8946 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8947 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8948 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8949 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8950 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8951 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8952 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8953 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8954 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8955 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8956 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8959 static expression_t *parse_subexpression(precedence_t precedence)
8961 if (token.type < 0) {
8962 return expected_expression_error();
8965 expression_parser_function_t *parser
8966 = &expression_parsers[token.type];
8967 source_position_t source_position = token.source_position;
8970 if (parser->parser != NULL) {
8971 left = parser->parser();
8973 left = parse_primary_expression();
8975 assert(left != NULL);
8976 left->base.source_position = source_position;
8979 if (token.type < 0) {
8980 return expected_expression_error();
8983 parser = &expression_parsers[token.type];
8984 if (parser->infix_parser == NULL)
8986 if (parser->infix_precedence < precedence)
8989 left = parser->infix_parser(left);
8991 assert(left != NULL);
8992 assert(left->kind != EXPR_UNKNOWN);
8993 left->base.source_position = source_position;
9000 * Parse an expression.
9002 static expression_t *parse_expression(void)
9004 return parse_subexpression(PREC_EXPRESSION);
9008 * Register a parser for a prefix-like operator.
9010 * @param parser the parser function
9011 * @param token_type the token type of the prefix token
9013 static void register_expression_parser(parse_expression_function parser,
9016 expression_parser_function_t *entry = &expression_parsers[token_type];
9018 if (entry->parser != NULL) {
9019 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9020 panic("trying to register multiple expression parsers for a token");
9022 entry->parser = parser;
9026 * Register a parser for an infix operator with given precedence.
9028 * @param parser the parser function
9029 * @param token_type the token type of the infix operator
9030 * @param precedence the precedence of the operator
9032 static void register_infix_parser(parse_expression_infix_function parser,
9033 int token_type, precedence_t precedence)
9035 expression_parser_function_t *entry = &expression_parsers[token_type];
9037 if (entry->infix_parser != NULL) {
9038 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9039 panic("trying to register multiple infix expression parsers for a "
9042 entry->infix_parser = parser;
9043 entry->infix_precedence = precedence;
9047 * Initialize the expression parsers.
9049 static void init_expression_parsers(void)
9051 memset(&expression_parsers, 0, sizeof(expression_parsers));
9053 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9054 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9055 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9056 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9057 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9058 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9059 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9060 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9061 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9062 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9063 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9064 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9065 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9066 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9067 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9068 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9069 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9070 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9071 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9072 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9073 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9074 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9075 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9076 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9077 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9078 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9079 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9080 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9081 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9082 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9083 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9084 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9085 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9086 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9087 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9088 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9089 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9091 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9092 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9093 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9094 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9095 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9096 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9097 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9098 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9099 register_expression_parser(parse_sizeof, T_sizeof);
9100 register_expression_parser(parse_alignof, T___alignof__);
9101 register_expression_parser(parse_extension, T___extension__);
9102 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9103 register_expression_parser(parse_delete, T_delete);
9104 register_expression_parser(parse_throw, T_throw);
9108 * Parse a asm statement arguments specification.
9110 static asm_argument_t *parse_asm_arguments(bool is_out)
9112 asm_argument_t *result = NULL;
9113 asm_argument_t **anchor = &result;
9115 while (token.type == T_STRING_LITERAL || token.type == '[') {
9116 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9117 memset(argument, 0, sizeof(argument[0]));
9120 if (token.type != T_IDENTIFIER) {
9121 parse_error_expected("while parsing asm argument",
9122 T_IDENTIFIER, NULL);
9125 argument->symbol = token.symbol;
9127 expect(']', end_error);
9130 argument->constraints = parse_string_literals();
9131 expect('(', end_error);
9132 add_anchor_token(')');
9133 expression_t *expression = parse_expression();
9134 rem_anchor_token(')');
9136 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9137 * change size or type representation (e.g. int -> long is ok, but
9138 * int -> float is not) */
9139 if (expression->kind == EXPR_UNARY_CAST) {
9140 type_t *const type = expression->base.type;
9141 type_kind_t const kind = type->kind;
9142 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9145 if (kind == TYPE_ATOMIC) {
9146 atomic_type_kind_t const akind = type->atomic.akind;
9147 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9148 size = get_atomic_type_size(akind);
9150 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9151 size = get_atomic_type_size(get_intptr_kind());
9155 expression_t *const value = expression->unary.value;
9156 type_t *const value_type = value->base.type;
9157 type_kind_t const value_kind = value_type->kind;
9159 unsigned value_flags;
9160 unsigned value_size;
9161 if (value_kind == TYPE_ATOMIC) {
9162 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9163 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9164 value_size = get_atomic_type_size(value_akind);
9165 } else if (value_kind == TYPE_POINTER) {
9166 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9167 value_size = get_atomic_type_size(get_intptr_kind());
9172 if (value_flags != flags || value_size != size)
9176 } while (expression->kind == EXPR_UNARY_CAST);
9180 if (!is_lvalue(expression)) {
9181 errorf(&expression->base.source_position,
9182 "asm output argument is not an lvalue");
9185 if (argument->constraints.begin[0] == '=')
9186 determine_lhs_ent(expression, NULL);
9188 mark_vars_read(expression, NULL);
9190 mark_vars_read(expression, NULL);
9192 argument->expression = expression;
9193 expect(')', end_error);
9195 set_address_taken(expression, true);
9198 anchor = &argument->next;
9210 * Parse a asm statement clobber specification.
9212 static asm_clobber_t *parse_asm_clobbers(void)
9214 asm_clobber_t *result = NULL;
9215 asm_clobber_t **anchor = &result;
9217 while (token.type == T_STRING_LITERAL) {
9218 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9219 clobber->clobber = parse_string_literals();
9222 anchor = &clobber->next;
9232 * Parse an asm statement.
9234 static statement_t *parse_asm_statement(void)
9236 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9237 asm_statement_t *asm_statement = &statement->asms;
9241 if (next_if(T_volatile))
9242 asm_statement->is_volatile = true;
9244 expect('(', end_error);
9245 add_anchor_token(')');
9246 if (token.type != T_STRING_LITERAL) {
9247 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9250 asm_statement->asm_text = parse_string_literals();
9252 add_anchor_token(':');
9253 if (!next_if(':')) {
9254 rem_anchor_token(':');
9258 asm_statement->outputs = parse_asm_arguments(true);
9259 if (!next_if(':')) {
9260 rem_anchor_token(':');
9264 asm_statement->inputs = parse_asm_arguments(false);
9265 if (!next_if(':')) {
9266 rem_anchor_token(':');
9269 rem_anchor_token(':');
9271 asm_statement->clobbers = parse_asm_clobbers();
9274 rem_anchor_token(')');
9275 expect(')', end_error);
9276 expect(';', end_error);
9278 if (asm_statement->outputs == NULL) {
9279 /* GCC: An 'asm' instruction without any output operands will be treated
9280 * identically to a volatile 'asm' instruction. */
9281 asm_statement->is_volatile = true;
9286 return create_invalid_statement();
9289 static statement_t *parse_label_inner_statement(char const *const label, bool const eat_empty_stmt)
9291 statement_t *inner_stmt;
9292 switch (token.type) {
9294 errorf(HERE, "%s at end of compound statement", label);
9295 inner_stmt = create_invalid_statement();
9299 if (eat_empty_stmt) {
9300 /* Eat an empty statement here, to avoid the warning about an empty
9301 * statement after a label. label:; is commonly used to have a label
9302 * before a closing brace. */
9303 inner_stmt = create_empty_statement();
9310 inner_stmt = parse_statement();
9311 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9312 errorf(&inner_stmt->base.source_position, "declaration after %s", label);
9320 * Parse a case statement.
9322 static statement_t *parse_case_statement(void)
9324 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9325 source_position_t *const pos = &statement->base.source_position;
9329 expression_t *const expression = parse_expression();
9330 statement->case_label.expression = expression;
9331 expression_classification_t const expr_class = is_constant_expression(expression);
9332 if (expr_class != EXPR_CLASS_CONSTANT) {
9333 if (expr_class != EXPR_CLASS_ERROR) {
9334 errorf(pos, "case label does not reduce to an integer constant");
9336 statement->case_label.is_bad = true;
9338 long const val = fold_constant_to_int(expression);
9339 statement->case_label.first_case = val;
9340 statement->case_label.last_case = val;
9344 if (next_if(T_DOTDOTDOT)) {
9345 expression_t *const end_range = parse_expression();
9346 statement->case_label.end_range = end_range;
9347 expression_classification_t const end_class = is_constant_expression(end_range);
9348 if (end_class != EXPR_CLASS_CONSTANT) {
9349 if (end_class != EXPR_CLASS_ERROR) {
9350 errorf(pos, "case range does not reduce to an integer constant");
9352 statement->case_label.is_bad = true;
9354 long const val = fold_constant_to_int(end_range);
9355 statement->case_label.last_case = val;
9357 if (warning.other && val < statement->case_label.first_case) {
9358 statement->case_label.is_empty_range = true;
9359 warningf(pos, "empty range specified");
9365 PUSH_PARENT(statement);
9367 expect(':', end_error);
9370 if (current_switch != NULL) {
9371 if (! statement->case_label.is_bad) {
9372 /* Check for duplicate case values */
9373 case_label_statement_t *c = &statement->case_label;
9374 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9375 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9378 if (c->last_case < l->first_case || c->first_case > l->last_case)
9381 errorf(pos, "duplicate case value (previously used %P)",
9382 &l->base.source_position);
9386 /* link all cases into the switch statement */
9387 if (current_switch->last_case == NULL) {
9388 current_switch->first_case = &statement->case_label;
9390 current_switch->last_case->next = &statement->case_label;
9392 current_switch->last_case = &statement->case_label;
9394 errorf(pos, "case label not within a switch statement");
9397 statement->case_label.statement = parse_label_inner_statement("case label", false);
9404 * Parse a default statement.
9406 static statement_t *parse_default_statement(void)
9408 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9412 PUSH_PARENT(statement);
9414 expect(':', end_error);
9417 if (current_switch != NULL) {
9418 const case_label_statement_t *def_label = current_switch->default_label;
9419 if (def_label != NULL) {
9420 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9421 &def_label->base.source_position);
9423 current_switch->default_label = &statement->case_label;
9425 /* link all cases into the switch statement */
9426 if (current_switch->last_case == NULL) {
9427 current_switch->first_case = &statement->case_label;
9429 current_switch->last_case->next = &statement->case_label;
9431 current_switch->last_case = &statement->case_label;
9434 errorf(&statement->base.source_position,
9435 "'default' label not within a switch statement");
9438 statement->case_label.statement = parse_label_inner_statement("default label", false);
9445 * Parse a label statement.
9447 static statement_t *parse_label_statement(void)
9449 assert(token.type == T_IDENTIFIER);
9450 symbol_t *symbol = token.symbol;
9451 label_t *label = get_label(symbol);
9453 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9454 statement->label.label = label;
9458 PUSH_PARENT(statement);
9460 /* if statement is already set then the label is defined twice,
9461 * otherwise it was just mentioned in a goto/local label declaration so far
9463 if (label->statement != NULL) {
9464 errorf(HERE, "duplicate label '%Y' (declared %P)",
9465 symbol, &label->base.source_position);
9467 label->base.source_position = token.source_position;
9468 label->statement = statement;
9473 statement->label.statement = parse_label_inner_statement("label", true);
9475 /* remember the labels in a list for later checking */
9476 *label_anchor = &statement->label;
9477 label_anchor = &statement->label.next;
9484 * Parse an if statement.
9486 static statement_t *parse_if(void)
9488 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9492 PUSH_PARENT(statement);
9494 add_anchor_token('{');
9496 expect('(', end_error);
9497 add_anchor_token(')');
9498 expression_t *const expr = parse_expression();
9499 statement->ifs.condition = expr;
9500 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9502 semantic_condition(expr, "condition of 'if'-statment");
9503 mark_vars_read(expr, NULL);
9504 rem_anchor_token(')');
9505 expect(')', end_error);
9508 rem_anchor_token('{');
9510 add_anchor_token(T_else);
9511 statement_t *const true_stmt = parse_statement();
9512 statement->ifs.true_statement = true_stmt;
9513 rem_anchor_token(T_else);
9515 if (next_if(T_else)) {
9516 statement->ifs.false_statement = parse_statement();
9517 } else if (warning.parentheses &&
9518 true_stmt->kind == STATEMENT_IF &&
9519 true_stmt->ifs.false_statement != NULL) {
9520 warningf(&true_stmt->base.source_position,
9521 "suggest explicit braces to avoid ambiguous 'else'");
9529 * Check that all enums are handled in a switch.
9531 * @param statement the switch statement to check
9533 static void check_enum_cases(const switch_statement_t *statement)
9535 const type_t *type = skip_typeref(statement->expression->base.type);
9536 if (! is_type_enum(type))
9538 const enum_type_t *enumt = &type->enumt;
9540 /* if we have a default, no warnings */
9541 if (statement->default_label != NULL)
9544 /* FIXME: calculation of value should be done while parsing */
9545 /* TODO: quadratic algorithm here. Change to an n log n one */
9546 long last_value = -1;
9547 const entity_t *entry = enumt->enume->base.next;
9548 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9549 entry = entry->base.next) {
9550 const expression_t *expression = entry->enum_value.value;
9551 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9553 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9554 if (l->expression == NULL)
9556 if (l->first_case <= value && value <= l->last_case) {
9562 warningf(&statement->base.source_position,
9563 "enumeration value '%Y' not handled in switch",
9564 entry->base.symbol);
9571 * Parse a switch statement.
9573 static statement_t *parse_switch(void)
9575 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9579 PUSH_PARENT(statement);
9581 expect('(', end_error);
9582 add_anchor_token(')');
9583 expression_t *const expr = parse_expression();
9584 mark_vars_read(expr, NULL);
9585 type_t * type = skip_typeref(expr->base.type);
9586 if (is_type_integer(type)) {
9587 type = promote_integer(type);
9588 if (warning.traditional) {
9589 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9590 warningf(&expr->base.source_position,
9591 "'%T' switch expression not converted to '%T' in ISO C",
9595 } else if (is_type_valid(type)) {
9596 errorf(&expr->base.source_position,
9597 "switch quantity is not an integer, but '%T'", type);
9598 type = type_error_type;
9600 statement->switchs.expression = create_implicit_cast(expr, type);
9601 expect(')', end_error);
9602 rem_anchor_token(')');
9604 switch_statement_t *rem = current_switch;
9605 current_switch = &statement->switchs;
9606 statement->switchs.body = parse_statement();
9607 current_switch = rem;
9609 if (warning.switch_default &&
9610 statement->switchs.default_label == NULL) {
9611 warningf(&statement->base.source_position, "switch has no default case");
9613 if (warning.switch_enum)
9614 check_enum_cases(&statement->switchs);
9620 return create_invalid_statement();
9623 static statement_t *parse_loop_body(statement_t *const loop)
9625 statement_t *const rem = current_loop;
9626 current_loop = loop;
9628 statement_t *const body = parse_statement();
9635 * Parse a while statement.
9637 static statement_t *parse_while(void)
9639 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9643 PUSH_PARENT(statement);
9645 expect('(', end_error);
9646 add_anchor_token(')');
9647 expression_t *const cond = parse_expression();
9648 statement->whiles.condition = cond;
9649 /* §6.8.5:2 The controlling expression of an iteration statement shall
9650 * have scalar type. */
9651 semantic_condition(cond, "condition of 'while'-statement");
9652 mark_vars_read(cond, NULL);
9653 rem_anchor_token(')');
9654 expect(')', end_error);
9656 statement->whiles.body = parse_loop_body(statement);
9662 return create_invalid_statement();
9666 * Parse a do statement.
9668 static statement_t *parse_do(void)
9670 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9674 PUSH_PARENT(statement);
9676 add_anchor_token(T_while);
9677 statement->do_while.body = parse_loop_body(statement);
9678 rem_anchor_token(T_while);
9680 expect(T_while, end_error);
9681 expect('(', end_error);
9682 add_anchor_token(')');
9683 expression_t *const cond = parse_expression();
9684 statement->do_while.condition = cond;
9685 /* §6.8.5:2 The controlling expression of an iteration statement shall
9686 * have scalar type. */
9687 semantic_condition(cond, "condition of 'do-while'-statement");
9688 mark_vars_read(cond, NULL);
9689 rem_anchor_token(')');
9690 expect(')', end_error);
9691 expect(';', end_error);
9697 return create_invalid_statement();
9701 * Parse a for statement.
9703 static statement_t *parse_for(void)
9705 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9709 expect('(', end_error1);
9710 add_anchor_token(')');
9712 PUSH_PARENT(statement);
9714 size_t const top = environment_top();
9715 scope_t *old_scope = scope_push(&statement->fors.scope);
9717 bool old_gcc_extension = in_gcc_extension;
9718 while (next_if(T___extension__)) {
9719 in_gcc_extension = true;
9723 } else if (is_declaration_specifier(&token, false)) {
9724 parse_declaration(record_entity, DECL_FLAGS_NONE);
9726 add_anchor_token(';');
9727 expression_t *const init = parse_expression();
9728 statement->fors.initialisation = init;
9729 mark_vars_read(init, ENT_ANY);
9730 if (warning.unused_value && !expression_has_effect(init)) {
9731 warningf(&init->base.source_position,
9732 "initialisation of 'for'-statement has no effect");
9734 rem_anchor_token(';');
9735 expect(';', end_error2);
9737 in_gcc_extension = old_gcc_extension;
9739 if (token.type != ';') {
9740 add_anchor_token(';');
9741 expression_t *const cond = parse_expression();
9742 statement->fors.condition = cond;
9743 /* §6.8.5:2 The controlling expression of an iteration statement
9744 * shall have scalar type. */
9745 semantic_condition(cond, "condition of 'for'-statement");
9746 mark_vars_read(cond, NULL);
9747 rem_anchor_token(';');
9749 expect(';', end_error2);
9750 if (token.type != ')') {
9751 expression_t *const step = parse_expression();
9752 statement->fors.step = step;
9753 mark_vars_read(step, ENT_ANY);
9754 if (warning.unused_value && !expression_has_effect(step)) {
9755 warningf(&step->base.source_position,
9756 "step of 'for'-statement has no effect");
9759 expect(')', end_error2);
9760 rem_anchor_token(')');
9761 statement->fors.body = parse_loop_body(statement);
9763 assert(current_scope == &statement->fors.scope);
9764 scope_pop(old_scope);
9765 environment_pop_to(top);
9772 rem_anchor_token(')');
9773 assert(current_scope == &statement->fors.scope);
9774 scope_pop(old_scope);
9775 environment_pop_to(top);
9779 return create_invalid_statement();
9783 * Parse a goto statement.
9785 static statement_t *parse_goto(void)
9787 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9790 if (GNU_MODE && next_if('*')) {
9791 expression_t *expression = parse_expression();
9792 mark_vars_read(expression, NULL);
9794 /* Argh: although documentation says the expression must be of type void*,
9795 * gcc accepts anything that can be casted into void* without error */
9796 type_t *type = expression->base.type;
9798 if (type != type_error_type) {
9799 if (!is_type_pointer(type) && !is_type_integer(type)) {
9800 errorf(&expression->base.source_position,
9801 "cannot convert to a pointer type");
9802 } else if (warning.other && type != type_void_ptr) {
9803 warningf(&expression->base.source_position,
9804 "type of computed goto expression should be 'void*' not '%T'", type);
9806 expression = create_implicit_cast(expression, type_void_ptr);
9809 statement->gotos.expression = expression;
9810 } else if (token.type == T_IDENTIFIER) {
9811 symbol_t *symbol = token.symbol;
9813 statement->gotos.label = get_label(symbol);
9816 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9818 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9820 return create_invalid_statement();
9823 /* remember the goto's in a list for later checking */
9824 *goto_anchor = &statement->gotos;
9825 goto_anchor = &statement->gotos.next;
9827 expect(';', end_error);
9834 * Parse a continue statement.
9836 static statement_t *parse_continue(void)
9838 if (current_loop == NULL) {
9839 errorf(HERE, "continue statement not within loop");
9842 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9845 expect(';', end_error);
9852 * Parse a break statement.
9854 static statement_t *parse_break(void)
9856 if (current_switch == NULL && current_loop == NULL) {
9857 errorf(HERE, "break statement not within loop or switch");
9860 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9863 expect(';', end_error);
9870 * Parse a __leave statement.
9872 static statement_t *parse_leave_statement(void)
9874 if (current_try == NULL) {
9875 errorf(HERE, "__leave statement not within __try");
9878 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9881 expect(';', end_error);
9888 * Check if a given entity represents a local variable.
9890 static bool is_local_variable(const entity_t *entity)
9892 if (entity->kind != ENTITY_VARIABLE)
9895 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9896 case STORAGE_CLASS_AUTO:
9897 case STORAGE_CLASS_REGISTER: {
9898 const type_t *type = skip_typeref(entity->declaration.type);
9899 if (is_type_function(type)) {
9911 * Check if a given expression represents a local variable.
9913 static bool expression_is_local_variable(const expression_t *expression)
9915 if (expression->base.kind != EXPR_REFERENCE) {
9918 const entity_t *entity = expression->reference.entity;
9919 return is_local_variable(entity);
9923 * Check if a given expression represents a local variable and
9924 * return its declaration then, else return NULL.
9926 entity_t *expression_is_variable(const expression_t *expression)
9928 if (expression->base.kind != EXPR_REFERENCE) {
9931 entity_t *entity = expression->reference.entity;
9932 if (entity->kind != ENTITY_VARIABLE)
9939 * Parse a return statement.
9941 static statement_t *parse_return(void)
9945 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9947 expression_t *return_value = NULL;
9948 if (token.type != ';') {
9949 return_value = parse_expression();
9950 mark_vars_read(return_value, NULL);
9953 const type_t *const func_type = skip_typeref(current_function->base.type);
9954 assert(is_type_function(func_type));
9955 type_t *const return_type = skip_typeref(func_type->function.return_type);
9957 source_position_t const *const pos = &statement->base.source_position;
9958 if (return_value != NULL) {
9959 type_t *return_value_type = skip_typeref(return_value->base.type);
9961 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9962 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9963 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9964 /* Only warn in C mode, because GCC does the same */
9965 if (c_mode & _CXX || strict_mode) {
9967 "'return' with a value, in function returning 'void'");
9968 } else if (warning.other) {
9970 "'return' with a value, in function returning 'void'");
9972 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9973 /* Only warn in C mode, because GCC does the same */
9976 "'return' with expression in function returning 'void'");
9977 } else if (warning.other) {
9979 "'return' with expression in function returning 'void'");
9983 assign_error_t error = semantic_assign(return_type, return_value);
9984 report_assign_error(error, return_type, return_value, "'return'",
9987 return_value = create_implicit_cast(return_value, return_type);
9988 /* check for returning address of a local var */
9989 if (warning.other && return_value != NULL
9990 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9991 const expression_t *expression = return_value->unary.value;
9992 if (expression_is_local_variable(expression)) {
9993 warningf(pos, "function returns address of local variable");
9996 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9997 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9998 if (c_mode & _CXX || strict_mode) {
10000 "'return' without value, in function returning non-void");
10003 "'return' without value, in function returning non-void");
10006 statement->returns.value = return_value;
10008 expect(';', end_error);
10015 * Parse a declaration statement.
10017 static statement_t *parse_declaration_statement(void)
10019 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10021 entity_t *before = current_scope->last_entity;
10023 parse_external_declaration();
10025 parse_declaration(record_entity, DECL_FLAGS_NONE);
10028 declaration_statement_t *const decl = &statement->declaration;
10029 entity_t *const begin =
10030 before != NULL ? before->base.next : current_scope->entities;
10031 decl->declarations_begin = begin;
10032 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10038 * Parse an expression statement, ie. expr ';'.
10040 static statement_t *parse_expression_statement(void)
10042 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10044 expression_t *const expr = parse_expression();
10045 statement->expression.expression = expr;
10046 mark_vars_read(expr, ENT_ANY);
10048 expect(';', end_error);
10055 * Parse a microsoft __try { } __finally { } or
10056 * __try{ } __except() { }
10058 static statement_t *parse_ms_try_statment(void)
10060 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10063 PUSH_PARENT(statement);
10065 ms_try_statement_t *rem = current_try;
10066 current_try = &statement->ms_try;
10067 statement->ms_try.try_statement = parse_compound_statement(false);
10072 if (next_if(T___except)) {
10073 expect('(', end_error);
10074 add_anchor_token(')');
10075 expression_t *const expr = parse_expression();
10076 mark_vars_read(expr, NULL);
10077 type_t * type = skip_typeref(expr->base.type);
10078 if (is_type_integer(type)) {
10079 type = promote_integer(type);
10080 } else if (is_type_valid(type)) {
10081 errorf(&expr->base.source_position,
10082 "__expect expression is not an integer, but '%T'", type);
10083 type = type_error_type;
10085 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10086 rem_anchor_token(')');
10087 expect(')', end_error);
10088 statement->ms_try.final_statement = parse_compound_statement(false);
10089 } else if (next_if(T__finally)) {
10090 statement->ms_try.final_statement = parse_compound_statement(false);
10092 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10093 return create_invalid_statement();
10097 return create_invalid_statement();
10100 static statement_t *parse_empty_statement(void)
10102 if (warning.empty_statement) {
10103 warningf(HERE, "statement is empty");
10105 statement_t *const statement = create_empty_statement();
10110 static statement_t *parse_local_label_declaration(void)
10112 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10116 entity_t *begin = NULL;
10117 entity_t *end = NULL;
10118 entity_t **anchor = &begin;
10120 if (token.type != T_IDENTIFIER) {
10121 parse_error_expected("while parsing local label declaration",
10122 T_IDENTIFIER, NULL);
10125 symbol_t *symbol = token.symbol;
10126 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10127 if (entity != NULL && entity->base.parent_scope == current_scope) {
10128 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10129 symbol, &entity->base.source_position);
10131 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10133 entity->base.parent_scope = current_scope;
10134 entity->base.namespc = NAMESPACE_LABEL;
10135 entity->base.source_position = token.source_position;
10136 entity->base.symbol = symbol;
10139 anchor = &entity->base.next;
10142 environment_push(entity);
10145 } while (next_if(','));
10146 expect(';', end_error);
10148 statement->declaration.declarations_begin = begin;
10149 statement->declaration.declarations_end = end;
10153 static void parse_namespace_definition(void)
10157 entity_t *entity = NULL;
10158 symbol_t *symbol = NULL;
10160 if (token.type == T_IDENTIFIER) {
10161 symbol = token.symbol;
10164 entity = get_entity(symbol, NAMESPACE_NORMAL);
10166 && entity->kind != ENTITY_NAMESPACE
10167 && entity->base.parent_scope == current_scope) {
10168 if (!is_error_entity(entity)) {
10169 error_redefined_as_different_kind(&token.source_position,
10170 entity, ENTITY_NAMESPACE);
10176 if (entity == NULL) {
10177 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10178 entity->base.symbol = symbol;
10179 entity->base.source_position = token.source_position;
10180 entity->base.namespc = NAMESPACE_NORMAL;
10181 entity->base.parent_scope = current_scope;
10184 if (token.type == '=') {
10185 /* TODO: parse namespace alias */
10186 panic("namespace alias definition not supported yet");
10189 environment_push(entity);
10190 append_entity(current_scope, entity);
10192 size_t const top = environment_top();
10193 scope_t *old_scope = scope_push(&entity->namespacee.members);
10195 entity_t *old_current_entity = current_entity;
10196 current_entity = entity;
10198 expect('{', end_error);
10200 expect('}', end_error);
10203 assert(current_scope == &entity->namespacee.members);
10204 assert(current_entity == entity);
10205 current_entity = old_current_entity;
10206 scope_pop(old_scope);
10207 environment_pop_to(top);
10211 * Parse a statement.
10212 * There's also parse_statement() which additionally checks for
10213 * "statement has no effect" warnings
10215 static statement_t *intern_parse_statement(void)
10217 statement_t *statement = NULL;
10219 /* declaration or statement */
10220 add_anchor_token(';');
10221 switch (token.type) {
10222 case T_IDENTIFIER: {
10223 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10224 if (la1_type == ':') {
10225 statement = parse_label_statement();
10226 } else if (is_typedef_symbol(token.symbol)) {
10227 statement = parse_declaration_statement();
10229 /* it's an identifier, the grammar says this must be an
10230 * expression statement. However it is common that users mistype
10231 * declaration types, so we guess a bit here to improve robustness
10232 * for incorrect programs */
10233 switch (la1_type) {
10236 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10238 statement = parse_expression_statement();
10242 statement = parse_declaration_statement();
10250 case T___extension__:
10251 /* This can be a prefix to a declaration or an expression statement.
10252 * We simply eat it now and parse the rest with tail recursion. */
10253 while (next_if(T___extension__)) {}
10254 bool old_gcc_extension = in_gcc_extension;
10255 in_gcc_extension = true;
10256 statement = intern_parse_statement();
10257 in_gcc_extension = old_gcc_extension;
10261 statement = parse_declaration_statement();
10265 statement = parse_local_label_declaration();
10268 case ';': statement = parse_empty_statement(); break;
10269 case '{': statement = parse_compound_statement(false); break;
10270 case T___leave: statement = parse_leave_statement(); break;
10271 case T___try: statement = parse_ms_try_statment(); break;
10272 case T_asm: statement = parse_asm_statement(); break;
10273 case T_break: statement = parse_break(); break;
10274 case T_case: statement = parse_case_statement(); break;
10275 case T_continue: statement = parse_continue(); break;
10276 case T_default: statement = parse_default_statement(); break;
10277 case T_do: statement = parse_do(); break;
10278 case T_for: statement = parse_for(); break;
10279 case T_goto: statement = parse_goto(); break;
10280 case T_if: statement = parse_if(); break;
10281 case T_return: statement = parse_return(); break;
10282 case T_switch: statement = parse_switch(); break;
10283 case T_while: statement = parse_while(); break;
10286 statement = parse_expression_statement();
10290 errorf(HERE, "unexpected token %K while parsing statement", &token);
10291 statement = create_invalid_statement();
10296 rem_anchor_token(';');
10298 assert(statement != NULL
10299 && statement->base.source_position.input_name != NULL);
10305 * parse a statement and emits "statement has no effect" warning if needed
10306 * (This is really a wrapper around intern_parse_statement with check for 1
10307 * single warning. It is needed, because for statement expressions we have
10308 * to avoid the warning on the last statement)
10310 static statement_t *parse_statement(void)
10312 statement_t *statement = intern_parse_statement();
10314 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10315 expression_t *expression = statement->expression.expression;
10316 if (!expression_has_effect(expression)) {
10317 warningf(&expression->base.source_position,
10318 "statement has no effect");
10326 * Parse a compound statement.
10328 static statement_t *parse_compound_statement(bool inside_expression_statement)
10330 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10332 PUSH_PARENT(statement);
10335 add_anchor_token('}');
10336 /* tokens, which can start a statement */
10337 /* TODO MS, __builtin_FOO */
10338 add_anchor_token('!');
10339 add_anchor_token('&');
10340 add_anchor_token('(');
10341 add_anchor_token('*');
10342 add_anchor_token('+');
10343 add_anchor_token('-');
10344 add_anchor_token('{');
10345 add_anchor_token('~');
10346 add_anchor_token(T_CHARACTER_CONSTANT);
10347 add_anchor_token(T_COLONCOLON);
10348 add_anchor_token(T_FLOATINGPOINT);
10349 add_anchor_token(T_IDENTIFIER);
10350 add_anchor_token(T_INTEGER);
10351 add_anchor_token(T_MINUSMINUS);
10352 add_anchor_token(T_PLUSPLUS);
10353 add_anchor_token(T_STRING_LITERAL);
10354 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10355 add_anchor_token(T_WIDE_STRING_LITERAL);
10356 add_anchor_token(T__Bool);
10357 add_anchor_token(T__Complex);
10358 add_anchor_token(T__Imaginary);
10359 add_anchor_token(T___FUNCTION__);
10360 add_anchor_token(T___PRETTY_FUNCTION__);
10361 add_anchor_token(T___alignof__);
10362 add_anchor_token(T___attribute__);
10363 add_anchor_token(T___builtin_va_start);
10364 add_anchor_token(T___extension__);
10365 add_anchor_token(T___func__);
10366 add_anchor_token(T___imag__);
10367 add_anchor_token(T___label__);
10368 add_anchor_token(T___real__);
10369 add_anchor_token(T___thread);
10370 add_anchor_token(T_asm);
10371 add_anchor_token(T_auto);
10372 add_anchor_token(T_bool);
10373 add_anchor_token(T_break);
10374 add_anchor_token(T_case);
10375 add_anchor_token(T_char);
10376 add_anchor_token(T_class);
10377 add_anchor_token(T_const);
10378 add_anchor_token(T_const_cast);
10379 add_anchor_token(T_continue);
10380 add_anchor_token(T_default);
10381 add_anchor_token(T_delete);
10382 add_anchor_token(T_double);
10383 add_anchor_token(T_do);
10384 add_anchor_token(T_dynamic_cast);
10385 add_anchor_token(T_enum);
10386 add_anchor_token(T_extern);
10387 add_anchor_token(T_false);
10388 add_anchor_token(T_float);
10389 add_anchor_token(T_for);
10390 add_anchor_token(T_goto);
10391 add_anchor_token(T_if);
10392 add_anchor_token(T_inline);
10393 add_anchor_token(T_int);
10394 add_anchor_token(T_long);
10395 add_anchor_token(T_new);
10396 add_anchor_token(T_operator);
10397 add_anchor_token(T_register);
10398 add_anchor_token(T_reinterpret_cast);
10399 add_anchor_token(T_restrict);
10400 add_anchor_token(T_return);
10401 add_anchor_token(T_short);
10402 add_anchor_token(T_signed);
10403 add_anchor_token(T_sizeof);
10404 add_anchor_token(T_static);
10405 add_anchor_token(T_static_cast);
10406 add_anchor_token(T_struct);
10407 add_anchor_token(T_switch);
10408 add_anchor_token(T_template);
10409 add_anchor_token(T_this);
10410 add_anchor_token(T_throw);
10411 add_anchor_token(T_true);
10412 add_anchor_token(T_try);
10413 add_anchor_token(T_typedef);
10414 add_anchor_token(T_typeid);
10415 add_anchor_token(T_typename);
10416 add_anchor_token(T_typeof);
10417 add_anchor_token(T_union);
10418 add_anchor_token(T_unsigned);
10419 add_anchor_token(T_using);
10420 add_anchor_token(T_void);
10421 add_anchor_token(T_volatile);
10422 add_anchor_token(T_wchar_t);
10423 add_anchor_token(T_while);
10425 size_t const top = environment_top();
10426 scope_t *old_scope = scope_push(&statement->compound.scope);
10428 statement_t **anchor = &statement->compound.statements;
10429 bool only_decls_so_far = true;
10430 while (token.type != '}') {
10431 if (token.type == T_EOF) {
10432 errorf(&statement->base.source_position,
10433 "EOF while parsing compound statement");
10436 statement_t *sub_statement = intern_parse_statement();
10437 if (is_invalid_statement(sub_statement)) {
10438 /* an error occurred. if we are at an anchor, return */
10444 if (warning.declaration_after_statement) {
10445 if (sub_statement->kind != STATEMENT_DECLARATION) {
10446 only_decls_so_far = false;
10447 } else if (!only_decls_so_far) {
10448 warningf(&sub_statement->base.source_position,
10449 "ISO C90 forbids mixed declarations and code");
10453 *anchor = sub_statement;
10455 while (sub_statement->base.next != NULL)
10456 sub_statement = sub_statement->base.next;
10458 anchor = &sub_statement->base.next;
10462 /* look over all statements again to produce no effect warnings */
10463 if (warning.unused_value) {
10464 statement_t *sub_statement = statement->compound.statements;
10465 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10466 if (sub_statement->kind != STATEMENT_EXPRESSION)
10468 /* don't emit a warning for the last expression in an expression
10469 * statement as it has always an effect */
10470 if (inside_expression_statement && sub_statement->base.next == NULL)
10473 expression_t *expression = sub_statement->expression.expression;
10474 if (!expression_has_effect(expression)) {
10475 warningf(&expression->base.source_position,
10476 "statement has no effect");
10482 rem_anchor_token(T_while);
10483 rem_anchor_token(T_wchar_t);
10484 rem_anchor_token(T_volatile);
10485 rem_anchor_token(T_void);
10486 rem_anchor_token(T_using);
10487 rem_anchor_token(T_unsigned);
10488 rem_anchor_token(T_union);
10489 rem_anchor_token(T_typeof);
10490 rem_anchor_token(T_typename);
10491 rem_anchor_token(T_typeid);
10492 rem_anchor_token(T_typedef);
10493 rem_anchor_token(T_try);
10494 rem_anchor_token(T_true);
10495 rem_anchor_token(T_throw);
10496 rem_anchor_token(T_this);
10497 rem_anchor_token(T_template);
10498 rem_anchor_token(T_switch);
10499 rem_anchor_token(T_struct);
10500 rem_anchor_token(T_static_cast);
10501 rem_anchor_token(T_static);
10502 rem_anchor_token(T_sizeof);
10503 rem_anchor_token(T_signed);
10504 rem_anchor_token(T_short);
10505 rem_anchor_token(T_return);
10506 rem_anchor_token(T_restrict);
10507 rem_anchor_token(T_reinterpret_cast);
10508 rem_anchor_token(T_register);
10509 rem_anchor_token(T_operator);
10510 rem_anchor_token(T_new);
10511 rem_anchor_token(T_long);
10512 rem_anchor_token(T_int);
10513 rem_anchor_token(T_inline);
10514 rem_anchor_token(T_if);
10515 rem_anchor_token(T_goto);
10516 rem_anchor_token(T_for);
10517 rem_anchor_token(T_float);
10518 rem_anchor_token(T_false);
10519 rem_anchor_token(T_extern);
10520 rem_anchor_token(T_enum);
10521 rem_anchor_token(T_dynamic_cast);
10522 rem_anchor_token(T_do);
10523 rem_anchor_token(T_double);
10524 rem_anchor_token(T_delete);
10525 rem_anchor_token(T_default);
10526 rem_anchor_token(T_continue);
10527 rem_anchor_token(T_const_cast);
10528 rem_anchor_token(T_const);
10529 rem_anchor_token(T_class);
10530 rem_anchor_token(T_char);
10531 rem_anchor_token(T_case);
10532 rem_anchor_token(T_break);
10533 rem_anchor_token(T_bool);
10534 rem_anchor_token(T_auto);
10535 rem_anchor_token(T_asm);
10536 rem_anchor_token(T___thread);
10537 rem_anchor_token(T___real__);
10538 rem_anchor_token(T___label__);
10539 rem_anchor_token(T___imag__);
10540 rem_anchor_token(T___func__);
10541 rem_anchor_token(T___extension__);
10542 rem_anchor_token(T___builtin_va_start);
10543 rem_anchor_token(T___attribute__);
10544 rem_anchor_token(T___alignof__);
10545 rem_anchor_token(T___PRETTY_FUNCTION__);
10546 rem_anchor_token(T___FUNCTION__);
10547 rem_anchor_token(T__Imaginary);
10548 rem_anchor_token(T__Complex);
10549 rem_anchor_token(T__Bool);
10550 rem_anchor_token(T_WIDE_STRING_LITERAL);
10551 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10552 rem_anchor_token(T_STRING_LITERAL);
10553 rem_anchor_token(T_PLUSPLUS);
10554 rem_anchor_token(T_MINUSMINUS);
10555 rem_anchor_token(T_INTEGER);
10556 rem_anchor_token(T_IDENTIFIER);
10557 rem_anchor_token(T_FLOATINGPOINT);
10558 rem_anchor_token(T_COLONCOLON);
10559 rem_anchor_token(T_CHARACTER_CONSTANT);
10560 rem_anchor_token('~');
10561 rem_anchor_token('{');
10562 rem_anchor_token('-');
10563 rem_anchor_token('+');
10564 rem_anchor_token('*');
10565 rem_anchor_token('(');
10566 rem_anchor_token('&');
10567 rem_anchor_token('!');
10568 rem_anchor_token('}');
10569 assert(current_scope == &statement->compound.scope);
10570 scope_pop(old_scope);
10571 environment_pop_to(top);
10578 * Check for unused global static functions and variables
10580 static void check_unused_globals(void)
10582 if (!warning.unused_function && !warning.unused_variable)
10585 for (const entity_t *entity = file_scope->entities; entity != NULL;
10586 entity = entity->base.next) {
10587 if (!is_declaration(entity))
10590 const declaration_t *declaration = &entity->declaration;
10591 if (declaration->used ||
10592 declaration->modifiers & DM_UNUSED ||
10593 declaration->modifiers & DM_USED ||
10594 declaration->storage_class != STORAGE_CLASS_STATIC)
10597 type_t *const type = declaration->type;
10599 if (entity->kind == ENTITY_FUNCTION) {
10600 /* inhibit warning for static inline functions */
10601 if (entity->function.is_inline)
10604 s = entity->function.statement != NULL ? "defined" : "declared";
10609 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10610 type, declaration->base.symbol, s);
10614 static void parse_global_asm(void)
10616 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10619 expect('(', end_error);
10621 statement->asms.asm_text = parse_string_literals();
10622 statement->base.next = unit->global_asm;
10623 unit->global_asm = statement;
10625 expect(')', end_error);
10626 expect(';', end_error);
10631 static void parse_linkage_specification(void)
10634 assert(token.type == T_STRING_LITERAL);
10636 const char *linkage = parse_string_literals().begin;
10638 linkage_kind_t old_linkage = current_linkage;
10639 linkage_kind_t new_linkage;
10640 if (strcmp(linkage, "C") == 0) {
10641 new_linkage = LINKAGE_C;
10642 } else if (strcmp(linkage, "C++") == 0) {
10643 new_linkage = LINKAGE_CXX;
10645 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10646 new_linkage = LINKAGE_INVALID;
10648 current_linkage = new_linkage;
10650 if (next_if('{')) {
10652 expect('}', end_error);
10658 assert(current_linkage == new_linkage);
10659 current_linkage = old_linkage;
10662 static void parse_external(void)
10664 switch (token.type) {
10665 DECLARATION_START_NO_EXTERN
10667 case T___extension__:
10668 /* tokens below are for implicit int */
10669 case '&': /* & x; -> int& x; (and error later, because C++ has no
10671 case '*': /* * x; -> int* x; */
10672 case '(': /* (x); -> int (x); */
10673 parse_external_declaration();
10677 if (look_ahead(1)->type == T_STRING_LITERAL) {
10678 parse_linkage_specification();
10680 parse_external_declaration();
10685 parse_global_asm();
10689 parse_namespace_definition();
10693 if (!strict_mode) {
10695 warningf(HERE, "stray ';' outside of function");
10702 errorf(HERE, "stray %K outside of function", &token);
10703 if (token.type == '(' || token.type == '{' || token.type == '[')
10704 eat_until_matching_token(token.type);
10710 static void parse_externals(void)
10712 add_anchor_token('}');
10713 add_anchor_token(T_EOF);
10716 unsigned char token_anchor_copy[T_LAST_TOKEN];
10717 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10720 while (token.type != T_EOF && token.type != '}') {
10722 bool anchor_leak = false;
10723 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10724 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10726 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10727 anchor_leak = true;
10730 if (in_gcc_extension) {
10731 errorf(HERE, "Leaked __extension__");
10732 anchor_leak = true;
10742 rem_anchor_token(T_EOF);
10743 rem_anchor_token('}');
10747 * Parse a translation unit.
10749 static void parse_translation_unit(void)
10751 add_anchor_token(T_EOF);
10756 if (token.type == T_EOF)
10759 errorf(HERE, "stray %K outside of function", &token);
10760 if (token.type == '(' || token.type == '{' || token.type == '[')
10761 eat_until_matching_token(token.type);
10769 * @return the translation unit or NULL if errors occurred.
10771 void start_parsing(void)
10773 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10774 label_stack = NEW_ARR_F(stack_entry_t, 0);
10775 diagnostic_count = 0;
10779 print_to_file(stderr);
10781 assert(unit == NULL);
10782 unit = allocate_ast_zero(sizeof(unit[0]));
10784 assert(file_scope == NULL);
10785 file_scope = &unit->scope;
10787 assert(current_scope == NULL);
10788 scope_push(&unit->scope);
10790 create_gnu_builtins();
10792 create_microsoft_intrinsics();
10795 translation_unit_t *finish_parsing(void)
10797 assert(current_scope == &unit->scope);
10800 assert(file_scope == &unit->scope);
10801 check_unused_globals();
10804 DEL_ARR_F(environment_stack);
10805 DEL_ARR_F(label_stack);
10807 translation_unit_t *result = unit;
10812 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10813 * are given length one. */
10814 static void complete_incomplete_arrays(void)
10816 size_t n = ARR_LEN(incomplete_arrays);
10817 for (size_t i = 0; i != n; ++i) {
10818 declaration_t *const decl = incomplete_arrays[i];
10819 type_t *const orig_type = decl->type;
10820 type_t *const type = skip_typeref(orig_type);
10822 if (!is_type_incomplete(type))
10825 if (warning.other) {
10826 warningf(&decl->base.source_position,
10827 "array '%#T' assumed to have one element",
10828 orig_type, decl->base.symbol);
10831 type_t *const new_type = duplicate_type(type);
10832 new_type->array.size_constant = true;
10833 new_type->array.has_implicit_size = true;
10834 new_type->array.size = 1;
10836 type_t *const result = identify_new_type(new_type);
10838 decl->type = result;
10842 void prepare_main_collect2(entity_t *entity)
10844 // create call to __main
10845 symbol_t *symbol = symbol_table_insert("__main");
10846 entity_t *subsubmain_ent
10847 = create_implicit_function(symbol, &builtin_source_position);
10849 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10850 type_t *ftype = subsubmain_ent->declaration.type;
10851 ref->base.source_position = builtin_source_position;
10852 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10853 ref->reference.entity = subsubmain_ent;
10855 expression_t *call = allocate_expression_zero(EXPR_CALL);
10856 call->base.source_position = builtin_source_position;
10857 call->base.type = type_void;
10858 call->call.function = ref;
10860 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10861 expr_statement->base.source_position = builtin_source_position;
10862 expr_statement->expression.expression = call;
10864 statement_t *statement = entity->function.statement;
10865 assert(statement->kind == STATEMENT_COMPOUND);
10866 compound_statement_t *compounds = &statement->compound;
10868 expr_statement->base.next = compounds->statements;
10869 compounds->statements = expr_statement;
10874 lookahead_bufpos = 0;
10875 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10878 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10879 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10880 parse_translation_unit();
10881 complete_incomplete_arrays();
10882 DEL_ARR_F(incomplete_arrays);
10883 incomplete_arrays = NULL;
10887 * Initialize the parser.
10889 void init_parser(void)
10891 sym_anonymous = symbol_table_insert("<anonymous>");
10893 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10895 init_expression_parsers();
10896 obstack_init(&temp_obst);
10898 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10899 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10903 * Terminate the parser.
10905 void exit_parser(void)
10907 obstack_free(&temp_obst, NULL);