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;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_PARENT(stmt) \
115 statement_t *const prev_parent = current_parent; \
116 ((void)(current_parent = (stmt)))
117 #define POP_PARENT ((void)(current_parent = prev_parent))
119 /** special symbol used for anonymous entities. */
120 static symbol_t *sym_anonymous = NULL;
122 /** The token anchor set */
123 static unsigned char token_anchor_set[T_LAST_TOKEN];
125 /** The current source position. */
126 #define HERE (&token.source_position)
128 /** true if we are in GCC mode. */
129 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
131 static statement_t *parse_compound_statement(bool inside_expression_statement);
132 static statement_t *parse_statement(void);
134 static expression_t *parse_subexpression(precedence_t);
135 static expression_t *parse_expression(void);
136 static type_t *parse_typename(void);
137 static void parse_externals(void);
138 static void parse_external(void);
140 static void parse_compound_type_entries(compound_t *compound_declaration);
142 static void check_call_argument(type_t *expected_type,
143 call_argument_t *argument, unsigned pos);
145 typedef enum declarator_flags_t {
147 DECL_MAY_BE_ABSTRACT = 1U << 0,
148 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
149 DECL_IS_PARAMETER = 1U << 2
150 } declarator_flags_t;
152 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
153 declarator_flags_t flags);
155 static void semantic_comparison(binary_expression_t *expression);
157 #define STORAGE_CLASSES \
158 STORAGE_CLASSES_NO_EXTERN \
161 #define STORAGE_CLASSES_NO_EXTERN \
168 #define TYPE_QUALIFIERS \
173 case T__forceinline: \
174 case T___attribute__:
176 #define COMPLEX_SPECIFIERS \
178 #define IMAGINARY_SPECIFIERS \
181 #define TYPE_SPECIFIERS \
183 case T___builtin_va_list: \
208 #define DECLARATION_START \
213 #define DECLARATION_START_NO_EXTERN \
214 STORAGE_CLASSES_NO_EXTERN \
218 #define EXPRESSION_START \
227 case T_CHARACTER_CONSTANT: \
228 case T_FLOATINGPOINT: \
229 case T_FLOATINGPOINT_HEXADECIMAL: \
231 case T_INTEGER_HEXADECIMAL: \
232 case T_INTEGER_OCTAL: \
235 case T_STRING_LITERAL: \
236 case T_WIDE_CHARACTER_CONSTANT: \
237 case T_WIDE_STRING_LITERAL: \
238 case T___FUNCDNAME__: \
239 case T___FUNCSIG__: \
240 case T___FUNCTION__: \
241 case T___PRETTY_FUNCTION__: \
242 case T___alignof__: \
243 case T___builtin_classify_type: \
244 case T___builtin_constant_p: \
245 case T___builtin_isgreater: \
246 case T___builtin_isgreaterequal: \
247 case T___builtin_isless: \
248 case T___builtin_islessequal: \
249 case T___builtin_islessgreater: \
250 case T___builtin_isunordered: \
251 case T___builtin_offsetof: \
252 case T___builtin_va_arg: \
253 case T___builtin_va_copy: \
254 case T___builtin_va_start: \
265 * Returns the size of a statement node.
267 * @param kind the statement kind
269 static size_t get_statement_struct_size(statement_kind_t kind)
271 static const size_t sizes[] = {
272 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
273 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
274 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
275 [STATEMENT_RETURN] = sizeof(return_statement_t),
276 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
277 [STATEMENT_IF] = sizeof(if_statement_t),
278 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
279 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
280 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
281 [STATEMENT_BREAK] = sizeof(statement_base_t),
282 [STATEMENT_GOTO] = sizeof(goto_statement_t),
283 [STATEMENT_LABEL] = sizeof(label_statement_t),
284 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
285 [STATEMENT_WHILE] = sizeof(while_statement_t),
286 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
287 [STATEMENT_FOR] = sizeof(for_statement_t),
288 [STATEMENT_ASM] = sizeof(asm_statement_t),
289 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
290 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
292 assert((size_t)kind < lengthof(sizes));
293 assert(sizes[kind] != 0);
298 * Returns the size of an expression node.
300 * @param kind the expression kind
302 static size_t get_expression_struct_size(expression_kind_t kind)
304 static const size_t sizes[] = {
305 [EXPR_INVALID] = sizeof(expression_base_t),
306 [EXPR_REFERENCE] = sizeof(reference_expression_t),
307 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
308 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
309 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
310 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
311 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
312 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
314 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
316 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
317 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
318 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
319 [EXPR_CALL] = sizeof(call_expression_t),
320 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
321 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
322 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
323 [EXPR_SELECT] = sizeof(select_expression_t),
324 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
325 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
326 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
327 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
328 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
329 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
330 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
331 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
332 [EXPR_VA_START] = sizeof(va_start_expression_t),
333 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
334 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
335 [EXPR_STATEMENT] = sizeof(statement_expression_t),
336 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
338 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
339 return sizes[EXPR_UNARY_FIRST];
341 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
342 return sizes[EXPR_BINARY_FIRST];
344 assert((size_t)kind < lengthof(sizes));
345 assert(sizes[kind] != 0);
350 * Allocate a statement node of given kind and initialize all
351 * fields with zero. Sets its source position to the position
352 * of the current token.
354 static statement_t *allocate_statement_zero(statement_kind_t kind)
356 size_t size = get_statement_struct_size(kind);
357 statement_t *res = allocate_ast_zero(size);
359 res->base.kind = kind;
360 res->base.parent = current_parent;
361 res->base.source_position = token.source_position;
366 * Allocate an expression node of given kind and initialize all
369 * @param kind the kind of the expression to allocate
371 static expression_t *allocate_expression_zero(expression_kind_t kind)
373 size_t size = get_expression_struct_size(kind);
374 expression_t *res = allocate_ast_zero(size);
376 res->base.kind = kind;
377 res->base.type = type_error_type;
378 res->base.source_position = token.source_position;
383 * Creates a new invalid expression at the source position
384 * of the current token.
386 static expression_t *create_invalid_expression(void)
388 return allocate_expression_zero(EXPR_INVALID);
392 * Creates a new invalid statement.
394 static statement_t *create_invalid_statement(void)
396 return allocate_statement_zero(STATEMENT_INVALID);
400 * Allocate a new empty statement.
402 static statement_t *create_empty_statement(void)
404 return allocate_statement_zero(STATEMENT_EMPTY);
407 static function_parameter_t *allocate_parameter(type_t *const type)
409 function_parameter_t *const param
410 = obstack_alloc(type_obst, sizeof(*param));
411 memset(param, 0, sizeof(*param));
417 * Returns the size of an initializer node.
419 * @param kind the initializer kind
421 static size_t get_initializer_size(initializer_kind_t kind)
423 static const size_t sizes[] = {
424 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
425 [INITIALIZER_STRING] = sizeof(initializer_string_t),
426 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
427 [INITIALIZER_LIST] = sizeof(initializer_list_t),
428 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
430 assert((size_t)kind < lengthof(sizes));
431 assert(sizes[kind] != 0);
436 * Allocate an initializer node of given kind and initialize all
439 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
441 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
448 * Returns the index of the top element of the environment stack.
450 static size_t environment_top(void)
452 return ARR_LEN(environment_stack);
456 * Returns the index of the top element of the global label stack.
458 static size_t label_top(void)
460 return ARR_LEN(label_stack);
464 * Return the next token.
466 static inline void next_token(void)
468 token = lookahead_buffer[lookahead_bufpos];
469 lookahead_buffer[lookahead_bufpos] = lexer_token;
472 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
475 print_token(stderr, &token);
476 fprintf(stderr, "\n");
480 static inline bool next_if(int const type)
482 if (token.type == type) {
491 * Return the next token with a given lookahead.
493 static inline const token_t *look_ahead(size_t num)
495 assert(0 < num && num <= MAX_LOOKAHEAD);
496 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
497 return &lookahead_buffer[pos];
501 * Adds a token type to the token type anchor set (a multi-set).
503 static void add_anchor_token(int token_type)
505 assert(0 <= token_type && token_type < T_LAST_TOKEN);
506 ++token_anchor_set[token_type];
510 * Set the number of tokens types of the given type
511 * to zero and return the old count.
513 static int save_and_reset_anchor_state(int token_type)
515 assert(0 <= token_type && token_type < T_LAST_TOKEN);
516 int count = token_anchor_set[token_type];
517 token_anchor_set[token_type] = 0;
522 * Restore the number of token types to the given count.
524 static void restore_anchor_state(int token_type, int count)
526 assert(0 <= token_type && token_type < T_LAST_TOKEN);
527 token_anchor_set[token_type] = count;
531 * Remove a token type from the token type anchor set (a multi-set).
533 static void rem_anchor_token(int token_type)
535 assert(0 <= token_type && token_type < T_LAST_TOKEN);
536 assert(token_anchor_set[token_type] != 0);
537 --token_anchor_set[token_type];
541 * Return true if the token type of the current token is
544 static bool at_anchor(void)
548 return token_anchor_set[token.type];
552 * Eat tokens until a matching token type is found.
554 static void eat_until_matching_token(int type)
558 case '(': end_token = ')'; break;
559 case '{': end_token = '}'; break;
560 case '[': end_token = ']'; break;
561 default: end_token = type; break;
564 unsigned parenthesis_count = 0;
565 unsigned brace_count = 0;
566 unsigned bracket_count = 0;
567 while (token.type != end_token ||
568 parenthesis_count != 0 ||
570 bracket_count != 0) {
571 switch (token.type) {
573 case '(': ++parenthesis_count; break;
574 case '{': ++brace_count; break;
575 case '[': ++bracket_count; break;
578 if (parenthesis_count > 0)
588 if (bracket_count > 0)
591 if (token.type == end_token &&
592 parenthesis_count == 0 &&
606 * Eat input tokens until an anchor is found.
608 static void eat_until_anchor(void)
610 while (token_anchor_set[token.type] == 0) {
611 if (token.type == '(' || token.type == '{' || token.type == '[')
612 eat_until_matching_token(token.type);
618 * Eat a whole block from input tokens.
620 static void eat_block(void)
622 eat_until_matching_token('{');
626 #define eat(token_type) (assert(token.type == (token_type)), next_token())
629 * Report a parse error because an expected token was not found.
632 #if defined __GNUC__ && __GNUC__ >= 4
633 __attribute__((sentinel))
635 void parse_error_expected(const char *message, ...)
637 if (message != NULL) {
638 errorf(HERE, "%s", message);
641 va_start(ap, message);
642 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
647 * Report an incompatible type.
649 static void type_error_incompatible(const char *msg,
650 const source_position_t *source_position, type_t *type1, type_t *type2)
652 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
657 * Expect the current token is the expected token.
658 * If not, generate an error, eat the current statement,
659 * and goto the error_label label.
661 #define expect(expected, error_label) \
663 if (UNLIKELY(token.type != (expected))) { \
664 parse_error_expected(NULL, (expected), NULL); \
665 add_anchor_token(expected); \
666 eat_until_anchor(); \
667 next_if((expected)); \
668 rem_anchor_token(expected); \
675 * Push a given scope on the scope stack and make it the
678 static scope_t *scope_push(scope_t *new_scope)
680 if (current_scope != NULL) {
681 new_scope->depth = current_scope->depth + 1;
684 scope_t *old_scope = current_scope;
685 current_scope = new_scope;
690 * Pop the current scope from the scope stack.
692 static void scope_pop(scope_t *old_scope)
694 current_scope = old_scope;
698 * Search an entity by its symbol in a given namespace.
700 static entity_t *get_entity(const symbol_t *const symbol,
701 namespace_tag_t namespc)
703 assert(namespc != NAMESPACE_INVALID);
704 entity_t *entity = symbol->entity;
705 for (; entity != NULL; entity = entity->base.symbol_next) {
706 if ((namespace_tag_t)entity->base.namespc == namespc)
713 /* §6.2.3:1 24) There is only one name space for tags even though three are
715 static entity_t *get_tag(symbol_t const *const symbol,
716 entity_kind_tag_t const kind)
718 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
719 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
721 "'%Y' defined as wrong kind of tag (previous definition %P)",
722 symbol, &entity->base.source_position);
729 * pushs an entity on the environment stack and links the corresponding symbol
732 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
734 symbol_t *symbol = entity->base.symbol;
735 entity_namespace_t namespc = entity->base.namespc;
736 assert(namespc != NAMESPACE_INVALID);
738 /* replace/add entity into entity list of the symbol */
741 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
746 /* replace an entry? */
747 if (iter->base.namespc == namespc) {
748 entity->base.symbol_next = iter->base.symbol_next;
754 /* remember old declaration */
756 entry.symbol = symbol;
757 entry.old_entity = iter;
758 entry.namespc = namespc;
759 ARR_APP1(stack_entry_t, *stack_ptr, entry);
763 * Push an entity on the environment stack.
765 static void environment_push(entity_t *entity)
767 assert(entity->base.source_position.input_name != NULL);
768 assert(entity->base.parent_scope != NULL);
769 stack_push(&environment_stack, entity);
773 * Push a declaration on the global label stack.
775 * @param declaration the declaration
777 static void label_push(entity_t *label)
779 /* we abuse the parameters scope as parent for the labels */
780 label->base.parent_scope = ¤t_function->parameters;
781 stack_push(&label_stack, label);
785 * pops symbols from the environment stack until @p new_top is the top element
787 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
789 stack_entry_t *stack = *stack_ptr;
790 size_t top = ARR_LEN(stack);
793 assert(new_top <= top);
797 for (i = top; i > new_top; --i) {
798 stack_entry_t *entry = &stack[i - 1];
800 entity_t *old_entity = entry->old_entity;
801 symbol_t *symbol = entry->symbol;
802 entity_namespace_t namespc = entry->namespc;
804 /* replace with old_entity/remove */
807 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
809 assert(iter != NULL);
810 /* replace an entry? */
811 if (iter->base.namespc == namespc)
815 /* restore definition from outer scopes (if there was one) */
816 if (old_entity != NULL) {
817 old_entity->base.symbol_next = iter->base.symbol_next;
818 *anchor = old_entity;
820 /* remove entry from list */
821 *anchor = iter->base.symbol_next;
825 ARR_SHRINKLEN(*stack_ptr, new_top);
829 * Pop all entries from the environment stack until the new_top
832 * @param new_top the new stack top
834 static void environment_pop_to(size_t new_top)
836 stack_pop_to(&environment_stack, new_top);
840 * Pop all entries from the global label stack until the new_top
843 * @param new_top the new stack top
845 static void label_pop_to(size_t new_top)
847 stack_pop_to(&label_stack, new_top);
850 static int get_akind_rank(atomic_type_kind_t akind)
856 * Return the type rank for an atomic type.
858 static int get_rank(const type_t *type)
860 assert(!is_typeref(type));
861 if (type->kind == TYPE_ENUM)
862 return get_akind_rank(type->enumt.akind);
864 assert(type->kind == TYPE_ATOMIC);
865 return get_akind_rank(type->atomic.akind);
869 * §6.3.1.1:2 Do integer promotion for a given type.
871 * @param type the type to promote
872 * @return the promoted type
874 static type_t *promote_integer(type_t *type)
876 if (type->kind == TYPE_BITFIELD)
877 type = type->bitfield.base_type;
879 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
886 * Create a cast expression.
888 * @param expression the expression to cast
889 * @param dest_type the destination type
891 static expression_t *create_cast_expression(expression_t *expression,
894 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
896 cast->unary.value = expression;
897 cast->base.type = dest_type;
903 * Check if a given expression represents a null pointer constant.
905 * @param expression the expression to check
907 static bool is_null_pointer_constant(const expression_t *expression)
909 /* skip void* cast */
910 if (expression->kind == EXPR_UNARY_CAST ||
911 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
912 type_t *const type = skip_typeref(expression->base.type);
913 if (types_compatible(type, type_void_ptr))
914 expression = expression->unary.value;
917 type_t *const type = skip_typeref(expression->base.type);
918 if (!is_type_integer(type))
920 switch (is_constant_expression(expression)) {
921 case EXPR_CLASS_ERROR: return true;
922 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
923 default: return false;
928 * Create an implicit cast expression.
930 * @param expression the expression to cast
931 * @param dest_type the destination type
933 static expression_t *create_implicit_cast(expression_t *expression,
936 type_t *const source_type = expression->base.type;
938 if (source_type == dest_type)
941 return create_cast_expression(expression, dest_type);
944 typedef enum assign_error_t {
946 ASSIGN_ERROR_INCOMPATIBLE,
947 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
948 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
949 ASSIGN_WARNING_POINTER_FROM_INT,
950 ASSIGN_WARNING_INT_FROM_POINTER
953 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
954 const expression_t *const right,
956 const source_position_t *source_position)
958 type_t *const orig_type_right = right->base.type;
959 type_t *const type_left = skip_typeref(orig_type_left);
960 type_t *const type_right = skip_typeref(orig_type_right);
965 case ASSIGN_ERROR_INCOMPATIBLE:
966 errorf(source_position,
967 "destination type '%T' in %s is incompatible with type '%T'",
968 orig_type_left, context, orig_type_right);
971 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
973 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
974 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
976 /* the left type has all qualifiers from the right type */
977 unsigned missing_qualifiers
978 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
979 warningf(source_position,
980 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
981 orig_type_left, context, orig_type_right, missing_qualifiers);
986 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
988 warningf(source_position,
989 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
990 orig_type_left, context, right, orig_type_right);
994 case ASSIGN_WARNING_POINTER_FROM_INT:
996 warningf(source_position,
997 "%s makes pointer '%T' from integer '%T' without a cast",
998 context, orig_type_left, orig_type_right);
1002 case ASSIGN_WARNING_INT_FROM_POINTER:
1003 if (warning.other) {
1004 warningf(source_position,
1005 "%s makes integer '%T' from pointer '%T' without a cast",
1006 context, orig_type_left, orig_type_right);
1011 panic("invalid error value");
1015 /** Implements the rules from §6.5.16.1 */
1016 static assign_error_t semantic_assign(type_t *orig_type_left,
1017 const expression_t *const right)
1019 type_t *const orig_type_right = right->base.type;
1020 type_t *const type_left = skip_typeref(orig_type_left);
1021 type_t *const type_right = skip_typeref(orig_type_right);
1023 if (is_type_pointer(type_left)) {
1024 if (is_null_pointer_constant(right)) {
1025 return ASSIGN_SUCCESS;
1026 } else if (is_type_pointer(type_right)) {
1027 type_t *points_to_left
1028 = skip_typeref(type_left->pointer.points_to);
1029 type_t *points_to_right
1030 = skip_typeref(type_right->pointer.points_to);
1031 assign_error_t res = ASSIGN_SUCCESS;
1033 /* the left type has all qualifiers from the right type */
1034 unsigned missing_qualifiers
1035 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1036 if (missing_qualifiers != 0) {
1037 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1040 points_to_left = get_unqualified_type(points_to_left);
1041 points_to_right = get_unqualified_type(points_to_right);
1043 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1046 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1047 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1048 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1051 if (!types_compatible(points_to_left, points_to_right)) {
1052 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1056 } else if (is_type_integer(type_right)) {
1057 return ASSIGN_WARNING_POINTER_FROM_INT;
1059 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1060 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1061 && is_type_pointer(type_right))) {
1062 return ASSIGN_SUCCESS;
1063 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1064 type_t *const unqual_type_left = get_unqualified_type(type_left);
1065 type_t *const unqual_type_right = get_unqualified_type(type_right);
1066 if (types_compatible(unqual_type_left, unqual_type_right)) {
1067 return ASSIGN_SUCCESS;
1069 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1070 return ASSIGN_WARNING_INT_FROM_POINTER;
1073 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1074 return ASSIGN_SUCCESS;
1076 return ASSIGN_ERROR_INCOMPATIBLE;
1079 static expression_t *parse_constant_expression(void)
1081 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1083 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1084 errorf(&result->base.source_position,
1085 "expression '%E' is not constant", result);
1091 static expression_t *parse_assignment_expression(void)
1093 return parse_subexpression(PREC_ASSIGNMENT);
1096 static void warn_string_concat(const source_position_t *pos)
1098 if (warning.traditional) {
1099 warningf(pos, "traditional C rejects string constant concatenation");
1103 static string_t parse_string_literals(void)
1105 assert(token.type == T_STRING_LITERAL);
1106 string_t result = token.literal;
1110 while (token.type == T_STRING_LITERAL) {
1111 warn_string_concat(&token.source_position);
1112 result = concat_strings(&result, &token.literal);
1120 * compare two string, ignoring double underscores on the second.
1122 static int strcmp_underscore(const char *s1, const char *s2)
1124 if (s2[0] == '_' && s2[1] == '_') {
1125 size_t len2 = strlen(s2);
1126 size_t len1 = strlen(s1);
1127 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1128 return strncmp(s1, s2+2, len2-4);
1132 return strcmp(s1, s2);
1135 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1137 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1138 attribute->kind = kind;
1143 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1146 * __attribute__ ( ( attribute-list ) )
1150 * attribute_list , attrib
1155 * any-word ( identifier )
1156 * any-word ( identifier , nonempty-expr-list )
1157 * any-word ( expr-list )
1159 * where the "identifier" must not be declared as a type, and
1160 * "any-word" may be any identifier (including one declared as a
1161 * type), a reserved word storage class specifier, type specifier or
1162 * type qualifier. ??? This still leaves out most reserved keywords
1163 * (following the old parser), shouldn't we include them, and why not
1164 * allow identifiers declared as types to start the arguments?
1166 * Matze: this all looks confusing and little systematic, so we're even less
1167 * strict and parse any list of things which are identifiers or
1168 * (assignment-)expressions.
1170 static attribute_argument_t *parse_attribute_arguments(void)
1172 attribute_argument_t *first = NULL;
1173 attribute_argument_t **anchor = &first;
1174 if (token.type != ')') do {
1175 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1177 /* is it an identifier */
1178 if (token.type == T_IDENTIFIER
1179 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1180 symbol_t *symbol = token.symbol;
1181 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1182 argument->v.symbol = symbol;
1185 /* must be an expression */
1186 expression_t *expression = parse_assignment_expression();
1188 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1189 argument->v.expression = expression;
1192 /* append argument */
1194 anchor = &argument->next;
1195 } while (next_if(','));
1196 expect(')', end_error);
1205 static attribute_t *parse_attribute_asm(void)
1209 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1211 expect('(', end_error);
1212 attribute->a.arguments = parse_attribute_arguments();
1219 static symbol_t *get_symbol_from_token(void)
1221 switch(token.type) {
1223 return token.symbol;
1252 /* maybe we need more tokens ... add them on demand */
1253 return get_token_symbol(&token);
1259 static attribute_t *parse_attribute_gnu_single(void)
1261 /* parse "any-word" */
1262 symbol_t *symbol = get_symbol_from_token();
1263 if (symbol == NULL) {
1264 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1268 attribute_kind_t kind;
1269 char const *const name = symbol->string;
1270 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1271 if (kind > ATTRIBUTE_GNU_LAST) {
1272 if (warning.attribute) {
1273 warningf(HERE, "unknown attribute '%s' ignored", name);
1275 /* TODO: we should still save the attribute in the list... */
1276 kind = ATTRIBUTE_UNKNOWN;
1280 const char *attribute_name = get_attribute_name(kind);
1281 if (attribute_name != NULL
1282 && strcmp_underscore(attribute_name, name) == 0)
1288 attribute_t *attribute = allocate_attribute_zero(kind);
1290 /* parse arguments */
1292 attribute->a.arguments = parse_attribute_arguments();
1297 static attribute_t *parse_attribute_gnu(void)
1299 attribute_t *first = NULL;
1300 attribute_t **anchor = &first;
1302 eat(T___attribute__);
1303 expect('(', end_error);
1304 expect('(', end_error);
1306 if (token.type != ')') do {
1307 attribute_t *attribute = parse_attribute_gnu_single();
1308 if (attribute == NULL)
1311 *anchor = attribute;
1312 anchor = &attribute->next;
1313 } while (next_if(','));
1314 expect(')', end_error);
1315 expect(')', end_error);
1321 /** Parse attributes. */
1322 static attribute_t *parse_attributes(attribute_t *first)
1324 attribute_t **anchor = &first;
1326 while (*anchor != NULL)
1327 anchor = &(*anchor)->next;
1329 attribute_t *attribute;
1330 switch (token.type) {
1331 case T___attribute__:
1332 attribute = parse_attribute_gnu();
1333 if (attribute == NULL)
1338 attribute = parse_attribute_asm();
1343 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1348 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1351 case T__forceinline:
1353 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1358 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1362 /* TODO record modifier */
1364 warningf(HERE, "Ignoring declaration modifier %K", &token);
1366 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1373 *anchor = attribute;
1374 anchor = &attribute->next;
1378 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1380 static entity_t *determine_lhs_ent(expression_t *const expr,
1383 switch (expr->kind) {
1384 case EXPR_REFERENCE: {
1385 entity_t *const entity = expr->reference.entity;
1386 /* we should only find variables as lvalues... */
1387 if (entity->base.kind != ENTITY_VARIABLE
1388 && entity->base.kind != ENTITY_PARAMETER)
1394 case EXPR_ARRAY_ACCESS: {
1395 expression_t *const ref = expr->array_access.array_ref;
1396 entity_t * ent = NULL;
1397 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1398 ent = determine_lhs_ent(ref, lhs_ent);
1401 mark_vars_read(expr->select.compound, lhs_ent);
1403 mark_vars_read(expr->array_access.index, lhs_ent);
1408 if (is_type_compound(skip_typeref(expr->base.type))) {
1409 return determine_lhs_ent(expr->select.compound, lhs_ent);
1411 mark_vars_read(expr->select.compound, lhs_ent);
1416 case EXPR_UNARY_DEREFERENCE: {
1417 expression_t *const val = expr->unary.value;
1418 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1420 return determine_lhs_ent(val->unary.value, lhs_ent);
1422 mark_vars_read(val, NULL);
1428 mark_vars_read(expr, NULL);
1433 #define ENT_ANY ((entity_t*)-1)
1436 * Mark declarations, which are read. This is used to detect variables, which
1440 * x is not marked as "read", because it is only read to calculate its own new
1444 * x and y are not detected as "not read", because multiple variables are
1447 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1449 switch (expr->kind) {
1450 case EXPR_REFERENCE: {
1451 entity_t *const entity = expr->reference.entity;
1452 if (entity->kind != ENTITY_VARIABLE
1453 && entity->kind != ENTITY_PARAMETER)
1456 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1457 if (entity->kind == ENTITY_VARIABLE) {
1458 entity->variable.read = true;
1460 entity->parameter.read = true;
1467 // TODO respect pure/const
1468 mark_vars_read(expr->call.function, NULL);
1469 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1470 mark_vars_read(arg->expression, NULL);
1474 case EXPR_CONDITIONAL:
1475 // TODO lhs_decl should depend on whether true/false have an effect
1476 mark_vars_read(expr->conditional.condition, NULL);
1477 if (expr->conditional.true_expression != NULL)
1478 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1479 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1483 if (lhs_ent == ENT_ANY
1484 && !is_type_compound(skip_typeref(expr->base.type)))
1486 mark_vars_read(expr->select.compound, lhs_ent);
1489 case EXPR_ARRAY_ACCESS: {
1490 expression_t *const ref = expr->array_access.array_ref;
1491 mark_vars_read(ref, lhs_ent);
1492 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1493 mark_vars_read(expr->array_access.index, lhs_ent);
1498 mark_vars_read(expr->va_arge.ap, lhs_ent);
1502 mark_vars_read(expr->va_copye.src, lhs_ent);
1505 case EXPR_UNARY_CAST:
1506 /* Special case: Use void cast to mark a variable as "read" */
1507 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1512 case EXPR_UNARY_THROW:
1513 if (expr->unary.value == NULL)
1516 case EXPR_UNARY_DEREFERENCE:
1517 case EXPR_UNARY_DELETE:
1518 case EXPR_UNARY_DELETE_ARRAY:
1519 if (lhs_ent == ENT_ANY)
1523 case EXPR_UNARY_NEGATE:
1524 case EXPR_UNARY_PLUS:
1525 case EXPR_UNARY_BITWISE_NEGATE:
1526 case EXPR_UNARY_NOT:
1527 case EXPR_UNARY_TAKE_ADDRESS:
1528 case EXPR_UNARY_POSTFIX_INCREMENT:
1529 case EXPR_UNARY_POSTFIX_DECREMENT:
1530 case EXPR_UNARY_PREFIX_INCREMENT:
1531 case EXPR_UNARY_PREFIX_DECREMENT:
1532 case EXPR_UNARY_CAST_IMPLICIT:
1533 case EXPR_UNARY_ASSUME:
1535 mark_vars_read(expr->unary.value, lhs_ent);
1538 case EXPR_BINARY_ADD:
1539 case EXPR_BINARY_SUB:
1540 case EXPR_BINARY_MUL:
1541 case EXPR_BINARY_DIV:
1542 case EXPR_BINARY_MOD:
1543 case EXPR_BINARY_EQUAL:
1544 case EXPR_BINARY_NOTEQUAL:
1545 case EXPR_BINARY_LESS:
1546 case EXPR_BINARY_LESSEQUAL:
1547 case EXPR_BINARY_GREATER:
1548 case EXPR_BINARY_GREATEREQUAL:
1549 case EXPR_BINARY_BITWISE_AND:
1550 case EXPR_BINARY_BITWISE_OR:
1551 case EXPR_BINARY_BITWISE_XOR:
1552 case EXPR_BINARY_LOGICAL_AND:
1553 case EXPR_BINARY_LOGICAL_OR:
1554 case EXPR_BINARY_SHIFTLEFT:
1555 case EXPR_BINARY_SHIFTRIGHT:
1556 case EXPR_BINARY_COMMA:
1557 case EXPR_BINARY_ISGREATER:
1558 case EXPR_BINARY_ISGREATEREQUAL:
1559 case EXPR_BINARY_ISLESS:
1560 case EXPR_BINARY_ISLESSEQUAL:
1561 case EXPR_BINARY_ISLESSGREATER:
1562 case EXPR_BINARY_ISUNORDERED:
1563 mark_vars_read(expr->binary.left, lhs_ent);
1564 mark_vars_read(expr->binary.right, lhs_ent);
1567 case EXPR_BINARY_ASSIGN:
1568 case EXPR_BINARY_MUL_ASSIGN:
1569 case EXPR_BINARY_DIV_ASSIGN:
1570 case EXPR_BINARY_MOD_ASSIGN:
1571 case EXPR_BINARY_ADD_ASSIGN:
1572 case EXPR_BINARY_SUB_ASSIGN:
1573 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1574 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1575 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1576 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1577 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1578 if (lhs_ent == ENT_ANY)
1580 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1581 mark_vars_read(expr->binary.right, lhs_ent);
1586 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1592 case EXPR_STRING_LITERAL:
1593 case EXPR_WIDE_STRING_LITERAL:
1594 case EXPR_COMPOUND_LITERAL: // TODO init?
1596 case EXPR_CLASSIFY_TYPE:
1599 case EXPR_BUILTIN_CONSTANT_P:
1600 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1602 case EXPR_STATEMENT: // TODO
1603 case EXPR_LABEL_ADDRESS:
1604 case EXPR_REFERENCE_ENUM_VALUE:
1608 panic("unhandled expression");
1611 static designator_t *parse_designation(void)
1613 designator_t *result = NULL;
1614 designator_t **anchor = &result;
1617 designator_t *designator;
1618 switch (token.type) {
1620 designator = allocate_ast_zero(sizeof(designator[0]));
1621 designator->source_position = token.source_position;
1623 add_anchor_token(']');
1624 designator->array_index = parse_constant_expression();
1625 rem_anchor_token(']');
1626 expect(']', end_error);
1629 designator = allocate_ast_zero(sizeof(designator[0]));
1630 designator->source_position = token.source_position;
1632 if (token.type != T_IDENTIFIER) {
1633 parse_error_expected("while parsing designator",
1634 T_IDENTIFIER, NULL);
1637 designator->symbol = token.symbol;
1641 expect('=', end_error);
1645 assert(designator != NULL);
1646 *anchor = designator;
1647 anchor = &designator->next;
1653 static initializer_t *initializer_from_string(array_type_t *const type,
1654 const string_t *const string)
1656 /* TODO: check len vs. size of array type */
1659 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1660 initializer->string.string = *string;
1665 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1666 const string_t *const string)
1668 /* TODO: check len vs. size of array type */
1671 initializer_t *const initializer =
1672 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1673 initializer->wide_string.string = *string;
1679 * Build an initializer from a given expression.
1681 static initializer_t *initializer_from_expression(type_t *orig_type,
1682 expression_t *expression)
1684 /* TODO check that expression is a constant expression */
1686 /* §6.7.8.14/15 char array may be initialized by string literals */
1687 type_t *type = skip_typeref(orig_type);
1688 type_t *expr_type_orig = expression->base.type;
1689 type_t *expr_type = skip_typeref(expr_type_orig);
1691 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1692 array_type_t *const array_type = &type->array;
1693 type_t *const element_type = skip_typeref(array_type->element_type);
1695 if (element_type->kind == TYPE_ATOMIC) {
1696 atomic_type_kind_t akind = element_type->atomic.akind;
1697 switch (expression->kind) {
1698 case EXPR_STRING_LITERAL:
1699 if (akind == ATOMIC_TYPE_CHAR
1700 || akind == ATOMIC_TYPE_SCHAR
1701 || akind == ATOMIC_TYPE_UCHAR) {
1702 return initializer_from_string(array_type,
1703 &expression->string_literal.value);
1707 case EXPR_WIDE_STRING_LITERAL: {
1708 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1709 if (get_unqualified_type(element_type) == bare_wchar_type) {
1710 return initializer_from_wide_string(array_type,
1711 &expression->string_literal.value);
1722 assign_error_t error = semantic_assign(type, expression);
1723 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1725 report_assign_error(error, type, expression, "initializer",
1726 &expression->base.source_position);
1728 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1729 result->value.value = create_implicit_cast(expression, type);
1735 * Checks if a given expression can be used as a constant initializer.
1737 static bool is_initializer_constant(const expression_t *expression)
1739 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1740 is_linker_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 */
1753 if (token.type == '{') {
1755 warningf(HERE, "extra curly braces around scalar initializer");
1759 } while (token.type == '{');
1762 expression_t *expression = parse_assignment_expression();
1763 mark_vars_read(expression, NULL);
1764 if (must_be_constant && !is_initializer_constant(expression)) {
1765 errorf(&expression->base.source_position,
1766 "initialisation expression '%E' is not constant",
1770 initializer_t *initializer = initializer_from_expression(type, expression);
1772 if (initializer == NULL) {
1773 errorf(&expression->base.source_position,
1774 "expression '%E' (type '%T') doesn't match expected type '%T'",
1775 expression, expression->base.type, type);
1780 bool additional_warning_displayed = false;
1781 while (braces > 0) {
1783 if (token.type != '}') {
1784 if (!additional_warning_displayed && warning.other) {
1785 warningf(HERE, "additional elements in scalar initializer");
1786 additional_warning_displayed = true;
1797 * An entry in the type path.
1799 typedef struct type_path_entry_t type_path_entry_t;
1800 struct type_path_entry_t {
1801 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1803 size_t index; /**< For array types: the current index. */
1804 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1809 * A type path expression a position inside compound or array types.
1811 typedef struct type_path_t type_path_t;
1812 struct type_path_t {
1813 type_path_entry_t *path; /**< An flexible array containing the current path. */
1814 type_t *top_type; /**< type of the element the path points */
1815 size_t max_index; /**< largest index in outermost array */
1819 * Prints a type path for debugging.
1821 static __attribute__((unused)) void debug_print_type_path(
1822 const type_path_t *path)
1824 size_t len = ARR_LEN(path->path);
1826 for (size_t i = 0; i < len; ++i) {
1827 const type_path_entry_t *entry = & path->path[i];
1829 type_t *type = skip_typeref(entry->type);
1830 if (is_type_compound(type)) {
1831 /* in gcc mode structs can have no members */
1832 if (entry->v.compound_entry == NULL) {
1836 fprintf(stderr, ".%s",
1837 entry->v.compound_entry->base.symbol->string);
1838 } else if (is_type_array(type)) {
1839 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1841 fprintf(stderr, "-INVALID-");
1844 if (path->top_type != NULL) {
1845 fprintf(stderr, " (");
1846 print_type(path->top_type);
1847 fprintf(stderr, ")");
1852 * Return the top type path entry, ie. in a path
1853 * (type).a.b returns the b.
1855 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1857 size_t len = ARR_LEN(path->path);
1859 return &path->path[len-1];
1863 * Enlarge the type path by an (empty) element.
1865 static type_path_entry_t *append_to_type_path(type_path_t *path)
1867 size_t len = ARR_LEN(path->path);
1868 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1870 type_path_entry_t *result = & path->path[len];
1871 memset(result, 0, sizeof(result[0]));
1876 * Descending into a sub-type. Enter the scope of the current top_type.
1878 static void descend_into_subtype(type_path_t *path)
1880 type_t *orig_top_type = path->top_type;
1881 type_t *top_type = skip_typeref(orig_top_type);
1883 type_path_entry_t *top = append_to_type_path(path);
1884 top->type = top_type;
1886 if (is_type_compound(top_type)) {
1887 compound_t *compound = top_type->compound.compound;
1888 entity_t *entry = compound->members.entities;
1890 if (entry != NULL) {
1891 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1892 top->v.compound_entry = &entry->declaration;
1893 path->top_type = entry->declaration.type;
1895 path->top_type = NULL;
1897 } else if (is_type_array(top_type)) {
1899 path->top_type = top_type->array.element_type;
1901 assert(!is_type_valid(top_type));
1906 * Pop an entry from the given type path, ie. returning from
1907 * (type).a.b to (type).a
1909 static void ascend_from_subtype(type_path_t *path)
1911 type_path_entry_t *top = get_type_path_top(path);
1913 path->top_type = top->type;
1915 size_t len = ARR_LEN(path->path);
1916 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1920 * Pop entries from the given type path until the given
1921 * path level is reached.
1923 static void ascend_to(type_path_t *path, size_t top_path_level)
1925 size_t len = ARR_LEN(path->path);
1927 while (len > top_path_level) {
1928 ascend_from_subtype(path);
1929 len = ARR_LEN(path->path);
1933 static bool walk_designator(type_path_t *path, const designator_t *designator,
1934 bool used_in_offsetof)
1936 for (; designator != NULL; designator = designator->next) {
1937 type_path_entry_t *top = get_type_path_top(path);
1938 type_t *orig_type = top->type;
1940 type_t *type = skip_typeref(orig_type);
1942 if (designator->symbol != NULL) {
1943 symbol_t *symbol = designator->symbol;
1944 if (!is_type_compound(type)) {
1945 if (is_type_valid(type)) {
1946 errorf(&designator->source_position,
1947 "'.%Y' designator used for non-compound type '%T'",
1951 top->type = type_error_type;
1952 top->v.compound_entry = NULL;
1953 orig_type = type_error_type;
1955 compound_t *compound = type->compound.compound;
1956 entity_t *iter = compound->members.entities;
1957 for (; iter != NULL; iter = iter->base.next) {
1958 if (iter->base.symbol == symbol) {
1963 errorf(&designator->source_position,
1964 "'%T' has no member named '%Y'", orig_type, symbol);
1967 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1968 if (used_in_offsetof) {
1969 type_t *real_type = skip_typeref(iter->declaration.type);
1970 if (real_type->kind == TYPE_BITFIELD) {
1971 errorf(&designator->source_position,
1972 "offsetof designator '%Y' must not specify bitfield",
1978 top->type = orig_type;
1979 top->v.compound_entry = &iter->declaration;
1980 orig_type = iter->declaration.type;
1983 expression_t *array_index = designator->array_index;
1984 assert(designator->array_index != NULL);
1986 if (!is_type_array(type)) {
1987 if (is_type_valid(type)) {
1988 errorf(&designator->source_position,
1989 "[%E] designator used for non-array type '%T'",
1990 array_index, orig_type);
1995 long index = fold_constant_to_int(array_index);
1996 if (!used_in_offsetof) {
1998 errorf(&designator->source_position,
1999 "array index [%E] must be positive", array_index);
2000 } else if (type->array.size_constant) {
2001 long array_size = type->array.size;
2002 if (index >= array_size) {
2003 errorf(&designator->source_position,
2004 "designator [%E] (%d) exceeds array size %d",
2005 array_index, index, array_size);
2010 top->type = orig_type;
2011 top->v.index = (size_t) index;
2012 orig_type = type->array.element_type;
2014 path->top_type = orig_type;
2016 if (designator->next != NULL) {
2017 descend_into_subtype(path);
2023 static void advance_current_object(type_path_t *path, size_t top_path_level)
2025 type_path_entry_t *top = get_type_path_top(path);
2027 type_t *type = skip_typeref(top->type);
2028 if (is_type_union(type)) {
2029 /* in unions only the first element is initialized */
2030 top->v.compound_entry = NULL;
2031 } else if (is_type_struct(type)) {
2032 declaration_t *entry = top->v.compound_entry;
2034 entity_t *next_entity = entry->base.next;
2035 if (next_entity != NULL) {
2036 assert(is_declaration(next_entity));
2037 entry = &next_entity->declaration;
2042 top->v.compound_entry = entry;
2043 if (entry != NULL) {
2044 path->top_type = entry->type;
2047 } else if (is_type_array(type)) {
2048 assert(is_type_array(type));
2052 if (!type->array.size_constant || top->v.index < type->array.size) {
2056 assert(!is_type_valid(type));
2060 /* we're past the last member of the current sub-aggregate, try if we
2061 * can ascend in the type hierarchy and continue with another subobject */
2062 size_t len = ARR_LEN(path->path);
2064 if (len > top_path_level) {
2065 ascend_from_subtype(path);
2066 advance_current_object(path, top_path_level);
2068 path->top_type = NULL;
2073 * skip any {...} blocks until a closing bracket is reached.
2075 static void skip_initializers(void)
2079 while (token.type != '}') {
2080 if (token.type == T_EOF)
2082 if (token.type == '{') {
2090 static initializer_t *create_empty_initializer(void)
2092 static initializer_t empty_initializer
2093 = { .list = { { INITIALIZER_LIST }, 0 } };
2094 return &empty_initializer;
2098 * Parse a part of an initialiser for a struct or union,
2100 static initializer_t *parse_sub_initializer(type_path_t *path,
2101 type_t *outer_type, size_t top_path_level,
2102 parse_initializer_env_t *env)
2104 if (token.type == '}') {
2105 /* empty initializer */
2106 return create_empty_initializer();
2109 type_t *orig_type = path->top_type;
2110 type_t *type = NULL;
2112 if (orig_type == NULL) {
2113 /* We are initializing an empty compound. */
2115 type = skip_typeref(orig_type);
2118 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2121 designator_t *designator = NULL;
2122 if (token.type == '.' || token.type == '[') {
2123 designator = parse_designation();
2124 goto finish_designator;
2125 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2126 /* GNU-style designator ("identifier: value") */
2127 designator = allocate_ast_zero(sizeof(designator[0]));
2128 designator->source_position = token.source_position;
2129 designator->symbol = token.symbol;
2134 /* reset path to toplevel, evaluate designator from there */
2135 ascend_to(path, top_path_level);
2136 if (!walk_designator(path, designator, false)) {
2137 /* can't continue after designation error */
2141 initializer_t *designator_initializer
2142 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2143 designator_initializer->designator.designator = designator;
2144 ARR_APP1(initializer_t*, initializers, designator_initializer);
2146 orig_type = path->top_type;
2147 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2152 if (token.type == '{') {
2153 if (type != NULL && is_type_scalar(type)) {
2154 sub = parse_scalar_initializer(type, env->must_be_constant);
2157 if (env->entity != NULL) {
2159 "extra brace group at end of initializer for '%Y'",
2160 env->entity->base.symbol);
2162 errorf(HERE, "extra brace group at end of initializer");
2167 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;
2204 if (warning.other) {
2205 source_position_t const* const pos = &expression->base.source_position;
2206 if (env->entity != NULL) {
2207 warningf(pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2209 warningf(pos, "excess elements in initializer");
2212 goto error_parse_next;
2215 /* handle { "string" } special case */
2216 if ((expression->kind == EXPR_STRING_LITERAL
2217 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2218 && outer_type != NULL) {
2219 sub = initializer_from_expression(outer_type, expression);
2222 if (token.type != '}' && warning.other) {
2223 warningf(HERE, "excessive elements in initializer for type '%T'",
2226 /* TODO: eat , ... */
2231 /* descend into subtypes until expression matches type */
2233 orig_type = path->top_type;
2234 type = skip_typeref(orig_type);
2236 sub = initializer_from_expression(orig_type, expression);
2240 if (!is_type_valid(type)) {
2243 if (is_type_scalar(type)) {
2244 errorf(&expression->base.source_position,
2245 "expression '%E' doesn't match expected type '%T'",
2246 expression, orig_type);
2250 descend_into_subtype(path);
2254 /* update largest index of top array */
2255 const type_path_entry_t *first = &path->path[0];
2256 type_t *first_type = first->type;
2257 first_type = skip_typeref(first_type);
2258 if (is_type_array(first_type)) {
2259 size_t index = first->v.index;
2260 if (index > path->max_index)
2261 path->max_index = index;
2264 /* append to initializers list */
2265 ARR_APP1(initializer_t*, initializers, sub);
2268 if (token.type == '}') {
2271 expect(',', end_error);
2272 if (token.type == '}') {
2277 /* advance to the next declaration if we are not at the end */
2278 advance_current_object(path, top_path_level);
2279 orig_type = path->top_type;
2280 if (orig_type != NULL)
2281 type = skip_typeref(orig_type);
2287 size_t len = ARR_LEN(initializers);
2288 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2289 initializer_t *result = allocate_ast_zero(size);
2290 result->kind = INITIALIZER_LIST;
2291 result->list.len = len;
2292 memcpy(&result->list.initializers, initializers,
2293 len * sizeof(initializers[0]));
2295 DEL_ARR_F(initializers);
2296 ascend_to(path, top_path_level+1);
2301 skip_initializers();
2302 DEL_ARR_F(initializers);
2303 ascend_to(path, top_path_level+1);
2307 static expression_t *make_size_literal(size_t value)
2309 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2310 literal->base.type = type_size_t;
2313 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2314 literal->literal.value = make_string(buf);
2320 * Parses an initializer. Parsers either a compound literal
2321 * (env->declaration == NULL) or an initializer of a declaration.
2323 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2325 type_t *type = skip_typeref(env->type);
2326 size_t max_index = 0;
2327 initializer_t *result;
2329 if (is_type_scalar(type)) {
2330 result = parse_scalar_initializer(type, env->must_be_constant);
2331 } else if (token.type == '{') {
2335 memset(&path, 0, sizeof(path));
2336 path.top_type = env->type;
2337 path.path = NEW_ARR_F(type_path_entry_t, 0);
2339 descend_into_subtype(&path);
2341 add_anchor_token('}');
2342 result = parse_sub_initializer(&path, env->type, 1, env);
2343 rem_anchor_token('}');
2345 max_index = path.max_index;
2346 DEL_ARR_F(path.path);
2348 expect('}', end_error);
2351 /* parse_scalar_initializer() also works in this case: we simply
2352 * have an expression without {} around it */
2353 result = parse_scalar_initializer(type, env->must_be_constant);
2356 /* §6.7.8:22 array initializers for arrays with unknown size determine
2357 * the array type size */
2358 if (is_type_array(type) && type->array.size_expression == NULL
2359 && result != NULL) {
2361 switch (result->kind) {
2362 case INITIALIZER_LIST:
2363 assert(max_index != 0xdeadbeaf);
2364 size = max_index + 1;
2367 case INITIALIZER_STRING:
2368 size = result->string.string.size;
2371 case INITIALIZER_WIDE_STRING:
2372 size = result->wide_string.string.size;
2375 case INITIALIZER_DESIGNATOR:
2376 case INITIALIZER_VALUE:
2377 /* can happen for parse errors */
2382 internal_errorf(HERE, "invalid initializer type");
2385 type_t *new_type = duplicate_type(type);
2387 new_type->array.size_expression = make_size_literal(size);
2388 new_type->array.size_constant = true;
2389 new_type->array.has_implicit_size = true;
2390 new_type->array.size = size;
2391 env->type = new_type;
2397 static void append_entity(scope_t *scope, entity_t *entity)
2399 if (scope->last_entity != NULL) {
2400 scope->last_entity->base.next = entity;
2402 scope->entities = entity;
2404 entity->base.parent_entity = current_entity;
2405 scope->last_entity = entity;
2409 static compound_t *parse_compound_type_specifier(bool is_struct)
2411 source_position_t const pos = *HERE;
2412 eat(is_struct ? T_struct : T_union);
2414 symbol_t *symbol = NULL;
2415 entity_t *entity = NULL;
2416 attribute_t *attributes = NULL;
2418 if (token.type == T___attribute__) {
2419 attributes = parse_attributes(NULL);
2422 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2423 if (token.type == T_IDENTIFIER) {
2424 /* the compound has a name, check if we have seen it already */
2425 symbol = token.symbol;
2426 entity = get_tag(symbol, kind);
2429 if (entity != NULL) {
2430 if (entity->base.parent_scope != current_scope &&
2431 (token.type == '{' || token.type == ';')) {
2432 /* we're in an inner scope and have a definition. Shadow
2433 * existing definition in outer scope */
2435 } else if (entity->compound.complete && token.type == '{') {
2436 source_position_t const *const ppos = &entity->base.source_position;
2437 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2438 /* clear members in the hope to avoid further errors */
2439 entity->compound.members.entities = NULL;
2442 } else if (token.type != '{') {
2443 char const *const msg =
2444 is_struct ? "while parsing struct type specifier" :
2445 "while parsing union type specifier";
2446 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2451 if (entity == NULL) {
2452 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2453 entity->compound.alignment = 1;
2454 entity->base.source_position = pos;
2455 entity->base.parent_scope = current_scope;
2456 if (symbol != NULL) {
2457 environment_push(entity);
2459 append_entity(current_scope, entity);
2462 if (token.type == '{') {
2463 parse_compound_type_entries(&entity->compound);
2465 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2466 if (symbol == NULL) {
2467 assert(anonymous_entity == NULL);
2468 anonymous_entity = entity;
2472 if (attributes != NULL) {
2473 handle_entity_attributes(attributes, entity);
2476 return &entity->compound;
2479 static void parse_enum_entries(type_t *const enum_type)
2483 if (token.type == '}') {
2484 errorf(HERE, "empty enum not allowed");
2489 add_anchor_token('}');
2491 if (token.type != T_IDENTIFIER) {
2492 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2494 rem_anchor_token('}');
2498 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, token.symbol);
2499 entity->enum_value.enum_type = enum_type;
2500 entity->base.source_position = token.source_position;
2504 expression_t *value = parse_constant_expression();
2506 value = create_implicit_cast(value, enum_type);
2507 entity->enum_value.value = value;
2512 record_entity(entity, false);
2513 } while (next_if(',') && token.type != '}');
2514 rem_anchor_token('}');
2516 expect('}', end_error);
2522 static type_t *parse_enum_specifier(void)
2524 source_position_t const pos = *HERE;
2529 switch (token.type) {
2531 symbol = token.symbol;
2532 entity = get_tag(symbol, ENTITY_ENUM);
2535 if (entity != NULL) {
2536 if (entity->base.parent_scope != current_scope &&
2537 (token.type == '{' || token.type == ';')) {
2538 /* we're in an inner scope and have a definition. Shadow
2539 * existing definition in outer scope */
2541 } else if (entity->enume.complete && token.type == '{') {
2542 source_position_t const *const ppos = &entity->base.source_position;
2543 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2554 parse_error_expected("while parsing enum type specifier",
2555 T_IDENTIFIER, '{', NULL);
2559 if (entity == NULL) {
2560 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2561 entity->base.source_position = pos;
2562 entity->base.parent_scope = current_scope;
2565 type_t *const type = allocate_type_zero(TYPE_ENUM);
2566 type->enumt.enume = &entity->enume;
2567 type->enumt.akind = ATOMIC_TYPE_INT;
2569 if (token.type == '{') {
2570 if (symbol != NULL) {
2571 environment_push(entity);
2573 append_entity(current_scope, entity);
2574 entity->enume.complete = true;
2576 parse_enum_entries(type);
2577 parse_attributes(NULL);
2579 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2580 if (symbol == NULL) {
2581 assert(anonymous_entity == NULL);
2582 anonymous_entity = entity;
2584 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2585 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2592 * if a symbol is a typedef to another type, return true
2594 static bool is_typedef_symbol(symbol_t *symbol)
2596 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2597 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2600 static type_t *parse_typeof(void)
2606 expect('(', end_error);
2607 add_anchor_token(')');
2609 expression_t *expression = NULL;
2611 bool old_type_prop = in_type_prop;
2612 bool old_gcc_extension = in_gcc_extension;
2613 in_type_prop = true;
2615 while (next_if(T___extension__)) {
2616 /* This can be a prefix to a typename or an expression. */
2617 in_gcc_extension = true;
2619 switch (token.type) {
2621 if (is_typedef_symbol(token.symbol)) {
2623 type = parse_typename();
2626 expression = parse_expression();
2627 type = revert_automatic_type_conversion(expression);
2631 in_type_prop = old_type_prop;
2632 in_gcc_extension = old_gcc_extension;
2634 rem_anchor_token(')');
2635 expect(')', end_error);
2637 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2638 typeof_type->typeoft.expression = expression;
2639 typeof_type->typeoft.typeof_type = type;
2646 typedef enum specifiers_t {
2647 SPECIFIER_SIGNED = 1 << 0,
2648 SPECIFIER_UNSIGNED = 1 << 1,
2649 SPECIFIER_LONG = 1 << 2,
2650 SPECIFIER_INT = 1 << 3,
2651 SPECIFIER_DOUBLE = 1 << 4,
2652 SPECIFIER_CHAR = 1 << 5,
2653 SPECIFIER_WCHAR_T = 1 << 6,
2654 SPECIFIER_SHORT = 1 << 7,
2655 SPECIFIER_LONG_LONG = 1 << 8,
2656 SPECIFIER_FLOAT = 1 << 9,
2657 SPECIFIER_BOOL = 1 << 10,
2658 SPECIFIER_VOID = 1 << 11,
2659 SPECIFIER_INT8 = 1 << 12,
2660 SPECIFIER_INT16 = 1 << 13,
2661 SPECIFIER_INT32 = 1 << 14,
2662 SPECIFIER_INT64 = 1 << 15,
2663 SPECIFIER_INT128 = 1 << 16,
2664 SPECIFIER_COMPLEX = 1 << 17,
2665 SPECIFIER_IMAGINARY = 1 << 18,
2668 static type_t *get_typedef_type(symbol_t *symbol)
2670 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2671 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2674 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2675 type->typedeft.typedefe = &entity->typedefe;
2680 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2682 expect('(', end_error);
2684 attribute_property_argument_t *property
2685 = allocate_ast_zero(sizeof(*property));
2688 if (token.type != T_IDENTIFIER) {
2689 parse_error_expected("while parsing property declspec",
2690 T_IDENTIFIER, NULL);
2695 symbol_t *symbol = token.symbol;
2696 if (strcmp(symbol->string, "put") == 0) {
2697 prop = &property->put_symbol;
2698 } else if (strcmp(symbol->string, "get") == 0) {
2699 prop = &property->get_symbol;
2701 errorf(HERE, "expected put or get in property declspec");
2705 expect('=', end_error);
2706 if (token.type != T_IDENTIFIER) {
2707 parse_error_expected("while parsing property declspec",
2708 T_IDENTIFIER, NULL);
2712 *prop = token.symbol;
2714 } while (next_if(','));
2716 attribute->a.property = property;
2718 expect(')', end_error);
2724 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2726 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2727 if (next_if(T_restrict)) {
2728 kind = ATTRIBUTE_MS_RESTRICT;
2729 } else if (token.type == T_IDENTIFIER) {
2730 const char *name = token.symbol->string;
2731 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2733 const char *attribute_name = get_attribute_name(k);
2734 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2740 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2741 warningf(HERE, "unknown __declspec '%s' ignored", name);
2745 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2749 attribute_t *attribute = allocate_attribute_zero(kind);
2751 if (kind == ATTRIBUTE_MS_PROPERTY) {
2752 return parse_attribute_ms_property(attribute);
2755 /* parse arguments */
2757 attribute->a.arguments = parse_attribute_arguments();
2762 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2766 expect('(', end_error);
2771 add_anchor_token(')');
2773 attribute_t **anchor = &first;
2775 while (*anchor != NULL)
2776 anchor = &(*anchor)->next;
2778 attribute_t *attribute
2779 = parse_microsoft_extended_decl_modifier_single();
2780 if (attribute == NULL)
2783 *anchor = attribute;
2784 anchor = &attribute->next;
2785 } while (next_if(','));
2787 rem_anchor_token(')');
2788 expect(')', end_error);
2792 rem_anchor_token(')');
2796 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2798 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2799 entity->base.source_position = *HERE;
2800 if (is_declaration(entity)) {
2801 entity->declaration.type = type_error_type;
2802 entity->declaration.implicit = true;
2803 } else if (kind == ENTITY_TYPEDEF) {
2804 entity->typedefe.type = type_error_type;
2805 entity->typedefe.builtin = true;
2807 if (kind != ENTITY_COMPOUND_MEMBER)
2808 record_entity(entity, false);
2812 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2814 type_t *type = NULL;
2815 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2816 unsigned type_specifiers = 0;
2817 bool newtype = false;
2818 bool saw_error = false;
2819 bool old_gcc_extension = in_gcc_extension;
2821 memset(specifiers, 0, sizeof(*specifiers));
2822 specifiers->source_position = token.source_position;
2825 specifiers->attributes = parse_attributes(specifiers->attributes);
2827 switch (token.type) {
2829 #define MATCH_STORAGE_CLASS(token, class) \
2831 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2832 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2834 specifiers->storage_class = class; \
2835 if (specifiers->thread_local) \
2836 goto check_thread_storage_class; \
2840 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2841 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2842 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2843 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2844 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2847 specifiers->attributes
2848 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2852 if (specifiers->thread_local) {
2853 errorf(HERE, "duplicate '__thread'");
2855 specifiers->thread_local = true;
2856 check_thread_storage_class:
2857 switch (specifiers->storage_class) {
2858 case STORAGE_CLASS_EXTERN:
2859 case STORAGE_CLASS_NONE:
2860 case STORAGE_CLASS_STATIC:
2864 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2865 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2866 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2867 wrong_thread_storage_class:
2868 errorf(HERE, "'__thread' used with '%s'", wrong);
2875 /* type qualifiers */
2876 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2878 qualifiers |= qualifier; \
2882 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2883 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2884 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2885 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2886 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2887 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2888 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2889 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2891 case T___extension__:
2893 in_gcc_extension = true;
2896 /* type specifiers */
2897 #define MATCH_SPECIFIER(token, specifier, name) \
2899 if (type_specifiers & specifier) { \
2900 errorf(HERE, "multiple " name " type specifiers given"); \
2902 type_specifiers |= specifier; \
2907 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2908 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2909 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2910 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2911 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2912 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2913 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2914 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2915 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2916 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2917 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2918 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2919 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2920 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2921 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2922 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2923 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2924 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2928 specifiers->is_inline = true;
2932 case T__forceinline:
2934 specifiers->modifiers |= DM_FORCEINLINE;
2939 if (type_specifiers & SPECIFIER_LONG_LONG) {
2940 errorf(HERE, "too many long type specifiers given");
2941 } else if (type_specifiers & SPECIFIER_LONG) {
2942 type_specifiers |= SPECIFIER_LONG_LONG;
2944 type_specifiers |= SPECIFIER_LONG;
2949 #define CHECK_DOUBLE_TYPE() \
2951 if ( type != NULL) \
2952 errorf(HERE, "multiple data types in declaration specifiers"); \
2956 CHECK_DOUBLE_TYPE();
2957 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2959 type->compound.compound = parse_compound_type_specifier(true);
2962 CHECK_DOUBLE_TYPE();
2963 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2964 type->compound.compound = parse_compound_type_specifier(false);
2967 CHECK_DOUBLE_TYPE();
2968 type = parse_enum_specifier();
2971 CHECK_DOUBLE_TYPE();
2972 type = parse_typeof();
2974 case T___builtin_va_list:
2975 CHECK_DOUBLE_TYPE();
2976 type = duplicate_type(type_valist);
2980 case T_IDENTIFIER: {
2981 /* only parse identifier if we haven't found a type yet */
2982 if (type != NULL || type_specifiers != 0) {
2983 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2984 * declaration, so it doesn't generate errors about expecting '(' or
2986 switch (look_ahead(1)->type) {
2993 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2997 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3002 goto finish_specifiers;
3006 type_t *const typedef_type = get_typedef_type(token.symbol);
3007 if (typedef_type == NULL) {
3008 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3009 * declaration, so it doesn't generate 'implicit int' followed by more
3010 * errors later on. */
3011 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3017 errorf(HERE, "%K does not name a type", &token);
3020 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3022 type = allocate_type_zero(TYPE_TYPEDEF);
3023 type->typedeft.typedefe = &entity->typedefe;
3031 goto finish_specifiers;
3036 type = typedef_type;
3040 /* function specifier */
3042 goto finish_specifiers;
3047 specifiers->attributes = parse_attributes(specifiers->attributes);
3049 in_gcc_extension = old_gcc_extension;
3051 if (type == NULL || (saw_error && type_specifiers != 0)) {
3052 atomic_type_kind_t atomic_type;
3054 /* match valid basic types */
3055 switch (type_specifiers) {
3056 case SPECIFIER_VOID:
3057 atomic_type = ATOMIC_TYPE_VOID;
3059 case SPECIFIER_WCHAR_T:
3060 atomic_type = ATOMIC_TYPE_WCHAR_T;
3062 case SPECIFIER_CHAR:
3063 atomic_type = ATOMIC_TYPE_CHAR;
3065 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3066 atomic_type = ATOMIC_TYPE_SCHAR;
3068 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3069 atomic_type = ATOMIC_TYPE_UCHAR;
3071 case SPECIFIER_SHORT:
3072 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3073 case SPECIFIER_SHORT | SPECIFIER_INT:
3074 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3075 atomic_type = ATOMIC_TYPE_SHORT;
3077 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3078 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3079 atomic_type = ATOMIC_TYPE_USHORT;
3082 case SPECIFIER_SIGNED:
3083 case SPECIFIER_SIGNED | SPECIFIER_INT:
3084 atomic_type = ATOMIC_TYPE_INT;
3086 case SPECIFIER_UNSIGNED:
3087 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3088 atomic_type = ATOMIC_TYPE_UINT;
3090 case SPECIFIER_LONG:
3091 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3092 case SPECIFIER_LONG | SPECIFIER_INT:
3093 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3094 atomic_type = ATOMIC_TYPE_LONG;
3096 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3097 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3098 atomic_type = ATOMIC_TYPE_ULONG;
3101 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3102 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3103 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3104 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3106 atomic_type = ATOMIC_TYPE_LONGLONG;
3107 goto warn_about_long_long;
3109 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3110 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3112 atomic_type = ATOMIC_TYPE_ULONGLONG;
3113 warn_about_long_long:
3114 if (warning.long_long) {
3115 warningf(&specifiers->source_position,
3116 "ISO C90 does not support 'long long'");
3120 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3121 atomic_type = unsigned_int8_type_kind;
3124 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3125 atomic_type = unsigned_int16_type_kind;
3128 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3129 atomic_type = unsigned_int32_type_kind;
3132 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3133 atomic_type = unsigned_int64_type_kind;
3136 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3137 atomic_type = unsigned_int128_type_kind;
3140 case SPECIFIER_INT8:
3141 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3142 atomic_type = int8_type_kind;
3145 case SPECIFIER_INT16:
3146 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3147 atomic_type = int16_type_kind;
3150 case SPECIFIER_INT32:
3151 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3152 atomic_type = int32_type_kind;
3155 case SPECIFIER_INT64:
3156 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3157 atomic_type = int64_type_kind;
3160 case SPECIFIER_INT128:
3161 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3162 atomic_type = int128_type_kind;
3165 case SPECIFIER_FLOAT:
3166 atomic_type = ATOMIC_TYPE_FLOAT;
3168 case SPECIFIER_DOUBLE:
3169 atomic_type = ATOMIC_TYPE_DOUBLE;
3171 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3172 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3174 case SPECIFIER_BOOL:
3175 atomic_type = ATOMIC_TYPE_BOOL;
3177 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3178 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3179 atomic_type = ATOMIC_TYPE_FLOAT;
3181 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3182 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3183 atomic_type = ATOMIC_TYPE_DOUBLE;
3185 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3186 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3187 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3190 /* invalid specifier combination, give an error message */
3191 source_position_t const* const pos = &specifiers->source_position;
3192 if (type_specifiers == 0) {
3194 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3195 if (!(c_mode & _CXX) && !strict_mode) {
3196 if (warning.implicit_int) {
3197 warningf(pos, "no type specifiers in declaration, using 'int'");
3199 atomic_type = ATOMIC_TYPE_INT;
3202 errorf(pos, "no type specifiers given in declaration");
3205 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3206 (type_specifiers & SPECIFIER_UNSIGNED)) {
3207 errorf(pos, "signed and unsigned specifiers given");
3208 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3209 errorf(pos, "only integer types can be signed or unsigned");
3211 errorf(pos, "multiple datatypes in declaration");
3217 if (type_specifiers & SPECIFIER_COMPLEX) {
3218 type = allocate_type_zero(TYPE_COMPLEX);
3219 type->complex.akind = atomic_type;
3220 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3221 type = allocate_type_zero(TYPE_IMAGINARY);
3222 type->imaginary.akind = atomic_type;
3224 type = allocate_type_zero(TYPE_ATOMIC);
3225 type->atomic.akind = atomic_type;
3228 } else if (type_specifiers != 0) {
3229 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3232 /* FIXME: check type qualifiers here */
3233 type->base.qualifiers = qualifiers;
3236 type = identify_new_type(type);
3238 type = typehash_insert(type);
3241 if (specifiers->attributes != NULL)
3242 type = handle_type_attributes(specifiers->attributes, type);
3243 specifiers->type = type;
3247 specifiers->type = type_error_type;
3250 static type_qualifiers_t parse_type_qualifiers(void)
3252 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3255 switch (token.type) {
3256 /* type qualifiers */
3257 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3258 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3259 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3260 /* microsoft extended type modifiers */
3261 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3262 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3263 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3264 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3265 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3274 * Parses an K&R identifier list
3276 static void parse_identifier_list(scope_t *scope)
3279 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.symbol);
3280 entity->base.source_position = token.source_position;
3281 /* a K&R parameter has no type, yet */
3285 append_entity(scope, entity);
3286 } while (next_if(',') && token.type == T_IDENTIFIER);
3289 static entity_t *parse_parameter(void)
3291 declaration_specifiers_t specifiers;
3292 parse_declaration_specifiers(&specifiers);
3294 entity_t *entity = parse_declarator(&specifiers,
3295 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3296 anonymous_entity = NULL;
3300 static void semantic_parameter_incomplete(const entity_t *entity)
3302 assert(entity->kind == ENTITY_PARAMETER);
3304 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3305 * list in a function declarator that is part of a
3306 * definition of that function shall not have
3307 * incomplete type. */
3308 type_t *type = skip_typeref(entity->declaration.type);
3309 if (is_type_incomplete(type)) {
3310 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3314 static bool has_parameters(void)
3316 /* func(void) is not a parameter */
3317 if (token.type == T_IDENTIFIER) {
3318 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3321 if (entity->kind != ENTITY_TYPEDEF)
3323 if (skip_typeref(entity->typedefe.type) != type_void)
3325 } else if (token.type != T_void) {
3328 if (look_ahead(1)->type != ')')
3335 * Parses function type parameters (and optionally creates variable_t entities
3336 * for them in a scope)
3338 static void parse_parameters(function_type_t *type, scope_t *scope)
3341 add_anchor_token(')');
3342 int saved_comma_state = save_and_reset_anchor_state(',');
3344 if (token.type == T_IDENTIFIER &&
3345 !is_typedef_symbol(token.symbol)) {
3346 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3347 if (la1_type == ',' || la1_type == ')') {
3348 type->kr_style_parameters = true;
3349 parse_identifier_list(scope);
3350 goto parameters_finished;
3354 if (token.type == ')') {
3355 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3356 if (!(c_mode & _CXX))
3357 type->unspecified_parameters = true;
3358 } else if (has_parameters()) {
3359 function_parameter_t **anchor = &type->parameters;
3361 switch (token.type) {
3364 type->variadic = true;
3365 goto parameters_finished;
3368 case T___extension__:
3371 entity_t *entity = parse_parameter();
3372 if (entity->kind == ENTITY_TYPEDEF) {
3373 errorf(&entity->base.source_position,
3374 "typedef not allowed as function parameter");
3377 assert(is_declaration(entity));
3379 semantic_parameter_incomplete(entity);
3381 function_parameter_t *const parameter =
3382 allocate_parameter(entity->declaration.type);
3384 if (scope != NULL) {
3385 append_entity(scope, entity);
3388 *anchor = parameter;
3389 anchor = ¶meter->next;
3394 goto parameters_finished;
3396 } while (next_if(','));
3399 parameters_finished:
3400 rem_anchor_token(')');
3401 expect(')', end_error);
3404 restore_anchor_state(',', saved_comma_state);
3407 typedef enum construct_type_kind_t {
3410 CONSTRUCT_REFERENCE,
3413 } construct_type_kind_t;
3415 typedef union construct_type_t construct_type_t;
3417 typedef struct construct_type_base_t {
3418 construct_type_kind_t kind;
3419 source_position_t pos;
3420 construct_type_t *next;
3421 } construct_type_base_t;
3423 typedef struct parsed_pointer_t {
3424 construct_type_base_t base;
3425 type_qualifiers_t type_qualifiers;
3426 variable_t *base_variable; /**< MS __based extension. */
3429 typedef struct parsed_reference_t {
3430 construct_type_base_t base;
3431 } parsed_reference_t;
3433 typedef struct construct_function_type_t {
3434 construct_type_base_t base;
3435 type_t *function_type;
3436 } construct_function_type_t;
3438 typedef struct parsed_array_t {
3439 construct_type_base_t base;
3440 type_qualifiers_t type_qualifiers;
3446 union construct_type_t {
3447 construct_type_kind_t kind;
3448 construct_type_base_t base;
3449 parsed_pointer_t pointer;
3450 parsed_reference_t reference;
3451 construct_function_type_t function;
3452 parsed_array_t array;
3455 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3457 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3458 memset(cons, 0, size);
3460 cons->base.pos = *HERE;
3465 static construct_type_t *parse_pointer_declarator(void)
3467 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3469 cons->pointer.type_qualifiers = parse_type_qualifiers();
3470 //cons->pointer.base_variable = base_variable;
3475 /* ISO/IEC 14882:1998(E) §8.3.2 */
3476 static construct_type_t *parse_reference_declarator(void)
3478 if (!(c_mode & _CXX))
3479 errorf(HERE, "references are only available for C++");
3481 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3488 static construct_type_t *parse_array_declarator(void)
3490 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3491 parsed_array_t *const array = &cons->array;
3494 add_anchor_token(']');
3496 bool is_static = next_if(T_static);
3498 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3501 is_static = next_if(T_static);
3503 array->type_qualifiers = type_qualifiers;
3504 array->is_static = is_static;
3506 expression_t *size = NULL;
3507 if (token.type == '*' && look_ahead(1)->type == ']') {
3508 array->is_variable = true;
3510 } else if (token.type != ']') {
3511 size = parse_assignment_expression();
3513 /* §6.7.5.2:1 Array size must have integer type */
3514 type_t *const orig_type = size->base.type;
3515 type_t *const type = skip_typeref(orig_type);
3516 if (!is_type_integer(type) && is_type_valid(type)) {
3517 errorf(&size->base.source_position,
3518 "array size '%E' must have integer type but has type '%T'",
3523 mark_vars_read(size, NULL);
3526 if (is_static && size == NULL)
3527 errorf(&array->base.pos, "static array parameters require a size");
3529 rem_anchor_token(']');
3530 expect(']', end_error);
3537 static construct_type_t *parse_function_declarator(scope_t *scope)
3539 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3541 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3542 function_type_t *ftype = &type->function;
3544 ftype->linkage = current_linkage;
3545 ftype->calling_convention = CC_DEFAULT;
3547 parse_parameters(ftype, scope);
3549 cons->function.function_type = type;
3554 typedef struct parse_declarator_env_t {
3555 bool may_be_abstract : 1;
3556 bool must_be_abstract : 1;
3557 decl_modifiers_t modifiers;
3559 source_position_t source_position;
3561 attribute_t *attributes;
3562 } parse_declarator_env_t;
3565 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3567 /* construct a single linked list of construct_type_t's which describe
3568 * how to construct the final declarator type */
3569 construct_type_t *first = NULL;
3570 construct_type_t **anchor = &first;
3572 env->attributes = parse_attributes(env->attributes);
3575 construct_type_t *type;
3576 //variable_t *based = NULL; /* MS __based extension */
3577 switch (token.type) {
3579 type = parse_reference_declarator();
3583 panic("based not supported anymore");
3588 type = parse_pointer_declarator();
3592 goto ptr_operator_end;
3596 anchor = &type->base.next;
3598 /* TODO: find out if this is correct */
3599 env->attributes = parse_attributes(env->attributes);
3603 construct_type_t *inner_types = NULL;
3605 switch (token.type) {
3607 if (env->must_be_abstract) {
3608 errorf(HERE, "no identifier expected in typename");
3610 env->symbol = token.symbol;
3611 env->source_position = token.source_position;
3617 /* Parenthesized declarator or function declarator? */
3618 token_t const *const la1 = look_ahead(1);
3619 switch (la1->type) {
3621 if (is_typedef_symbol(la1->symbol)) {
3623 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3624 * interpreted as ``function with no parameter specification'', rather
3625 * than redundant parentheses around the omitted identifier. */
3627 /* Function declarator. */
3628 if (!env->may_be_abstract) {
3629 errorf(HERE, "function declarator must have a name");
3636 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3637 /* Paranthesized declarator. */
3639 add_anchor_token(')');
3640 inner_types = parse_inner_declarator(env);
3641 if (inner_types != NULL) {
3642 /* All later declarators only modify the return type */
3643 env->must_be_abstract = true;
3645 rem_anchor_token(')');
3646 expect(')', end_error);
3654 if (env->may_be_abstract)
3656 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3661 construct_type_t **const p = anchor;
3664 construct_type_t *type;
3665 switch (token.type) {
3667 scope_t *scope = NULL;
3668 if (!env->must_be_abstract) {
3669 scope = &env->parameters;
3672 type = parse_function_declarator(scope);
3676 type = parse_array_declarator();
3679 goto declarator_finished;
3682 /* insert in the middle of the list (at p) */
3683 type->base.next = *p;
3686 anchor = &type->base.next;
3689 declarator_finished:
3690 /* append inner_types at the end of the list, we don't to set anchor anymore
3691 * as it's not needed anymore */
3692 *anchor = inner_types;
3699 static type_t *construct_declarator_type(construct_type_t *construct_list,
3702 construct_type_t *iter = construct_list;
3703 for (; iter != NULL; iter = iter->base.next) {
3704 source_position_t const* const pos = &iter->base.pos;
3705 switch (iter->kind) {
3706 case CONSTRUCT_INVALID:
3708 case CONSTRUCT_FUNCTION: {
3709 construct_function_type_t *function = &iter->function;
3710 type_t *function_type = function->function_type;
3712 function_type->function.return_type = type;
3714 type_t *skipped_return_type = skip_typeref(type);
3716 if (is_type_function(skipped_return_type)) {
3717 errorf(pos, "function returning function is not allowed");
3718 } else if (is_type_array(skipped_return_type)) {
3719 errorf(pos, "function returning array is not allowed");
3721 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3722 warningf(pos, "type qualifiers in return type of function type are meaningless");
3726 /* The function type was constructed earlier. Freeing it here will
3727 * destroy other types. */
3728 type = typehash_insert(function_type);
3732 case CONSTRUCT_POINTER: {
3733 if (is_type_reference(skip_typeref(type)))
3734 errorf(pos, "cannot declare a pointer to reference");
3736 parsed_pointer_t *pointer = &iter->pointer;
3737 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3741 case CONSTRUCT_REFERENCE:
3742 if (is_type_reference(skip_typeref(type)))
3743 errorf(pos, "cannot declare a reference to reference");
3745 type = make_reference_type(type);
3748 case CONSTRUCT_ARRAY: {
3749 if (is_type_reference(skip_typeref(type)))
3750 errorf(pos, "cannot declare an array of references");
3752 parsed_array_t *array = &iter->array;
3753 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3755 expression_t *size_expression = array->size;
3756 if (size_expression != NULL) {
3758 = create_implicit_cast(size_expression, type_size_t);
3761 array_type->base.qualifiers = array->type_qualifiers;
3762 array_type->array.element_type = type;
3763 array_type->array.is_static = array->is_static;
3764 array_type->array.is_variable = array->is_variable;
3765 array_type->array.size_expression = size_expression;
3767 if (size_expression != NULL) {
3768 switch (is_constant_expression(size_expression)) {
3769 case EXPR_CLASS_CONSTANT: {
3770 long const size = fold_constant_to_int(size_expression);
3771 array_type->array.size = size;
3772 array_type->array.size_constant = true;
3773 /* §6.7.5.2:1 If the expression is a constant expression,
3774 * it shall have a value greater than zero. */
3776 errorf(&size_expression->base.source_position,
3777 "size of array must be greater than zero");
3778 } else if (size == 0 && !GNU_MODE) {
3779 errorf(&size_expression->base.source_position,
3780 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3785 case EXPR_CLASS_VARIABLE:
3786 array_type->array.is_vla = true;
3789 case EXPR_CLASS_ERROR:
3794 type_t *skipped_type = skip_typeref(type);
3796 if (is_type_incomplete(skipped_type)) {
3797 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3798 } else if (is_type_function(skipped_type)) {
3799 errorf(pos, "array of functions is not allowed");
3801 type = identify_new_type(array_type);
3805 internal_errorf(pos, "invalid type construction found");
3811 static type_t *automatic_type_conversion(type_t *orig_type);
3813 static type_t *semantic_parameter(const source_position_t *pos,
3815 const declaration_specifiers_t *specifiers,
3816 entity_t const *const param)
3818 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3819 * shall be adjusted to ``qualified pointer to type'',
3821 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3822 * type'' shall be adjusted to ``pointer to function
3823 * returning type'', as in 6.3.2.1. */
3824 type = automatic_type_conversion(type);
3826 if (specifiers->is_inline && is_type_valid(type)) {
3827 errorf(pos, "'%N' declared 'inline'", param);
3830 /* §6.9.1:6 The declarations in the declaration list shall contain
3831 * no storage-class specifier other than register and no
3832 * initializations. */
3833 if (specifiers->thread_local || (
3834 specifiers->storage_class != STORAGE_CLASS_NONE &&
3835 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3837 errorf(pos, "invalid storage class for '%N'", param);
3840 /* delay test for incomplete type, because we might have (void)
3841 * which is legal but incomplete... */
3846 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3847 declarator_flags_t flags)
3849 parse_declarator_env_t env;
3850 memset(&env, 0, sizeof(env));
3851 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3853 construct_type_t *construct_type = parse_inner_declarator(&env);
3855 construct_declarator_type(construct_type, specifiers->type);
3856 type_t *type = skip_typeref(orig_type);
3858 if (construct_type != NULL) {
3859 obstack_free(&temp_obst, construct_type);
3862 attribute_t *attributes = parse_attributes(env.attributes);
3863 /* append (shared) specifier attribute behind attributes of this
3865 attribute_t **anchor = &attributes;
3866 while (*anchor != NULL)
3867 anchor = &(*anchor)->next;
3868 *anchor = specifiers->attributes;
3871 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3872 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3873 entity->base.source_position = env.source_position;
3874 entity->typedefe.type = orig_type;
3876 if (anonymous_entity != NULL) {
3877 if (is_type_compound(type)) {
3878 assert(anonymous_entity->compound.alias == NULL);
3879 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3880 anonymous_entity->kind == ENTITY_UNION);
3881 anonymous_entity->compound.alias = entity;
3882 anonymous_entity = NULL;
3883 } else if (is_type_enum(type)) {
3884 assert(anonymous_entity->enume.alias == NULL);
3885 assert(anonymous_entity->kind == ENTITY_ENUM);
3886 anonymous_entity->enume.alias = entity;
3887 anonymous_entity = NULL;
3891 /* create a declaration type entity */
3892 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3893 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3895 if (env.symbol != NULL) {
3896 if (specifiers->is_inline && is_type_valid(type)) {
3897 errorf(&env.source_position,
3898 "compound member '%Y' declared 'inline'", env.symbol);
3901 if (specifiers->thread_local ||
3902 specifiers->storage_class != STORAGE_CLASS_NONE) {
3903 errorf(&env.source_position,
3904 "compound member '%Y' must have no storage class",
3908 } else if (flags & DECL_IS_PARAMETER) {
3909 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3910 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3911 } else if (is_type_function(type)) {
3912 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3913 entity->function.is_inline = specifiers->is_inline;
3914 entity->function.elf_visibility = default_visibility;
3915 entity->function.parameters = env.parameters;
3917 if (env.symbol != NULL) {
3918 /* this needs fixes for C++ */
3919 bool in_function_scope = current_function != NULL;
3921 if (specifiers->thread_local || (
3922 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3923 specifiers->storage_class != STORAGE_CLASS_NONE &&
3924 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3926 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3930 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3931 entity->variable.elf_visibility = default_visibility;
3932 entity->variable.thread_local = specifiers->thread_local;
3934 if (env.symbol != NULL) {
3935 if (specifiers->is_inline && is_type_valid(type)) {
3936 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3939 bool invalid_storage_class = false;
3940 if (current_scope == file_scope) {
3941 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3942 specifiers->storage_class != STORAGE_CLASS_NONE &&
3943 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3944 invalid_storage_class = true;
3947 if (specifiers->thread_local &&
3948 specifiers->storage_class == STORAGE_CLASS_NONE) {
3949 invalid_storage_class = true;
3952 if (invalid_storage_class) {
3953 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3958 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3959 entity->declaration.type = orig_type;
3960 entity->declaration.alignment = get_type_alignment(orig_type);
3961 entity->declaration.modifiers = env.modifiers;
3962 entity->declaration.attributes = attributes;
3964 storage_class_t storage_class = specifiers->storage_class;
3965 entity->declaration.declared_storage_class = storage_class;
3967 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3968 storage_class = STORAGE_CLASS_AUTO;
3969 entity->declaration.storage_class = storage_class;
3972 if (attributes != NULL) {
3973 handle_entity_attributes(attributes, entity);
3979 static type_t *parse_abstract_declarator(type_t *base_type)
3981 parse_declarator_env_t env;
3982 memset(&env, 0, sizeof(env));
3983 env.may_be_abstract = true;
3984 env.must_be_abstract = true;
3986 construct_type_t *construct_type = parse_inner_declarator(&env);
3988 type_t *result = construct_declarator_type(construct_type, base_type);
3989 if (construct_type != NULL) {
3990 obstack_free(&temp_obst, construct_type);
3992 result = handle_type_attributes(env.attributes, result);
3998 * Check if the declaration of main is suspicious. main should be a
3999 * function with external linkage, returning int, taking either zero
4000 * arguments, two, or three arguments of appropriate types, ie.
4002 * int main([ int argc, char **argv [, char **env ] ]).
4004 * @param decl the declaration to check
4005 * @param type the function type of the declaration
4007 static void check_main(const entity_t *entity)
4009 const source_position_t *pos = &entity->base.source_position;
4010 if (entity->kind != ENTITY_FUNCTION) {
4011 warningf(pos, "'main' is not a function");
4015 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4016 warningf(pos, "'main' is normally a non-static function");
4019 type_t *type = skip_typeref(entity->declaration.type);
4020 assert(is_type_function(type));
4022 function_type_t *func_type = &type->function;
4023 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4024 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4025 func_type->return_type);
4027 const function_parameter_t *parm = func_type->parameters;
4029 type_t *const first_type = skip_typeref(parm->type);
4030 type_t *const first_type_unqual = get_unqualified_type(first_type);
4031 if (!types_compatible(first_type_unqual, type_int)) {
4033 "first argument of 'main' should be 'int', but is '%T'",
4038 type_t *const second_type = skip_typeref(parm->type);
4039 type_t *const second_type_unqual
4040 = get_unqualified_type(second_type);
4041 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4042 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'",
4047 type_t *const third_type = skip_typeref(parm->type);
4048 type_t *const third_type_unqual
4049 = get_unqualified_type(third_type);
4050 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4051 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'",
4056 goto warn_arg_count;
4060 warningf(pos, "'main' takes only zero, two or three arguments");
4066 * Check if a symbol is the equal to "main".
4068 static bool is_sym_main(const symbol_t *const sym)
4070 return strcmp(sym->string, "main") == 0;
4073 static void error_redefined_as_different_kind(const source_position_t *pos,
4074 const entity_t *old, entity_kind_t new_kind)
4076 char const *const what = get_entity_kind_name(new_kind);
4077 source_position_t const *const ppos = &old->base.source_position;
4078 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4081 static bool is_entity_valid(entity_t *const ent)
4083 if (is_declaration(ent)) {
4084 return is_type_valid(skip_typeref(ent->declaration.type));
4085 } else if (ent->kind == ENTITY_TYPEDEF) {
4086 return is_type_valid(skip_typeref(ent->typedefe.type));
4091 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4093 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4094 if (attributes_equal(tattr, attr))
4101 * test wether new_list contains any attributes not included in old_list
4103 static bool has_new_attributes(const attribute_t *old_list,
4104 const attribute_t *new_list)
4106 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4107 if (!contains_attribute(old_list, attr))
4114 * Merge in attributes from an attribute list (probably from a previous
4115 * declaration with the same name). Warning: destroys the old structure
4116 * of the attribute list - don't reuse attributes after this call.
4118 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4121 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4123 if (contains_attribute(decl->attributes, attr))
4126 /* move attribute to new declarations attributes list */
4127 attr->next = decl->attributes;
4128 decl->attributes = attr;
4133 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4134 * for various problems that occur for multiple definitions
4136 entity_t *record_entity(entity_t *entity, const bool is_definition)
4138 const symbol_t *const symbol = entity->base.symbol;
4139 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4140 const source_position_t *pos = &entity->base.source_position;
4142 /* can happen in error cases */
4146 entity_t *const previous_entity = get_entity(symbol, namespc);
4147 /* pushing the same entity twice will break the stack structure */
4148 assert(previous_entity != entity);
4150 if (entity->kind == ENTITY_FUNCTION) {
4151 type_t *const orig_type = entity->declaration.type;
4152 type_t *const type = skip_typeref(orig_type);
4154 assert(is_type_function(type));
4155 if (type->function.unspecified_parameters &&
4156 warning.strict_prototypes &&
4157 previous_entity == NULL) {
4158 warningf(pos, "function declaration '%#N' is not a prototype", entity);
4161 if (warning.main && current_scope == file_scope
4162 && is_sym_main(symbol)) {
4167 if (is_declaration(entity) &&
4168 warning.nested_externs &&
4169 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4170 current_scope != file_scope) {
4171 warningf(pos, "nested extern declaration of '%#N'", entity);
4174 if (previous_entity != NULL) {
4175 source_position_t const *const ppos = &previous_entity->base.source_position;
4177 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4178 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4179 assert(previous_entity->kind == ENTITY_PARAMETER);
4180 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4184 if (previous_entity->base.parent_scope == current_scope) {
4185 if (previous_entity->kind != entity->kind) {
4186 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4187 error_redefined_as_different_kind(pos, previous_entity,
4192 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4193 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4196 if (previous_entity->kind == ENTITY_TYPEDEF) {
4197 /* TODO: C++ allows this for exactly the same type */
4198 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4202 /* at this point we should have only VARIABLES or FUNCTIONS */
4203 assert(is_declaration(previous_entity) && is_declaration(entity));
4205 declaration_t *const prev_decl = &previous_entity->declaration;
4206 declaration_t *const decl = &entity->declaration;
4208 /* can happen for K&R style declarations */
4209 if (prev_decl->type == NULL &&
4210 previous_entity->kind == ENTITY_PARAMETER &&
4211 entity->kind == ENTITY_PARAMETER) {
4212 prev_decl->type = decl->type;
4213 prev_decl->storage_class = decl->storage_class;
4214 prev_decl->declared_storage_class = decl->declared_storage_class;
4215 prev_decl->modifiers = decl->modifiers;
4216 return previous_entity;
4219 type_t *const type = skip_typeref(decl->type);
4220 type_t *const prev_type = skip_typeref(prev_decl->type);
4222 if (!types_compatible(type, prev_type)) {
4223 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4225 unsigned old_storage_class = prev_decl->storage_class;
4227 if (warning.redundant_decls &&
4230 !(prev_decl->modifiers & DM_USED) &&
4231 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4232 warningf(ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4235 storage_class_t new_storage_class = decl->storage_class;
4237 /* pretend no storage class means extern for function
4238 * declarations (except if the previous declaration is neither
4239 * none nor extern) */
4240 if (entity->kind == ENTITY_FUNCTION) {
4241 /* the previous declaration could have unspecified parameters or
4242 * be a typedef, so use the new type */
4243 if (prev_type->function.unspecified_parameters || is_definition)
4244 prev_decl->type = type;
4246 switch (old_storage_class) {
4247 case STORAGE_CLASS_NONE:
4248 old_storage_class = STORAGE_CLASS_EXTERN;
4251 case STORAGE_CLASS_EXTERN:
4252 if (is_definition) {
4253 if (warning.missing_prototypes &&
4254 prev_type->function.unspecified_parameters &&
4255 !is_sym_main(symbol)) {
4256 warningf(pos, "no previous prototype for '%#N'", entity);
4258 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4259 new_storage_class = STORAGE_CLASS_EXTERN;
4266 } else if (is_type_incomplete(prev_type)) {
4267 prev_decl->type = type;
4270 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4271 new_storage_class == STORAGE_CLASS_EXTERN) {
4273 warn_redundant_declaration: ;
4275 = has_new_attributes(prev_decl->attributes,
4277 if (has_new_attrs) {
4278 merge_in_attributes(decl, prev_decl->attributes);
4279 } else if (!is_definition &&
4280 warning.redundant_decls &&
4281 is_type_valid(prev_type) &&
4282 strcmp(ppos->input_name, "<builtin>") != 0) {
4283 warningf(pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4285 } else if (current_function == NULL) {
4286 if (old_storage_class != STORAGE_CLASS_STATIC &&
4287 new_storage_class == STORAGE_CLASS_STATIC) {
4288 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4289 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4290 prev_decl->storage_class = STORAGE_CLASS_NONE;
4291 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4293 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4295 goto error_redeclaration;
4296 goto warn_redundant_declaration;
4298 } else if (is_type_valid(prev_type)) {
4299 if (old_storage_class == new_storage_class) {
4300 error_redeclaration:
4301 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4303 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4308 prev_decl->modifiers |= decl->modifiers;
4309 if (entity->kind == ENTITY_FUNCTION) {
4310 previous_entity->function.is_inline |= entity->function.is_inline;
4312 return previous_entity;
4315 if (warning.shadow ||
4316 (warning.shadow_local && previous_entity->base.parent_scope != file_scope)) {
4317 char const *const what = get_entity_kind_name(previous_entity->kind);
4318 warningf(pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4322 if (entity->kind == ENTITY_FUNCTION) {
4323 if (is_definition &&
4324 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4325 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4326 warningf(pos, "no previous prototype for '%#N'", entity);
4327 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4328 warningf(pos, "no previous declaration for '%#N'", entity);
4331 } else if (entity->kind == ENTITY_VARIABLE) {
4332 if (warning.missing_declarations &&
4333 current_scope == file_scope &&
4334 entity->declaration.storage_class == STORAGE_CLASS_NONE) {
4335 warningf(pos, "no previous declaration for '%#N'", entity);
4340 assert(entity->base.parent_scope == NULL);
4341 assert(current_scope != NULL);
4343 entity->base.parent_scope = current_scope;
4344 environment_push(entity);
4345 append_entity(current_scope, entity);
4350 static void parser_error_multiple_definition(entity_t *entity,
4351 const source_position_t *source_position)
4353 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4354 entity->base.symbol, &entity->base.source_position);
4357 static bool is_declaration_specifier(const token_t *token)
4359 switch (token->type) {
4363 return is_typedef_symbol(token->symbol);
4370 static void parse_init_declarator_rest(entity_t *entity)
4372 type_t *orig_type = type_error_type;
4374 if (entity->base.kind == ENTITY_TYPEDEF) {
4375 source_position_t const *const pos = &entity->base.source_position;
4376 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4378 assert(is_declaration(entity));
4379 orig_type = entity->declaration.type;
4382 type_t *type = skip_typeref(orig_type);
4384 if (entity->kind == ENTITY_VARIABLE
4385 && entity->variable.initializer != NULL) {
4386 parser_error_multiple_definition(entity, HERE);
4390 declaration_t *const declaration = &entity->declaration;
4391 bool must_be_constant = false;
4392 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4393 entity->base.parent_scope == file_scope) {
4394 must_be_constant = true;
4397 if (is_type_function(type)) {
4398 source_position_t const *const pos = &entity->base.source_position;
4399 errorf(pos, "'%N' is initialized like a variable", entity);
4400 orig_type = type_error_type;
4403 parse_initializer_env_t env;
4404 env.type = orig_type;
4405 env.must_be_constant = must_be_constant;
4406 env.entity = entity;
4407 current_init_decl = entity;
4409 initializer_t *initializer = parse_initializer(&env);
4410 current_init_decl = NULL;
4412 if (entity->kind == ENTITY_VARIABLE) {
4413 /* §6.7.5:22 array initializers for arrays with unknown size
4414 * determine the array type size */
4415 declaration->type = env.type;
4416 entity->variable.initializer = initializer;
4420 /* parse rest of a declaration without any declarator */
4421 static void parse_anonymous_declaration_rest(
4422 const declaration_specifiers_t *specifiers)
4425 anonymous_entity = NULL;
4427 if (warning.other) {
4428 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4429 specifiers->thread_local) {
4430 warningf(&specifiers->source_position,
4431 "useless storage class in empty declaration");
4434 type_t *type = specifiers->type;
4435 switch (type->kind) {
4436 case TYPE_COMPOUND_STRUCT:
4437 case TYPE_COMPOUND_UNION: {
4438 if (type->compound.compound->base.symbol == NULL) {
4439 warningf(&specifiers->source_position,
4440 "unnamed struct/union that defines no instances");
4449 warningf(&specifiers->source_position, "empty declaration");
4455 static void check_variable_type_complete(entity_t *ent)
4457 if (ent->kind != ENTITY_VARIABLE)
4460 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4461 * type for the object shall be complete [...] */
4462 declaration_t *decl = &ent->declaration;
4463 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4464 decl->storage_class == STORAGE_CLASS_STATIC)
4467 type_t *const type = skip_typeref(decl->type);
4468 if (!is_type_incomplete(type))
4471 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4472 * are given length one. */
4473 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4474 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4478 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4482 static void parse_declaration_rest(entity_t *ndeclaration,
4483 const declaration_specifiers_t *specifiers,
4484 parsed_declaration_func finished_declaration,
4485 declarator_flags_t flags)
4487 add_anchor_token(';');
4488 add_anchor_token(',');
4490 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4492 if (token.type == '=') {
4493 parse_init_declarator_rest(entity);
4494 } else if (entity->kind == ENTITY_VARIABLE) {
4495 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4496 * [...] where the extern specifier is explicitly used. */
4497 declaration_t *decl = &entity->declaration;
4498 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4499 type_t *type = decl->type;
4500 if (is_type_reference(skip_typeref(type))) {
4501 source_position_t const *const pos = &entity->base.source_position;
4502 errorf(pos, "reference '%#N' must be initialized", entity);
4507 check_variable_type_complete(entity);
4512 add_anchor_token('=');
4513 ndeclaration = parse_declarator(specifiers, flags);
4514 rem_anchor_token('=');
4516 expect(';', end_error);
4519 anonymous_entity = NULL;
4520 rem_anchor_token(';');
4521 rem_anchor_token(',');
4524 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4526 symbol_t *symbol = entity->base.symbol;
4530 assert(entity->base.namespc == NAMESPACE_NORMAL);
4531 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4532 if (previous_entity == NULL
4533 || previous_entity->base.parent_scope != current_scope) {
4534 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4539 if (is_definition) {
4540 errorf(HERE, "'%N' is initialised", entity);
4543 return record_entity(entity, false);
4546 static void parse_declaration(parsed_declaration_func finished_declaration,
4547 declarator_flags_t flags)
4549 add_anchor_token(';');
4550 declaration_specifiers_t specifiers;
4551 parse_declaration_specifiers(&specifiers);
4552 rem_anchor_token(';');
4554 if (token.type == ';') {
4555 parse_anonymous_declaration_rest(&specifiers);
4557 entity_t *entity = parse_declarator(&specifiers, flags);
4558 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4563 static type_t *get_default_promoted_type(type_t *orig_type)
4565 type_t *result = orig_type;
4567 type_t *type = skip_typeref(orig_type);
4568 if (is_type_integer(type)) {
4569 result = promote_integer(type);
4570 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4571 result = type_double;
4577 static void parse_kr_declaration_list(entity_t *entity)
4579 if (entity->kind != ENTITY_FUNCTION)
4582 type_t *type = skip_typeref(entity->declaration.type);
4583 assert(is_type_function(type));
4584 if (!type->function.kr_style_parameters)
4587 add_anchor_token('{');
4589 /* push function parameters */
4590 size_t const top = environment_top();
4591 scope_t *old_scope = scope_push(&entity->function.parameters);
4593 entity_t *parameter = entity->function.parameters.entities;
4594 for ( ; parameter != NULL; parameter = parameter->base.next) {
4595 assert(parameter->base.parent_scope == NULL);
4596 parameter->base.parent_scope = current_scope;
4597 environment_push(parameter);
4600 /* parse declaration list */
4602 switch (token.type) {
4604 case T___extension__:
4605 /* This covers symbols, which are no type, too, and results in
4606 * better error messages. The typical cases are misspelled type
4607 * names and missing includes. */
4609 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4617 /* pop function parameters */
4618 assert(current_scope == &entity->function.parameters);
4619 scope_pop(old_scope);
4620 environment_pop_to(top);
4622 /* update function type */
4623 type_t *new_type = duplicate_type(type);
4625 function_parameter_t *parameters = NULL;
4626 function_parameter_t **anchor = ¶meters;
4628 /* did we have an earlier prototype? */
4629 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4630 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4633 function_parameter_t *proto_parameter = NULL;
4634 if (proto_type != NULL) {
4635 type_t *proto_type_type = proto_type->declaration.type;
4636 proto_parameter = proto_type_type->function.parameters;
4637 /* If a K&R function definition has a variadic prototype earlier, then
4638 * make the function definition variadic, too. This should conform to
4639 * §6.7.5.3:15 and §6.9.1:8. */
4640 new_type->function.variadic = proto_type_type->function.variadic;
4642 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4644 new_type->function.unspecified_parameters = true;
4647 bool need_incompatible_warning = false;
4648 parameter = entity->function.parameters.entities;
4649 for (; parameter != NULL; parameter = parameter->base.next,
4651 proto_parameter == NULL ? NULL : proto_parameter->next) {
4652 if (parameter->kind != ENTITY_PARAMETER)
4655 type_t *parameter_type = parameter->declaration.type;
4656 if (parameter_type == NULL) {
4657 source_position_t const* const pos = ¶meter->base.source_position;
4659 errorf(pos, "no type specified for function '%N'", parameter);
4660 parameter_type = type_error_type;
4662 if (warning.implicit_int) {
4663 warningf(pos, "no type specified for function '%N', using 'int'", parameter);
4665 parameter_type = type_int;
4667 parameter->declaration.type = parameter_type;
4670 semantic_parameter_incomplete(parameter);
4672 /* we need the default promoted types for the function type */
4673 type_t *not_promoted = parameter_type;
4674 parameter_type = get_default_promoted_type(parameter_type);
4676 /* gcc special: if the type of the prototype matches the unpromoted
4677 * type don't promote */
4678 if (!strict_mode && proto_parameter != NULL) {
4679 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4680 type_t *promo_skip = skip_typeref(parameter_type);
4681 type_t *param_skip = skip_typeref(not_promoted);
4682 if (!types_compatible(proto_p_type, promo_skip)
4683 && types_compatible(proto_p_type, param_skip)) {
4685 need_incompatible_warning = true;
4686 parameter_type = not_promoted;
4689 function_parameter_t *const function_parameter
4690 = allocate_parameter(parameter_type);
4692 *anchor = function_parameter;
4693 anchor = &function_parameter->next;
4696 new_type->function.parameters = parameters;
4697 new_type = identify_new_type(new_type);
4699 if (warning.other && need_incompatible_warning) {
4700 source_position_t const *const pos = &entity->base.source_position;
4701 source_position_t const *const ppos = &proto_type->base.source_position;
4702 symbol_t const *const sym = entity->base.symbol;
4703 warningf(pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4705 entity->declaration.type = new_type;
4707 rem_anchor_token('{');
4710 static bool first_err = true;
4713 * When called with first_err set, prints the name of the current function,
4716 static void print_in_function(void)
4720 char const *const file = current_function->base.base.source_position.input_name;
4721 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4726 * Check if all labels are defined in the current function.
4727 * Check if all labels are used in the current function.
4729 static void check_labels(void)
4731 for (const goto_statement_t *goto_statement = goto_first;
4732 goto_statement != NULL;
4733 goto_statement = goto_statement->next) {
4734 /* skip computed gotos */
4735 if (goto_statement->expression != NULL)
4738 label_t *label = goto_statement->label;
4739 if (label->base.source_position.input_name == NULL) {
4740 print_in_function();
4741 source_position_t const *const pos = &goto_statement->base.source_position;
4742 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4746 if (warning.unused_label) {
4747 for (const label_statement_t *label_statement = label_first;
4748 label_statement != NULL;
4749 label_statement = label_statement->next) {
4750 label_t *label = label_statement->label;
4752 if (! label->used) {
4753 print_in_function();
4754 source_position_t const *const pos = &label_statement->base.source_position;
4755 warningf(pos, "'%N' defined but not used", (entity_t const*)label);
4761 static void warn_unused_entity(entity_t *entity, entity_t *last)
4763 entity_t const *const end = last != NULL ? last->base.next : NULL;
4764 for (; entity != end; entity = entity->base.next) {
4765 if (!is_declaration(entity))
4768 declaration_t *declaration = &entity->declaration;
4769 if (declaration->implicit)
4772 if (!declaration->used) {
4773 print_in_function();
4774 warningf(&entity->base.source_position, "'%N' is unused", entity);
4775 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4776 print_in_function();
4777 warningf(&entity->base.source_position, "'%N' is never read", entity);
4782 static void check_unused_variables(statement_t *const stmt, void *const env)
4786 switch (stmt->kind) {
4787 case STATEMENT_DECLARATION: {
4788 declaration_statement_t const *const decls = &stmt->declaration;
4789 warn_unused_entity(decls->declarations_begin,
4790 decls->declarations_end);
4795 warn_unused_entity(stmt->fors.scope.entities, NULL);
4804 * Check declarations of current_function for unused entities.
4806 static void check_declarations(void)
4808 if (warning.unused_parameter) {
4809 const scope_t *scope = ¤t_function->parameters;
4811 /* do not issue unused warnings for main */
4812 if (!is_sym_main(current_function->base.base.symbol)) {
4813 warn_unused_entity(scope->entities, NULL);
4816 if (warning.unused_variable) {
4817 walk_statements(current_function->statement, check_unused_variables,
4822 static int determine_truth(expression_t const* const cond)
4825 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4826 fold_constant_to_bool(cond) ? 1 :
4830 static void check_reachable(statement_t *);
4831 static bool reaches_end;
4833 static bool expression_returns(expression_t const *const expr)
4835 switch (expr->kind) {
4837 expression_t const *const func = expr->call.function;
4838 if (func->kind == EXPR_REFERENCE) {
4839 entity_t *entity = func->reference.entity;
4840 if (entity->kind == ENTITY_FUNCTION
4841 && entity->declaration.modifiers & DM_NORETURN)
4845 if (!expression_returns(func))
4848 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4849 if (!expression_returns(arg->expression))
4856 case EXPR_REFERENCE:
4857 case EXPR_REFERENCE_ENUM_VALUE:
4859 case EXPR_STRING_LITERAL:
4860 case EXPR_WIDE_STRING_LITERAL:
4861 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4862 case EXPR_LABEL_ADDRESS:
4863 case EXPR_CLASSIFY_TYPE:
4864 case EXPR_SIZEOF: // TODO handle obscure VLA case
4867 case EXPR_BUILTIN_CONSTANT_P:
4868 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4873 case EXPR_STATEMENT: {
4874 bool old_reaches_end = reaches_end;
4875 reaches_end = false;
4876 check_reachable(expr->statement.statement);
4877 bool returns = reaches_end;
4878 reaches_end = old_reaches_end;
4882 case EXPR_CONDITIONAL:
4883 // TODO handle constant expression
4885 if (!expression_returns(expr->conditional.condition))
4888 if (expr->conditional.true_expression != NULL
4889 && expression_returns(expr->conditional.true_expression))
4892 return expression_returns(expr->conditional.false_expression);
4895 return expression_returns(expr->select.compound);
4897 case EXPR_ARRAY_ACCESS:
4899 expression_returns(expr->array_access.array_ref) &&
4900 expression_returns(expr->array_access.index);
4903 return expression_returns(expr->va_starte.ap);
4906 return expression_returns(expr->va_arge.ap);
4909 return expression_returns(expr->va_copye.src);
4911 EXPR_UNARY_CASES_MANDATORY
4912 return expression_returns(expr->unary.value);
4914 case EXPR_UNARY_THROW:
4918 // TODO handle constant lhs of && and ||
4920 expression_returns(expr->binary.left) &&
4921 expression_returns(expr->binary.right);
4927 panic("unhandled expression");
4930 static bool initializer_returns(initializer_t const *const init)
4932 switch (init->kind) {
4933 case INITIALIZER_VALUE:
4934 return expression_returns(init->value.value);
4936 case INITIALIZER_LIST: {
4937 initializer_t * const* i = init->list.initializers;
4938 initializer_t * const* const end = i + init->list.len;
4939 bool returns = true;
4940 for (; i != end; ++i) {
4941 if (!initializer_returns(*i))
4947 case INITIALIZER_STRING:
4948 case INITIALIZER_WIDE_STRING:
4949 case INITIALIZER_DESIGNATOR: // designators have no payload
4952 panic("unhandled initializer");
4955 static bool noreturn_candidate;
4957 static void check_reachable(statement_t *const stmt)
4959 if (stmt->base.reachable)
4961 if (stmt->kind != STATEMENT_DO_WHILE)
4962 stmt->base.reachable = true;
4964 statement_t *last = stmt;
4966 switch (stmt->kind) {
4967 case STATEMENT_INVALID:
4968 case STATEMENT_EMPTY:
4970 next = stmt->base.next;
4973 case STATEMENT_DECLARATION: {
4974 declaration_statement_t const *const decl = &stmt->declaration;
4975 entity_t const * ent = decl->declarations_begin;
4976 entity_t const *const last_decl = decl->declarations_end;
4978 for (;; ent = ent->base.next) {
4979 if (ent->kind == ENTITY_VARIABLE &&
4980 ent->variable.initializer != NULL &&
4981 !initializer_returns(ent->variable.initializer)) {
4984 if (ent == last_decl)
4988 next = stmt->base.next;
4992 case STATEMENT_COMPOUND:
4993 next = stmt->compound.statements;
4995 next = stmt->base.next;
4998 case STATEMENT_RETURN: {
4999 expression_t const *const val = stmt->returns.value;
5000 if (val == NULL || expression_returns(val))
5001 noreturn_candidate = false;
5005 case STATEMENT_IF: {
5006 if_statement_t const *const ifs = &stmt->ifs;
5007 expression_t const *const cond = ifs->condition;
5009 if (!expression_returns(cond))
5012 int const val = determine_truth(cond);
5015 check_reachable(ifs->true_statement);
5020 if (ifs->false_statement != NULL) {
5021 check_reachable(ifs->false_statement);
5025 next = stmt->base.next;
5029 case STATEMENT_SWITCH: {
5030 switch_statement_t const *const switchs = &stmt->switchs;
5031 expression_t const *const expr = switchs->expression;
5033 if (!expression_returns(expr))
5036 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5037 long const val = fold_constant_to_int(expr);
5038 case_label_statement_t * defaults = NULL;
5039 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5040 if (i->expression == NULL) {
5045 if (i->first_case <= val && val <= i->last_case) {
5046 check_reachable((statement_t*)i);
5051 if (defaults != NULL) {
5052 check_reachable((statement_t*)defaults);
5056 bool has_default = false;
5057 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5058 if (i->expression == NULL)
5061 check_reachable((statement_t*)i);
5068 next = stmt->base.next;
5072 case STATEMENT_EXPRESSION: {
5073 /* Check for noreturn function call */
5074 expression_t const *const expr = stmt->expression.expression;
5075 if (!expression_returns(expr))
5078 next = stmt->base.next;
5082 case STATEMENT_CONTINUE:
5083 for (statement_t *parent = stmt;;) {
5084 parent = parent->base.parent;
5085 if (parent == NULL) /* continue not within loop */
5089 switch (parent->kind) {
5090 case STATEMENT_WHILE: goto continue_while;
5091 case STATEMENT_DO_WHILE: goto continue_do_while;
5092 case STATEMENT_FOR: goto continue_for;
5098 case STATEMENT_BREAK:
5099 for (statement_t *parent = stmt;;) {
5100 parent = parent->base.parent;
5101 if (parent == NULL) /* break not within loop/switch */
5104 switch (parent->kind) {
5105 case STATEMENT_SWITCH:
5106 case STATEMENT_WHILE:
5107 case STATEMENT_DO_WHILE:
5110 next = parent->base.next;
5111 goto found_break_parent;
5119 case STATEMENT_GOTO:
5120 if (stmt->gotos.expression) {
5121 if (!expression_returns(stmt->gotos.expression))
5124 statement_t *parent = stmt->base.parent;
5125 if (parent == NULL) /* top level goto */
5129 next = stmt->gotos.label->statement;
5130 if (next == NULL) /* missing label */
5135 case STATEMENT_LABEL:
5136 next = stmt->label.statement;
5139 case STATEMENT_CASE_LABEL:
5140 next = stmt->case_label.statement;
5143 case STATEMENT_WHILE: {
5144 while_statement_t const *const whiles = &stmt->whiles;
5145 expression_t const *const cond = whiles->condition;
5147 if (!expression_returns(cond))
5150 int const val = determine_truth(cond);
5153 check_reachable(whiles->body);
5158 next = stmt->base.next;
5162 case STATEMENT_DO_WHILE:
5163 next = stmt->do_while.body;
5166 case STATEMENT_FOR: {
5167 for_statement_t *const fors = &stmt->fors;
5169 if (fors->condition_reachable)
5171 fors->condition_reachable = true;
5173 expression_t const *const cond = fors->condition;
5178 } else if (expression_returns(cond)) {
5179 val = determine_truth(cond);
5185 check_reachable(fors->body);
5190 next = stmt->base.next;
5194 case STATEMENT_MS_TRY: {
5195 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5196 check_reachable(ms_try->try_statement);
5197 next = ms_try->final_statement;
5201 case STATEMENT_LEAVE: {
5202 statement_t *parent = stmt;
5204 parent = parent->base.parent;
5205 if (parent == NULL) /* __leave not within __try */
5208 if (parent->kind == STATEMENT_MS_TRY) {
5210 next = parent->ms_try.final_statement;
5218 panic("invalid statement kind");
5221 while (next == NULL) {
5222 next = last->base.parent;
5224 noreturn_candidate = false;
5226 type_t *const type = skip_typeref(current_function->base.type);
5227 assert(is_type_function(type));
5228 type_t *const ret = skip_typeref(type->function.return_type);
5229 if (warning.return_type &&
5230 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5231 is_type_valid(ret) &&
5232 !is_sym_main(current_function->base.base.symbol)) {
5233 warningf(&stmt->base.source_position,
5234 "control reaches end of non-void function");
5239 switch (next->kind) {
5240 case STATEMENT_INVALID:
5241 case STATEMENT_EMPTY:
5242 case STATEMENT_DECLARATION:
5243 case STATEMENT_EXPRESSION:
5245 case STATEMENT_RETURN:
5246 case STATEMENT_CONTINUE:
5247 case STATEMENT_BREAK:
5248 case STATEMENT_GOTO:
5249 case STATEMENT_LEAVE:
5250 panic("invalid control flow in function");
5252 case STATEMENT_COMPOUND:
5253 if (next->compound.stmt_expr) {
5259 case STATEMENT_SWITCH:
5260 case STATEMENT_LABEL:
5261 case STATEMENT_CASE_LABEL:
5263 next = next->base.next;
5266 case STATEMENT_WHILE: {
5268 if (next->base.reachable)
5270 next->base.reachable = true;
5272 while_statement_t const *const whiles = &next->whiles;
5273 expression_t const *const cond = whiles->condition;
5275 if (!expression_returns(cond))
5278 int const val = determine_truth(cond);
5281 check_reachable(whiles->body);
5287 next = next->base.next;
5291 case STATEMENT_DO_WHILE: {
5293 if (next->base.reachable)
5295 next->base.reachable = true;
5297 do_while_statement_t const *const dw = &next->do_while;
5298 expression_t const *const cond = dw->condition;
5300 if (!expression_returns(cond))
5303 int const val = determine_truth(cond);
5306 check_reachable(dw->body);
5312 next = next->base.next;
5316 case STATEMENT_FOR: {
5318 for_statement_t *const fors = &next->fors;
5320 fors->step_reachable = true;
5322 if (fors->condition_reachable)
5324 fors->condition_reachable = true;
5326 expression_t const *const cond = fors->condition;
5331 } else if (expression_returns(cond)) {
5332 val = determine_truth(cond);
5338 check_reachable(fors->body);
5344 next = next->base.next;
5348 case STATEMENT_MS_TRY:
5350 next = next->ms_try.final_statement;
5355 check_reachable(next);
5358 static void check_unreachable(statement_t* const stmt, void *const env)
5362 switch (stmt->kind) {
5363 case STATEMENT_DO_WHILE:
5364 if (!stmt->base.reachable) {
5365 expression_t const *const cond = stmt->do_while.condition;
5366 if (determine_truth(cond) >= 0) {
5367 warningf(&cond->base.source_position,
5368 "condition of do-while-loop is unreachable");
5373 case STATEMENT_FOR: {
5374 for_statement_t const* const fors = &stmt->fors;
5376 // if init and step are unreachable, cond is unreachable, too
5377 if (!stmt->base.reachable && !fors->step_reachable) {
5378 warningf(&stmt->base.source_position, "statement is unreachable");
5380 if (!stmt->base.reachable && fors->initialisation != NULL) {
5381 warningf(&fors->initialisation->base.source_position,
5382 "initialisation of for-statement is unreachable");
5385 if (!fors->condition_reachable && fors->condition != NULL) {
5386 warningf(&fors->condition->base.source_position,
5387 "condition of for-statement is unreachable");
5390 if (!fors->step_reachable && fors->step != NULL) {
5391 warningf(&fors->step->base.source_position,
5392 "step of for-statement is unreachable");
5398 case STATEMENT_COMPOUND:
5399 if (stmt->compound.statements != NULL)
5401 goto warn_unreachable;
5403 case STATEMENT_DECLARATION: {
5404 /* Only warn if there is at least one declarator with an initializer.
5405 * This typically occurs in switch statements. */
5406 declaration_statement_t const *const decl = &stmt->declaration;
5407 entity_t const * ent = decl->declarations_begin;
5408 entity_t const *const last = decl->declarations_end;
5410 for (;; ent = ent->base.next) {
5411 if (ent->kind == ENTITY_VARIABLE &&
5412 ent->variable.initializer != NULL) {
5413 goto warn_unreachable;
5423 if (!stmt->base.reachable)
5424 warningf(&stmt->base.source_position, "statement is unreachable");
5429 static void parse_external_declaration(void)
5431 /* function-definitions and declarations both start with declaration
5433 add_anchor_token(';');
5434 declaration_specifiers_t specifiers;
5435 parse_declaration_specifiers(&specifiers);
5436 rem_anchor_token(';');
5438 /* must be a declaration */
5439 if (token.type == ';') {
5440 parse_anonymous_declaration_rest(&specifiers);
5444 add_anchor_token(',');
5445 add_anchor_token('=');
5446 add_anchor_token(';');
5447 add_anchor_token('{');
5449 /* declarator is common to both function-definitions and declarations */
5450 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5452 rem_anchor_token('{');
5453 rem_anchor_token(';');
5454 rem_anchor_token('=');
5455 rem_anchor_token(',');
5457 /* must be a declaration */
5458 switch (token.type) {
5462 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5467 /* must be a function definition */
5468 parse_kr_declaration_list(ndeclaration);
5470 if (token.type != '{') {
5471 parse_error_expected("while parsing function definition", '{', NULL);
5472 eat_until_matching_token(';');
5476 assert(is_declaration(ndeclaration));
5477 type_t *const orig_type = ndeclaration->declaration.type;
5478 type_t * type = skip_typeref(orig_type);
5480 if (!is_type_function(type)) {
5481 if (is_type_valid(type)) {
5482 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5488 source_position_t const *const pos = &ndeclaration->base.source_position;
5489 if (is_typeref(orig_type)) {
5491 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5494 if (warning.aggregate_return &&
5495 is_type_compound(skip_typeref(type->function.return_type))) {
5496 warningf(pos, "'%N' returns an aggregate", ndeclaration);
5498 if (warning.traditional && !type->function.unspecified_parameters) {
5499 warningf(pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5501 if (warning.old_style_definition && type->function.unspecified_parameters) {
5502 warningf(pos, "old-style definition of '%N'", ndeclaration);
5505 /* §6.7.5.3:14 a function definition with () means no
5506 * parameters (and not unspecified parameters) */
5507 if (type->function.unspecified_parameters &&
5508 type->function.parameters == NULL) {
5509 type_t *copy = duplicate_type(type);
5510 copy->function.unspecified_parameters = false;
5511 type = identify_new_type(copy);
5513 ndeclaration->declaration.type = type;
5516 entity_t *const entity = record_entity(ndeclaration, true);
5517 assert(entity->kind == ENTITY_FUNCTION);
5518 assert(ndeclaration->kind == ENTITY_FUNCTION);
5520 function_t *const function = &entity->function;
5521 if (ndeclaration != entity) {
5522 function->parameters = ndeclaration->function.parameters;
5524 assert(is_declaration(entity));
5525 type = skip_typeref(entity->declaration.type);
5527 /* push function parameters and switch scope */
5528 size_t const top = environment_top();
5529 scope_t *old_scope = scope_push(&function->parameters);
5531 entity_t *parameter = function->parameters.entities;
5532 for (; parameter != NULL; parameter = parameter->base.next) {
5533 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5534 parameter->base.parent_scope = current_scope;
5536 assert(parameter->base.parent_scope == NULL
5537 || parameter->base.parent_scope == current_scope);
5538 parameter->base.parent_scope = current_scope;
5539 if (parameter->base.symbol == NULL) {
5540 errorf(¶meter->base.source_position, "parameter name omitted");
5543 environment_push(parameter);
5546 if (function->statement != NULL) {
5547 parser_error_multiple_definition(entity, HERE);
5550 /* parse function body */
5551 int label_stack_top = label_top();
5552 function_t *old_current_function = current_function;
5553 entity_t *old_current_entity = current_entity;
5554 current_function = function;
5555 current_entity = entity;
5556 current_parent = NULL;
5559 goto_anchor = &goto_first;
5561 label_anchor = &label_first;
5563 statement_t *const body = parse_compound_statement(false);
5564 function->statement = body;
5567 check_declarations();
5568 if (warning.return_type ||
5569 warning.unreachable_code ||
5570 (warning.missing_noreturn
5571 && !(function->base.modifiers & DM_NORETURN))) {
5572 noreturn_candidate = true;
5573 check_reachable(body);
5574 if (warning.unreachable_code)
5575 walk_statements(body, check_unreachable, NULL);
5576 if (warning.missing_noreturn &&
5577 noreturn_candidate &&
5578 !(function->base.modifiers & DM_NORETURN)) {
5579 source_position_t const *const pos = &body->base.source_position;
5580 warningf(pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5584 assert(current_parent == NULL);
5585 assert(current_function == function);
5586 assert(current_entity == entity);
5587 current_entity = old_current_entity;
5588 current_function = old_current_function;
5589 label_pop_to(label_stack_top);
5592 assert(current_scope == &function->parameters);
5593 scope_pop(old_scope);
5594 environment_pop_to(top);
5597 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5598 source_position_t *source_position,
5599 const symbol_t *symbol)
5601 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5603 type->bitfield.base_type = base_type;
5604 type->bitfield.size_expression = size;
5607 type_t *skipped_type = skip_typeref(base_type);
5608 if (!is_type_integer(skipped_type)) {
5609 errorf(source_position, "bitfield base type '%T' is not an integer type", base_type);
5612 bit_size = get_type_size(base_type) * 8;
5615 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5616 long v = fold_constant_to_int(size);
5617 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5620 errorf(source_position, "negative width in bit-field '%Y'",
5622 } else if (v == 0 && symbol != NULL) {
5623 errorf(source_position, "zero width for bit-field '%Y'",
5625 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5626 errorf(source_position, "width of '%Y' exceeds its type",
5629 type->bitfield.bit_size = v;
5636 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5638 entity_t *iter = compound->members.entities;
5639 for (; iter != NULL; iter = iter->base.next) {
5640 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5643 if (iter->base.symbol == symbol) {
5645 } else if (iter->base.symbol == NULL) {
5646 /* search in anonymous structs and unions */
5647 type_t *type = skip_typeref(iter->declaration.type);
5648 if (is_type_compound(type)) {
5649 if (find_compound_entry(type->compound.compound, symbol)
5660 static void check_deprecated(const source_position_t *source_position,
5661 const entity_t *entity)
5663 if (!warning.deprecated_declarations)
5665 if (!is_declaration(entity))
5667 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5670 source_position_t const *const pos = &entity->base.source_position;
5671 char const* const msg = get_deprecated_string(entity->declaration.attributes);
5673 warningf(source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, pos, msg);
5675 warningf(source_position, "'%N' is deprecated (declared %P)", entity, pos);
5680 static expression_t *create_select(const source_position_t *pos,
5682 type_qualifiers_t qualifiers,
5685 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5687 check_deprecated(pos, entry);
5689 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5690 select->select.compound = addr;
5691 select->select.compound_entry = entry;
5693 type_t *entry_type = entry->declaration.type;
5694 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5696 /* we always do the auto-type conversions; the & and sizeof parser contains
5697 * code to revert this! */
5698 select->base.type = automatic_type_conversion(res_type);
5699 if (res_type->kind == TYPE_BITFIELD) {
5700 select->base.type = res_type->bitfield.base_type;
5707 * Find entry with symbol in compound. Search anonymous structs and unions and
5708 * creates implicit select expressions for them.
5709 * Returns the adress for the innermost compound.
5711 static expression_t *find_create_select(const source_position_t *pos,
5713 type_qualifiers_t qualifiers,
5714 compound_t *compound, symbol_t *symbol)
5716 entity_t *iter = compound->members.entities;
5717 for (; iter != NULL; iter = iter->base.next) {
5718 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5721 symbol_t *iter_symbol = iter->base.symbol;
5722 if (iter_symbol == NULL) {
5723 type_t *type = iter->declaration.type;
5724 if (type->kind != TYPE_COMPOUND_STRUCT
5725 && type->kind != TYPE_COMPOUND_UNION)
5728 compound_t *sub_compound = type->compound.compound;
5730 if (find_compound_entry(sub_compound, symbol) == NULL)
5733 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5734 sub_addr->base.source_position = *pos;
5735 sub_addr->select.implicit = true;
5736 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5740 if (iter_symbol == symbol) {
5741 return create_select(pos, addr, qualifiers, iter);
5748 static void parse_compound_declarators(compound_t *compound,
5749 const declaration_specifiers_t *specifiers)
5754 if (token.type == ':') {
5755 source_position_t source_position = *HERE;
5758 type_t *base_type = specifiers->type;
5759 expression_t *size = parse_constant_expression();
5761 type_t *type = make_bitfield_type(base_type, size,
5762 &source_position, NULL);
5764 attribute_t *attributes = parse_attributes(NULL);
5765 attribute_t **anchor = &attributes;
5766 while (*anchor != NULL)
5767 anchor = &(*anchor)->next;
5768 *anchor = specifiers->attributes;
5770 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL);
5771 entity->base.source_position = source_position;
5772 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5773 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5774 entity->declaration.type = type;
5775 entity->declaration.attributes = attributes;
5777 if (attributes != NULL) {
5778 handle_entity_attributes(attributes, entity);
5780 append_entity(&compound->members, entity);
5782 entity = parse_declarator(specifiers,
5783 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5784 source_position_t const *const pos = &entity->base.source_position;
5785 if (entity->kind == ENTITY_TYPEDEF) {
5786 errorf(pos, "typedef not allowed as compound member");
5788 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5790 /* make sure we don't define a symbol multiple times */
5791 symbol_t *symbol = entity->base.symbol;
5792 if (symbol != NULL) {
5793 entity_t *prev = find_compound_entry(compound, symbol);
5795 source_position_t const *const ppos = &prev->base.source_position;
5796 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5800 if (token.type == ':') {
5801 source_position_t source_position = *HERE;
5803 expression_t *size = parse_constant_expression();
5805 type_t *type = entity->declaration.type;
5806 type_t *bitfield_type = make_bitfield_type(type, size,
5807 &source_position, entity->base.symbol);
5809 attribute_t *attributes = parse_attributes(NULL);
5810 entity->declaration.type = bitfield_type;
5811 handle_entity_attributes(attributes, entity);
5813 type_t *orig_type = entity->declaration.type;
5814 type_t *type = skip_typeref(orig_type);
5815 if (is_type_function(type)) {
5816 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5817 } else if (is_type_incomplete(type)) {
5818 /* §6.7.2.1:16 flexible array member */
5819 if (!is_type_array(type) ||
5820 token.type != ';' ||
5821 look_ahead(1)->type != '}') {
5822 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5827 append_entity(&compound->members, entity);
5830 } while (next_if(','));
5831 expect(';', end_error);
5834 anonymous_entity = NULL;
5837 static void parse_compound_type_entries(compound_t *compound)
5840 add_anchor_token('}');
5842 while (token.type != '}') {
5843 if (token.type == T_EOF) {
5844 errorf(HERE, "EOF while parsing struct");
5847 declaration_specifiers_t specifiers;
5848 parse_declaration_specifiers(&specifiers);
5849 parse_compound_declarators(compound, &specifiers);
5851 rem_anchor_token('}');
5855 compound->complete = true;
5858 static type_t *parse_typename(void)
5860 declaration_specifiers_t specifiers;
5861 parse_declaration_specifiers(&specifiers);
5862 if (specifiers.storage_class != STORAGE_CLASS_NONE
5863 || specifiers.thread_local) {
5864 /* TODO: improve error message, user does probably not know what a
5865 * storage class is...
5867 errorf(&specifiers.source_position, "typename must not have a storage class");
5870 type_t *result = parse_abstract_declarator(specifiers.type);
5878 typedef expression_t* (*parse_expression_function)(void);
5879 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5881 typedef struct expression_parser_function_t expression_parser_function_t;
5882 struct expression_parser_function_t {
5883 parse_expression_function parser;
5884 precedence_t infix_precedence;
5885 parse_expression_infix_function infix_parser;
5888 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5891 * Prints an error message if an expression was expected but not read
5893 static expression_t *expected_expression_error(void)
5895 /* skip the error message if the error token was read */
5896 if (token.type != T_ERROR) {
5897 errorf(HERE, "expected expression, got token %K", &token);
5901 return create_invalid_expression();
5904 static type_t *get_string_type(void)
5906 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
5909 static type_t *get_wide_string_type(void)
5911 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5915 * Parse a string constant.
5917 static expression_t *parse_string_literal(void)
5919 source_position_t begin = token.source_position;
5920 string_t res = token.literal;
5921 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5924 while (token.type == T_STRING_LITERAL
5925 || token.type == T_WIDE_STRING_LITERAL) {
5926 warn_string_concat(&token.source_position);
5927 res = concat_strings(&res, &token.literal);
5929 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5932 expression_t *literal;
5934 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5935 literal->base.type = get_wide_string_type();
5937 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5938 literal->base.type = get_string_type();
5940 literal->base.source_position = begin;
5941 literal->literal.value = res;
5947 * Parse a boolean constant.
5949 static expression_t *parse_boolean_literal(bool value)
5951 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5952 literal->base.source_position = token.source_position;
5953 literal->base.type = type_bool;
5954 literal->literal.value.begin = value ? "true" : "false";
5955 literal->literal.value.size = value ? 4 : 5;
5961 static void warn_traditional_suffix(void)
5963 if (!warning.traditional)
5965 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
5969 static void check_integer_suffix(void)
5971 symbol_t *suffix = token.symbol;
5975 bool not_traditional = false;
5976 const char *c = suffix->string;
5977 if (*c == 'l' || *c == 'L') {
5980 not_traditional = true;
5982 if (*c == 'u' || *c == 'U') {
5985 } else if (*c == 'u' || *c == 'U') {
5986 not_traditional = true;
5989 } else if (*c == 'u' || *c == 'U') {
5990 not_traditional = true;
5992 if (*c == 'l' || *c == 'L') {
6000 errorf(&token.source_position,
6001 "invalid suffix '%s' on integer constant", suffix->string);
6002 } else if (not_traditional) {
6003 warn_traditional_suffix();
6007 static type_t *check_floatingpoint_suffix(void)
6009 symbol_t *suffix = token.symbol;
6010 type_t *type = type_double;
6014 bool not_traditional = false;
6015 const char *c = suffix->string;
6016 if (*c == 'f' || *c == 'F') {
6019 } else if (*c == 'l' || *c == 'L') {
6021 type = type_long_double;
6024 errorf(&token.source_position,
6025 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6026 } else if (not_traditional) {
6027 warn_traditional_suffix();
6034 * Parse an integer constant.
6036 static expression_t *parse_number_literal(void)
6038 expression_kind_t kind;
6041 switch (token.type) {
6043 kind = EXPR_LITERAL_INTEGER;
6044 check_integer_suffix();
6047 case T_INTEGER_OCTAL:
6048 kind = EXPR_LITERAL_INTEGER_OCTAL;
6049 check_integer_suffix();
6052 case T_INTEGER_HEXADECIMAL:
6053 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6054 check_integer_suffix();
6057 case T_FLOATINGPOINT:
6058 kind = EXPR_LITERAL_FLOATINGPOINT;
6059 type = check_floatingpoint_suffix();
6061 case T_FLOATINGPOINT_HEXADECIMAL:
6062 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6063 type = check_floatingpoint_suffix();
6066 panic("unexpected token type in parse_number_literal");
6069 expression_t *literal = allocate_expression_zero(kind);
6070 literal->base.source_position = token.source_position;
6071 literal->base.type = type;
6072 literal->literal.value = token.literal;
6073 literal->literal.suffix = token.symbol;
6076 /* integer type depends on the size of the number and the size
6077 * representable by the types. The backend/codegeneration has to determine
6080 determine_literal_type(&literal->literal);
6085 * Parse a character constant.
6087 static expression_t *parse_character_constant(void)
6089 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6090 literal->base.source_position = token.source_position;
6091 literal->base.type = c_mode & _CXX ? type_char : type_int;
6092 literal->literal.value = token.literal;
6094 size_t len = literal->literal.value.size;
6096 if (!GNU_MODE && !(c_mode & _C99)) {
6097 errorf(HERE, "more than 1 character in character constant");
6098 } else if (warning.multichar) {
6099 literal->base.type = type_int;
6100 warningf(HERE, "multi-character character constant");
6109 * Parse a wide character constant.
6111 static expression_t *parse_wide_character_constant(void)
6113 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6114 literal->base.source_position = token.source_position;
6115 literal->base.type = type_int;
6116 literal->literal.value = token.literal;
6118 size_t len = wstrlen(&literal->literal.value);
6120 warningf(HERE, "multi-character character constant");
6127 static entity_t *create_implicit_function(symbol_t *symbol,
6128 const source_position_t *source_position)
6130 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6131 ntype->function.return_type = type_int;
6132 ntype->function.unspecified_parameters = true;
6133 ntype->function.linkage = LINKAGE_C;
6134 type_t *type = identify_new_type(ntype);
6136 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6137 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6138 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6139 entity->declaration.type = type;
6140 entity->declaration.implicit = true;
6141 entity->base.source_position = *source_position;
6143 if (current_scope != NULL) {
6144 bool strict_prototypes_old = warning.strict_prototypes;
6145 warning.strict_prototypes = false;
6146 record_entity(entity, false);
6147 warning.strict_prototypes = strict_prototypes_old;
6154 * Performs automatic type cast as described in §6.3.2.1.
6156 * @param orig_type the original type
6158 static type_t *automatic_type_conversion(type_t *orig_type)
6160 type_t *type = skip_typeref(orig_type);
6161 if (is_type_array(type)) {
6162 array_type_t *array_type = &type->array;
6163 type_t *element_type = array_type->element_type;
6164 unsigned qualifiers = array_type->base.qualifiers;
6166 return make_pointer_type(element_type, qualifiers);
6169 if (is_type_function(type)) {
6170 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6177 * reverts the automatic casts of array to pointer types and function
6178 * to function-pointer types as defined §6.3.2.1
6180 type_t *revert_automatic_type_conversion(const expression_t *expression)
6182 switch (expression->kind) {
6183 case EXPR_REFERENCE: {
6184 entity_t *entity = expression->reference.entity;
6185 if (is_declaration(entity)) {
6186 return entity->declaration.type;
6187 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6188 return entity->enum_value.enum_type;
6190 panic("no declaration or enum in reference");
6195 entity_t *entity = expression->select.compound_entry;
6196 assert(is_declaration(entity));
6197 type_t *type = entity->declaration.type;
6198 return get_qualified_type(type,
6199 expression->base.type->base.qualifiers);
6202 case EXPR_UNARY_DEREFERENCE: {
6203 const expression_t *const value = expression->unary.value;
6204 type_t *const type = skip_typeref(value->base.type);
6205 if (!is_type_pointer(type))
6206 return type_error_type;
6207 return type->pointer.points_to;
6210 case EXPR_ARRAY_ACCESS: {
6211 const expression_t *array_ref = expression->array_access.array_ref;
6212 type_t *type_left = skip_typeref(array_ref->base.type);
6213 if (!is_type_pointer(type_left))
6214 return type_error_type;
6215 return type_left->pointer.points_to;
6218 case EXPR_STRING_LITERAL: {
6219 size_t size = expression->string_literal.value.size;
6220 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6223 case EXPR_WIDE_STRING_LITERAL: {
6224 size_t size = wstrlen(&expression->string_literal.value);
6225 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6228 case EXPR_COMPOUND_LITERAL:
6229 return expression->compound_literal.type;
6234 return expression->base.type;
6238 * Find an entity matching a symbol in a scope.
6239 * Uses current scope if scope is NULL
6241 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6242 namespace_tag_t namespc)
6244 if (scope == NULL) {
6245 return get_entity(symbol, namespc);
6248 /* we should optimize here, if scope grows above a certain size we should
6249 construct a hashmap here... */
6250 entity_t *entity = scope->entities;
6251 for ( ; entity != NULL; entity = entity->base.next) {
6252 if (entity->base.symbol == symbol
6253 && (namespace_tag_t)entity->base.namespc == namespc)
6260 static entity_t *parse_qualified_identifier(void)
6262 /* namespace containing the symbol */
6264 source_position_t pos;
6265 const scope_t *lookup_scope = NULL;
6267 if (next_if(T_COLONCOLON))
6268 lookup_scope = &unit->scope;
6272 if (token.type != T_IDENTIFIER) {
6273 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6274 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6276 symbol = token.symbol;
6281 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6283 if (!next_if(T_COLONCOLON))
6286 switch (entity->kind) {
6287 case ENTITY_NAMESPACE:
6288 lookup_scope = &entity->namespacee.members;
6293 lookup_scope = &entity->compound.members;
6296 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6297 symbol, get_entity_kind_name(entity->kind));
6299 /* skip further qualifications */
6300 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6302 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6306 if (entity == NULL) {
6307 if (!strict_mode && token.type == '(') {
6308 /* an implicitly declared function */
6309 if (warning.error_implicit_function_declaration) {
6310 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6311 } else if (warning.implicit_function_declaration) {
6312 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6315 entity = create_implicit_function(symbol, &pos);
6317 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6318 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6325 static expression_t *parse_reference(void)
6327 source_position_t const pos = token.source_position;
6328 entity_t *const entity = parse_qualified_identifier();
6331 if (is_declaration(entity)) {
6332 orig_type = entity->declaration.type;
6333 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6334 orig_type = entity->enum_value.enum_type;
6336 panic("expected declaration or enum value in reference");
6339 /* we always do the auto-type conversions; the & and sizeof parser contains
6340 * code to revert this! */
6341 type_t *type = automatic_type_conversion(orig_type);
6343 expression_kind_t kind = EXPR_REFERENCE;
6344 if (entity->kind == ENTITY_ENUM_VALUE)
6345 kind = EXPR_REFERENCE_ENUM_VALUE;
6347 expression_t *expression = allocate_expression_zero(kind);
6348 expression->base.source_position = pos;
6349 expression->base.type = type;
6350 expression->reference.entity = entity;
6352 /* this declaration is used */
6353 if (is_declaration(entity)) {
6354 entity->declaration.used = true;
6357 if (entity->base.parent_scope != file_scope
6358 && (current_function != NULL
6359 && entity->base.parent_scope->depth < current_function->parameters.depth)
6360 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6361 if (entity->kind == ENTITY_VARIABLE) {
6362 /* access of a variable from an outer function */
6363 entity->variable.address_taken = true;
6364 } else if (entity->kind == ENTITY_PARAMETER) {
6365 entity->parameter.address_taken = true;
6367 current_function->need_closure = true;
6370 check_deprecated(&pos, entity);
6372 if (warning.init_self && entity == current_init_decl && !in_type_prop
6373 && entity->kind == ENTITY_VARIABLE) {
6374 current_init_decl = NULL;
6375 warningf(&pos, "variable '%#N' is initialized by itself", entity);
6381 static bool semantic_cast(expression_t *cast)
6383 expression_t *expression = cast->unary.value;
6384 type_t *orig_dest_type = cast->base.type;
6385 type_t *orig_type_right = expression->base.type;
6386 type_t const *dst_type = skip_typeref(orig_dest_type);
6387 type_t const *src_type = skip_typeref(orig_type_right);
6388 source_position_t const *pos = &cast->base.source_position;
6390 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6391 if (dst_type == type_void)
6394 /* only integer and pointer can be casted to pointer */
6395 if (is_type_pointer(dst_type) &&
6396 !is_type_pointer(src_type) &&
6397 !is_type_integer(src_type) &&
6398 is_type_valid(src_type)) {
6399 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6403 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6404 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6408 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6409 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6413 if (warning.cast_qual &&
6414 is_type_pointer(src_type) &&
6415 is_type_pointer(dst_type)) {
6416 type_t *src = skip_typeref(src_type->pointer.points_to);
6417 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6418 unsigned missing_qualifiers =
6419 src->base.qualifiers & ~dst->base.qualifiers;
6420 if (missing_qualifiers != 0) {
6422 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6423 missing_qualifiers, orig_type_right);
6429 static expression_t *parse_compound_literal(type_t *type)
6431 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6433 parse_initializer_env_t env;
6436 env.must_be_constant = false;
6437 initializer_t *initializer = parse_initializer(&env);
6440 expression->compound_literal.initializer = initializer;
6441 expression->compound_literal.type = type;
6442 expression->base.type = automatic_type_conversion(type);
6448 * Parse a cast expression.
6450 static expression_t *parse_cast(void)
6452 source_position_t source_position = token.source_position;
6455 add_anchor_token(')');
6457 type_t *type = parse_typename();
6459 rem_anchor_token(')');
6460 expect(')', end_error);
6462 if (token.type == '{') {
6463 return parse_compound_literal(type);
6466 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6467 cast->base.source_position = source_position;
6469 expression_t *value = parse_subexpression(PREC_CAST);
6470 cast->base.type = type;
6471 cast->unary.value = value;
6473 if (! semantic_cast(cast)) {
6474 /* TODO: record the error in the AST. else it is impossible to detect it */
6479 return create_invalid_expression();
6483 * Parse a statement expression.
6485 static expression_t *parse_statement_expression(void)
6487 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6490 add_anchor_token(')');
6492 statement_t *statement = parse_compound_statement(true);
6493 statement->compound.stmt_expr = true;
6494 expression->statement.statement = statement;
6496 /* find last statement and use its type */
6497 type_t *type = type_void;
6498 const statement_t *stmt = statement->compound.statements;
6500 while (stmt->base.next != NULL)
6501 stmt = stmt->base.next;
6503 if (stmt->kind == STATEMENT_EXPRESSION) {
6504 type = stmt->expression.expression->base.type;
6506 } else if (warning.other) {
6507 warningf(&expression->base.source_position, "empty statement expression ({})");
6509 expression->base.type = type;
6511 rem_anchor_token(')');
6512 expect(')', end_error);
6519 * Parse a parenthesized expression.
6521 static expression_t *parse_parenthesized_expression(void)
6523 token_t const* const la1 = look_ahead(1);
6524 switch (la1->type) {
6526 /* gcc extension: a statement expression */
6527 return parse_statement_expression();
6530 if (is_typedef_symbol(la1->symbol)) {
6532 return parse_cast();
6537 add_anchor_token(')');
6538 expression_t *result = parse_expression();
6539 result->base.parenthesized = true;
6540 rem_anchor_token(')');
6541 expect(')', end_error);
6547 static expression_t *parse_function_keyword(void)
6551 if (current_function == NULL) {
6552 errorf(HERE, "'__func__' used outside of a function");
6555 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6556 expression->base.type = type_char_ptr;
6557 expression->funcname.kind = FUNCNAME_FUNCTION;
6564 static expression_t *parse_pretty_function_keyword(void)
6566 if (current_function == NULL) {
6567 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6570 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6571 expression->base.type = type_char_ptr;
6572 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6574 eat(T___PRETTY_FUNCTION__);
6579 static expression_t *parse_funcsig_keyword(void)
6581 if (current_function == NULL) {
6582 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6585 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6586 expression->base.type = type_char_ptr;
6587 expression->funcname.kind = FUNCNAME_FUNCSIG;
6594 static expression_t *parse_funcdname_keyword(void)
6596 if (current_function == NULL) {
6597 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6600 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6601 expression->base.type = type_char_ptr;
6602 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6604 eat(T___FUNCDNAME__);
6609 static designator_t *parse_designator(void)
6611 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6612 result->source_position = *HERE;
6614 if (token.type != T_IDENTIFIER) {
6615 parse_error_expected("while parsing member designator",
6616 T_IDENTIFIER, NULL);
6619 result->symbol = token.symbol;
6622 designator_t *last_designator = result;
6625 if (token.type != T_IDENTIFIER) {
6626 parse_error_expected("while parsing member designator",
6627 T_IDENTIFIER, NULL);
6630 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6631 designator->source_position = *HERE;
6632 designator->symbol = token.symbol;
6635 last_designator->next = designator;
6636 last_designator = designator;
6640 add_anchor_token(']');
6641 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6642 designator->source_position = *HERE;
6643 designator->array_index = parse_expression();
6644 rem_anchor_token(']');
6645 expect(']', end_error);
6646 if (designator->array_index == NULL) {
6650 last_designator->next = designator;
6651 last_designator = designator;
6663 * Parse the __builtin_offsetof() expression.
6665 static expression_t *parse_offsetof(void)
6667 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6668 expression->base.type = type_size_t;
6670 eat(T___builtin_offsetof);
6672 expect('(', end_error);
6673 add_anchor_token(',');
6674 type_t *type = parse_typename();
6675 rem_anchor_token(',');
6676 expect(',', end_error);
6677 add_anchor_token(')');
6678 designator_t *designator = parse_designator();
6679 rem_anchor_token(')');
6680 expect(')', end_error);
6682 expression->offsetofe.type = type;
6683 expression->offsetofe.designator = designator;
6686 memset(&path, 0, sizeof(path));
6687 path.top_type = type;
6688 path.path = NEW_ARR_F(type_path_entry_t, 0);
6690 descend_into_subtype(&path);
6692 if (!walk_designator(&path, designator, true)) {
6693 return create_invalid_expression();
6696 DEL_ARR_F(path.path);
6700 return create_invalid_expression();
6704 * Parses a _builtin_va_start() expression.
6706 static expression_t *parse_va_start(void)
6708 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6710 eat(T___builtin_va_start);
6712 expect('(', end_error);
6713 add_anchor_token(',');
6714 expression->va_starte.ap = parse_assignment_expression();
6715 rem_anchor_token(',');
6716 expect(',', end_error);
6717 expression_t *const expr = parse_assignment_expression();
6718 if (expr->kind == EXPR_REFERENCE) {
6719 entity_t *const entity = expr->reference.entity;
6720 if (!current_function->base.type->function.variadic) {
6721 errorf(&expr->base.source_position,
6722 "'va_start' used in non-variadic function");
6723 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6724 entity->base.next != NULL ||
6725 entity->kind != ENTITY_PARAMETER) {
6726 errorf(&expr->base.source_position,
6727 "second argument of 'va_start' must be last parameter of the current function");
6729 expression->va_starte.parameter = &entity->variable;
6731 expect(')', end_error);
6734 expect(')', end_error);
6736 return create_invalid_expression();
6740 * Parses a __builtin_va_arg() expression.
6742 static expression_t *parse_va_arg(void)
6744 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6746 eat(T___builtin_va_arg);
6748 expect('(', end_error);
6750 ap.expression = parse_assignment_expression();
6751 expression->va_arge.ap = ap.expression;
6752 check_call_argument(type_valist, &ap, 1);
6754 expect(',', end_error);
6755 expression->base.type = parse_typename();
6756 expect(')', end_error);
6760 return create_invalid_expression();
6764 * Parses a __builtin_va_copy() expression.
6766 static expression_t *parse_va_copy(void)
6768 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6770 eat(T___builtin_va_copy);
6772 expect('(', end_error);
6773 expression_t *dst = parse_assignment_expression();
6774 assign_error_t error = semantic_assign(type_valist, dst);
6775 report_assign_error(error, type_valist, dst, "call argument 1",
6776 &dst->base.source_position);
6777 expression->va_copye.dst = dst;
6779 expect(',', end_error);
6781 call_argument_t src;
6782 src.expression = parse_assignment_expression();
6783 check_call_argument(type_valist, &src, 2);
6784 expression->va_copye.src = src.expression;
6785 expect(')', end_error);
6789 return create_invalid_expression();
6793 * Parses a __builtin_constant_p() expression.
6795 static expression_t *parse_builtin_constant(void)
6797 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6799 eat(T___builtin_constant_p);
6801 expect('(', end_error);
6802 add_anchor_token(')');
6803 expression->builtin_constant.value = parse_assignment_expression();
6804 rem_anchor_token(')');
6805 expect(')', end_error);
6806 expression->base.type = type_int;
6810 return create_invalid_expression();
6814 * Parses a __builtin_types_compatible_p() expression.
6816 static expression_t *parse_builtin_types_compatible(void)
6818 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6820 eat(T___builtin_types_compatible_p);
6822 expect('(', end_error);
6823 add_anchor_token(')');
6824 add_anchor_token(',');
6825 expression->builtin_types_compatible.left = parse_typename();
6826 rem_anchor_token(',');
6827 expect(',', end_error);
6828 expression->builtin_types_compatible.right = parse_typename();
6829 rem_anchor_token(')');
6830 expect(')', end_error);
6831 expression->base.type = type_int;
6835 return create_invalid_expression();
6839 * Parses a __builtin_is_*() compare expression.
6841 static expression_t *parse_compare_builtin(void)
6843 expression_t *expression;
6845 switch (token.type) {
6846 case T___builtin_isgreater:
6847 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6849 case T___builtin_isgreaterequal:
6850 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6852 case T___builtin_isless:
6853 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6855 case T___builtin_islessequal:
6856 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6858 case T___builtin_islessgreater:
6859 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6861 case T___builtin_isunordered:
6862 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6865 internal_errorf(HERE, "invalid compare builtin found");
6867 expression->base.source_position = *HERE;
6870 expect('(', end_error);
6871 expression->binary.left = parse_assignment_expression();
6872 expect(',', end_error);
6873 expression->binary.right = parse_assignment_expression();
6874 expect(')', end_error);
6876 type_t *const orig_type_left = expression->binary.left->base.type;
6877 type_t *const orig_type_right = expression->binary.right->base.type;
6879 type_t *const type_left = skip_typeref(orig_type_left);
6880 type_t *const type_right = skip_typeref(orig_type_right);
6881 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6882 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6883 type_error_incompatible("invalid operands in comparison",
6884 &expression->base.source_position, orig_type_left, orig_type_right);
6887 semantic_comparison(&expression->binary);
6892 return create_invalid_expression();
6896 * Parses a MS assume() expression.
6898 static expression_t *parse_assume(void)
6900 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6904 expect('(', end_error);
6905 add_anchor_token(')');
6906 expression->unary.value = parse_assignment_expression();
6907 rem_anchor_token(')');
6908 expect(')', end_error);
6910 expression->base.type = type_void;
6913 return create_invalid_expression();
6917 * Return the label for the current symbol or create a new one.
6919 static label_t *get_label(void)
6921 assert(token.type == T_IDENTIFIER);
6922 assert(current_function != NULL);
6924 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6925 /* If we find a local label, we already created the declaration. */
6926 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6927 if (label->base.parent_scope != current_scope) {
6928 assert(label->base.parent_scope->depth < current_scope->depth);
6929 current_function->goto_to_outer = true;
6931 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6932 /* There is no matching label in the same function, so create a new one. */
6933 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6938 return &label->label;
6942 * Parses a GNU && label address expression.
6944 static expression_t *parse_label_address(void)
6946 source_position_t source_position = token.source_position;
6948 if (token.type != T_IDENTIFIER) {
6949 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6950 return create_invalid_expression();
6953 label_t *const label = get_label();
6955 label->address_taken = true;
6957 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6958 expression->base.source_position = source_position;
6960 /* label address is treated as a void pointer */
6961 expression->base.type = type_void_ptr;
6962 expression->label_address.label = label;
6967 * Parse a microsoft __noop expression.
6969 static expression_t *parse_noop_expression(void)
6971 /* the result is a (int)0 */
6972 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6973 literal->base.type = type_int;
6974 literal->base.source_position = token.source_position;
6975 literal->literal.value.begin = "__noop";
6976 literal->literal.value.size = 6;
6980 if (token.type == '(') {
6981 /* parse arguments */
6983 add_anchor_token(')');
6984 add_anchor_token(',');
6986 if (token.type != ')') do {
6987 (void)parse_assignment_expression();
6988 } while (next_if(','));
6990 rem_anchor_token(',');
6991 rem_anchor_token(')');
6992 expect(')', end_error);
6999 * Parses a primary expression.
7001 static expression_t *parse_primary_expression(void)
7003 switch (token.type) {
7004 case T_false: return parse_boolean_literal(false);
7005 case T_true: return parse_boolean_literal(true);
7007 case T_INTEGER_OCTAL:
7008 case T_INTEGER_HEXADECIMAL:
7009 case T_FLOATINGPOINT:
7010 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7011 case T_CHARACTER_CONSTANT: return parse_character_constant();
7012 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7013 case T_STRING_LITERAL:
7014 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7015 case T___FUNCTION__:
7016 case T___func__: return parse_function_keyword();
7017 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7018 case T___FUNCSIG__: return parse_funcsig_keyword();
7019 case T___FUNCDNAME__: return parse_funcdname_keyword();
7020 case T___builtin_offsetof: return parse_offsetof();
7021 case T___builtin_va_start: return parse_va_start();
7022 case T___builtin_va_arg: return parse_va_arg();
7023 case T___builtin_va_copy: return parse_va_copy();
7024 case T___builtin_isgreater:
7025 case T___builtin_isgreaterequal:
7026 case T___builtin_isless:
7027 case T___builtin_islessequal:
7028 case T___builtin_islessgreater:
7029 case T___builtin_isunordered: return parse_compare_builtin();
7030 case T___builtin_constant_p: return parse_builtin_constant();
7031 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7032 case T__assume: return parse_assume();
7035 return parse_label_address();
7038 case '(': return parse_parenthesized_expression();
7039 case T___noop: return parse_noop_expression();
7041 /* Gracefully handle type names while parsing expressions. */
7043 return parse_reference();
7045 if (!is_typedef_symbol(token.symbol)) {
7046 return parse_reference();
7050 source_position_t const pos = *HERE;
7051 declaration_specifiers_t specifiers;
7052 parse_declaration_specifiers(&specifiers);
7053 type_t const *const type = parse_abstract_declarator(specifiers.type);
7054 errorf(&pos, "encountered type '%T' while parsing expression", type);
7055 return create_invalid_expression();
7059 errorf(HERE, "unexpected token %K, expected an expression", &token);
7061 return create_invalid_expression();
7064 static expression_t *parse_array_expression(expression_t *left)
7066 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7067 array_access_expression_t *const arr = &expr->array_access;
7070 add_anchor_token(']');
7072 expression_t *const inside = parse_expression();
7074 type_t *const orig_type_left = left->base.type;
7075 type_t *const orig_type_inside = inside->base.type;
7077 type_t *const type_left = skip_typeref(orig_type_left);
7078 type_t *const type_inside = skip_typeref(orig_type_inside);
7084 if (is_type_pointer(type_left)) {
7087 idx_type = type_inside;
7088 res_type = type_left->pointer.points_to;
7090 } else if (is_type_pointer(type_inside)) {
7091 arr->flipped = true;
7094 idx_type = type_left;
7095 res_type = type_inside->pointer.points_to;
7097 res_type = automatic_type_conversion(res_type);
7098 if (!is_type_integer(idx_type)) {
7099 errorf(&idx->base.source_position, "array subscript must have integer type");
7100 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR) && warning.char_subscripts) {
7101 warningf(&idx->base.source_position, "array subscript has char type");
7104 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7105 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7107 res_type = type_error_type;
7112 arr->array_ref = ref;
7114 arr->base.type = res_type;
7116 rem_anchor_token(']');
7117 expect(']', end_error);
7122 static expression_t *parse_typeprop(expression_kind_t const kind)
7124 expression_t *tp_expression = allocate_expression_zero(kind);
7125 tp_expression->base.type = type_size_t;
7127 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7129 /* we only refer to a type property, mark this case */
7130 bool old = in_type_prop;
7131 in_type_prop = true;
7134 expression_t *expression;
7135 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7137 add_anchor_token(')');
7138 orig_type = parse_typename();
7139 rem_anchor_token(')');
7140 expect(')', end_error);
7142 if (token.type == '{') {
7143 /* It was not sizeof(type) after all. It is sizeof of an expression
7144 * starting with a compound literal */
7145 expression = parse_compound_literal(orig_type);
7146 goto typeprop_expression;
7149 expression = parse_subexpression(PREC_UNARY);
7151 typeprop_expression:
7152 tp_expression->typeprop.tp_expression = expression;
7154 orig_type = revert_automatic_type_conversion(expression);
7155 expression->base.type = orig_type;
7158 tp_expression->typeprop.type = orig_type;
7159 type_t const* const type = skip_typeref(orig_type);
7160 char const* wrong_type = NULL;
7161 if (is_type_incomplete(type)) {
7162 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7163 wrong_type = "incomplete";
7164 } else if (type->kind == TYPE_FUNCTION) {
7166 /* function types are allowed (and return 1) */
7167 if (warning.other) {
7168 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7169 warningf(&tp_expression->base.source_position,
7170 "%s expression with function argument returns invalid result", what);
7173 wrong_type = "function";
7176 if (is_type_incomplete(type))
7177 wrong_type = "incomplete";
7179 if (type->kind == TYPE_BITFIELD)
7180 wrong_type = "bitfield";
7182 if (wrong_type != NULL) {
7183 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7184 errorf(&tp_expression->base.source_position,
7185 "operand of %s expression must not be of %s type '%T'",
7186 what, wrong_type, orig_type);
7191 return tp_expression;
7194 static expression_t *parse_sizeof(void)
7196 return parse_typeprop(EXPR_SIZEOF);
7199 static expression_t *parse_alignof(void)
7201 return parse_typeprop(EXPR_ALIGNOF);
7204 static expression_t *parse_select_expression(expression_t *addr)
7206 assert(token.type == '.' || token.type == T_MINUSGREATER);
7207 bool select_left_arrow = (token.type == T_MINUSGREATER);
7208 source_position_t const pos = *HERE;
7211 if (token.type != T_IDENTIFIER) {
7212 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7213 return create_invalid_expression();
7215 symbol_t *symbol = token.symbol;
7218 type_t *const orig_type = addr->base.type;
7219 type_t *const type = skip_typeref(orig_type);
7222 bool saw_error = false;
7223 if (is_type_pointer(type)) {
7224 if (!select_left_arrow) {
7226 "request for member '%Y' in something not a struct or union, but '%T'",
7230 type_left = skip_typeref(type->pointer.points_to);
7232 if (select_left_arrow && is_type_valid(type)) {
7233 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7239 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7240 type_left->kind != TYPE_COMPOUND_UNION) {
7242 if (is_type_valid(type_left) && !saw_error) {
7244 "request for member '%Y' in something not a struct or union, but '%T'",
7247 return create_invalid_expression();
7250 compound_t *compound = type_left->compound.compound;
7251 if (!compound->complete) {
7252 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7254 return create_invalid_expression();
7257 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7258 expression_t *result =
7259 find_create_select(&pos, addr, qualifiers, compound, symbol);
7261 if (result == NULL) {
7262 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7263 return create_invalid_expression();
7269 static void check_call_argument(type_t *expected_type,
7270 call_argument_t *argument, unsigned pos)
7272 type_t *expected_type_skip = skip_typeref(expected_type);
7273 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7274 expression_t *arg_expr = argument->expression;
7275 type_t *arg_type = skip_typeref(arg_expr->base.type);
7277 /* handle transparent union gnu extension */
7278 if (is_type_union(expected_type_skip)
7279 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7280 compound_t *union_decl = expected_type_skip->compound.compound;
7281 type_t *best_type = NULL;
7282 entity_t *entry = union_decl->members.entities;
7283 for ( ; entry != NULL; entry = entry->base.next) {
7284 assert(is_declaration(entry));
7285 type_t *decl_type = entry->declaration.type;
7286 error = semantic_assign(decl_type, arg_expr);
7287 if (error == ASSIGN_ERROR_INCOMPATIBLE
7288 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7291 if (error == ASSIGN_SUCCESS) {
7292 best_type = decl_type;
7293 } else if (best_type == NULL) {
7294 best_type = decl_type;
7298 if (best_type != NULL) {
7299 expected_type = best_type;
7303 error = semantic_assign(expected_type, arg_expr);
7304 argument->expression = create_implicit_cast(arg_expr, expected_type);
7306 if (error != ASSIGN_SUCCESS) {
7307 /* report exact scope in error messages (like "in argument 3") */
7309 snprintf(buf, sizeof(buf), "call argument %u", pos);
7310 report_assign_error(error, expected_type, arg_expr, buf,
7311 &arg_expr->base.source_position);
7312 } else if (warning.traditional || warning.conversion) {
7313 type_t *const promoted_type = get_default_promoted_type(arg_type);
7314 if (!types_compatible(expected_type_skip, promoted_type) &&
7315 !types_compatible(expected_type_skip, type_void_ptr) &&
7316 !types_compatible(type_void_ptr, promoted_type)) {
7317 /* Deliberately show the skipped types in this warning */
7318 warningf(&arg_expr->base.source_position,
7319 "passing call argument %u as '%T' rather than '%T' due to prototype",
7320 pos, expected_type_skip, promoted_type);
7326 * Handle the semantic restrictions of builtin calls
7328 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7329 switch (call->function->reference.entity->function.btk) {
7330 case bk_gnu_builtin_return_address:
7331 case bk_gnu_builtin_frame_address: {
7332 /* argument must be constant */
7333 call_argument_t *argument = call->arguments;
7335 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7336 errorf(&call->base.source_position,
7337 "argument of '%Y' must be a constant expression",
7338 call->function->reference.entity->base.symbol);
7342 case bk_gnu_builtin_object_size:
7343 if (call->arguments == NULL)
7346 call_argument_t *arg = call->arguments->next;
7347 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7348 errorf(&call->base.source_position,
7349 "second argument of '%Y' must be a constant expression",
7350 call->function->reference.entity->base.symbol);
7353 case bk_gnu_builtin_prefetch:
7354 /* second and third argument must be constant if existent */
7355 if (call->arguments == NULL)
7357 call_argument_t *rw = call->arguments->next;
7358 call_argument_t *locality = NULL;
7361 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7362 errorf(&call->base.source_position,
7363 "second argument of '%Y' must be a constant expression",
7364 call->function->reference.entity->base.symbol);
7366 locality = rw->next;
7368 if (locality != NULL) {
7369 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7370 errorf(&call->base.source_position,
7371 "third argument of '%Y' must be a constant expression",
7372 call->function->reference.entity->base.symbol);
7374 locality = rw->next;
7383 * Parse a call expression, ie. expression '( ... )'.
7385 * @param expression the function address
7387 static expression_t *parse_call_expression(expression_t *expression)
7389 expression_t *result = allocate_expression_zero(EXPR_CALL);
7390 call_expression_t *call = &result->call;
7391 call->function = expression;
7393 type_t *const orig_type = expression->base.type;
7394 type_t *const type = skip_typeref(orig_type);
7396 function_type_t *function_type = NULL;
7397 if (is_type_pointer(type)) {
7398 type_t *const to_type = skip_typeref(type->pointer.points_to);
7400 if (is_type_function(to_type)) {
7401 function_type = &to_type->function;
7402 call->base.type = function_type->return_type;
7406 if (function_type == NULL && is_type_valid(type)) {
7408 "called object '%E' (type '%T') is not a pointer to a function",
7409 expression, orig_type);
7412 /* parse arguments */
7414 add_anchor_token(')');
7415 add_anchor_token(',');
7417 if (token.type != ')') {
7418 call_argument_t **anchor = &call->arguments;
7420 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7421 argument->expression = parse_assignment_expression();
7424 anchor = &argument->next;
7425 } while (next_if(','));
7427 rem_anchor_token(',');
7428 rem_anchor_token(')');
7429 expect(')', end_error);
7431 if (function_type == NULL)
7434 /* check type and count of call arguments */
7435 function_parameter_t *parameter = function_type->parameters;
7436 call_argument_t *argument = call->arguments;
7437 if (!function_type->unspecified_parameters) {
7438 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7439 parameter = parameter->next, argument = argument->next) {
7440 check_call_argument(parameter->type, argument, ++pos);
7443 if (parameter != NULL) {
7444 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7445 } else if (argument != NULL && !function_type->variadic) {
7446 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7450 /* do default promotion for other arguments */
7451 for (; argument != NULL; argument = argument->next) {
7452 type_t *argument_type = argument->expression->base.type;
7453 if (!is_type_object(skip_typeref(argument_type))) {
7454 errorf(&argument->expression->base.source_position,
7455 "call argument '%E' must not be void", argument->expression);
7458 argument_type = get_default_promoted_type(argument_type);
7460 argument->expression
7461 = create_implicit_cast(argument->expression, argument_type);
7466 if (warning.aggregate_return &&
7467 is_type_compound(skip_typeref(function_type->return_type))) {
7468 warningf(&expression->base.source_position,
7469 "function call has aggregate value");
7472 if (expression->kind == EXPR_REFERENCE) {
7473 reference_expression_t *reference = &expression->reference;
7474 if (reference->entity->kind == ENTITY_FUNCTION &&
7475 reference->entity->function.btk != bk_none)
7476 handle_builtin_argument_restrictions(call);
7483 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7485 static bool same_compound_type(const type_t *type1, const type_t *type2)
7488 is_type_compound(type1) &&
7489 type1->kind == type2->kind &&
7490 type1->compound.compound == type2->compound.compound;
7493 static expression_t const *get_reference_address(expression_t const *expr)
7495 bool regular_take_address = true;
7497 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7498 expr = expr->unary.value;
7500 regular_take_address = false;
7503 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7506 expr = expr->unary.value;
7509 if (expr->kind != EXPR_REFERENCE)
7512 /* special case for functions which are automatically converted to a
7513 * pointer to function without an extra TAKE_ADDRESS operation */
7514 if (!regular_take_address &&
7515 expr->reference.entity->kind != ENTITY_FUNCTION) {
7522 static void warn_reference_address_as_bool(expression_t const* expr)
7524 if (!warning.address)
7527 expr = get_reference_address(expr);
7529 source_position_t const *const pos = &expr->base.source_position;
7530 entity_t const *const ent = expr->reference.entity;
7531 warningf(pos, "the address of '%N' will always evaluate as 'true'", ent);
7535 static void warn_assignment_in_condition(const expression_t *const expr)
7537 if (!warning.parentheses)
7539 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7541 if (expr->base.parenthesized)
7543 warningf(&expr->base.source_position,
7544 "suggest parentheses around assignment used as truth value");
7547 static void semantic_condition(expression_t const *const expr,
7548 char const *const context)
7550 type_t *const type = skip_typeref(expr->base.type);
7551 if (is_type_scalar(type)) {
7552 warn_reference_address_as_bool(expr);
7553 warn_assignment_in_condition(expr);
7554 } else if (is_type_valid(type)) {
7555 errorf(&expr->base.source_position,
7556 "%s must have scalar type", context);
7561 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7563 * @param expression the conditional expression
7565 static expression_t *parse_conditional_expression(expression_t *expression)
7567 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7569 conditional_expression_t *conditional = &result->conditional;
7570 conditional->condition = expression;
7573 add_anchor_token(':');
7575 /* §6.5.15:2 The first operand shall have scalar type. */
7576 semantic_condition(expression, "condition of conditional operator");
7578 expression_t *true_expression = expression;
7579 bool gnu_cond = false;
7580 if (GNU_MODE && token.type == ':') {
7583 true_expression = parse_expression();
7585 rem_anchor_token(':');
7586 expect(':', end_error);
7588 expression_t *false_expression =
7589 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7591 type_t *const orig_true_type = true_expression->base.type;
7592 type_t *const orig_false_type = false_expression->base.type;
7593 type_t *const true_type = skip_typeref(orig_true_type);
7594 type_t *const false_type = skip_typeref(orig_false_type);
7597 type_t *result_type;
7598 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7599 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7600 /* ISO/IEC 14882:1998(E) §5.16:2 */
7601 if (true_expression->kind == EXPR_UNARY_THROW) {
7602 result_type = false_type;
7603 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7604 result_type = true_type;
7606 if (warning.other && (
7607 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7608 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7610 warningf(&conditional->base.source_position,
7611 "ISO C forbids conditional expression with only one void side");
7613 result_type = type_void;
7615 } else if (is_type_arithmetic(true_type)
7616 && is_type_arithmetic(false_type)) {
7617 result_type = semantic_arithmetic(true_type, false_type);
7618 } else if (same_compound_type(true_type, false_type)) {
7619 /* just take 1 of the 2 types */
7620 result_type = true_type;
7621 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7622 type_t *pointer_type;
7624 expression_t *other_expression;
7625 if (is_type_pointer(true_type) &&
7626 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7627 pointer_type = true_type;
7628 other_type = false_type;
7629 other_expression = false_expression;
7631 pointer_type = false_type;
7632 other_type = true_type;
7633 other_expression = true_expression;
7636 if (is_null_pointer_constant(other_expression)) {
7637 result_type = pointer_type;
7638 } else if (is_type_pointer(other_type)) {
7639 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7640 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7643 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7644 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7646 } else if (types_compatible(get_unqualified_type(to1),
7647 get_unqualified_type(to2))) {
7650 if (warning.other) {
7651 warningf(&conditional->base.source_position,
7652 "pointer types '%T' and '%T' in conditional expression are incompatible",
7653 true_type, false_type);
7658 type_t *const type =
7659 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7660 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7661 } else if (is_type_integer(other_type)) {
7662 if (warning.other) {
7663 warningf(&conditional->base.source_position,
7664 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7666 result_type = pointer_type;
7668 goto types_incompatible;
7672 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7673 type_error_incompatible("while parsing conditional",
7674 &conditional->base.source_position, true_type,
7677 result_type = type_error_type;
7680 conditional->true_expression
7681 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7682 conditional->false_expression
7683 = create_implicit_cast(false_expression, result_type);
7684 conditional->base.type = result_type;
7689 * Parse an extension expression.
7691 static expression_t *parse_extension(void)
7693 eat(T___extension__);
7695 bool old_gcc_extension = in_gcc_extension;
7696 in_gcc_extension = true;
7697 expression_t *expression = parse_subexpression(PREC_UNARY);
7698 in_gcc_extension = old_gcc_extension;
7703 * Parse a __builtin_classify_type() expression.
7705 static expression_t *parse_builtin_classify_type(void)
7707 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7708 result->base.type = type_int;
7710 eat(T___builtin_classify_type);
7712 expect('(', end_error);
7713 add_anchor_token(')');
7714 expression_t *expression = parse_expression();
7715 rem_anchor_token(')');
7716 expect(')', end_error);
7717 result->classify_type.type_expression = expression;
7721 return create_invalid_expression();
7725 * Parse a delete expression
7726 * ISO/IEC 14882:1998(E) §5.3.5
7728 static expression_t *parse_delete(void)
7730 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7731 result->base.type = type_void;
7736 result->kind = EXPR_UNARY_DELETE_ARRAY;
7737 expect(']', end_error);
7741 expression_t *const value = parse_subexpression(PREC_CAST);
7742 result->unary.value = value;
7744 type_t *const type = skip_typeref(value->base.type);
7745 if (!is_type_pointer(type)) {
7746 if (is_type_valid(type)) {
7747 errorf(&value->base.source_position,
7748 "operand of delete must have pointer type");
7750 } else if (warning.other &&
7751 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7752 warningf(&value->base.source_position,
7753 "deleting 'void*' is undefined");
7760 * Parse a throw expression
7761 * ISO/IEC 14882:1998(E) §15:1
7763 static expression_t *parse_throw(void)
7765 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7766 result->base.type = type_void;
7770 expression_t *value = NULL;
7771 switch (token.type) {
7773 value = parse_assignment_expression();
7774 /* ISO/IEC 14882:1998(E) §15.1:3 */
7775 type_t *const orig_type = value->base.type;
7776 type_t *const type = skip_typeref(orig_type);
7777 if (is_type_incomplete(type)) {
7778 errorf(&value->base.source_position,
7779 "cannot throw object of incomplete type '%T'", orig_type);
7780 } else if (is_type_pointer(type)) {
7781 type_t *const points_to = skip_typeref(type->pointer.points_to);
7782 if (is_type_incomplete(points_to) &&
7783 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7784 errorf(&value->base.source_position,
7785 "cannot throw pointer to incomplete type '%T'", orig_type);
7793 result->unary.value = value;
7798 static bool check_pointer_arithmetic(const source_position_t *source_position,
7799 type_t *pointer_type,
7800 type_t *orig_pointer_type)
7802 type_t *points_to = pointer_type->pointer.points_to;
7803 points_to = skip_typeref(points_to);
7805 if (is_type_incomplete(points_to)) {
7806 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7807 errorf(source_position,
7808 "arithmetic with pointer to incomplete type '%T' not allowed",
7811 } else if (warning.pointer_arith) {
7812 warningf(source_position,
7813 "pointer of type '%T' used in arithmetic",
7816 } else if (is_type_function(points_to)) {
7818 errorf(source_position,
7819 "arithmetic with pointer to function type '%T' not allowed",
7822 } else if (warning.pointer_arith) {
7823 warningf(source_position,
7824 "pointer to a function '%T' used in arithmetic",
7831 static bool is_lvalue(const expression_t *expression)
7833 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7834 switch (expression->kind) {
7835 case EXPR_ARRAY_ACCESS:
7836 case EXPR_COMPOUND_LITERAL:
7837 case EXPR_REFERENCE:
7839 case EXPR_UNARY_DEREFERENCE:
7843 type_t *type = skip_typeref(expression->base.type);
7845 /* ISO/IEC 14882:1998(E) §3.10:3 */
7846 is_type_reference(type) ||
7847 /* Claim it is an lvalue, if the type is invalid. There was a parse
7848 * error before, which maybe prevented properly recognizing it as
7850 !is_type_valid(type);
7855 static void semantic_incdec(unary_expression_t *expression)
7857 type_t *const orig_type = expression->value->base.type;
7858 type_t *const type = skip_typeref(orig_type);
7859 if (is_type_pointer(type)) {
7860 if (!check_pointer_arithmetic(&expression->base.source_position,
7864 } else if (!is_type_real(type) && is_type_valid(type)) {
7865 /* TODO: improve error message */
7866 errorf(&expression->base.source_position,
7867 "operation needs an arithmetic or pointer type");
7870 if (!is_lvalue(expression->value)) {
7871 /* TODO: improve error message */
7872 errorf(&expression->base.source_position, "lvalue required as operand");
7874 expression->base.type = orig_type;
7877 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7879 type_t *const orig_type = expression->value->base.type;
7880 type_t *const type = skip_typeref(orig_type);
7881 if (!is_type_arithmetic(type)) {
7882 if (is_type_valid(type)) {
7883 /* TODO: improve error message */
7884 errorf(&expression->base.source_position,
7885 "operation needs an arithmetic type");
7890 expression->base.type = orig_type;
7893 static void semantic_unexpr_plus(unary_expression_t *expression)
7895 semantic_unexpr_arithmetic(expression);
7896 if (warning.traditional)
7897 warningf(&expression->base.source_position,
7898 "traditional C rejects the unary plus operator");
7901 static void semantic_not(unary_expression_t *expression)
7903 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7904 semantic_condition(expression->value, "operand of !");
7905 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7908 static void semantic_unexpr_integer(unary_expression_t *expression)
7910 type_t *const orig_type = expression->value->base.type;
7911 type_t *const type = skip_typeref(orig_type);
7912 if (!is_type_integer(type)) {
7913 if (is_type_valid(type)) {
7914 errorf(&expression->base.source_position,
7915 "operand of ~ must be of integer type");
7920 expression->base.type = orig_type;
7923 static void semantic_dereference(unary_expression_t *expression)
7925 type_t *const orig_type = expression->value->base.type;
7926 type_t *const type = skip_typeref(orig_type);
7927 if (!is_type_pointer(type)) {
7928 if (is_type_valid(type)) {
7929 errorf(&expression->base.source_position,
7930 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7935 type_t *result_type = type->pointer.points_to;
7936 result_type = automatic_type_conversion(result_type);
7937 expression->base.type = result_type;
7941 * Record that an address is taken (expression represents an lvalue).
7943 * @param expression the expression
7944 * @param may_be_register if true, the expression might be an register
7946 static void set_address_taken(expression_t *expression, bool may_be_register)
7948 if (expression->kind != EXPR_REFERENCE)
7951 entity_t *const entity = expression->reference.entity;
7953 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7956 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7957 && !may_be_register) {
7958 source_position_t const *const pos = &expression->base.source_position;
7959 errorf(pos, "address of register '%N' requested", entity);
7962 if (entity->kind == ENTITY_VARIABLE) {
7963 entity->variable.address_taken = true;
7965 assert(entity->kind == ENTITY_PARAMETER);
7966 entity->parameter.address_taken = true;
7971 * Check the semantic of the address taken expression.
7973 static void semantic_take_addr(unary_expression_t *expression)
7975 expression_t *value = expression->value;
7976 value->base.type = revert_automatic_type_conversion(value);
7978 type_t *orig_type = value->base.type;
7979 type_t *type = skip_typeref(orig_type);
7980 if (!is_type_valid(type))
7984 if (!is_lvalue(value)) {
7985 errorf(&expression->base.source_position, "'&' requires an lvalue");
7987 if (type->kind == TYPE_BITFIELD) {
7988 errorf(&expression->base.source_position,
7989 "'&' not allowed on object with bitfield type '%T'",
7993 set_address_taken(value, false);
7995 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7998 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7999 static expression_t *parse_##unexpression_type(void) \
8001 expression_t *unary_expression \
8002 = allocate_expression_zero(unexpression_type); \
8004 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8006 sfunc(&unary_expression->unary); \
8008 return unary_expression; \
8011 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8012 semantic_unexpr_arithmetic)
8013 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8014 semantic_unexpr_plus)
8015 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8017 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8018 semantic_dereference)
8019 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8021 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8022 semantic_unexpr_integer)
8023 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8025 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8028 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8030 static expression_t *parse_##unexpression_type(expression_t *left) \
8032 expression_t *unary_expression \
8033 = allocate_expression_zero(unexpression_type); \
8035 unary_expression->unary.value = left; \
8037 sfunc(&unary_expression->unary); \
8039 return unary_expression; \
8042 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8043 EXPR_UNARY_POSTFIX_INCREMENT,
8045 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8046 EXPR_UNARY_POSTFIX_DECREMENT,
8049 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8051 /* TODO: handle complex + imaginary types */
8053 type_left = get_unqualified_type(type_left);
8054 type_right = get_unqualified_type(type_right);
8056 /* §6.3.1.8 Usual arithmetic conversions */
8057 if (type_left == type_long_double || type_right == type_long_double) {
8058 return type_long_double;
8059 } else if (type_left == type_double || type_right == type_double) {
8061 } else if (type_left == type_float || type_right == type_float) {
8065 type_left = promote_integer(type_left);
8066 type_right = promote_integer(type_right);
8068 if (type_left == type_right)
8071 bool const signed_left = is_type_signed(type_left);
8072 bool const signed_right = is_type_signed(type_right);
8073 int const rank_left = get_rank(type_left);
8074 int const rank_right = get_rank(type_right);
8076 if (signed_left == signed_right)
8077 return rank_left >= rank_right ? type_left : type_right;
8086 u_rank = rank_right;
8087 u_type = type_right;
8089 s_rank = rank_right;
8090 s_type = type_right;
8095 if (u_rank >= s_rank)
8098 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8100 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8101 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8105 case ATOMIC_TYPE_INT: return type_unsigned_int;
8106 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8107 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8109 default: panic("invalid atomic type");
8114 * Check the semantic restrictions for a binary expression.
8116 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8118 expression_t *const left = expression->left;
8119 expression_t *const right = expression->right;
8120 type_t *const orig_type_left = left->base.type;
8121 type_t *const orig_type_right = right->base.type;
8122 type_t *const type_left = skip_typeref(orig_type_left);
8123 type_t *const type_right = skip_typeref(orig_type_right);
8125 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8126 /* TODO: improve error message */
8127 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8128 errorf(&expression->base.source_position,
8129 "operation needs arithmetic types");
8134 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8135 expression->left = create_implicit_cast(left, arithmetic_type);
8136 expression->right = create_implicit_cast(right, arithmetic_type);
8137 expression->base.type = arithmetic_type;
8140 static void semantic_binexpr_integer(binary_expression_t *const expression)
8142 expression_t *const left = expression->left;
8143 expression_t *const right = expression->right;
8144 type_t *const orig_type_left = left->base.type;
8145 type_t *const orig_type_right = right->base.type;
8146 type_t *const type_left = skip_typeref(orig_type_left);
8147 type_t *const type_right = skip_typeref(orig_type_right);
8149 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8150 /* TODO: improve error message */
8151 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8152 errorf(&expression->base.source_position,
8153 "operation needs integer types");
8158 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8159 expression->left = create_implicit_cast(left, result_type);
8160 expression->right = create_implicit_cast(right, result_type);
8161 expression->base.type = result_type;
8164 static void warn_div_by_zero(binary_expression_t const *const expression)
8166 if (!warning.div_by_zero ||
8167 !is_type_integer(expression->base.type))
8170 expression_t const *const right = expression->right;
8171 /* The type of the right operand can be different for /= */
8172 if (is_type_integer(right->base.type) &&
8173 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8174 !fold_constant_to_bool(right)) {
8175 warningf(&expression->base.source_position, "division by zero");
8180 * Check the semantic restrictions for a div/mod expression.
8182 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8184 semantic_binexpr_arithmetic(expression);
8185 warn_div_by_zero(expression);
8188 static void warn_addsub_in_shift(const expression_t *const expr)
8190 if (expr->base.parenthesized)
8194 switch (expr->kind) {
8195 case EXPR_BINARY_ADD: op = '+'; break;
8196 case EXPR_BINARY_SUB: op = '-'; break;
8200 warningf(&expr->base.source_position,
8201 "suggest parentheses around '%c' inside shift", op);
8204 static bool semantic_shift(binary_expression_t *expression)
8206 expression_t *const left = expression->left;
8207 expression_t *const right = expression->right;
8208 type_t *const orig_type_left = left->base.type;
8209 type_t *const orig_type_right = right->base.type;
8210 type_t * type_left = skip_typeref(orig_type_left);
8211 type_t * type_right = skip_typeref(orig_type_right);
8213 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8214 /* TODO: improve error message */
8215 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8216 errorf(&expression->base.source_position,
8217 "operands of shift operation must have integer types");
8222 type_left = promote_integer(type_left);
8224 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8225 long count = fold_constant_to_int(right);
8227 warningf(&right->base.source_position,
8228 "shift count must be non-negative");
8229 } else if ((unsigned long)count >=
8230 get_atomic_type_size(type_left->atomic.akind) * 8) {
8231 warningf(&right->base.source_position,
8232 "shift count must be less than type width");
8236 type_right = promote_integer(type_right);
8237 expression->right = create_implicit_cast(right, type_right);
8242 static void semantic_shift_op(binary_expression_t *expression)
8244 expression_t *const left = expression->left;
8245 expression_t *const right = expression->right;
8247 if (!semantic_shift(expression))
8250 if (warning.parentheses) {
8251 warn_addsub_in_shift(left);
8252 warn_addsub_in_shift(right);
8255 type_t *const orig_type_left = left->base.type;
8256 type_t * type_left = skip_typeref(orig_type_left);
8258 type_left = promote_integer(type_left);
8259 expression->left = create_implicit_cast(left, type_left);
8260 expression->base.type = type_left;
8263 static void semantic_add(binary_expression_t *expression)
8265 expression_t *const left = expression->left;
8266 expression_t *const right = expression->right;
8267 type_t *const orig_type_left = left->base.type;
8268 type_t *const orig_type_right = right->base.type;
8269 type_t *const type_left = skip_typeref(orig_type_left);
8270 type_t *const type_right = skip_typeref(orig_type_right);
8273 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8274 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8275 expression->left = create_implicit_cast(left, arithmetic_type);
8276 expression->right = create_implicit_cast(right, arithmetic_type);
8277 expression->base.type = arithmetic_type;
8278 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8279 check_pointer_arithmetic(&expression->base.source_position,
8280 type_left, orig_type_left);
8281 expression->base.type = type_left;
8282 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8283 check_pointer_arithmetic(&expression->base.source_position,
8284 type_right, orig_type_right);
8285 expression->base.type = type_right;
8286 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8287 errorf(&expression->base.source_position,
8288 "invalid operands to binary + ('%T', '%T')",
8289 orig_type_left, orig_type_right);
8293 static void semantic_sub(binary_expression_t *expression)
8295 expression_t *const left = expression->left;
8296 expression_t *const right = expression->right;
8297 type_t *const orig_type_left = left->base.type;
8298 type_t *const orig_type_right = right->base.type;
8299 type_t *const type_left = skip_typeref(orig_type_left);
8300 type_t *const type_right = skip_typeref(orig_type_right);
8301 source_position_t const *const pos = &expression->base.source_position;
8304 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8305 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8306 expression->left = create_implicit_cast(left, arithmetic_type);
8307 expression->right = create_implicit_cast(right, arithmetic_type);
8308 expression->base.type = arithmetic_type;
8309 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8310 check_pointer_arithmetic(&expression->base.source_position,
8311 type_left, orig_type_left);
8312 expression->base.type = type_left;
8313 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8314 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8315 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8316 if (!types_compatible(unqual_left, unqual_right)) {
8318 "subtracting pointers to incompatible types '%T' and '%T'",
8319 orig_type_left, orig_type_right);
8320 } else if (!is_type_object(unqual_left)) {
8321 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8322 errorf(pos, "subtracting pointers to non-object types '%T'",
8324 } else if (warning.other) {
8325 warningf(pos, "subtracting pointers to void");
8328 expression->base.type = type_ptrdiff_t;
8329 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8330 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8331 orig_type_left, orig_type_right);
8335 static void warn_string_literal_address(expression_t const* expr)
8337 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8338 expr = expr->unary.value;
8339 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8341 expr = expr->unary.value;
8344 if (expr->kind == EXPR_STRING_LITERAL
8345 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8346 warningf(&expr->base.source_position,
8347 "comparison with string literal results in unspecified behaviour");
8351 static bool maybe_negative(expression_t const *const expr)
8353 switch (is_constant_expression(expr)) {
8354 case EXPR_CLASS_ERROR: return false;
8355 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8356 default: return true;
8360 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8362 if (warning.address) {
8363 warn_string_literal_address(expr);
8365 expression_t const* const ref = get_reference_address(expr);
8366 if (ref != NULL && is_null_pointer_constant(other)) {
8367 entity_t const *const ent = ref->reference.entity;
8368 warningf(pos, "the address of '%N' will never be NULL", ent);
8372 if (warning.parentheses && !expr->base.parenthesized) {
8373 switch (expr->base.kind) {
8374 case EXPR_BINARY_LESS:
8375 case EXPR_BINARY_GREATER:
8376 case EXPR_BINARY_LESSEQUAL:
8377 case EXPR_BINARY_GREATEREQUAL:
8378 case EXPR_BINARY_NOTEQUAL:
8379 case EXPR_BINARY_EQUAL:
8380 warningf(pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8389 * Check the semantics of comparison expressions.
8391 * @param expression The expression to check.
8393 static void semantic_comparison(binary_expression_t *expression)
8395 source_position_t const *const pos = &expression->base.source_position;
8396 expression_t *const left = expression->left;
8397 expression_t *const right = expression->right;
8399 warn_comparison(pos, left, right);
8400 warn_comparison(pos, right, left);
8402 type_t *orig_type_left = left->base.type;
8403 type_t *orig_type_right = right->base.type;
8404 type_t *type_left = skip_typeref(orig_type_left);
8405 type_t *type_right = skip_typeref(orig_type_right);
8407 /* TODO non-arithmetic types */
8408 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8409 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8411 /* test for signed vs unsigned compares */
8412 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8413 bool const signed_left = is_type_signed(type_left);
8414 bool const signed_right = is_type_signed(type_right);
8415 if (signed_left != signed_right) {
8416 /* FIXME long long needs better const folding magic */
8417 /* TODO check whether constant value can be represented by other type */
8418 if ((signed_left && maybe_negative(left)) ||
8419 (signed_right && maybe_negative(right))) {
8420 warningf(pos, "comparison between signed and unsigned");
8425 expression->left = create_implicit_cast(left, arithmetic_type);
8426 expression->right = create_implicit_cast(right, arithmetic_type);
8427 expression->base.type = arithmetic_type;
8428 if (warning.float_equal &&
8429 (expression->base.kind == EXPR_BINARY_EQUAL ||
8430 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8431 is_type_float(arithmetic_type)) {
8432 warningf(pos, "comparing floating point with == or != is unsafe");
8434 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8435 /* TODO check compatibility */
8436 } else if (is_type_pointer(type_left)) {
8437 expression->right = create_implicit_cast(right, type_left);
8438 } else if (is_type_pointer(type_right)) {
8439 expression->left = create_implicit_cast(left, type_right);
8440 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8441 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8443 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8447 * Checks if a compound type has constant fields.
8449 static bool has_const_fields(const compound_type_t *type)
8451 compound_t *compound = type->compound;
8452 entity_t *entry = compound->members.entities;
8454 for (; entry != NULL; entry = entry->base.next) {
8455 if (!is_declaration(entry))
8458 const type_t *decl_type = skip_typeref(entry->declaration.type);
8459 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8466 static bool is_valid_assignment_lhs(expression_t const* const left)
8468 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8469 type_t *const type_left = skip_typeref(orig_type_left);
8471 if (!is_lvalue(left)) {
8472 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8477 if (left->kind == EXPR_REFERENCE
8478 && left->reference.entity->kind == ENTITY_FUNCTION) {
8479 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8483 if (is_type_array(type_left)) {
8484 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8487 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8488 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8492 if (is_type_incomplete(type_left)) {
8493 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8494 left, orig_type_left);
8497 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8498 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8499 left, orig_type_left);
8506 static void semantic_arithmetic_assign(binary_expression_t *expression)
8508 expression_t *left = expression->left;
8509 expression_t *right = expression->right;
8510 type_t *orig_type_left = left->base.type;
8511 type_t *orig_type_right = right->base.type;
8513 if (!is_valid_assignment_lhs(left))
8516 type_t *type_left = skip_typeref(orig_type_left);
8517 type_t *type_right = skip_typeref(orig_type_right);
8519 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8520 /* TODO: improve error message */
8521 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8522 errorf(&expression->base.source_position,
8523 "operation needs arithmetic types");
8528 /* combined instructions are tricky. We can't create an implicit cast on
8529 * the left side, because we need the uncasted form for the store.
8530 * The ast2firm pass has to know that left_type must be right_type
8531 * for the arithmetic operation and create a cast by itself */
8532 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8533 expression->right = create_implicit_cast(right, arithmetic_type);
8534 expression->base.type = type_left;
8537 static void semantic_divmod_assign(binary_expression_t *expression)
8539 semantic_arithmetic_assign(expression);
8540 warn_div_by_zero(expression);
8543 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8545 expression_t *const left = expression->left;
8546 expression_t *const right = expression->right;
8547 type_t *const orig_type_left = left->base.type;
8548 type_t *const orig_type_right = right->base.type;
8549 type_t *const type_left = skip_typeref(orig_type_left);
8550 type_t *const type_right = skip_typeref(orig_type_right);
8552 if (!is_valid_assignment_lhs(left))
8555 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8556 /* combined instructions are tricky. We can't create an implicit cast on
8557 * the left side, because we need the uncasted form for the store.
8558 * The ast2firm pass has to know that left_type must be right_type
8559 * for the arithmetic operation and create a cast by itself */
8560 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8561 expression->right = create_implicit_cast(right, arithmetic_type);
8562 expression->base.type = type_left;
8563 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8564 check_pointer_arithmetic(&expression->base.source_position,
8565 type_left, orig_type_left);
8566 expression->base.type = type_left;
8567 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8568 errorf(&expression->base.source_position,
8569 "incompatible types '%T' and '%T' in assignment",
8570 orig_type_left, orig_type_right);
8574 static void semantic_integer_assign(binary_expression_t *expression)
8576 expression_t *left = expression->left;
8577 expression_t *right = expression->right;
8578 type_t *orig_type_left = left->base.type;
8579 type_t *orig_type_right = right->base.type;
8581 if (!is_valid_assignment_lhs(left))
8584 type_t *type_left = skip_typeref(orig_type_left);
8585 type_t *type_right = skip_typeref(orig_type_right);
8587 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8588 /* TODO: improve error message */
8589 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8590 errorf(&expression->base.source_position,
8591 "operation needs integer types");
8596 /* combined instructions are tricky. We can't create an implicit cast on
8597 * the left side, because we need the uncasted form for the store.
8598 * The ast2firm pass has to know that left_type must be right_type
8599 * for the arithmetic operation and create a cast by itself */
8600 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8601 expression->right = create_implicit_cast(right, arithmetic_type);
8602 expression->base.type = type_left;
8605 static void semantic_shift_assign(binary_expression_t *expression)
8607 expression_t *left = expression->left;
8609 if (!is_valid_assignment_lhs(left))
8612 if (!semantic_shift(expression))
8615 expression->base.type = skip_typeref(left->base.type);
8618 static void warn_logical_and_within_or(const expression_t *const expr)
8620 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8622 if (expr->base.parenthesized)
8624 warningf(&expr->base.source_position,
8625 "suggest parentheses around && within ||");
8629 * Check the semantic restrictions of a logical expression.
8631 static void semantic_logical_op(binary_expression_t *expression)
8633 /* §6.5.13:2 Each of the operands shall have scalar type.
8634 * §6.5.14:2 Each of the operands shall have scalar type. */
8635 semantic_condition(expression->left, "left operand of logical operator");
8636 semantic_condition(expression->right, "right operand of logical operator");
8637 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8638 warning.parentheses) {
8639 warn_logical_and_within_or(expression->left);
8640 warn_logical_and_within_or(expression->right);
8642 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8646 * Check the semantic restrictions of a binary assign expression.
8648 static void semantic_binexpr_assign(binary_expression_t *expression)
8650 expression_t *left = expression->left;
8651 type_t *orig_type_left = left->base.type;
8653 if (!is_valid_assignment_lhs(left))
8656 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8657 report_assign_error(error, orig_type_left, expression->right,
8658 "assignment", &left->base.source_position);
8659 expression->right = create_implicit_cast(expression->right, orig_type_left);
8660 expression->base.type = orig_type_left;
8664 * Determine if the outermost operation (or parts thereof) of the given
8665 * expression has no effect in order to generate a warning about this fact.
8666 * Therefore in some cases this only examines some of the operands of the
8667 * expression (see comments in the function and examples below).
8669 * f() + 23; // warning, because + has no effect
8670 * x || f(); // no warning, because x controls execution of f()
8671 * x ? y : f(); // warning, because y has no effect
8672 * (void)x; // no warning to be able to suppress the warning
8673 * This function can NOT be used for an "expression has definitely no effect"-
8675 static bool expression_has_effect(const expression_t *const expr)
8677 switch (expr->kind) {
8678 case EXPR_UNKNOWN: break;
8679 case EXPR_INVALID: return true; /* do NOT warn */
8680 case EXPR_REFERENCE: return false;
8681 case EXPR_REFERENCE_ENUM_VALUE: return false;
8682 case EXPR_LABEL_ADDRESS: return false;
8684 /* suppress the warning for microsoft __noop operations */
8685 case EXPR_LITERAL_MS_NOOP: return true;
8686 case EXPR_LITERAL_BOOLEAN:
8687 case EXPR_LITERAL_CHARACTER:
8688 case EXPR_LITERAL_WIDE_CHARACTER:
8689 case EXPR_LITERAL_INTEGER:
8690 case EXPR_LITERAL_INTEGER_OCTAL:
8691 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8692 case EXPR_LITERAL_FLOATINGPOINT:
8693 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8694 case EXPR_STRING_LITERAL: return false;
8695 case EXPR_WIDE_STRING_LITERAL: return false;
8698 const call_expression_t *const call = &expr->call;
8699 if (call->function->kind != EXPR_REFERENCE)
8702 switch (call->function->reference.entity->function.btk) {
8703 /* FIXME: which builtins have no effect? */
8704 default: return true;
8708 /* Generate the warning if either the left or right hand side of a
8709 * conditional expression has no effect */
8710 case EXPR_CONDITIONAL: {
8711 conditional_expression_t const *const cond = &expr->conditional;
8712 expression_t const *const t = cond->true_expression;
8714 (t == NULL || expression_has_effect(t)) &&
8715 expression_has_effect(cond->false_expression);
8718 case EXPR_SELECT: return false;
8719 case EXPR_ARRAY_ACCESS: return false;
8720 case EXPR_SIZEOF: return false;
8721 case EXPR_CLASSIFY_TYPE: return false;
8722 case EXPR_ALIGNOF: return false;
8724 case EXPR_FUNCNAME: return false;
8725 case EXPR_BUILTIN_CONSTANT_P: return false;
8726 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8727 case EXPR_OFFSETOF: return false;
8728 case EXPR_VA_START: return true;
8729 case EXPR_VA_ARG: return true;
8730 case EXPR_VA_COPY: return true;
8731 case EXPR_STATEMENT: return true; // TODO
8732 case EXPR_COMPOUND_LITERAL: return false;
8734 case EXPR_UNARY_NEGATE: return false;
8735 case EXPR_UNARY_PLUS: return false;
8736 case EXPR_UNARY_BITWISE_NEGATE: return false;
8737 case EXPR_UNARY_NOT: return false;
8738 case EXPR_UNARY_DEREFERENCE: return false;
8739 case EXPR_UNARY_TAKE_ADDRESS: return false;
8740 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8741 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8742 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8743 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8745 /* Treat void casts as if they have an effect in order to being able to
8746 * suppress the warning */
8747 case EXPR_UNARY_CAST: {
8748 type_t *const type = skip_typeref(expr->base.type);
8749 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8752 case EXPR_UNARY_CAST_IMPLICIT: return true;
8753 case EXPR_UNARY_ASSUME: return true;
8754 case EXPR_UNARY_DELETE: return true;
8755 case EXPR_UNARY_DELETE_ARRAY: return true;
8756 case EXPR_UNARY_THROW: return true;
8758 case EXPR_BINARY_ADD: return false;
8759 case EXPR_BINARY_SUB: return false;
8760 case EXPR_BINARY_MUL: return false;
8761 case EXPR_BINARY_DIV: return false;
8762 case EXPR_BINARY_MOD: return false;
8763 case EXPR_BINARY_EQUAL: return false;
8764 case EXPR_BINARY_NOTEQUAL: return false;
8765 case EXPR_BINARY_LESS: return false;
8766 case EXPR_BINARY_LESSEQUAL: return false;
8767 case EXPR_BINARY_GREATER: return false;
8768 case EXPR_BINARY_GREATEREQUAL: return false;
8769 case EXPR_BINARY_BITWISE_AND: return false;
8770 case EXPR_BINARY_BITWISE_OR: return false;
8771 case EXPR_BINARY_BITWISE_XOR: return false;
8772 case EXPR_BINARY_SHIFTLEFT: return false;
8773 case EXPR_BINARY_SHIFTRIGHT: return false;
8774 case EXPR_BINARY_ASSIGN: return true;
8775 case EXPR_BINARY_MUL_ASSIGN: return true;
8776 case EXPR_BINARY_DIV_ASSIGN: return true;
8777 case EXPR_BINARY_MOD_ASSIGN: return true;
8778 case EXPR_BINARY_ADD_ASSIGN: return true;
8779 case EXPR_BINARY_SUB_ASSIGN: return true;
8780 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8781 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8782 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8783 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8784 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8786 /* Only examine the right hand side of && and ||, because the left hand
8787 * side already has the effect of controlling the execution of the right
8789 case EXPR_BINARY_LOGICAL_AND:
8790 case EXPR_BINARY_LOGICAL_OR:
8791 /* Only examine the right hand side of a comma expression, because the left
8792 * hand side has a separate warning */
8793 case EXPR_BINARY_COMMA:
8794 return expression_has_effect(expr->binary.right);
8796 case EXPR_BINARY_ISGREATER: return false;
8797 case EXPR_BINARY_ISGREATEREQUAL: return false;
8798 case EXPR_BINARY_ISLESS: return false;
8799 case EXPR_BINARY_ISLESSEQUAL: return false;
8800 case EXPR_BINARY_ISLESSGREATER: return false;
8801 case EXPR_BINARY_ISUNORDERED: return false;
8804 internal_errorf(HERE, "unexpected expression");
8807 static void semantic_comma(binary_expression_t *expression)
8809 if (warning.unused_value) {
8810 const expression_t *const left = expression->left;
8811 if (!expression_has_effect(left)) {
8812 warningf(&left->base.source_position,
8813 "left-hand operand of comma expression has no effect");
8816 expression->base.type = expression->right->base.type;
8820 * @param prec_r precedence of the right operand
8822 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8823 static expression_t *parse_##binexpression_type(expression_t *left) \
8825 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8826 binexpr->binary.left = left; \
8829 expression_t *right = parse_subexpression(prec_r); \
8831 binexpr->binary.right = right; \
8832 sfunc(&binexpr->binary); \
8837 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8838 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8839 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8840 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8841 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8842 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8843 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8844 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8845 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8846 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8847 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8848 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8849 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8850 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8851 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8852 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8853 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8854 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8855 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8856 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8857 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8858 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8859 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8860 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8861 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8862 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8863 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8864 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8865 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8866 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8869 static expression_t *parse_subexpression(precedence_t precedence)
8871 if (token.type < 0) {
8872 return expected_expression_error();
8875 expression_parser_function_t *parser
8876 = &expression_parsers[token.type];
8877 source_position_t source_position = token.source_position;
8880 if (parser->parser != NULL) {
8881 left = parser->parser();
8883 left = parse_primary_expression();
8885 assert(left != NULL);
8886 left->base.source_position = source_position;
8889 if (token.type < 0) {
8890 return expected_expression_error();
8893 parser = &expression_parsers[token.type];
8894 if (parser->infix_parser == NULL)
8896 if (parser->infix_precedence < precedence)
8899 left = parser->infix_parser(left);
8901 assert(left != NULL);
8902 assert(left->kind != EXPR_UNKNOWN);
8903 left->base.source_position = source_position;
8910 * Parse an expression.
8912 static expression_t *parse_expression(void)
8914 return parse_subexpression(PREC_EXPRESSION);
8918 * Register a parser for a prefix-like operator.
8920 * @param parser the parser function
8921 * @param token_type the token type of the prefix token
8923 static void register_expression_parser(parse_expression_function parser,
8926 expression_parser_function_t *entry = &expression_parsers[token_type];
8928 if (entry->parser != NULL) {
8929 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8930 panic("trying to register multiple expression parsers for a token");
8932 entry->parser = parser;
8936 * Register a parser for an infix operator with given precedence.
8938 * @param parser the parser function
8939 * @param token_type the token type of the infix operator
8940 * @param precedence the precedence of the operator
8942 static void register_infix_parser(parse_expression_infix_function parser,
8943 int token_type, precedence_t precedence)
8945 expression_parser_function_t *entry = &expression_parsers[token_type];
8947 if (entry->infix_parser != NULL) {
8948 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8949 panic("trying to register multiple infix expression parsers for a "
8952 entry->infix_parser = parser;
8953 entry->infix_precedence = precedence;
8957 * Initialize the expression parsers.
8959 static void init_expression_parsers(void)
8961 memset(&expression_parsers, 0, sizeof(expression_parsers));
8963 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8964 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8965 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8966 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8967 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8968 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8969 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8970 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8971 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8972 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8973 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8974 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8975 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8976 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8977 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8978 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8979 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8980 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8981 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8982 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8983 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8984 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8985 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8986 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8987 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8988 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8989 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8990 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8991 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8992 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8993 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8994 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8995 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8996 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8997 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8998 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8999 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9001 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9002 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9003 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9004 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9005 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9006 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9007 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9008 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9009 register_expression_parser(parse_sizeof, T_sizeof);
9010 register_expression_parser(parse_alignof, T___alignof__);
9011 register_expression_parser(parse_extension, T___extension__);
9012 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9013 register_expression_parser(parse_delete, T_delete);
9014 register_expression_parser(parse_throw, T_throw);
9018 * Parse a asm statement arguments specification.
9020 static asm_argument_t *parse_asm_arguments(bool is_out)
9022 asm_argument_t *result = NULL;
9023 asm_argument_t **anchor = &result;
9025 while (token.type == T_STRING_LITERAL || token.type == '[') {
9026 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9027 memset(argument, 0, sizeof(argument[0]));
9030 if (token.type != T_IDENTIFIER) {
9031 parse_error_expected("while parsing asm argument",
9032 T_IDENTIFIER, NULL);
9035 argument->symbol = token.symbol;
9037 expect(']', end_error);
9040 argument->constraints = parse_string_literals();
9041 expect('(', end_error);
9042 add_anchor_token(')');
9043 expression_t *expression = parse_expression();
9044 rem_anchor_token(')');
9046 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9047 * change size or type representation (e.g. int -> long is ok, but
9048 * int -> float is not) */
9049 if (expression->kind == EXPR_UNARY_CAST) {
9050 type_t *const type = expression->base.type;
9051 type_kind_t const kind = type->kind;
9052 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9055 if (kind == TYPE_ATOMIC) {
9056 atomic_type_kind_t const akind = type->atomic.akind;
9057 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9058 size = get_atomic_type_size(akind);
9060 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9061 size = get_atomic_type_size(get_intptr_kind());
9065 expression_t *const value = expression->unary.value;
9066 type_t *const value_type = value->base.type;
9067 type_kind_t const value_kind = value_type->kind;
9069 unsigned value_flags;
9070 unsigned value_size;
9071 if (value_kind == TYPE_ATOMIC) {
9072 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9073 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9074 value_size = get_atomic_type_size(value_akind);
9075 } else if (value_kind == TYPE_POINTER) {
9076 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9077 value_size = get_atomic_type_size(get_intptr_kind());
9082 if (value_flags != flags || value_size != size)
9086 } while (expression->kind == EXPR_UNARY_CAST);
9090 if (!is_lvalue(expression)) {
9091 errorf(&expression->base.source_position,
9092 "asm output argument is not an lvalue");
9095 if (argument->constraints.begin[0] == '=')
9096 determine_lhs_ent(expression, NULL);
9098 mark_vars_read(expression, NULL);
9100 mark_vars_read(expression, NULL);
9102 argument->expression = expression;
9103 expect(')', end_error);
9105 set_address_taken(expression, true);
9108 anchor = &argument->next;
9120 * Parse a asm statement clobber specification.
9122 static asm_clobber_t *parse_asm_clobbers(void)
9124 asm_clobber_t *result = NULL;
9125 asm_clobber_t **anchor = &result;
9127 while (token.type == T_STRING_LITERAL) {
9128 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9129 clobber->clobber = parse_string_literals();
9132 anchor = &clobber->next;
9142 * Parse an asm statement.
9144 static statement_t *parse_asm_statement(void)
9146 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9147 asm_statement_t *asm_statement = &statement->asms;
9151 if (next_if(T_volatile))
9152 asm_statement->is_volatile = true;
9154 expect('(', end_error);
9155 add_anchor_token(')');
9156 if (token.type != T_STRING_LITERAL) {
9157 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9160 asm_statement->asm_text = parse_string_literals();
9162 add_anchor_token(':');
9163 if (!next_if(':')) {
9164 rem_anchor_token(':');
9168 asm_statement->outputs = parse_asm_arguments(true);
9169 if (!next_if(':')) {
9170 rem_anchor_token(':');
9174 asm_statement->inputs = parse_asm_arguments(false);
9175 if (!next_if(':')) {
9176 rem_anchor_token(':');
9179 rem_anchor_token(':');
9181 asm_statement->clobbers = parse_asm_clobbers();
9184 rem_anchor_token(')');
9185 expect(')', end_error);
9186 expect(';', end_error);
9188 if (asm_statement->outputs == NULL) {
9189 /* GCC: An 'asm' instruction without any output operands will be treated
9190 * identically to a volatile 'asm' instruction. */
9191 asm_statement->is_volatile = true;
9196 return create_invalid_statement();
9199 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9201 statement_t *inner_stmt;
9202 switch (token.type) {
9204 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9205 inner_stmt = create_invalid_statement();
9209 if (label->kind == STATEMENT_LABEL) {
9210 /* Eat an empty statement here, to avoid the warning about an empty
9211 * statement after a label. label:; is commonly used to have a label
9212 * before a closing brace. */
9213 inner_stmt = create_empty_statement();
9220 inner_stmt = parse_statement();
9221 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9222 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9223 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9231 * Parse a case statement.
9233 static statement_t *parse_case_statement(void)
9235 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9236 source_position_t *const pos = &statement->base.source_position;
9240 expression_t *const expression = parse_expression();
9241 statement->case_label.expression = expression;
9242 expression_classification_t const expr_class = is_constant_expression(expression);
9243 if (expr_class != EXPR_CLASS_CONSTANT) {
9244 if (expr_class != EXPR_CLASS_ERROR) {
9245 errorf(pos, "case label does not reduce to an integer constant");
9247 statement->case_label.is_bad = true;
9249 long const val = fold_constant_to_int(expression);
9250 statement->case_label.first_case = val;
9251 statement->case_label.last_case = val;
9255 if (next_if(T_DOTDOTDOT)) {
9256 expression_t *const end_range = parse_expression();
9257 statement->case_label.end_range = end_range;
9258 expression_classification_t const end_class = is_constant_expression(end_range);
9259 if (end_class != EXPR_CLASS_CONSTANT) {
9260 if (end_class != EXPR_CLASS_ERROR) {
9261 errorf(pos, "case range does not reduce to an integer constant");
9263 statement->case_label.is_bad = true;
9265 long const val = fold_constant_to_int(end_range);
9266 statement->case_label.last_case = val;
9268 if (warning.other && val < statement->case_label.first_case) {
9269 statement->case_label.is_empty_range = true;
9270 warningf(pos, "empty range specified");
9276 PUSH_PARENT(statement);
9278 expect(':', end_error);
9281 if (current_switch != NULL) {
9282 if (! statement->case_label.is_bad) {
9283 /* Check for duplicate case values */
9284 case_label_statement_t *c = &statement->case_label;
9285 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9286 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9289 if (c->last_case < l->first_case || c->first_case > l->last_case)
9292 errorf(pos, "duplicate case value (previously used %P)",
9293 &l->base.source_position);
9297 /* link all cases into the switch statement */
9298 if (current_switch->last_case == NULL) {
9299 current_switch->first_case = &statement->case_label;
9301 current_switch->last_case->next = &statement->case_label;
9303 current_switch->last_case = &statement->case_label;
9305 errorf(pos, "case label not within a switch statement");
9308 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9315 * Parse a default statement.
9317 static statement_t *parse_default_statement(void)
9319 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9323 PUSH_PARENT(statement);
9325 expect(':', end_error);
9328 if (current_switch != NULL) {
9329 const case_label_statement_t *def_label = current_switch->default_label;
9330 if (def_label != NULL) {
9331 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9333 current_switch->default_label = &statement->case_label;
9335 /* link all cases into the switch statement */
9336 if (current_switch->last_case == NULL) {
9337 current_switch->first_case = &statement->case_label;
9339 current_switch->last_case->next = &statement->case_label;
9341 current_switch->last_case = &statement->case_label;
9344 errorf(&statement->base.source_position,
9345 "'default' label not within a switch statement");
9348 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9355 * Parse a label statement.
9357 static statement_t *parse_label_statement(void)
9359 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9360 label_t *const label = get_label();
9361 statement->label.label = label;
9363 PUSH_PARENT(statement);
9365 /* if statement is already set then the label is defined twice,
9366 * otherwise it was just mentioned in a goto/local label declaration so far
9368 source_position_t const* const pos = &statement->base.source_position;
9369 if (label->statement != NULL) {
9370 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9372 label->base.source_position = *pos;
9373 label->statement = statement;
9378 statement->label.statement = parse_label_inner_statement(statement, "label");
9380 /* remember the labels in a list for later checking */
9381 *label_anchor = &statement->label;
9382 label_anchor = &statement->label.next;
9389 * Parse an if statement.
9391 static statement_t *parse_if(void)
9393 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9397 PUSH_PARENT(statement);
9399 add_anchor_token('{');
9401 expect('(', end_error);
9402 add_anchor_token(')');
9403 expression_t *const expr = parse_expression();
9404 statement->ifs.condition = expr;
9405 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9407 semantic_condition(expr, "condition of 'if'-statment");
9408 mark_vars_read(expr, NULL);
9409 rem_anchor_token(')');
9410 expect(')', end_error);
9413 rem_anchor_token('{');
9415 add_anchor_token(T_else);
9416 statement_t *const true_stmt = parse_statement();
9417 statement->ifs.true_statement = true_stmt;
9418 rem_anchor_token(T_else);
9420 if (next_if(T_else)) {
9421 statement->ifs.false_statement = parse_statement();
9422 } else if (warning.parentheses &&
9423 true_stmt->kind == STATEMENT_IF &&
9424 true_stmt->ifs.false_statement != NULL) {
9425 warningf(&true_stmt->base.source_position,
9426 "suggest explicit braces to avoid ambiguous 'else'");
9434 * Check that all enums are handled in a switch.
9436 * @param statement the switch statement to check
9438 static void check_enum_cases(const switch_statement_t *statement)
9440 const type_t *type = skip_typeref(statement->expression->base.type);
9441 if (! is_type_enum(type))
9443 const enum_type_t *enumt = &type->enumt;
9445 /* if we have a default, no warnings */
9446 if (statement->default_label != NULL)
9449 /* FIXME: calculation of value should be done while parsing */
9450 /* TODO: quadratic algorithm here. Change to an n log n one */
9451 long last_value = -1;
9452 const entity_t *entry = enumt->enume->base.next;
9453 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9454 entry = entry->base.next) {
9455 const expression_t *expression = entry->enum_value.value;
9456 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9458 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9459 if (l->expression == NULL)
9461 if (l->first_case <= value && value <= l->last_case) {
9467 warningf(&statement->base.source_position, "'%N' not handled in switch", entry);
9474 * Parse a switch statement.
9476 static statement_t *parse_switch(void)
9478 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9482 PUSH_PARENT(statement);
9484 expect('(', end_error);
9485 add_anchor_token(')');
9486 expression_t *const expr = parse_expression();
9487 mark_vars_read(expr, NULL);
9488 type_t * type = skip_typeref(expr->base.type);
9489 if (is_type_integer(type)) {
9490 type = promote_integer(type);
9491 if (warning.traditional) {
9492 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9493 warningf(&expr->base.source_position,
9494 "'%T' switch expression not converted to '%T' in ISO C",
9498 } else if (is_type_valid(type)) {
9499 errorf(&expr->base.source_position,
9500 "switch quantity is not an integer, but '%T'", type);
9501 type = type_error_type;
9503 statement->switchs.expression = create_implicit_cast(expr, type);
9504 expect(')', end_error);
9505 rem_anchor_token(')');
9507 switch_statement_t *rem = current_switch;
9508 current_switch = &statement->switchs;
9509 statement->switchs.body = parse_statement();
9510 current_switch = rem;
9512 if (warning.switch_default &&
9513 statement->switchs.default_label == NULL) {
9514 warningf(&statement->base.source_position, "switch has no default case");
9516 if (warning.switch_enum)
9517 check_enum_cases(&statement->switchs);
9523 return create_invalid_statement();
9526 static statement_t *parse_loop_body(statement_t *const loop)
9528 statement_t *const rem = current_loop;
9529 current_loop = loop;
9531 statement_t *const body = parse_statement();
9538 * Parse a while statement.
9540 static statement_t *parse_while(void)
9542 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9546 PUSH_PARENT(statement);
9548 expect('(', end_error);
9549 add_anchor_token(')');
9550 expression_t *const cond = parse_expression();
9551 statement->whiles.condition = cond;
9552 /* §6.8.5:2 The controlling expression of an iteration statement shall
9553 * have scalar type. */
9554 semantic_condition(cond, "condition of 'while'-statement");
9555 mark_vars_read(cond, NULL);
9556 rem_anchor_token(')');
9557 expect(')', end_error);
9559 statement->whiles.body = parse_loop_body(statement);
9565 return create_invalid_statement();
9569 * Parse a do statement.
9571 static statement_t *parse_do(void)
9573 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9577 PUSH_PARENT(statement);
9579 add_anchor_token(T_while);
9580 statement->do_while.body = parse_loop_body(statement);
9581 rem_anchor_token(T_while);
9583 expect(T_while, end_error);
9584 expect('(', end_error);
9585 add_anchor_token(')');
9586 expression_t *const cond = parse_expression();
9587 statement->do_while.condition = cond;
9588 /* §6.8.5:2 The controlling expression of an iteration statement shall
9589 * have scalar type. */
9590 semantic_condition(cond, "condition of 'do-while'-statement");
9591 mark_vars_read(cond, NULL);
9592 rem_anchor_token(')');
9593 expect(')', end_error);
9594 expect(';', end_error);
9600 return create_invalid_statement();
9604 * Parse a for statement.
9606 static statement_t *parse_for(void)
9608 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9612 expect('(', end_error1);
9613 add_anchor_token(')');
9615 PUSH_PARENT(statement);
9617 size_t const top = environment_top();
9618 scope_t *old_scope = scope_push(&statement->fors.scope);
9620 bool old_gcc_extension = in_gcc_extension;
9621 while (next_if(T___extension__)) {
9622 in_gcc_extension = true;
9626 } else if (is_declaration_specifier(&token)) {
9627 parse_declaration(record_entity, DECL_FLAGS_NONE);
9629 add_anchor_token(';');
9630 expression_t *const init = parse_expression();
9631 statement->fors.initialisation = init;
9632 mark_vars_read(init, ENT_ANY);
9633 if (warning.unused_value && !expression_has_effect(init)) {
9634 warningf(&init->base.source_position,
9635 "initialisation of 'for'-statement has no effect");
9637 rem_anchor_token(';');
9638 expect(';', end_error2);
9640 in_gcc_extension = old_gcc_extension;
9642 if (token.type != ';') {
9643 add_anchor_token(';');
9644 expression_t *const cond = parse_expression();
9645 statement->fors.condition = cond;
9646 /* §6.8.5:2 The controlling expression of an iteration statement
9647 * shall have scalar type. */
9648 semantic_condition(cond, "condition of 'for'-statement");
9649 mark_vars_read(cond, NULL);
9650 rem_anchor_token(';');
9652 expect(';', end_error2);
9653 if (token.type != ')') {
9654 expression_t *const step = parse_expression();
9655 statement->fors.step = step;
9656 mark_vars_read(step, ENT_ANY);
9657 if (warning.unused_value && !expression_has_effect(step)) {
9658 warningf(&step->base.source_position,
9659 "step of 'for'-statement has no effect");
9662 expect(')', end_error2);
9663 rem_anchor_token(')');
9664 statement->fors.body = parse_loop_body(statement);
9666 assert(current_scope == &statement->fors.scope);
9667 scope_pop(old_scope);
9668 environment_pop_to(top);
9675 rem_anchor_token(')');
9676 assert(current_scope == &statement->fors.scope);
9677 scope_pop(old_scope);
9678 environment_pop_to(top);
9682 return create_invalid_statement();
9686 * Parse a goto statement.
9688 static statement_t *parse_goto(void)
9690 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9693 if (GNU_MODE && next_if('*')) {
9694 expression_t *expression = parse_expression();
9695 mark_vars_read(expression, NULL);
9697 /* Argh: although documentation says the expression must be of type void*,
9698 * gcc accepts anything that can be casted into void* without error */
9699 type_t *type = expression->base.type;
9701 if (type != type_error_type) {
9702 if (!is_type_pointer(type) && !is_type_integer(type)) {
9703 errorf(&expression->base.source_position,
9704 "cannot convert to a pointer type");
9705 } else if (warning.other && type != type_void_ptr) {
9706 warningf(&expression->base.source_position,
9707 "type of computed goto expression should be 'void*' not '%T'", type);
9709 expression = create_implicit_cast(expression, type_void_ptr);
9712 statement->gotos.expression = expression;
9713 } else if (token.type == T_IDENTIFIER) {
9714 label_t *const label = get_label();
9716 statement->gotos.label = label;
9719 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9721 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9723 return create_invalid_statement();
9726 /* remember the goto's in a list for later checking */
9727 *goto_anchor = &statement->gotos;
9728 goto_anchor = &statement->gotos.next;
9730 expect(';', end_error);
9737 * Parse a continue statement.
9739 static statement_t *parse_continue(void)
9741 if (current_loop == NULL) {
9742 errorf(HERE, "continue statement not within loop");
9745 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9748 expect(';', end_error);
9755 * Parse a break statement.
9757 static statement_t *parse_break(void)
9759 if (current_switch == NULL && current_loop == NULL) {
9760 errorf(HERE, "break statement not within loop or switch");
9763 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9766 expect(';', end_error);
9773 * Parse a __leave statement.
9775 static statement_t *parse_leave_statement(void)
9777 if (current_try == NULL) {
9778 errorf(HERE, "__leave statement not within __try");
9781 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9784 expect(';', end_error);
9791 * Check if a given entity represents a local variable.
9793 static bool is_local_variable(const entity_t *entity)
9795 if (entity->kind != ENTITY_VARIABLE)
9798 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9799 case STORAGE_CLASS_AUTO:
9800 case STORAGE_CLASS_REGISTER: {
9801 const type_t *type = skip_typeref(entity->declaration.type);
9802 if (is_type_function(type)) {
9814 * Check if a given expression represents a local variable.
9816 static bool expression_is_local_variable(const expression_t *expression)
9818 if (expression->base.kind != EXPR_REFERENCE) {
9821 const entity_t *entity = expression->reference.entity;
9822 return is_local_variable(entity);
9826 * Check if a given expression represents a local variable and
9827 * return its declaration then, else return NULL.
9829 entity_t *expression_is_variable(const expression_t *expression)
9831 if (expression->base.kind != EXPR_REFERENCE) {
9834 entity_t *entity = expression->reference.entity;
9835 if (entity->kind != ENTITY_VARIABLE)
9842 * Parse a return statement.
9844 static statement_t *parse_return(void)
9848 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9850 expression_t *return_value = NULL;
9851 if (token.type != ';') {
9852 return_value = parse_expression();
9853 mark_vars_read(return_value, NULL);
9856 const type_t *const func_type = skip_typeref(current_function->base.type);
9857 assert(is_type_function(func_type));
9858 type_t *const return_type = skip_typeref(func_type->function.return_type);
9860 source_position_t const *const pos = &statement->base.source_position;
9861 if (return_value != NULL) {
9862 type_t *return_value_type = skip_typeref(return_value->base.type);
9864 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9865 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9866 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9867 /* Only warn in C mode, because GCC does the same */
9868 if (c_mode & _CXX || strict_mode) {
9870 "'return' with a value, in function returning 'void'");
9871 } else if (warning.other) {
9873 "'return' with a value, in function returning 'void'");
9875 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9876 /* Only warn in C mode, because GCC does the same */
9879 "'return' with expression in function returning 'void'");
9880 } else if (warning.other) {
9882 "'return' with expression in function returning 'void'");
9886 assign_error_t error = semantic_assign(return_type, return_value);
9887 report_assign_error(error, return_type, return_value, "'return'",
9890 return_value = create_implicit_cast(return_value, return_type);
9891 /* check for returning address of a local var */
9892 if (warning.other && return_value != NULL
9893 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9894 const expression_t *expression = return_value->unary.value;
9895 if (expression_is_local_variable(expression)) {
9896 warningf(pos, "function returns address of local variable");
9899 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9900 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9901 if (c_mode & _CXX || strict_mode) {
9903 "'return' without value, in function returning non-void");
9906 "'return' without value, in function returning non-void");
9909 statement->returns.value = return_value;
9911 expect(';', end_error);
9918 * Parse a declaration statement.
9920 static statement_t *parse_declaration_statement(void)
9922 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9924 entity_t *before = current_scope->last_entity;
9926 parse_external_declaration();
9928 parse_declaration(record_entity, DECL_FLAGS_NONE);
9931 declaration_statement_t *const decl = &statement->declaration;
9932 entity_t *const begin =
9933 before != NULL ? before->base.next : current_scope->entities;
9934 decl->declarations_begin = begin;
9935 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9941 * Parse an expression statement, ie. expr ';'.
9943 static statement_t *parse_expression_statement(void)
9945 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9947 expression_t *const expr = parse_expression();
9948 statement->expression.expression = expr;
9949 mark_vars_read(expr, ENT_ANY);
9951 expect(';', end_error);
9958 * Parse a microsoft __try { } __finally { } or
9959 * __try{ } __except() { }
9961 static statement_t *parse_ms_try_statment(void)
9963 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9966 PUSH_PARENT(statement);
9968 ms_try_statement_t *rem = current_try;
9969 current_try = &statement->ms_try;
9970 statement->ms_try.try_statement = parse_compound_statement(false);
9975 if (next_if(T___except)) {
9976 expect('(', end_error);
9977 add_anchor_token(')');
9978 expression_t *const expr = parse_expression();
9979 mark_vars_read(expr, NULL);
9980 type_t * type = skip_typeref(expr->base.type);
9981 if (is_type_integer(type)) {
9982 type = promote_integer(type);
9983 } else if (is_type_valid(type)) {
9984 errorf(&expr->base.source_position,
9985 "__expect expression is not an integer, but '%T'", type);
9986 type = type_error_type;
9988 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9989 rem_anchor_token(')');
9990 expect(')', end_error);
9991 statement->ms_try.final_statement = parse_compound_statement(false);
9992 } else if (next_if(T__finally)) {
9993 statement->ms_try.final_statement = parse_compound_statement(false);
9995 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9996 return create_invalid_statement();
10000 return create_invalid_statement();
10003 static statement_t *parse_empty_statement(void)
10005 if (warning.empty_statement) {
10006 warningf(HERE, "statement is empty");
10008 statement_t *const statement = create_empty_statement();
10013 static statement_t *parse_local_label_declaration(void)
10015 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10019 entity_t *begin = NULL;
10020 entity_t *end = NULL;
10021 entity_t **anchor = &begin;
10023 if (token.type != T_IDENTIFIER) {
10024 parse_error_expected("while parsing local label declaration",
10025 T_IDENTIFIER, NULL);
10028 symbol_t *symbol = token.symbol;
10029 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10030 if (entity != NULL && entity->base.parent_scope == current_scope) {
10031 source_position_t const *const ppos = &entity->base.source_position;
10032 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
10034 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
10035 entity->base.parent_scope = current_scope;
10036 entity->base.source_position = token.source_position;
10039 anchor = &entity->base.next;
10042 environment_push(entity);
10045 } while (next_if(','));
10046 expect(';', end_error);
10048 statement->declaration.declarations_begin = begin;
10049 statement->declaration.declarations_end = end;
10053 static void parse_namespace_definition(void)
10057 entity_t *entity = NULL;
10058 symbol_t *symbol = NULL;
10060 if (token.type == T_IDENTIFIER) {
10061 symbol = token.symbol;
10064 entity = get_entity(symbol, NAMESPACE_NORMAL);
10066 && entity->kind != ENTITY_NAMESPACE
10067 && entity->base.parent_scope == current_scope) {
10068 if (is_entity_valid(entity)) {
10069 error_redefined_as_different_kind(&token.source_position,
10070 entity, ENTITY_NAMESPACE);
10076 if (entity == NULL) {
10077 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
10078 entity->base.source_position = token.source_position;
10079 entity->base.parent_scope = current_scope;
10082 if (token.type == '=') {
10083 /* TODO: parse namespace alias */
10084 panic("namespace alias definition not supported yet");
10087 environment_push(entity);
10088 append_entity(current_scope, entity);
10090 size_t const top = environment_top();
10091 scope_t *old_scope = scope_push(&entity->namespacee.members);
10093 entity_t *old_current_entity = current_entity;
10094 current_entity = entity;
10096 expect('{', end_error);
10098 expect('}', end_error);
10101 assert(current_scope == &entity->namespacee.members);
10102 assert(current_entity == entity);
10103 current_entity = old_current_entity;
10104 scope_pop(old_scope);
10105 environment_pop_to(top);
10109 * Parse a statement.
10110 * There's also parse_statement() which additionally checks for
10111 * "statement has no effect" warnings
10113 static statement_t *intern_parse_statement(void)
10115 statement_t *statement = NULL;
10117 /* declaration or statement */
10118 add_anchor_token(';');
10119 switch (token.type) {
10120 case T_IDENTIFIER: {
10121 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10122 if (la1_type == ':') {
10123 statement = parse_label_statement();
10124 } else if (is_typedef_symbol(token.symbol)) {
10125 statement = parse_declaration_statement();
10127 /* it's an identifier, the grammar says this must be an
10128 * expression statement. However it is common that users mistype
10129 * declaration types, so we guess a bit here to improve robustness
10130 * for incorrect programs */
10131 switch (la1_type) {
10134 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10136 statement = parse_expression_statement();
10140 statement = parse_declaration_statement();
10148 case T___extension__:
10149 /* This can be a prefix to a declaration or an expression statement.
10150 * We simply eat it now and parse the rest with tail recursion. */
10151 while (next_if(T___extension__)) {}
10152 bool old_gcc_extension = in_gcc_extension;
10153 in_gcc_extension = true;
10154 statement = intern_parse_statement();
10155 in_gcc_extension = old_gcc_extension;
10159 statement = parse_declaration_statement();
10163 statement = parse_local_label_declaration();
10166 case ';': statement = parse_empty_statement(); break;
10167 case '{': statement = parse_compound_statement(false); break;
10168 case T___leave: statement = parse_leave_statement(); break;
10169 case T___try: statement = parse_ms_try_statment(); break;
10170 case T_asm: statement = parse_asm_statement(); break;
10171 case T_break: statement = parse_break(); break;
10172 case T_case: statement = parse_case_statement(); break;
10173 case T_continue: statement = parse_continue(); break;
10174 case T_default: statement = parse_default_statement(); break;
10175 case T_do: statement = parse_do(); break;
10176 case T_for: statement = parse_for(); break;
10177 case T_goto: statement = parse_goto(); break;
10178 case T_if: statement = parse_if(); break;
10179 case T_return: statement = parse_return(); break;
10180 case T_switch: statement = parse_switch(); break;
10181 case T_while: statement = parse_while(); break;
10184 statement = parse_expression_statement();
10188 errorf(HERE, "unexpected token %K while parsing statement", &token);
10189 statement = create_invalid_statement();
10194 rem_anchor_token(';');
10196 assert(statement != NULL
10197 && statement->base.source_position.input_name != NULL);
10203 * parse a statement and emits "statement has no effect" warning if needed
10204 * (This is really a wrapper around intern_parse_statement with check for 1
10205 * single warning. It is needed, because for statement expressions we have
10206 * to avoid the warning on the last statement)
10208 static statement_t *parse_statement(void)
10210 statement_t *statement = intern_parse_statement();
10212 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10213 expression_t *expression = statement->expression.expression;
10214 if (!expression_has_effect(expression)) {
10215 warningf(&expression->base.source_position,
10216 "statement has no effect");
10224 * Parse a compound statement.
10226 static statement_t *parse_compound_statement(bool inside_expression_statement)
10228 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10230 PUSH_PARENT(statement);
10233 add_anchor_token('}');
10234 /* tokens, which can start a statement */
10235 /* TODO MS, __builtin_FOO */
10236 add_anchor_token('!');
10237 add_anchor_token('&');
10238 add_anchor_token('(');
10239 add_anchor_token('*');
10240 add_anchor_token('+');
10241 add_anchor_token('-');
10242 add_anchor_token('{');
10243 add_anchor_token('~');
10244 add_anchor_token(T_CHARACTER_CONSTANT);
10245 add_anchor_token(T_COLONCOLON);
10246 add_anchor_token(T_FLOATINGPOINT);
10247 add_anchor_token(T_IDENTIFIER);
10248 add_anchor_token(T_INTEGER);
10249 add_anchor_token(T_MINUSMINUS);
10250 add_anchor_token(T_PLUSPLUS);
10251 add_anchor_token(T_STRING_LITERAL);
10252 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10253 add_anchor_token(T_WIDE_STRING_LITERAL);
10254 add_anchor_token(T__Bool);
10255 add_anchor_token(T__Complex);
10256 add_anchor_token(T__Imaginary);
10257 add_anchor_token(T___FUNCTION__);
10258 add_anchor_token(T___PRETTY_FUNCTION__);
10259 add_anchor_token(T___alignof__);
10260 add_anchor_token(T___attribute__);
10261 add_anchor_token(T___builtin_va_start);
10262 add_anchor_token(T___extension__);
10263 add_anchor_token(T___func__);
10264 add_anchor_token(T___imag__);
10265 add_anchor_token(T___label__);
10266 add_anchor_token(T___real__);
10267 add_anchor_token(T___thread);
10268 add_anchor_token(T_asm);
10269 add_anchor_token(T_auto);
10270 add_anchor_token(T_bool);
10271 add_anchor_token(T_break);
10272 add_anchor_token(T_case);
10273 add_anchor_token(T_char);
10274 add_anchor_token(T_class);
10275 add_anchor_token(T_const);
10276 add_anchor_token(T_const_cast);
10277 add_anchor_token(T_continue);
10278 add_anchor_token(T_default);
10279 add_anchor_token(T_delete);
10280 add_anchor_token(T_double);
10281 add_anchor_token(T_do);
10282 add_anchor_token(T_dynamic_cast);
10283 add_anchor_token(T_enum);
10284 add_anchor_token(T_extern);
10285 add_anchor_token(T_false);
10286 add_anchor_token(T_float);
10287 add_anchor_token(T_for);
10288 add_anchor_token(T_goto);
10289 add_anchor_token(T_if);
10290 add_anchor_token(T_inline);
10291 add_anchor_token(T_int);
10292 add_anchor_token(T_long);
10293 add_anchor_token(T_new);
10294 add_anchor_token(T_operator);
10295 add_anchor_token(T_register);
10296 add_anchor_token(T_reinterpret_cast);
10297 add_anchor_token(T_restrict);
10298 add_anchor_token(T_return);
10299 add_anchor_token(T_short);
10300 add_anchor_token(T_signed);
10301 add_anchor_token(T_sizeof);
10302 add_anchor_token(T_static);
10303 add_anchor_token(T_static_cast);
10304 add_anchor_token(T_struct);
10305 add_anchor_token(T_switch);
10306 add_anchor_token(T_template);
10307 add_anchor_token(T_this);
10308 add_anchor_token(T_throw);
10309 add_anchor_token(T_true);
10310 add_anchor_token(T_try);
10311 add_anchor_token(T_typedef);
10312 add_anchor_token(T_typeid);
10313 add_anchor_token(T_typename);
10314 add_anchor_token(T_typeof);
10315 add_anchor_token(T_union);
10316 add_anchor_token(T_unsigned);
10317 add_anchor_token(T_using);
10318 add_anchor_token(T_void);
10319 add_anchor_token(T_volatile);
10320 add_anchor_token(T_wchar_t);
10321 add_anchor_token(T_while);
10323 size_t const top = environment_top();
10324 scope_t *old_scope = scope_push(&statement->compound.scope);
10326 statement_t **anchor = &statement->compound.statements;
10327 bool only_decls_so_far = true;
10328 while (token.type != '}') {
10329 if (token.type == T_EOF) {
10330 errorf(&statement->base.source_position,
10331 "EOF while parsing compound statement");
10334 statement_t *sub_statement = intern_parse_statement();
10335 if (is_invalid_statement(sub_statement)) {
10336 /* an error occurred. if we are at an anchor, return */
10342 if (warning.declaration_after_statement) {
10343 if (sub_statement->kind != STATEMENT_DECLARATION) {
10344 only_decls_so_far = false;
10345 } else if (!only_decls_so_far) {
10346 warningf(&sub_statement->base.source_position,
10347 "ISO C90 forbids mixed declarations and code");
10351 *anchor = sub_statement;
10353 while (sub_statement->base.next != NULL)
10354 sub_statement = sub_statement->base.next;
10356 anchor = &sub_statement->base.next;
10360 /* look over all statements again to produce no effect warnings */
10361 if (warning.unused_value) {
10362 statement_t *sub_statement = statement->compound.statements;
10363 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10364 if (sub_statement->kind != STATEMENT_EXPRESSION)
10366 /* don't emit a warning for the last expression in an expression
10367 * statement as it has always an effect */
10368 if (inside_expression_statement && sub_statement->base.next == NULL)
10371 expression_t *expression = sub_statement->expression.expression;
10372 if (!expression_has_effect(expression)) {
10373 warningf(&expression->base.source_position,
10374 "statement has no effect");
10380 rem_anchor_token(T_while);
10381 rem_anchor_token(T_wchar_t);
10382 rem_anchor_token(T_volatile);
10383 rem_anchor_token(T_void);
10384 rem_anchor_token(T_using);
10385 rem_anchor_token(T_unsigned);
10386 rem_anchor_token(T_union);
10387 rem_anchor_token(T_typeof);
10388 rem_anchor_token(T_typename);
10389 rem_anchor_token(T_typeid);
10390 rem_anchor_token(T_typedef);
10391 rem_anchor_token(T_try);
10392 rem_anchor_token(T_true);
10393 rem_anchor_token(T_throw);
10394 rem_anchor_token(T_this);
10395 rem_anchor_token(T_template);
10396 rem_anchor_token(T_switch);
10397 rem_anchor_token(T_struct);
10398 rem_anchor_token(T_static_cast);
10399 rem_anchor_token(T_static);
10400 rem_anchor_token(T_sizeof);
10401 rem_anchor_token(T_signed);
10402 rem_anchor_token(T_short);
10403 rem_anchor_token(T_return);
10404 rem_anchor_token(T_restrict);
10405 rem_anchor_token(T_reinterpret_cast);
10406 rem_anchor_token(T_register);
10407 rem_anchor_token(T_operator);
10408 rem_anchor_token(T_new);
10409 rem_anchor_token(T_long);
10410 rem_anchor_token(T_int);
10411 rem_anchor_token(T_inline);
10412 rem_anchor_token(T_if);
10413 rem_anchor_token(T_goto);
10414 rem_anchor_token(T_for);
10415 rem_anchor_token(T_float);
10416 rem_anchor_token(T_false);
10417 rem_anchor_token(T_extern);
10418 rem_anchor_token(T_enum);
10419 rem_anchor_token(T_dynamic_cast);
10420 rem_anchor_token(T_do);
10421 rem_anchor_token(T_double);
10422 rem_anchor_token(T_delete);
10423 rem_anchor_token(T_default);
10424 rem_anchor_token(T_continue);
10425 rem_anchor_token(T_const_cast);
10426 rem_anchor_token(T_const);
10427 rem_anchor_token(T_class);
10428 rem_anchor_token(T_char);
10429 rem_anchor_token(T_case);
10430 rem_anchor_token(T_break);
10431 rem_anchor_token(T_bool);
10432 rem_anchor_token(T_auto);
10433 rem_anchor_token(T_asm);
10434 rem_anchor_token(T___thread);
10435 rem_anchor_token(T___real__);
10436 rem_anchor_token(T___label__);
10437 rem_anchor_token(T___imag__);
10438 rem_anchor_token(T___func__);
10439 rem_anchor_token(T___extension__);
10440 rem_anchor_token(T___builtin_va_start);
10441 rem_anchor_token(T___attribute__);
10442 rem_anchor_token(T___alignof__);
10443 rem_anchor_token(T___PRETTY_FUNCTION__);
10444 rem_anchor_token(T___FUNCTION__);
10445 rem_anchor_token(T__Imaginary);
10446 rem_anchor_token(T__Complex);
10447 rem_anchor_token(T__Bool);
10448 rem_anchor_token(T_WIDE_STRING_LITERAL);
10449 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10450 rem_anchor_token(T_STRING_LITERAL);
10451 rem_anchor_token(T_PLUSPLUS);
10452 rem_anchor_token(T_MINUSMINUS);
10453 rem_anchor_token(T_INTEGER);
10454 rem_anchor_token(T_IDENTIFIER);
10455 rem_anchor_token(T_FLOATINGPOINT);
10456 rem_anchor_token(T_COLONCOLON);
10457 rem_anchor_token(T_CHARACTER_CONSTANT);
10458 rem_anchor_token('~');
10459 rem_anchor_token('{');
10460 rem_anchor_token('-');
10461 rem_anchor_token('+');
10462 rem_anchor_token('*');
10463 rem_anchor_token('(');
10464 rem_anchor_token('&');
10465 rem_anchor_token('!');
10466 rem_anchor_token('}');
10467 assert(current_scope == &statement->compound.scope);
10468 scope_pop(old_scope);
10469 environment_pop_to(top);
10476 * Check for unused global static functions and variables
10478 static void check_unused_globals(void)
10480 if (!warning.unused_function && !warning.unused_variable)
10483 for (const entity_t *entity = file_scope->entities; entity != NULL;
10484 entity = entity->base.next) {
10485 if (!is_declaration(entity))
10488 const declaration_t *declaration = &entity->declaration;
10489 if (declaration->used ||
10490 declaration->modifiers & DM_UNUSED ||
10491 declaration->modifiers & DM_USED ||
10492 declaration->storage_class != STORAGE_CLASS_STATIC)
10496 if (entity->kind == ENTITY_FUNCTION) {
10497 /* inhibit warning for static inline functions */
10498 if (entity->function.is_inline)
10501 s = entity->function.statement != NULL ? "defined" : "declared";
10506 warningf(&declaration->base.source_position, "'%#N' %s but not used", entity);
10510 static void parse_global_asm(void)
10512 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10515 expect('(', end_error);
10517 statement->asms.asm_text = parse_string_literals();
10518 statement->base.next = unit->global_asm;
10519 unit->global_asm = statement;
10521 expect(')', end_error);
10522 expect(';', end_error);
10527 static void parse_linkage_specification(void)
10531 source_position_t const pos = *HERE;
10532 char const *const linkage = parse_string_literals().begin;
10534 linkage_kind_t old_linkage = current_linkage;
10535 linkage_kind_t new_linkage;
10536 if (strcmp(linkage, "C") == 0) {
10537 new_linkage = LINKAGE_C;
10538 } else if (strcmp(linkage, "C++") == 0) {
10539 new_linkage = LINKAGE_CXX;
10541 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10542 new_linkage = LINKAGE_INVALID;
10544 current_linkage = new_linkage;
10546 if (next_if('{')) {
10548 expect('}', end_error);
10554 assert(current_linkage == new_linkage);
10555 current_linkage = old_linkage;
10558 static void parse_external(void)
10560 switch (token.type) {
10561 DECLARATION_START_NO_EXTERN
10563 case T___extension__:
10564 /* tokens below are for implicit int */
10565 case '&': /* & x; -> int& x; (and error later, because C++ has no
10567 case '*': /* * x; -> int* x; */
10568 case '(': /* (x); -> int (x); */
10569 parse_external_declaration();
10573 if (look_ahead(1)->type == T_STRING_LITERAL) {
10574 parse_linkage_specification();
10576 parse_external_declaration();
10581 parse_global_asm();
10585 parse_namespace_definition();
10589 if (!strict_mode) {
10591 warningf(HERE, "stray ';' outside of function");
10598 errorf(HERE, "stray %K outside of function", &token);
10599 if (token.type == '(' || token.type == '{' || token.type == '[')
10600 eat_until_matching_token(token.type);
10606 static void parse_externals(void)
10608 add_anchor_token('}');
10609 add_anchor_token(T_EOF);
10612 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10613 unsigned char token_anchor_copy[T_LAST_TOKEN];
10614 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10617 while (token.type != T_EOF && token.type != '}') {
10619 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10620 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10622 /* the anchor set and its copy differs */
10623 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10626 if (in_gcc_extension) {
10627 /* an gcc extension scope was not closed */
10628 internal_errorf(HERE, "Leaked __extension__");
10635 rem_anchor_token(T_EOF);
10636 rem_anchor_token('}');
10640 * Parse a translation unit.
10642 static void parse_translation_unit(void)
10644 add_anchor_token(T_EOF);
10649 if (token.type == T_EOF)
10652 errorf(HERE, "stray %K outside of function", &token);
10653 if (token.type == '(' || token.type == '{' || token.type == '[')
10654 eat_until_matching_token(token.type);
10659 void set_default_visibility(elf_visibility_tag_t visibility)
10661 default_visibility = visibility;
10667 * @return the translation unit or NULL if errors occurred.
10669 void start_parsing(void)
10671 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10672 label_stack = NEW_ARR_F(stack_entry_t, 0);
10673 diagnostic_count = 0;
10677 print_to_file(stderr);
10679 assert(unit == NULL);
10680 unit = allocate_ast_zero(sizeof(unit[0]));
10682 assert(file_scope == NULL);
10683 file_scope = &unit->scope;
10685 assert(current_scope == NULL);
10686 scope_push(&unit->scope);
10688 create_gnu_builtins();
10690 create_microsoft_intrinsics();
10693 translation_unit_t *finish_parsing(void)
10695 assert(current_scope == &unit->scope);
10698 assert(file_scope == &unit->scope);
10699 check_unused_globals();
10702 DEL_ARR_F(environment_stack);
10703 DEL_ARR_F(label_stack);
10705 translation_unit_t *result = unit;
10710 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10711 * are given length one. */
10712 static void complete_incomplete_arrays(void)
10714 size_t n = ARR_LEN(incomplete_arrays);
10715 for (size_t i = 0; i != n; ++i) {
10716 declaration_t *const decl = incomplete_arrays[i];
10717 type_t *const type = skip_typeref(decl->type);
10719 if (!is_type_incomplete(type))
10722 if (warning.other) {
10723 source_position_t const *const pos = &decl->base.source_position;
10724 warningf(pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10727 type_t *const new_type = duplicate_type(type);
10728 new_type->array.size_constant = true;
10729 new_type->array.has_implicit_size = true;
10730 new_type->array.size = 1;
10732 type_t *const result = identify_new_type(new_type);
10734 decl->type = result;
10738 void prepare_main_collect2(entity_t *entity)
10740 // create call to __main
10741 symbol_t *symbol = symbol_table_insert("__main");
10742 entity_t *subsubmain_ent
10743 = create_implicit_function(symbol, &builtin_source_position);
10745 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10746 type_t *ftype = subsubmain_ent->declaration.type;
10747 ref->base.source_position = builtin_source_position;
10748 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10749 ref->reference.entity = subsubmain_ent;
10751 expression_t *call = allocate_expression_zero(EXPR_CALL);
10752 call->base.source_position = builtin_source_position;
10753 call->base.type = type_void;
10754 call->call.function = ref;
10756 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10757 expr_statement->base.source_position = builtin_source_position;
10758 expr_statement->expression.expression = call;
10760 statement_t *statement = entity->function.statement;
10761 assert(statement->kind == STATEMENT_COMPOUND);
10762 compound_statement_t *compounds = &statement->compound;
10764 expr_statement->base.next = compounds->statements;
10765 compounds->statements = expr_statement;
10770 lookahead_bufpos = 0;
10771 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10774 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10775 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10776 parse_translation_unit();
10777 complete_incomplete_arrays();
10778 DEL_ARR_F(incomplete_arrays);
10779 incomplete_arrays = NULL;
10783 * Initialize the parser.
10785 void init_parser(void)
10787 sym_anonymous = symbol_table_insert("<anonymous>");
10789 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10791 init_expression_parsers();
10792 obstack_init(&temp_obst);
10796 * Terminate the parser.
10798 void exit_parser(void)
10800 obstack_free(&temp_obst, NULL);