2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_PARENT(stmt) \
113 statement_t *const new_parent = (stmt); \
114 statement_t *const old_parent = current_parent; \
115 ((void)(current_parent = new_parent))
116 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
118 #define PUSH_SCOPE(scope) \
119 size_t const top = environment_top(); \
120 scope_t *const new_scope = (scope); \
121 scope_t *const old_scope = scope_push(new_scope)
122 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
124 #define PUSH_EXTENSION() \
126 bool const old_gcc_extension = in_gcc_extension; \
127 while (next_if(T___extension__)) { \
128 in_gcc_extension = true; \
131 #define POP_EXTENSION() \
132 ((void)(in_gcc_extension = old_gcc_extension))
134 /** special symbol used for anonymous entities. */
135 static symbol_t *sym_anonymous = NULL;
137 /** The token anchor set */
138 static unsigned short token_anchor_set[T_LAST_TOKEN];
140 /** The current source position. */
141 #define HERE (&token.base.source_position)
143 /** true if we are in GCC mode. */
144 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
146 static statement_t *parse_compound_statement(bool inside_expression_statement);
147 static statement_t *parse_statement(void);
149 static expression_t *parse_subexpression(precedence_t);
150 static expression_t *parse_expression(void);
151 static type_t *parse_typename(void);
152 static void parse_externals(void);
153 static void parse_external(void);
155 static void parse_compound_type_entries(compound_t *compound_declaration);
157 static void check_call_argument(type_t *expected_type,
158 call_argument_t *argument, unsigned pos);
160 typedef enum declarator_flags_t {
162 DECL_MAY_BE_ABSTRACT = 1U << 0,
163 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
164 DECL_IS_PARAMETER = 1U << 2
165 } declarator_flags_t;
167 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
168 declarator_flags_t flags);
170 static void semantic_comparison(binary_expression_t *expression);
172 #define STORAGE_CLASSES \
173 STORAGE_CLASSES_NO_EXTERN \
176 #define STORAGE_CLASSES_NO_EXTERN \
183 #define TYPE_QUALIFIERS \
188 case T__forceinline: \
189 case T___attribute__:
191 #define COMPLEX_SPECIFIERS \
193 #define IMAGINARY_SPECIFIERS \
196 #define TYPE_SPECIFIERS \
198 case T___builtin_va_list: \
223 #define DECLARATION_START \
228 #define DECLARATION_START_NO_EXTERN \
229 STORAGE_CLASSES_NO_EXTERN \
233 #define EXPRESSION_START \
242 case T_CHARACTER_CONSTANT: \
243 case T_FLOATINGPOINT: \
244 case T_FLOATINGPOINT_HEXADECIMAL: \
246 case T_INTEGER_HEXADECIMAL: \
247 case T_INTEGER_OCTAL: \
250 case T_STRING_LITERAL: \
251 case T_WIDE_CHARACTER_CONSTANT: \
252 case T_WIDE_STRING_LITERAL: \
253 case T___FUNCDNAME__: \
254 case T___FUNCSIG__: \
255 case T___FUNCTION__: \
256 case T___PRETTY_FUNCTION__: \
257 case T___alignof__: \
258 case T___builtin_classify_type: \
259 case T___builtin_constant_p: \
260 case T___builtin_isgreater: \
261 case T___builtin_isgreaterequal: \
262 case T___builtin_isless: \
263 case T___builtin_islessequal: \
264 case T___builtin_islessgreater: \
265 case T___builtin_isunordered: \
266 case T___builtin_offsetof: \
267 case T___builtin_va_arg: \
268 case T___builtin_va_copy: \
269 case T___builtin_va_start: \
280 * Returns the size of a statement node.
282 * @param kind the statement kind
284 static size_t get_statement_struct_size(statement_kind_t kind)
286 static const size_t sizes[] = {
287 [STATEMENT_ERROR] = sizeof(statement_base_t),
288 [STATEMENT_EMPTY] = sizeof(statement_base_t),
289 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
290 [STATEMENT_RETURN] = sizeof(return_statement_t),
291 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
292 [STATEMENT_IF] = sizeof(if_statement_t),
293 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
294 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
295 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
296 [STATEMENT_BREAK] = sizeof(statement_base_t),
297 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
298 [STATEMENT_GOTO] = sizeof(goto_statement_t),
299 [STATEMENT_LABEL] = sizeof(label_statement_t),
300 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
301 [STATEMENT_WHILE] = sizeof(while_statement_t),
302 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
303 [STATEMENT_FOR] = sizeof(for_statement_t),
304 [STATEMENT_ASM] = sizeof(asm_statement_t),
305 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
306 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
308 assert((size_t)kind < lengthof(sizes));
309 assert(sizes[kind] != 0);
314 * Returns the size of an expression node.
316 * @param kind the expression kind
318 static size_t get_expression_struct_size(expression_kind_t kind)
320 static const size_t sizes[] = {
321 [EXPR_ERROR] = sizeof(expression_base_t),
322 [EXPR_REFERENCE] = sizeof(reference_expression_t),
323 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
324 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
328 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
332 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
333 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
334 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
335 [EXPR_CALL] = sizeof(call_expression_t),
336 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
337 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
338 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
339 [EXPR_SELECT] = sizeof(select_expression_t),
340 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
341 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
342 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
343 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
344 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
345 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
346 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
347 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
348 [EXPR_VA_START] = sizeof(va_start_expression_t),
349 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
350 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
351 [EXPR_STATEMENT] = sizeof(statement_expression_t),
352 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
354 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
355 return sizes[EXPR_UNARY_FIRST];
357 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
358 return sizes[EXPR_BINARY_FIRST];
360 assert((size_t)kind < lengthof(sizes));
361 assert(sizes[kind] != 0);
366 * Allocate a statement node of given kind and initialize all
367 * fields with zero. Sets its source position to the position
368 * of the current token.
370 static statement_t *allocate_statement_zero(statement_kind_t kind)
372 size_t size = get_statement_struct_size(kind);
373 statement_t *res = allocate_ast_zero(size);
375 res->base.kind = kind;
376 res->base.parent = current_parent;
377 res->base.source_position = token.base.source_position;
382 * Allocate an expression node of given kind and initialize all
385 * @param kind the kind of the expression to allocate
387 static expression_t *allocate_expression_zero(expression_kind_t kind)
389 size_t size = get_expression_struct_size(kind);
390 expression_t *res = allocate_ast_zero(size);
392 res->base.kind = kind;
393 res->base.type = type_error_type;
394 res->base.source_position = token.base.source_position;
399 * Creates a new invalid expression at the source position
400 * of the current token.
402 static expression_t *create_error_expression(void)
404 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
405 expression->base.type = type_error_type;
410 * Creates a new invalid statement.
412 static statement_t *create_error_statement(void)
414 return allocate_statement_zero(STATEMENT_ERROR);
418 * Allocate a new empty statement.
420 static statement_t *create_empty_statement(void)
422 return allocate_statement_zero(STATEMENT_EMPTY);
426 * Returns the size of an initializer node.
428 * @param kind the initializer kind
430 static size_t get_initializer_size(initializer_kind_t kind)
432 static const size_t sizes[] = {
433 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
434 [INITIALIZER_STRING] = sizeof(initializer_string_t),
435 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
436 [INITIALIZER_LIST] = sizeof(initializer_list_t),
437 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
439 assert((size_t)kind < lengthof(sizes));
440 assert(sizes[kind] != 0);
445 * Allocate an initializer node of given kind and initialize all
448 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
450 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
457 * Returns the index of the top element of the environment stack.
459 static size_t environment_top(void)
461 return ARR_LEN(environment_stack);
465 * Returns the index of the top element of the global label stack.
467 static size_t label_top(void)
469 return ARR_LEN(label_stack);
473 * Return the next token.
475 static inline void next_token(void)
477 token = lookahead_buffer[lookahead_bufpos];
478 lookahead_buffer[lookahead_bufpos] = lexer_token;
481 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
484 print_token(stderr, &token);
485 fprintf(stderr, "\n");
489 static inline bool next_if(int const type)
491 if (token.kind == type) {
500 * Return the next token with a given lookahead.
502 static inline const token_t *look_ahead(size_t num)
504 assert(0 < num && num <= MAX_LOOKAHEAD);
505 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
506 return &lookahead_buffer[pos];
510 * Adds a token type to the token type anchor set (a multi-set).
512 static void add_anchor_token(int token_kind)
514 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
515 ++token_anchor_set[token_kind];
519 * Set the number of tokens types of the given type
520 * to zero and return the old count.
522 static int save_and_reset_anchor_state(int token_kind)
524 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
525 int count = token_anchor_set[token_kind];
526 token_anchor_set[token_kind] = 0;
531 * Restore the number of token types to the given count.
533 static void restore_anchor_state(int token_kind, int count)
535 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
536 token_anchor_set[token_kind] = count;
540 * Remove a token type from the token type anchor set (a multi-set).
542 static void rem_anchor_token(int token_kind)
544 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
545 assert(token_anchor_set[token_kind] != 0);
546 --token_anchor_set[token_kind];
550 * Eat tokens until a matching token type is found.
552 static void eat_until_matching_token(int type)
556 case '(': end_token = ')'; break;
557 case '{': end_token = '}'; break;
558 case '[': end_token = ']'; break;
559 default: end_token = type; break;
562 unsigned parenthesis_count = 0;
563 unsigned brace_count = 0;
564 unsigned bracket_count = 0;
565 while (token.kind != end_token ||
566 parenthesis_count != 0 ||
568 bracket_count != 0) {
569 switch (token.kind) {
571 case '(': ++parenthesis_count; break;
572 case '{': ++brace_count; break;
573 case '[': ++bracket_count; break;
576 if (parenthesis_count > 0)
586 if (bracket_count > 0)
589 if (token.kind == end_token &&
590 parenthesis_count == 0 &&
604 * Eat input tokens until an anchor is found.
606 static void eat_until_anchor(void)
608 while (token_anchor_set[token.kind] == 0) {
609 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
610 eat_until_matching_token(token.kind);
616 * Eat a whole block from input tokens.
618 static void eat_block(void)
620 eat_until_matching_token('{');
624 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
627 * Report a parse error because an expected token was not found.
630 #if defined __GNUC__ && __GNUC__ >= 4
631 __attribute__((sentinel))
633 void parse_error_expected(const char *message, ...)
635 if (message != NULL) {
636 errorf(HERE, "%s", message);
639 va_start(ap, message);
640 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
645 * Report an incompatible type.
647 static void type_error_incompatible(const char *msg,
648 const source_position_t *source_position, type_t *type1, type_t *type2)
650 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
655 * Expect the current token is the expected token.
656 * If not, generate an error and skip until the next anchor.
658 static void expect(token_kind_t const expected)
660 if (UNLIKELY(token.kind != expected)) {
661 parse_error_expected(NULL, expected, NULL);
662 add_anchor_token(expected);
664 rem_anchor_token(expected);
665 if (token.kind != expected)
671 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
673 if (token.kind != T_IDENTIFIER) {
674 parse_error_expected(context, T_IDENTIFIER, NULL);
675 add_anchor_token(T_IDENTIFIER);
677 rem_anchor_token(T_IDENTIFIER);
678 if (token.kind != T_IDENTIFIER)
681 symbol_t *const sym = token.identifier.symbol;
689 * Push a given scope on the scope stack and make it the
692 static scope_t *scope_push(scope_t *new_scope)
694 if (current_scope != NULL) {
695 new_scope->depth = current_scope->depth + 1;
698 scope_t *old_scope = current_scope;
699 current_scope = new_scope;
704 * Pop the current scope from the scope stack.
706 static void scope_pop(scope_t *old_scope)
708 current_scope = old_scope;
712 * Search an entity by its symbol in a given namespace.
714 static entity_t *get_entity(const symbol_t *const symbol,
715 namespace_tag_t namespc)
717 entity_t *entity = symbol->entity;
718 for (; entity != NULL; entity = entity->base.symbol_next) {
719 if ((namespace_tag_t)entity->base.namespc == namespc)
726 /* §6.2.3:1 24) There is only one name space for tags even though three are
728 static entity_t *get_tag(symbol_t const *const symbol,
729 entity_kind_tag_t const kind)
731 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
732 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
734 "'%Y' defined as wrong kind of tag (previous definition %P)",
735 symbol, &entity->base.source_position);
742 * pushs an entity on the environment stack and links the corresponding symbol
745 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
747 symbol_t *symbol = entity->base.symbol;
748 entity_namespace_t namespc = entity->base.namespc;
749 assert(namespc != 0);
751 /* replace/add entity into entity list of the symbol */
754 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
759 /* replace an entry? */
760 if (iter->base.namespc == namespc) {
761 entity->base.symbol_next = iter->base.symbol_next;
767 /* remember old declaration */
769 entry.symbol = symbol;
770 entry.old_entity = iter;
771 entry.namespc = namespc;
772 ARR_APP1(stack_entry_t, *stack_ptr, entry);
776 * Push an entity on the environment stack.
778 static void environment_push(entity_t *entity)
780 assert(entity->base.source_position.input_name != NULL);
781 assert(entity->base.parent_scope != NULL);
782 stack_push(&environment_stack, entity);
786 * Push a declaration on the global label stack.
788 * @param declaration the declaration
790 static void label_push(entity_t *label)
792 /* we abuse the parameters scope as parent for the labels */
793 label->base.parent_scope = ¤t_function->parameters;
794 stack_push(&label_stack, label);
798 * pops symbols from the environment stack until @p new_top is the top element
800 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
802 stack_entry_t *stack = *stack_ptr;
803 size_t top = ARR_LEN(stack);
806 assert(new_top <= top);
810 for (i = top; i > new_top; --i) {
811 stack_entry_t *entry = &stack[i - 1];
813 entity_t *old_entity = entry->old_entity;
814 symbol_t *symbol = entry->symbol;
815 entity_namespace_t namespc = entry->namespc;
817 /* replace with old_entity/remove */
820 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
822 assert(iter != NULL);
823 /* replace an entry? */
824 if (iter->base.namespc == namespc)
828 /* restore definition from outer scopes (if there was one) */
829 if (old_entity != NULL) {
830 old_entity->base.symbol_next = iter->base.symbol_next;
831 *anchor = old_entity;
833 /* remove entry from list */
834 *anchor = iter->base.symbol_next;
838 ARR_SHRINKLEN(*stack_ptr, new_top);
842 * Pop all entries from the environment stack until the new_top
845 * @param new_top the new stack top
847 static void environment_pop_to(size_t new_top)
849 stack_pop_to(&environment_stack, new_top);
853 * Pop all entries from the global label stack until the new_top
856 * @param new_top the new stack top
858 static void label_pop_to(size_t new_top)
860 stack_pop_to(&label_stack, new_top);
863 static atomic_type_kind_t get_akind(const type_t *type)
865 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
866 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
867 return type->atomic.akind;
871 * §6.3.1.1:2 Do integer promotion for a given type.
873 * @param type the type to promote
874 * @return the promoted type
876 static type_t *promote_integer(type_t *type)
878 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
885 * Check if a given expression represents a null pointer constant.
887 * @param expression the expression to check
889 static bool is_null_pointer_constant(const expression_t *expression)
891 /* skip void* cast */
892 if (expression->kind == EXPR_UNARY_CAST) {
893 type_t *const type = skip_typeref(expression->base.type);
894 if (types_compatible(type, type_void_ptr))
895 expression = expression->unary.value;
898 type_t *const type = skip_typeref(expression->base.type);
899 if (!is_type_integer(type))
901 switch (is_constant_expression(expression)) {
902 case EXPR_CLASS_ERROR: return true;
903 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
904 default: return false;
909 * Create an implicit cast expression.
911 * @param expression the expression to cast
912 * @param dest_type the destination type
914 static expression_t *create_implicit_cast(expression_t *expression,
917 type_t *const source_type = expression->base.type;
919 if (source_type == dest_type)
922 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
923 cast->unary.value = expression;
924 cast->base.type = dest_type;
925 cast->base.implicit = true;
930 typedef enum assign_error_t {
932 ASSIGN_ERROR_INCOMPATIBLE,
933 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
934 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
935 ASSIGN_WARNING_POINTER_FROM_INT,
936 ASSIGN_WARNING_INT_FROM_POINTER
939 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, source_position_t const *const pos)
941 type_t *const orig_type_right = right->base.type;
942 type_t *const type_left = skip_typeref(orig_type_left);
943 type_t *const type_right = skip_typeref(orig_type_right);
948 case ASSIGN_ERROR_INCOMPATIBLE:
949 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
952 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
953 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
954 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
956 /* the left type has all qualifiers from the right type */
957 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
958 warningf(WARN_OTHER, pos, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type", orig_type_left, context, orig_type_right, missing_qualifiers);
962 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
963 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
966 case ASSIGN_WARNING_POINTER_FROM_INT:
967 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
970 case ASSIGN_WARNING_INT_FROM_POINTER:
971 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
975 panic("invalid error value");
979 /** Implements the rules from §6.5.16.1 */
980 static assign_error_t semantic_assign(type_t *orig_type_left,
981 const expression_t *const right)
983 type_t *const orig_type_right = right->base.type;
984 type_t *const type_left = skip_typeref(orig_type_left);
985 type_t *const type_right = skip_typeref(orig_type_right);
987 if (is_type_pointer(type_left)) {
988 if (is_null_pointer_constant(right)) {
989 return ASSIGN_SUCCESS;
990 } else if (is_type_pointer(type_right)) {
991 type_t *points_to_left
992 = skip_typeref(type_left->pointer.points_to);
993 type_t *points_to_right
994 = skip_typeref(type_right->pointer.points_to);
995 assign_error_t res = ASSIGN_SUCCESS;
997 /* the left type has all qualifiers from the right type */
998 unsigned missing_qualifiers
999 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1000 if (missing_qualifiers != 0) {
1001 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1004 points_to_left = get_unqualified_type(points_to_left);
1005 points_to_right = get_unqualified_type(points_to_right);
1007 if (is_type_void(points_to_left))
1010 if (is_type_void(points_to_right)) {
1011 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1012 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1015 if (!types_compatible(points_to_left, points_to_right)) {
1016 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1020 } else if (is_type_integer(type_right)) {
1021 return ASSIGN_WARNING_POINTER_FROM_INT;
1023 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1024 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1025 && is_type_pointer(type_right))) {
1026 return ASSIGN_SUCCESS;
1027 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1028 type_t *const unqual_type_left = get_unqualified_type(type_left);
1029 type_t *const unqual_type_right = get_unqualified_type(type_right);
1030 if (types_compatible(unqual_type_left, unqual_type_right)) {
1031 return ASSIGN_SUCCESS;
1033 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1034 return ASSIGN_WARNING_INT_FROM_POINTER;
1037 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1038 return ASSIGN_SUCCESS;
1040 return ASSIGN_ERROR_INCOMPATIBLE;
1043 static expression_t *parse_constant_expression(void)
1045 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1047 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1048 errorf(&result->base.source_position,
1049 "expression '%E' is not constant", result);
1055 static expression_t *parse_assignment_expression(void)
1057 return parse_subexpression(PREC_ASSIGNMENT);
1060 static void warn_string_concat(const source_position_t *pos)
1062 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1065 static string_t parse_string_literals(void)
1067 assert(token.kind == T_STRING_LITERAL);
1068 string_t result = token.string.string;
1072 while (token.kind == T_STRING_LITERAL) {
1073 warn_string_concat(&token.base.source_position);
1074 result = concat_strings(&result, &token.string.string);
1081 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1083 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1084 attribute->kind = kind;
1085 attribute->source_position = *HERE;
1090 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1093 * __attribute__ ( ( attribute-list ) )
1097 * attribute_list , attrib
1102 * any-word ( identifier )
1103 * any-word ( identifier , nonempty-expr-list )
1104 * any-word ( expr-list )
1106 * where the "identifier" must not be declared as a type, and
1107 * "any-word" may be any identifier (including one declared as a
1108 * type), a reserved word storage class specifier, type specifier or
1109 * type qualifier. ??? This still leaves out most reserved keywords
1110 * (following the old parser), shouldn't we include them, and why not
1111 * allow identifiers declared as types to start the arguments?
1113 * Matze: this all looks confusing and little systematic, so we're even less
1114 * strict and parse any list of things which are identifiers or
1115 * (assignment-)expressions.
1117 static attribute_argument_t *parse_attribute_arguments(void)
1119 attribute_argument_t *first = NULL;
1120 attribute_argument_t **anchor = &first;
1121 if (token.kind != ')') do {
1122 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1124 /* is it an identifier */
1125 if (token.kind == T_IDENTIFIER
1126 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1127 symbol_t *symbol = token.identifier.symbol;
1128 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1129 argument->v.symbol = symbol;
1132 /* must be an expression */
1133 expression_t *expression = parse_assignment_expression();
1135 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1136 argument->v.expression = expression;
1139 /* append argument */
1141 anchor = &argument->next;
1142 } while (next_if(','));
1147 static attribute_t *parse_attribute_asm(void)
1149 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1152 attribute->a.arguments = parse_attribute_arguments();
1156 static symbol_t *get_symbol_from_token(void)
1158 switch(token.kind) {
1160 return token.identifier.symbol;
1189 /* maybe we need more tokens ... add them on demand */
1190 return get_token_kind_symbol(token.kind);
1196 static attribute_t *parse_attribute_gnu_single(void)
1198 /* parse "any-word" */
1199 symbol_t *symbol = get_symbol_from_token();
1200 if (symbol == NULL) {
1201 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1205 attribute_kind_t kind;
1206 char const *const name = symbol->string;
1207 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1208 if (kind > ATTRIBUTE_GNU_LAST) {
1209 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1210 /* TODO: we should still save the attribute in the list... */
1211 kind = ATTRIBUTE_UNKNOWN;
1215 const char *attribute_name = get_attribute_name(kind);
1216 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1220 attribute_t *attribute = allocate_attribute_zero(kind);
1223 /* parse arguments */
1225 attribute->a.arguments = parse_attribute_arguments();
1230 static attribute_t *parse_attribute_gnu(void)
1232 attribute_t *first = NULL;
1233 attribute_t **anchor = &first;
1235 eat(T___attribute__);
1239 add_anchor_token(')');
1240 add_anchor_token(',');
1241 if (token.kind != ')') do {
1242 attribute_t *attribute = parse_attribute_gnu_single();
1244 *anchor = attribute;
1245 anchor = &attribute->next;
1247 } while (next_if(','));
1248 rem_anchor_token(',');
1249 rem_anchor_token(')');
1256 /** Parse attributes. */
1257 static attribute_t *parse_attributes(attribute_t *first)
1259 attribute_t **anchor = &first;
1261 while (*anchor != NULL)
1262 anchor = &(*anchor)->next;
1264 attribute_t *attribute;
1265 switch (token.kind) {
1266 case T___attribute__:
1267 attribute = parse_attribute_gnu();
1268 if (attribute == NULL)
1273 attribute = parse_attribute_asm();
1277 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1282 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1286 case T__forceinline:
1287 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1288 eat(T__forceinline);
1292 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1297 /* TODO record modifier */
1298 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1299 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1307 *anchor = attribute;
1308 anchor = &attribute->next;
1312 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1314 static entity_t *determine_lhs_ent(expression_t *const expr,
1317 switch (expr->kind) {
1318 case EXPR_REFERENCE: {
1319 entity_t *const entity = expr->reference.entity;
1320 /* we should only find variables as lvalues... */
1321 if (entity->base.kind != ENTITY_VARIABLE
1322 && entity->base.kind != ENTITY_PARAMETER)
1328 case EXPR_ARRAY_ACCESS: {
1329 expression_t *const ref = expr->array_access.array_ref;
1330 entity_t * ent = NULL;
1331 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1332 ent = determine_lhs_ent(ref, lhs_ent);
1335 mark_vars_read(ref, lhs_ent);
1337 mark_vars_read(expr->array_access.index, lhs_ent);
1342 mark_vars_read(expr->select.compound, lhs_ent);
1343 if (is_type_compound(skip_typeref(expr->base.type)))
1344 return determine_lhs_ent(expr->select.compound, lhs_ent);
1348 case EXPR_UNARY_DEREFERENCE: {
1349 expression_t *const val = expr->unary.value;
1350 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1352 return determine_lhs_ent(val->unary.value, lhs_ent);
1354 mark_vars_read(val, NULL);
1360 mark_vars_read(expr, NULL);
1365 #define ENT_ANY ((entity_t*)-1)
1368 * Mark declarations, which are read. This is used to detect variables, which
1372 * x is not marked as "read", because it is only read to calculate its own new
1376 * x and y are not detected as "not read", because multiple variables are
1379 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1381 switch (expr->kind) {
1382 case EXPR_REFERENCE: {
1383 entity_t *const entity = expr->reference.entity;
1384 if (entity->kind != ENTITY_VARIABLE
1385 && entity->kind != ENTITY_PARAMETER)
1388 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1389 if (entity->kind == ENTITY_VARIABLE) {
1390 entity->variable.read = true;
1392 entity->parameter.read = true;
1399 // TODO respect pure/const
1400 mark_vars_read(expr->call.function, NULL);
1401 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1402 mark_vars_read(arg->expression, NULL);
1406 case EXPR_CONDITIONAL:
1407 // TODO lhs_decl should depend on whether true/false have an effect
1408 mark_vars_read(expr->conditional.condition, NULL);
1409 if (expr->conditional.true_expression != NULL)
1410 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1411 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1415 if (lhs_ent == ENT_ANY
1416 && !is_type_compound(skip_typeref(expr->base.type)))
1418 mark_vars_read(expr->select.compound, lhs_ent);
1421 case EXPR_ARRAY_ACCESS: {
1422 mark_vars_read(expr->array_access.index, lhs_ent);
1423 expression_t *const ref = expr->array_access.array_ref;
1424 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1425 if (lhs_ent == ENT_ANY)
1428 mark_vars_read(ref, lhs_ent);
1433 mark_vars_read(expr->va_arge.ap, lhs_ent);
1437 mark_vars_read(expr->va_copye.src, lhs_ent);
1440 case EXPR_UNARY_CAST:
1441 /* Special case: Use void cast to mark a variable as "read" */
1442 if (is_type_void(skip_typeref(expr->base.type)))
1447 case EXPR_UNARY_THROW:
1448 if (expr->unary.value == NULL)
1451 case EXPR_UNARY_DEREFERENCE:
1452 case EXPR_UNARY_DELETE:
1453 case EXPR_UNARY_DELETE_ARRAY:
1454 if (lhs_ent == ENT_ANY)
1458 case EXPR_UNARY_NEGATE:
1459 case EXPR_UNARY_PLUS:
1460 case EXPR_UNARY_BITWISE_NEGATE:
1461 case EXPR_UNARY_NOT:
1462 case EXPR_UNARY_TAKE_ADDRESS:
1463 case EXPR_UNARY_POSTFIX_INCREMENT:
1464 case EXPR_UNARY_POSTFIX_DECREMENT:
1465 case EXPR_UNARY_PREFIX_INCREMENT:
1466 case EXPR_UNARY_PREFIX_DECREMENT:
1467 case EXPR_UNARY_ASSUME:
1469 mark_vars_read(expr->unary.value, lhs_ent);
1472 case EXPR_BINARY_ADD:
1473 case EXPR_BINARY_SUB:
1474 case EXPR_BINARY_MUL:
1475 case EXPR_BINARY_DIV:
1476 case EXPR_BINARY_MOD:
1477 case EXPR_BINARY_EQUAL:
1478 case EXPR_BINARY_NOTEQUAL:
1479 case EXPR_BINARY_LESS:
1480 case EXPR_BINARY_LESSEQUAL:
1481 case EXPR_BINARY_GREATER:
1482 case EXPR_BINARY_GREATEREQUAL:
1483 case EXPR_BINARY_BITWISE_AND:
1484 case EXPR_BINARY_BITWISE_OR:
1485 case EXPR_BINARY_BITWISE_XOR:
1486 case EXPR_BINARY_LOGICAL_AND:
1487 case EXPR_BINARY_LOGICAL_OR:
1488 case EXPR_BINARY_SHIFTLEFT:
1489 case EXPR_BINARY_SHIFTRIGHT:
1490 case EXPR_BINARY_COMMA:
1491 case EXPR_BINARY_ISGREATER:
1492 case EXPR_BINARY_ISGREATEREQUAL:
1493 case EXPR_BINARY_ISLESS:
1494 case EXPR_BINARY_ISLESSEQUAL:
1495 case EXPR_BINARY_ISLESSGREATER:
1496 case EXPR_BINARY_ISUNORDERED:
1497 mark_vars_read(expr->binary.left, lhs_ent);
1498 mark_vars_read(expr->binary.right, lhs_ent);
1501 case EXPR_BINARY_ASSIGN:
1502 case EXPR_BINARY_MUL_ASSIGN:
1503 case EXPR_BINARY_DIV_ASSIGN:
1504 case EXPR_BINARY_MOD_ASSIGN:
1505 case EXPR_BINARY_ADD_ASSIGN:
1506 case EXPR_BINARY_SUB_ASSIGN:
1507 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1508 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1509 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1510 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1511 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1512 if (lhs_ent == ENT_ANY)
1514 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1515 mark_vars_read(expr->binary.right, lhs_ent);
1520 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1523 case EXPR_LITERAL_CASES:
1525 case EXPR_STRING_LITERAL:
1526 case EXPR_WIDE_STRING_LITERAL:
1527 case EXPR_COMPOUND_LITERAL: // TODO init?
1529 case EXPR_CLASSIFY_TYPE:
1532 case EXPR_BUILTIN_CONSTANT_P:
1533 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1535 case EXPR_STATEMENT: // TODO
1536 case EXPR_LABEL_ADDRESS:
1537 case EXPR_ENUM_CONSTANT:
1541 panic("unhandled expression");
1544 static designator_t *parse_designation(void)
1546 designator_t *result = NULL;
1547 designator_t **anchor = &result;
1550 designator_t *designator;
1551 switch (token.kind) {
1553 designator = allocate_ast_zero(sizeof(designator[0]));
1554 designator->source_position = token.base.source_position;
1556 add_anchor_token(']');
1557 designator->array_index = parse_constant_expression();
1558 rem_anchor_token(']');
1562 designator = allocate_ast_zero(sizeof(designator[0]));
1563 designator->source_position = token.base.source_position;
1565 designator->symbol = expect_identifier("while parsing designator", NULL);
1566 if (!designator->symbol)
1574 assert(designator != NULL);
1575 *anchor = designator;
1576 anchor = &designator->next;
1580 static initializer_t *initializer_from_string(array_type_t *const type,
1581 const string_t *const string)
1583 /* TODO: check len vs. size of array type */
1586 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1587 initializer->string.string = *string;
1592 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1593 const string_t *const string)
1595 /* TODO: check len vs. size of array type */
1598 initializer_t *const initializer =
1599 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1600 initializer->wide_string.string = *string;
1606 * Build an initializer from a given expression.
1608 static initializer_t *initializer_from_expression(type_t *orig_type,
1609 expression_t *expression)
1611 /* TODO check that expression is a constant expression */
1613 /* §6.7.8.14/15 char array may be initialized by string literals */
1614 type_t *type = skip_typeref(orig_type);
1615 type_t *expr_type_orig = expression->base.type;
1616 type_t *expr_type = skip_typeref(expr_type_orig);
1618 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1619 array_type_t *const array_type = &type->array;
1620 type_t *const element_type = skip_typeref(array_type->element_type);
1622 if (element_type->kind == TYPE_ATOMIC) {
1623 atomic_type_kind_t akind = element_type->atomic.akind;
1624 switch (expression->kind) {
1625 case EXPR_STRING_LITERAL:
1626 if (akind == ATOMIC_TYPE_CHAR
1627 || akind == ATOMIC_TYPE_SCHAR
1628 || akind == ATOMIC_TYPE_UCHAR) {
1629 return initializer_from_string(array_type,
1630 &expression->string_literal.value);
1634 case EXPR_WIDE_STRING_LITERAL: {
1635 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1636 if (get_unqualified_type(element_type) == bare_wchar_type) {
1637 return initializer_from_wide_string(array_type,
1638 &expression->string_literal.value);
1649 assign_error_t error = semantic_assign(type, expression);
1650 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1652 report_assign_error(error, type, expression, "initializer",
1653 &expression->base.source_position);
1655 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1656 result->value.value = create_implicit_cast(expression, type);
1662 * Parses an scalar initializer.
1664 * §6.7.8.11; eat {} without warning
1666 static initializer_t *parse_scalar_initializer(type_t *type,
1667 bool must_be_constant)
1669 /* there might be extra {} hierarchies */
1671 if (token.kind == '{') {
1672 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1676 } while (token.kind == '{');
1679 expression_t *expression = parse_assignment_expression();
1680 mark_vars_read(expression, NULL);
1681 if (must_be_constant && !is_linker_constant(expression)) {
1682 errorf(&expression->base.source_position,
1683 "initialisation expression '%E' is not constant",
1687 initializer_t *initializer = initializer_from_expression(type, expression);
1689 if (initializer == NULL) {
1690 errorf(&expression->base.source_position,
1691 "expression '%E' (type '%T') doesn't match expected type '%T'",
1692 expression, expression->base.type, type);
1697 bool additional_warning_displayed = false;
1698 while (braces > 0) {
1700 if (token.kind != '}') {
1701 if (!additional_warning_displayed) {
1702 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1703 additional_warning_displayed = true;
1714 * An entry in the type path.
1716 typedef struct type_path_entry_t type_path_entry_t;
1717 struct type_path_entry_t {
1718 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1720 size_t index; /**< For array types: the current index. */
1721 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1726 * A type path expression a position inside compound or array types.
1728 typedef struct type_path_t type_path_t;
1729 struct type_path_t {
1730 type_path_entry_t *path; /**< An flexible array containing the current path. */
1731 type_t *top_type; /**< type of the element the path points */
1732 size_t max_index; /**< largest index in outermost array */
1736 * Prints a type path for debugging.
1738 static __attribute__((unused)) void debug_print_type_path(
1739 const type_path_t *path)
1741 size_t len = ARR_LEN(path->path);
1743 for (size_t i = 0; i < len; ++i) {
1744 const type_path_entry_t *entry = & path->path[i];
1746 type_t *type = skip_typeref(entry->type);
1747 if (is_type_compound(type)) {
1748 /* in gcc mode structs can have no members */
1749 if (entry->v.compound_entry == NULL) {
1753 fprintf(stderr, ".%s",
1754 entry->v.compound_entry->base.symbol->string);
1755 } else if (is_type_array(type)) {
1756 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1758 fprintf(stderr, "-INVALID-");
1761 if (path->top_type != NULL) {
1762 fprintf(stderr, " (");
1763 print_type(path->top_type);
1764 fprintf(stderr, ")");
1769 * Return the top type path entry, ie. in a path
1770 * (type).a.b returns the b.
1772 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1774 size_t len = ARR_LEN(path->path);
1776 return &path->path[len-1];
1780 * Enlarge the type path by an (empty) element.
1782 static type_path_entry_t *append_to_type_path(type_path_t *path)
1784 size_t len = ARR_LEN(path->path);
1785 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1787 type_path_entry_t *result = & path->path[len];
1788 memset(result, 0, sizeof(result[0]));
1793 * Descending into a sub-type. Enter the scope of the current top_type.
1795 static void descend_into_subtype(type_path_t *path)
1797 type_t *orig_top_type = path->top_type;
1798 type_t *top_type = skip_typeref(orig_top_type);
1800 type_path_entry_t *top = append_to_type_path(path);
1801 top->type = top_type;
1803 if (is_type_compound(top_type)) {
1804 compound_t *const compound = top_type->compound.compound;
1805 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1807 if (entry != NULL) {
1808 top->v.compound_entry = &entry->declaration;
1809 path->top_type = entry->declaration.type;
1811 path->top_type = NULL;
1813 } else if (is_type_array(top_type)) {
1815 path->top_type = top_type->array.element_type;
1817 assert(!is_type_valid(top_type));
1822 * Pop an entry from the given type path, ie. returning from
1823 * (type).a.b to (type).a
1825 static void ascend_from_subtype(type_path_t *path)
1827 type_path_entry_t *top = get_type_path_top(path);
1829 path->top_type = top->type;
1831 size_t len = ARR_LEN(path->path);
1832 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1836 * Pop entries from the given type path until the given
1837 * path level is reached.
1839 static void ascend_to(type_path_t *path, size_t top_path_level)
1841 size_t len = ARR_LEN(path->path);
1843 while (len > top_path_level) {
1844 ascend_from_subtype(path);
1845 len = ARR_LEN(path->path);
1849 static bool walk_designator(type_path_t *path, const designator_t *designator,
1850 bool used_in_offsetof)
1852 for (; designator != NULL; designator = designator->next) {
1853 type_path_entry_t *top = get_type_path_top(path);
1854 type_t *orig_type = top->type;
1856 type_t *type = skip_typeref(orig_type);
1858 if (designator->symbol != NULL) {
1859 symbol_t *symbol = designator->symbol;
1860 if (!is_type_compound(type)) {
1861 if (is_type_valid(type)) {
1862 errorf(&designator->source_position,
1863 "'.%Y' designator used for non-compound type '%T'",
1867 top->type = type_error_type;
1868 top->v.compound_entry = NULL;
1869 orig_type = type_error_type;
1871 compound_t *compound = type->compound.compound;
1872 entity_t *iter = compound->members.entities;
1873 for (; iter != NULL; iter = iter->base.next) {
1874 if (iter->base.symbol == symbol) {
1879 errorf(&designator->source_position,
1880 "'%T' has no member named '%Y'", orig_type, symbol);
1883 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1884 if (used_in_offsetof && iter->compound_member.bitfield) {
1885 errorf(&designator->source_position,
1886 "offsetof designator '%Y' must not specify bitfield",
1891 top->type = orig_type;
1892 top->v.compound_entry = &iter->declaration;
1893 orig_type = iter->declaration.type;
1896 expression_t *array_index = designator->array_index;
1897 assert(designator->array_index != NULL);
1899 if (!is_type_array(type)) {
1900 if (is_type_valid(type)) {
1901 errorf(&designator->source_position,
1902 "[%E] designator used for non-array type '%T'",
1903 array_index, orig_type);
1908 long index = fold_constant_to_int(array_index);
1909 if (!used_in_offsetof) {
1911 errorf(&designator->source_position,
1912 "array index [%E] must be positive", array_index);
1913 } else if (type->array.size_constant) {
1914 long array_size = type->array.size;
1915 if (index >= array_size) {
1916 errorf(&designator->source_position,
1917 "designator [%E] (%d) exceeds array size %d",
1918 array_index, index, array_size);
1923 top->type = orig_type;
1924 top->v.index = (size_t) index;
1925 orig_type = type->array.element_type;
1927 path->top_type = orig_type;
1929 if (designator->next != NULL) {
1930 descend_into_subtype(path);
1936 static void advance_current_object(type_path_t *path, size_t top_path_level)
1938 type_path_entry_t *top = get_type_path_top(path);
1940 type_t *type = skip_typeref(top->type);
1941 if (is_type_union(type)) {
1942 /* in unions only the first element is initialized */
1943 top->v.compound_entry = NULL;
1944 } else if (is_type_struct(type)) {
1945 declaration_t *entry = top->v.compound_entry;
1947 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1948 if (next_entity != NULL) {
1949 assert(is_declaration(next_entity));
1950 entry = &next_entity->declaration;
1955 top->v.compound_entry = entry;
1956 if (entry != NULL) {
1957 path->top_type = entry->type;
1960 } else if (is_type_array(type)) {
1961 assert(is_type_array(type));
1965 if (!type->array.size_constant || top->v.index < type->array.size) {
1969 assert(!is_type_valid(type));
1973 /* we're past the last member of the current sub-aggregate, try if we
1974 * can ascend in the type hierarchy and continue with another subobject */
1975 size_t len = ARR_LEN(path->path);
1977 if (len > top_path_level) {
1978 ascend_from_subtype(path);
1979 advance_current_object(path, top_path_level);
1981 path->top_type = NULL;
1986 * skip any {...} blocks until a closing bracket is reached.
1988 static void skip_initializers(void)
1992 while (token.kind != '}') {
1993 if (token.kind == T_EOF)
1995 if (token.kind == '{') {
2003 static initializer_t *create_empty_initializer(void)
2005 static initializer_t empty_initializer
2006 = { .list = { { INITIALIZER_LIST }, 0 } };
2007 return &empty_initializer;
2011 * Parse a part of an initialiser for a struct or union,
2013 static initializer_t *parse_sub_initializer(type_path_t *path,
2014 type_t *outer_type, size_t top_path_level,
2015 parse_initializer_env_t *env)
2017 if (token.kind == '}') {
2018 /* empty initializer */
2019 return create_empty_initializer();
2022 type_t *orig_type = path->top_type;
2023 type_t *type = NULL;
2025 if (orig_type == NULL) {
2026 /* We are initializing an empty compound. */
2028 type = skip_typeref(orig_type);
2031 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2034 designator_t *designator = NULL;
2035 if (token.kind == '.' || token.kind == '[') {
2036 designator = parse_designation();
2037 goto finish_designator;
2038 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2039 /* GNU-style designator ("identifier: value") */
2040 designator = allocate_ast_zero(sizeof(designator[0]));
2041 designator->source_position = token.base.source_position;
2042 designator->symbol = token.identifier.symbol;
2047 /* reset path to toplevel, evaluate designator from there */
2048 ascend_to(path, top_path_level);
2049 if (!walk_designator(path, designator, false)) {
2050 /* can't continue after designation error */
2054 initializer_t *designator_initializer
2055 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2056 designator_initializer->designator.designator = designator;
2057 ARR_APP1(initializer_t*, initializers, designator_initializer);
2059 orig_type = path->top_type;
2060 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2065 if (token.kind == '{') {
2066 if (type != NULL && is_type_scalar(type)) {
2067 sub = parse_scalar_initializer(type, env->must_be_constant);
2070 if (env->entity != NULL) {
2072 "extra brace group at end of initializer for '%Y'",
2073 env->entity->base.symbol);
2075 errorf(HERE, "extra brace group at end of initializer");
2080 descend_into_subtype(path);
2083 add_anchor_token('}');
2084 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2086 rem_anchor_token('}');
2091 goto error_parse_next;
2093 ascend_from_subtype(path);
2096 /* must be an expression */
2097 expression_t *expression = parse_assignment_expression();
2098 mark_vars_read(expression, NULL);
2100 if (env->must_be_constant && !is_linker_constant(expression)) {
2101 errorf(&expression->base.source_position,
2102 "Initialisation expression '%E' is not constant",
2107 /* we are already outside, ... */
2108 if (outer_type == NULL)
2109 goto error_parse_next;
2110 type_t *const outer_type_skip = skip_typeref(outer_type);
2111 if (is_type_compound(outer_type_skip) &&
2112 !outer_type_skip->compound.compound->complete) {
2113 goto error_parse_next;
2116 source_position_t const* const pos = &expression->base.source_position;
2117 if (env->entity != NULL) {
2118 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2120 warningf(WARN_OTHER, pos, "excess elements in initializer");
2122 goto error_parse_next;
2125 /* handle { "string" } special case */
2126 if ((expression->kind == EXPR_STRING_LITERAL
2127 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2128 && outer_type != NULL) {
2129 sub = initializer_from_expression(outer_type, expression);
2132 if (token.kind != '}') {
2133 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2135 /* TODO: eat , ... */
2140 /* descend into subtypes until expression matches type */
2142 orig_type = path->top_type;
2143 type = skip_typeref(orig_type);
2145 sub = initializer_from_expression(orig_type, expression);
2149 if (!is_type_valid(type)) {
2152 if (is_type_scalar(type)) {
2153 errorf(&expression->base.source_position,
2154 "expression '%E' doesn't match expected type '%T'",
2155 expression, orig_type);
2159 descend_into_subtype(path);
2163 /* update largest index of top array */
2164 const type_path_entry_t *first = &path->path[0];
2165 type_t *first_type = first->type;
2166 first_type = skip_typeref(first_type);
2167 if (is_type_array(first_type)) {
2168 size_t index = first->v.index;
2169 if (index > path->max_index)
2170 path->max_index = index;
2173 /* append to initializers list */
2174 ARR_APP1(initializer_t*, initializers, sub);
2177 if (token.kind == '}') {
2180 add_anchor_token('}');
2182 rem_anchor_token('}');
2183 if (token.kind == '}') {
2188 /* advance to the next declaration if we are not at the end */
2189 advance_current_object(path, top_path_level);
2190 orig_type = path->top_type;
2191 if (orig_type != NULL)
2192 type = skip_typeref(orig_type);
2198 size_t len = ARR_LEN(initializers);
2199 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2200 initializer_t *result = allocate_ast_zero(size);
2201 result->kind = INITIALIZER_LIST;
2202 result->list.len = len;
2203 memcpy(&result->list.initializers, initializers,
2204 len * sizeof(initializers[0]));
2206 DEL_ARR_F(initializers);
2207 ascend_to(path, top_path_level+1);
2212 skip_initializers();
2213 DEL_ARR_F(initializers);
2214 ascend_to(path, top_path_level+1);
2218 static expression_t *make_size_literal(size_t value)
2220 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2221 literal->base.type = type_size_t;
2224 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2225 literal->literal.value = make_string(buf);
2231 * Parses an initializer. Parsers either a compound literal
2232 * (env->declaration == NULL) or an initializer of a declaration.
2234 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2236 type_t *type = skip_typeref(env->type);
2237 size_t max_index = 0;
2238 initializer_t *result;
2240 if (is_type_scalar(type)) {
2241 result = parse_scalar_initializer(type, env->must_be_constant);
2242 } else if (token.kind == '{') {
2246 memset(&path, 0, sizeof(path));
2247 path.top_type = env->type;
2248 path.path = NEW_ARR_F(type_path_entry_t, 0);
2250 descend_into_subtype(&path);
2252 add_anchor_token('}');
2253 result = parse_sub_initializer(&path, env->type, 1, env);
2254 rem_anchor_token('}');
2256 max_index = path.max_index;
2257 DEL_ARR_F(path.path);
2261 /* parse_scalar_initializer() also works in this case: we simply
2262 * have an expression without {} around it */
2263 result = parse_scalar_initializer(type, env->must_be_constant);
2266 /* §6.7.8:22 array initializers for arrays with unknown size determine
2267 * the array type size */
2268 if (is_type_array(type) && type->array.size_expression == NULL
2269 && result != NULL) {
2271 switch (result->kind) {
2272 case INITIALIZER_LIST:
2273 assert(max_index != 0xdeadbeaf);
2274 size = max_index + 1;
2277 case INITIALIZER_STRING:
2278 size = result->string.string.size;
2281 case INITIALIZER_WIDE_STRING:
2282 size = result->wide_string.string.size;
2285 case INITIALIZER_DESIGNATOR:
2286 case INITIALIZER_VALUE:
2287 /* can happen for parse errors */
2292 internal_errorf(HERE, "invalid initializer type");
2295 type_t *new_type = duplicate_type(type);
2297 new_type->array.size_expression = make_size_literal(size);
2298 new_type->array.size_constant = true;
2299 new_type->array.has_implicit_size = true;
2300 new_type->array.size = size;
2301 env->type = new_type;
2307 static void append_entity(scope_t *scope, entity_t *entity)
2309 if (scope->last_entity != NULL) {
2310 scope->last_entity->base.next = entity;
2312 scope->entities = entity;
2314 entity->base.parent_entity = current_entity;
2315 scope->last_entity = entity;
2319 static compound_t *parse_compound_type_specifier(bool is_struct)
2321 source_position_t const pos = *HERE;
2322 eat(is_struct ? T_struct : T_union);
2324 symbol_t *symbol = NULL;
2325 entity_t *entity = NULL;
2326 attribute_t *attributes = NULL;
2328 if (token.kind == T___attribute__) {
2329 attributes = parse_attributes(NULL);
2332 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2333 if (token.kind == T_IDENTIFIER) {
2334 /* the compound has a name, check if we have seen it already */
2335 symbol = token.identifier.symbol;
2336 entity = get_tag(symbol, kind);
2339 if (entity != NULL) {
2340 if (entity->base.parent_scope != current_scope &&
2341 (token.kind == '{' || token.kind == ';')) {
2342 /* we're in an inner scope and have a definition. Shadow
2343 * existing definition in outer scope */
2345 } else if (entity->compound.complete && token.kind == '{') {
2346 source_position_t const *const ppos = &entity->base.source_position;
2347 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2348 /* clear members in the hope to avoid further errors */
2349 entity->compound.members.entities = NULL;
2352 } else if (token.kind != '{') {
2353 char const *const msg =
2354 is_struct ? "while parsing struct type specifier" :
2355 "while parsing union type specifier";
2356 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2361 if (entity == NULL) {
2362 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2363 entity->compound.alignment = 1;
2364 entity->base.parent_scope = current_scope;
2365 if (symbol != NULL) {
2366 environment_push(entity);
2368 append_entity(current_scope, entity);
2371 if (token.kind == '{') {
2372 parse_compound_type_entries(&entity->compound);
2374 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2375 if (symbol == NULL) {
2376 assert(anonymous_entity == NULL);
2377 anonymous_entity = entity;
2381 if (attributes != NULL) {
2382 handle_entity_attributes(attributes, entity);
2385 return &entity->compound;
2388 static void parse_enum_entries(type_t *const enum_type)
2392 if (token.kind == '}') {
2393 errorf(HERE, "empty enum not allowed");
2398 add_anchor_token('}');
2399 add_anchor_token(',');
2401 add_anchor_token('=');
2402 source_position_t pos;
2403 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2404 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2405 entity->enum_value.enum_type = enum_type;
2406 rem_anchor_token('=');
2409 expression_t *value = parse_constant_expression();
2411 value = create_implicit_cast(value, enum_type);
2412 entity->enum_value.value = value;
2417 record_entity(entity, false);
2418 } while (next_if(',') && token.kind != '}');
2419 rem_anchor_token(',');
2420 rem_anchor_token('}');
2425 static type_t *parse_enum_specifier(void)
2427 source_position_t const pos = *HERE;
2432 switch (token.kind) {
2434 symbol = token.identifier.symbol;
2435 entity = get_tag(symbol, ENTITY_ENUM);
2438 if (entity != NULL) {
2439 if (entity->base.parent_scope != current_scope &&
2440 (token.kind == '{' || token.kind == ';')) {
2441 /* we're in an inner scope and have a definition. Shadow
2442 * existing definition in outer scope */
2444 } else if (entity->enume.complete && token.kind == '{') {
2445 source_position_t const *const ppos = &entity->base.source_position;
2446 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2457 parse_error_expected("while parsing enum type specifier",
2458 T_IDENTIFIER, '{', NULL);
2462 if (entity == NULL) {
2463 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2464 entity->base.parent_scope = current_scope;
2467 type_t *const type = allocate_type_zero(TYPE_ENUM);
2468 type->enumt.enume = &entity->enume;
2469 type->enumt.base.akind = ATOMIC_TYPE_INT;
2471 if (token.kind == '{') {
2472 if (symbol != NULL) {
2473 environment_push(entity);
2475 append_entity(current_scope, entity);
2476 entity->enume.complete = true;
2478 parse_enum_entries(type);
2479 parse_attributes(NULL);
2481 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2482 if (symbol == NULL) {
2483 assert(anonymous_entity == NULL);
2484 anonymous_entity = entity;
2486 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2487 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2494 * if a symbol is a typedef to another type, return true
2496 static bool is_typedef_symbol(symbol_t *symbol)
2498 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2499 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2502 static type_t *parse_typeof(void)
2509 add_anchor_token(')');
2511 expression_t *expression = NULL;
2513 switch (token.kind) {
2515 if (is_typedef_symbol(token.identifier.symbol)) {
2517 type = parse_typename();
2520 expression = parse_expression();
2521 type = revert_automatic_type_conversion(expression);
2526 rem_anchor_token(')');
2529 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2530 typeof_type->typeoft.expression = expression;
2531 typeof_type->typeoft.typeof_type = type;
2536 typedef enum specifiers_t {
2537 SPECIFIER_SIGNED = 1 << 0,
2538 SPECIFIER_UNSIGNED = 1 << 1,
2539 SPECIFIER_LONG = 1 << 2,
2540 SPECIFIER_INT = 1 << 3,
2541 SPECIFIER_DOUBLE = 1 << 4,
2542 SPECIFIER_CHAR = 1 << 5,
2543 SPECIFIER_WCHAR_T = 1 << 6,
2544 SPECIFIER_SHORT = 1 << 7,
2545 SPECIFIER_LONG_LONG = 1 << 8,
2546 SPECIFIER_FLOAT = 1 << 9,
2547 SPECIFIER_BOOL = 1 << 10,
2548 SPECIFIER_VOID = 1 << 11,
2549 SPECIFIER_INT8 = 1 << 12,
2550 SPECIFIER_INT16 = 1 << 13,
2551 SPECIFIER_INT32 = 1 << 14,
2552 SPECIFIER_INT64 = 1 << 15,
2553 SPECIFIER_INT128 = 1 << 16,
2554 SPECIFIER_COMPLEX = 1 << 17,
2555 SPECIFIER_IMAGINARY = 1 << 18,
2558 static type_t *get_typedef_type(symbol_t *symbol)
2560 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2561 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2564 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2565 type->typedeft.typedefe = &entity->typedefe;
2570 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2572 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2576 add_anchor_token(')');
2577 add_anchor_token(',');
2579 add_anchor_token('=');
2580 source_position_t pos;
2581 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2582 rem_anchor_token('=');
2584 symbol_t **prop = NULL;
2586 if (streq(prop_sym->string, "put")) {
2587 prop = &property->put_symbol;
2588 } else if (streq(prop_sym->string, "get")) {
2589 prop = &property->get_symbol;
2591 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2595 add_anchor_token(T_IDENTIFIER);
2597 rem_anchor_token(T_IDENTIFIER);
2599 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2601 *prop = sym ? sym : sym_anonymous;
2602 } while (next_if(','));
2603 rem_anchor_token(',');
2604 rem_anchor_token(')');
2606 attribute->a.property = property;
2612 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2614 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2615 if (next_if(T_restrict)) {
2616 kind = ATTRIBUTE_MS_RESTRICT;
2617 } else if (token.kind == T_IDENTIFIER) {
2618 const char *name = token.identifier.symbol->string;
2619 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2621 const char *attribute_name = get_attribute_name(k);
2622 if (attribute_name != NULL && streq(attribute_name, name)) {
2628 if (kind == ATTRIBUTE_UNKNOWN) {
2629 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2632 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2636 attribute_t *attribute = allocate_attribute_zero(kind);
2639 if (kind == ATTRIBUTE_MS_PROPERTY) {
2640 return parse_attribute_ms_property(attribute);
2643 /* parse arguments */
2645 attribute->a.arguments = parse_attribute_arguments();
2650 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2655 if (token.kind != ')') {
2656 add_anchor_token(')');
2658 attribute_t **anchor = &first;
2660 while (*anchor != NULL)
2661 anchor = &(*anchor)->next;
2663 attribute_t *attribute
2664 = parse_microsoft_extended_decl_modifier_single();
2665 if (attribute == NULL)
2668 *anchor = attribute;
2669 anchor = &attribute->next;
2670 } while (next_if(','));
2672 rem_anchor_token(')');
2678 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2680 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2681 if (is_declaration(entity)) {
2682 entity->declaration.type = type_error_type;
2683 entity->declaration.implicit = true;
2684 } else if (kind == ENTITY_TYPEDEF) {
2685 entity->typedefe.type = type_error_type;
2686 entity->typedefe.builtin = true;
2688 if (kind != ENTITY_COMPOUND_MEMBER)
2689 record_entity(entity, false);
2693 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2695 type_t *type = NULL;
2696 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2697 unsigned type_specifiers = 0;
2698 bool newtype = false;
2699 bool saw_error = false;
2701 memset(specifiers, 0, sizeof(*specifiers));
2702 specifiers->source_position = token.base.source_position;
2705 specifiers->attributes = parse_attributes(specifiers->attributes);
2707 switch (token.kind) {
2709 #define MATCH_STORAGE_CLASS(token, class) \
2711 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2712 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2714 specifiers->storage_class = class; \
2715 if (specifiers->thread_local) \
2716 goto check_thread_storage_class; \
2720 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2721 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2722 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2723 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2724 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2727 specifiers->attributes
2728 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2732 if (specifiers->thread_local) {
2733 errorf(HERE, "duplicate '__thread'");
2735 specifiers->thread_local = true;
2736 check_thread_storage_class:
2737 switch (specifiers->storage_class) {
2738 case STORAGE_CLASS_EXTERN:
2739 case STORAGE_CLASS_NONE:
2740 case STORAGE_CLASS_STATIC:
2744 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2745 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2746 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2747 wrong_thread_storage_class:
2748 errorf(HERE, "'__thread' used with '%s'", wrong);
2755 /* type qualifiers */
2756 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2758 qualifiers |= qualifier; \
2762 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2763 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2764 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2765 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2766 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2767 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2768 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2769 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2771 /* type specifiers */
2772 #define MATCH_SPECIFIER(token, specifier, name) \
2774 if (type_specifiers & specifier) { \
2775 errorf(HERE, "multiple " name " type specifiers given"); \
2777 type_specifiers |= specifier; \
2782 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2783 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2784 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2785 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2786 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2787 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2788 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2789 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2790 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2791 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2792 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2793 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2794 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2795 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2796 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2797 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2798 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2799 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2803 specifiers->is_inline = true;
2807 case T__forceinline:
2809 specifiers->modifiers |= DM_FORCEINLINE;
2814 if (type_specifiers & SPECIFIER_LONG_LONG) {
2815 errorf(HERE, "too many long type specifiers given");
2816 } else if (type_specifiers & SPECIFIER_LONG) {
2817 type_specifiers |= SPECIFIER_LONG_LONG;
2819 type_specifiers |= SPECIFIER_LONG;
2824 #define CHECK_DOUBLE_TYPE() \
2825 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2828 CHECK_DOUBLE_TYPE();
2829 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2831 type->compound.compound = parse_compound_type_specifier(true);
2834 CHECK_DOUBLE_TYPE();
2835 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2836 type->compound.compound = parse_compound_type_specifier(false);
2839 CHECK_DOUBLE_TYPE();
2840 type = parse_enum_specifier();
2843 CHECK_DOUBLE_TYPE();
2844 type = parse_typeof();
2846 case T___builtin_va_list:
2847 CHECK_DOUBLE_TYPE();
2848 type = duplicate_type(type_valist);
2852 case T_IDENTIFIER: {
2853 /* only parse identifier if we haven't found a type yet */
2854 if (type != NULL || type_specifiers != 0) {
2855 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2856 * declaration, so it doesn't generate errors about expecting '(' or
2858 switch (look_ahead(1)->kind) {
2865 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2869 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2874 goto finish_specifiers;
2878 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2879 if (typedef_type == NULL) {
2880 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2881 * declaration, so it doesn't generate 'implicit int' followed by more
2882 * errors later on. */
2883 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2889 errorf(HERE, "%K does not name a type", &token);
2891 symbol_t *symbol = token.identifier.symbol;
2893 = create_error_entity(symbol, ENTITY_TYPEDEF);
2895 type = allocate_type_zero(TYPE_TYPEDEF);
2896 type->typedeft.typedefe = &entity->typedefe;
2904 goto finish_specifiers;
2909 type = typedef_type;
2913 /* function specifier */
2915 goto finish_specifiers;
2920 specifiers->attributes = parse_attributes(specifiers->attributes);
2922 if (type == NULL || (saw_error && type_specifiers != 0)) {
2923 atomic_type_kind_t atomic_type;
2925 /* match valid basic types */
2926 switch (type_specifiers) {
2927 case SPECIFIER_VOID:
2928 atomic_type = ATOMIC_TYPE_VOID;
2930 case SPECIFIER_WCHAR_T:
2931 atomic_type = ATOMIC_TYPE_WCHAR_T;
2933 case SPECIFIER_CHAR:
2934 atomic_type = ATOMIC_TYPE_CHAR;
2936 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2937 atomic_type = ATOMIC_TYPE_SCHAR;
2939 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2940 atomic_type = ATOMIC_TYPE_UCHAR;
2942 case SPECIFIER_SHORT:
2943 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2944 case SPECIFIER_SHORT | SPECIFIER_INT:
2945 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2946 atomic_type = ATOMIC_TYPE_SHORT;
2948 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2949 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2950 atomic_type = ATOMIC_TYPE_USHORT;
2953 case SPECIFIER_SIGNED:
2954 case SPECIFIER_SIGNED | SPECIFIER_INT:
2955 atomic_type = ATOMIC_TYPE_INT;
2957 case SPECIFIER_UNSIGNED:
2958 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2959 atomic_type = ATOMIC_TYPE_UINT;
2961 case SPECIFIER_LONG:
2962 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2963 case SPECIFIER_LONG | SPECIFIER_INT:
2964 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2965 atomic_type = ATOMIC_TYPE_LONG;
2967 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2968 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2969 atomic_type = ATOMIC_TYPE_ULONG;
2972 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2973 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2974 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2975 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2977 atomic_type = ATOMIC_TYPE_LONGLONG;
2978 goto warn_about_long_long;
2980 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2981 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2983 atomic_type = ATOMIC_TYPE_ULONGLONG;
2984 warn_about_long_long:
2985 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2988 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2989 atomic_type = unsigned_int8_type_kind;
2992 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2993 atomic_type = unsigned_int16_type_kind;
2996 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2997 atomic_type = unsigned_int32_type_kind;
3000 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3001 atomic_type = unsigned_int64_type_kind;
3004 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3005 atomic_type = unsigned_int128_type_kind;
3008 case SPECIFIER_INT8:
3009 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3010 atomic_type = int8_type_kind;
3013 case SPECIFIER_INT16:
3014 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3015 atomic_type = int16_type_kind;
3018 case SPECIFIER_INT32:
3019 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3020 atomic_type = int32_type_kind;
3023 case SPECIFIER_INT64:
3024 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3025 atomic_type = int64_type_kind;
3028 case SPECIFIER_INT128:
3029 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3030 atomic_type = int128_type_kind;
3033 case SPECIFIER_FLOAT:
3034 atomic_type = ATOMIC_TYPE_FLOAT;
3036 case SPECIFIER_DOUBLE:
3037 atomic_type = ATOMIC_TYPE_DOUBLE;
3039 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3040 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3042 case SPECIFIER_BOOL:
3043 atomic_type = ATOMIC_TYPE_BOOL;
3045 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3046 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3047 atomic_type = ATOMIC_TYPE_FLOAT;
3049 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3050 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3051 atomic_type = ATOMIC_TYPE_DOUBLE;
3053 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3054 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3055 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3058 /* invalid specifier combination, give an error message */
3059 source_position_t const* const pos = &specifiers->source_position;
3060 if (type_specifiers == 0) {
3062 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3063 if (!(c_mode & _CXX) && !strict_mode) {
3064 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3065 atomic_type = ATOMIC_TYPE_INT;
3068 errorf(pos, "no type specifiers given in declaration");
3071 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3072 (type_specifiers & SPECIFIER_UNSIGNED)) {
3073 errorf(pos, "signed and unsigned specifiers given");
3074 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3075 errorf(pos, "only integer types can be signed or unsigned");
3077 errorf(pos, "multiple datatypes in declaration");
3083 if (type_specifiers & SPECIFIER_COMPLEX) {
3084 type = allocate_type_zero(TYPE_COMPLEX);
3085 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3086 type = allocate_type_zero(TYPE_IMAGINARY);
3088 type = allocate_type_zero(TYPE_ATOMIC);
3090 type->atomic.akind = atomic_type;
3092 } else if (type_specifiers != 0) {
3093 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3096 /* FIXME: check type qualifiers here */
3097 type->base.qualifiers = qualifiers;
3100 type = identify_new_type(type);
3102 type = typehash_insert(type);
3105 if (specifiers->attributes != NULL)
3106 type = handle_type_attributes(specifiers->attributes, type);
3107 specifiers->type = type;
3111 specifiers->type = type_error_type;
3114 static type_qualifiers_t parse_type_qualifiers(void)
3116 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3119 switch (token.kind) {
3120 /* type qualifiers */
3121 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3122 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3123 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3124 /* microsoft extended type modifiers */
3125 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3126 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3127 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3128 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3129 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3138 * Parses an K&R identifier list
3140 static void parse_identifier_list(scope_t *scope)
3142 assert(token.kind == T_IDENTIFIER);
3144 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3145 /* a K&R parameter has no type, yet */
3149 append_entity(scope, entity);
3150 } while (next_if(',') && token.kind == T_IDENTIFIER);
3153 static entity_t *parse_parameter(void)
3155 declaration_specifiers_t specifiers;
3156 parse_declaration_specifiers(&specifiers);
3158 entity_t *entity = parse_declarator(&specifiers,
3159 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3160 anonymous_entity = NULL;
3164 static void semantic_parameter_incomplete(const entity_t *entity)
3166 assert(entity->kind == ENTITY_PARAMETER);
3168 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3169 * list in a function declarator that is part of a
3170 * definition of that function shall not have
3171 * incomplete type. */
3172 type_t *type = skip_typeref(entity->declaration.type);
3173 if (is_type_incomplete(type)) {
3174 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3178 static bool has_parameters(void)
3180 /* func(void) is not a parameter */
3181 if (look_ahead(1)->kind != ')')
3183 if (token.kind == T_IDENTIFIER) {
3184 entity_t const *const entity
3185 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3188 if (entity->kind != ENTITY_TYPEDEF)
3190 type_t const *const type = skip_typeref(entity->typedefe.type);
3191 if (!is_type_void(type))
3193 if (c_mode & _CXX) {
3194 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3195 * is not allowed. */
3196 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3197 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3198 /* §6.7.5.3:10 Qualification is not allowed here. */
3199 errorf(HERE, "'void' as parameter must not have type qualifiers");
3201 } else if (token.kind != T_void) {
3209 * Parses function type parameters (and optionally creates variable_t entities
3210 * for them in a scope)
3212 static void parse_parameters(function_type_t *type, scope_t *scope)
3215 add_anchor_token(')');
3216 int saved_comma_state = save_and_reset_anchor_state(',');
3218 if (token.kind == T_IDENTIFIER
3219 && !is_typedef_symbol(token.identifier.symbol)) {
3220 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3221 if (la1_type == ',' || la1_type == ')') {
3222 type->kr_style_parameters = true;
3223 parse_identifier_list(scope);
3224 goto parameters_finished;
3228 if (token.kind == ')') {
3229 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3230 if (!(c_mode & _CXX))
3231 type->unspecified_parameters = true;
3232 } else if (has_parameters()) {
3233 function_parameter_t **anchor = &type->parameters;
3235 switch (token.kind) {
3238 type->variadic = true;
3239 goto parameters_finished;
3244 entity_t *entity = parse_parameter();
3245 if (entity->kind == ENTITY_TYPEDEF) {
3246 errorf(&entity->base.source_position,
3247 "typedef not allowed as function parameter");
3250 assert(is_declaration(entity));
3252 semantic_parameter_incomplete(entity);
3254 function_parameter_t *const parameter =
3255 allocate_parameter(entity->declaration.type);
3257 if (scope != NULL) {
3258 append_entity(scope, entity);
3261 *anchor = parameter;
3262 anchor = ¶meter->next;
3267 goto parameters_finished;
3269 } while (next_if(','));
3272 parameters_finished:
3273 rem_anchor_token(')');
3276 restore_anchor_state(',', saved_comma_state);
3279 typedef enum construct_type_kind_t {
3280 CONSTRUCT_POINTER = 1,
3281 CONSTRUCT_REFERENCE,
3284 } construct_type_kind_t;
3286 typedef union construct_type_t construct_type_t;
3288 typedef struct construct_type_base_t {
3289 construct_type_kind_t kind;
3290 source_position_t pos;
3291 construct_type_t *next;
3292 } construct_type_base_t;
3294 typedef struct parsed_pointer_t {
3295 construct_type_base_t base;
3296 type_qualifiers_t type_qualifiers;
3297 variable_t *base_variable; /**< MS __based extension. */
3300 typedef struct parsed_reference_t {
3301 construct_type_base_t base;
3302 } parsed_reference_t;
3304 typedef struct construct_function_type_t {
3305 construct_type_base_t base;
3306 type_t *function_type;
3307 } construct_function_type_t;
3309 typedef struct parsed_array_t {
3310 construct_type_base_t base;
3311 type_qualifiers_t type_qualifiers;
3317 union construct_type_t {
3318 construct_type_kind_t kind;
3319 construct_type_base_t base;
3320 parsed_pointer_t pointer;
3321 parsed_reference_t reference;
3322 construct_function_type_t function;
3323 parsed_array_t array;
3326 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3328 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3329 memset(cons, 0, size);
3331 cons->base.pos = *HERE;
3336 static construct_type_t *parse_pointer_declarator(void)
3338 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3340 cons->pointer.type_qualifiers = parse_type_qualifiers();
3341 //cons->pointer.base_variable = base_variable;
3346 /* ISO/IEC 14882:1998(E) §8.3.2 */
3347 static construct_type_t *parse_reference_declarator(void)
3349 if (!(c_mode & _CXX))
3350 errorf(HERE, "references are only available for C++");
3352 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3359 static construct_type_t *parse_array_declarator(void)
3361 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3362 parsed_array_t *const array = &cons->array;
3365 add_anchor_token(']');
3367 bool is_static = next_if(T_static);
3369 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3372 is_static = next_if(T_static);
3374 array->type_qualifiers = type_qualifiers;
3375 array->is_static = is_static;
3377 expression_t *size = NULL;
3378 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3379 array->is_variable = true;
3381 } else if (token.kind != ']') {
3382 size = parse_assignment_expression();
3384 /* §6.7.5.2:1 Array size must have integer type */
3385 type_t *const orig_type = size->base.type;
3386 type_t *const type = skip_typeref(orig_type);
3387 if (!is_type_integer(type) && is_type_valid(type)) {
3388 errorf(&size->base.source_position,
3389 "array size '%E' must have integer type but has type '%T'",
3394 mark_vars_read(size, NULL);
3397 if (is_static && size == NULL)
3398 errorf(&array->base.pos, "static array parameters require a size");
3400 rem_anchor_token(']');
3406 static construct_type_t *parse_function_declarator(scope_t *scope)
3408 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3410 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3411 function_type_t *ftype = &type->function;
3413 ftype->linkage = current_linkage;
3414 ftype->calling_convention = CC_DEFAULT;
3416 parse_parameters(ftype, scope);
3418 cons->function.function_type = type;
3423 typedef struct parse_declarator_env_t {
3424 bool may_be_abstract : 1;
3425 bool must_be_abstract : 1;
3426 decl_modifiers_t modifiers;
3428 source_position_t source_position;
3430 attribute_t *attributes;
3431 } parse_declarator_env_t;
3434 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3436 /* construct a single linked list of construct_type_t's which describe
3437 * how to construct the final declarator type */
3438 construct_type_t *first = NULL;
3439 construct_type_t **anchor = &first;
3441 env->attributes = parse_attributes(env->attributes);
3444 construct_type_t *type;
3445 //variable_t *based = NULL; /* MS __based extension */
3446 switch (token.kind) {
3448 type = parse_reference_declarator();
3452 panic("based not supported anymore");
3457 type = parse_pointer_declarator();
3461 goto ptr_operator_end;
3465 anchor = &type->base.next;
3467 /* TODO: find out if this is correct */
3468 env->attributes = parse_attributes(env->attributes);
3472 construct_type_t *inner_types = NULL;
3474 switch (token.kind) {
3476 if (env->must_be_abstract) {
3477 errorf(HERE, "no identifier expected in typename");
3479 env->symbol = token.identifier.symbol;
3480 env->source_position = token.base.source_position;
3486 /* Parenthesized declarator or function declarator? */
3487 token_t const *const la1 = look_ahead(1);
3488 switch (la1->kind) {
3490 if (is_typedef_symbol(la1->identifier.symbol)) {
3492 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3493 * interpreted as ``function with no parameter specification'', rather
3494 * than redundant parentheses around the omitted identifier. */
3496 /* Function declarator. */
3497 if (!env->may_be_abstract) {
3498 errorf(HERE, "function declarator must have a name");
3505 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3506 /* Paranthesized declarator. */
3508 add_anchor_token(')');
3509 inner_types = parse_inner_declarator(env);
3510 if (inner_types != NULL) {
3511 /* All later declarators only modify the return type */
3512 env->must_be_abstract = true;
3514 rem_anchor_token(')');
3523 if (env->may_be_abstract)
3525 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3530 construct_type_t **const p = anchor;
3533 construct_type_t *type;
3534 switch (token.kind) {
3536 scope_t *scope = NULL;
3537 if (!env->must_be_abstract) {
3538 scope = &env->parameters;
3541 type = parse_function_declarator(scope);
3545 type = parse_array_declarator();
3548 goto declarator_finished;
3551 /* insert in the middle of the list (at p) */
3552 type->base.next = *p;
3555 anchor = &type->base.next;
3558 declarator_finished:
3559 /* append inner_types at the end of the list, we don't to set anchor anymore
3560 * as it's not needed anymore */
3561 *anchor = inner_types;
3566 static type_t *construct_declarator_type(construct_type_t *construct_list,
3569 construct_type_t *iter = construct_list;
3570 for (; iter != NULL; iter = iter->base.next) {
3571 source_position_t const* const pos = &iter->base.pos;
3572 switch (iter->kind) {
3573 case CONSTRUCT_FUNCTION: {
3574 construct_function_type_t *function = &iter->function;
3575 type_t *function_type = function->function_type;
3577 function_type->function.return_type = type;
3579 type_t *skipped_return_type = skip_typeref(type);
3581 if (is_type_function(skipped_return_type)) {
3582 errorf(pos, "function returning function is not allowed");
3583 } else if (is_type_array(skipped_return_type)) {
3584 errorf(pos, "function returning array is not allowed");
3586 if (skipped_return_type->base.qualifiers != 0) {
3587 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3591 /* The function type was constructed earlier. Freeing it here will
3592 * destroy other types. */
3593 type = typehash_insert(function_type);
3597 case CONSTRUCT_POINTER: {
3598 if (is_type_reference(skip_typeref(type)))
3599 errorf(pos, "cannot declare a pointer to reference");
3601 parsed_pointer_t *pointer = &iter->pointer;
3602 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3606 case CONSTRUCT_REFERENCE:
3607 if (is_type_reference(skip_typeref(type)))
3608 errorf(pos, "cannot declare a reference to reference");
3610 type = make_reference_type(type);
3613 case CONSTRUCT_ARRAY: {
3614 if (is_type_reference(skip_typeref(type)))
3615 errorf(pos, "cannot declare an array of references");
3617 parsed_array_t *array = &iter->array;
3618 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3620 expression_t *size_expression = array->size;
3621 if (size_expression != NULL) {
3623 = create_implicit_cast(size_expression, type_size_t);
3626 array_type->base.qualifiers = array->type_qualifiers;
3627 array_type->array.element_type = type;
3628 array_type->array.is_static = array->is_static;
3629 array_type->array.is_variable = array->is_variable;
3630 array_type->array.size_expression = size_expression;
3632 if (size_expression != NULL) {
3633 switch (is_constant_expression(size_expression)) {
3634 case EXPR_CLASS_CONSTANT: {
3635 long const size = fold_constant_to_int(size_expression);
3636 array_type->array.size = size;
3637 array_type->array.size_constant = true;
3638 /* §6.7.5.2:1 If the expression is a constant expression,
3639 * it shall have a value greater than zero. */
3641 errorf(&size_expression->base.source_position,
3642 "size of array must be greater than zero");
3643 } else if (size == 0 && !GNU_MODE) {
3644 errorf(&size_expression->base.source_position,
3645 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3650 case EXPR_CLASS_VARIABLE:
3651 array_type->array.is_vla = true;
3654 case EXPR_CLASS_ERROR:
3659 type_t *skipped_type = skip_typeref(type);
3661 if (is_type_incomplete(skipped_type)) {
3662 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3663 } else if (is_type_function(skipped_type)) {
3664 errorf(pos, "array of functions is not allowed");
3666 type = identify_new_type(array_type);
3670 internal_errorf(pos, "invalid type construction found");
3676 static type_t *automatic_type_conversion(type_t *orig_type);
3678 static type_t *semantic_parameter(const source_position_t *pos,
3680 const declaration_specifiers_t *specifiers,
3681 entity_t const *const param)
3683 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3684 * shall be adjusted to ``qualified pointer to type'',
3686 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3687 * type'' shall be adjusted to ``pointer to function
3688 * returning type'', as in 6.3.2.1. */
3689 type = automatic_type_conversion(type);
3691 if (specifiers->is_inline && is_type_valid(type)) {
3692 errorf(pos, "'%N' declared 'inline'", param);
3695 /* §6.9.1:6 The declarations in the declaration list shall contain
3696 * no storage-class specifier other than register and no
3697 * initializations. */
3698 if (specifiers->thread_local || (
3699 specifiers->storage_class != STORAGE_CLASS_NONE &&
3700 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3702 errorf(pos, "invalid storage class for '%N'", param);
3705 /* delay test for incomplete type, because we might have (void)
3706 * which is legal but incomplete... */
3711 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3712 declarator_flags_t flags)
3714 parse_declarator_env_t env;
3715 memset(&env, 0, sizeof(env));
3716 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3718 construct_type_t *construct_type = parse_inner_declarator(&env);
3720 construct_declarator_type(construct_type, specifiers->type);
3721 type_t *type = skip_typeref(orig_type);
3723 if (construct_type != NULL) {
3724 obstack_free(&temp_obst, construct_type);
3727 attribute_t *attributes = parse_attributes(env.attributes);
3728 /* append (shared) specifier attribute behind attributes of this
3730 attribute_t **anchor = &attributes;
3731 while (*anchor != NULL)
3732 anchor = &(*anchor)->next;
3733 *anchor = specifiers->attributes;
3736 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3737 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3738 entity->typedefe.type = orig_type;
3740 if (anonymous_entity != NULL) {
3741 if (is_type_compound(type)) {
3742 assert(anonymous_entity->compound.alias == NULL);
3743 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3744 anonymous_entity->kind == ENTITY_UNION);
3745 anonymous_entity->compound.alias = entity;
3746 anonymous_entity = NULL;
3747 } else if (is_type_enum(type)) {
3748 assert(anonymous_entity->enume.alias == NULL);
3749 assert(anonymous_entity->kind == ENTITY_ENUM);
3750 anonymous_entity->enume.alias = entity;
3751 anonymous_entity = NULL;
3755 /* create a declaration type entity */
3756 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3757 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3758 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3760 if (env.symbol != NULL) {
3761 if (specifiers->is_inline && is_type_valid(type)) {
3762 errorf(&env.source_position,
3763 "compound member '%Y' declared 'inline'", env.symbol);
3766 if (specifiers->thread_local ||
3767 specifiers->storage_class != STORAGE_CLASS_NONE) {
3768 errorf(&env.source_position,
3769 "compound member '%Y' must have no storage class",
3773 } else if (flags & DECL_IS_PARAMETER) {
3774 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3775 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3776 } else if (is_type_function(type)) {
3777 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3778 entity->function.is_inline = specifiers->is_inline;
3779 entity->function.elf_visibility = default_visibility;
3780 entity->function.parameters = env.parameters;
3782 if (env.symbol != NULL) {
3783 /* this needs fixes for C++ */
3784 bool in_function_scope = current_function != NULL;
3786 if (specifiers->thread_local || (
3787 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3788 specifiers->storage_class != STORAGE_CLASS_NONE &&
3789 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3791 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3795 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3796 entity->variable.elf_visibility = default_visibility;
3797 entity->variable.thread_local = specifiers->thread_local;
3799 if (env.symbol != NULL) {
3800 if (specifiers->is_inline && is_type_valid(type)) {
3801 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3804 bool invalid_storage_class = false;
3805 if (current_scope == file_scope) {
3806 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3807 specifiers->storage_class != STORAGE_CLASS_NONE &&
3808 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3809 invalid_storage_class = true;
3812 if (specifiers->thread_local &&
3813 specifiers->storage_class == STORAGE_CLASS_NONE) {
3814 invalid_storage_class = true;
3817 if (invalid_storage_class) {
3818 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3823 entity->declaration.type = orig_type;
3824 entity->declaration.alignment = get_type_alignment(orig_type);
3825 entity->declaration.modifiers = env.modifiers;
3826 entity->declaration.attributes = attributes;
3828 storage_class_t storage_class = specifiers->storage_class;
3829 entity->declaration.declared_storage_class = storage_class;
3831 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3832 storage_class = STORAGE_CLASS_AUTO;
3833 entity->declaration.storage_class = storage_class;
3836 if (attributes != NULL) {
3837 handle_entity_attributes(attributes, entity);
3840 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3841 adapt_special_functions(&entity->function);
3847 static type_t *parse_abstract_declarator(type_t *base_type)
3849 parse_declarator_env_t env;
3850 memset(&env, 0, sizeof(env));
3851 env.may_be_abstract = true;
3852 env.must_be_abstract = true;
3854 construct_type_t *construct_type = parse_inner_declarator(&env);
3856 type_t *result = construct_declarator_type(construct_type, base_type);
3857 if (construct_type != NULL) {
3858 obstack_free(&temp_obst, construct_type);
3860 result = handle_type_attributes(env.attributes, result);
3866 * Check if the declaration of main is suspicious. main should be a
3867 * function with external linkage, returning int, taking either zero
3868 * arguments, two, or three arguments of appropriate types, ie.
3870 * int main([ int argc, char **argv [, char **env ] ]).
3872 * @param decl the declaration to check
3873 * @param type the function type of the declaration
3875 static void check_main(const entity_t *entity)
3877 const source_position_t *pos = &entity->base.source_position;
3878 if (entity->kind != ENTITY_FUNCTION) {
3879 warningf(WARN_MAIN, pos, "'main' is not a function");
3883 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3884 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3887 type_t *type = skip_typeref(entity->declaration.type);
3888 assert(is_type_function(type));
3890 function_type_t const *const func_type = &type->function;
3891 type_t *const ret_type = func_type->return_type;
3892 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3893 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3895 const function_parameter_t *parm = func_type->parameters;
3897 type_t *const first_type = skip_typeref(parm->type);
3898 type_t *const first_type_unqual = get_unqualified_type(first_type);
3899 if (!types_compatible(first_type_unqual, type_int)) {
3900 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3904 type_t *const second_type = skip_typeref(parm->type);
3905 type_t *const second_type_unqual
3906 = get_unqualified_type(second_type);
3907 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3908 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3912 type_t *const third_type = skip_typeref(parm->type);
3913 type_t *const third_type_unqual
3914 = get_unqualified_type(third_type);
3915 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3916 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3920 goto warn_arg_count;
3924 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3930 * Check if a symbol is the equal to "main".
3932 static bool is_sym_main(const symbol_t *const sym)
3934 return streq(sym->string, "main");
3937 static void error_redefined_as_different_kind(const source_position_t *pos,
3938 const entity_t *old, entity_kind_t new_kind)
3940 char const *const what = get_entity_kind_name(new_kind);
3941 source_position_t const *const ppos = &old->base.source_position;
3942 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3945 static bool is_entity_valid(entity_t *const ent)
3947 if (is_declaration(ent)) {
3948 return is_type_valid(skip_typeref(ent->declaration.type));
3949 } else if (ent->kind == ENTITY_TYPEDEF) {
3950 return is_type_valid(skip_typeref(ent->typedefe.type));
3955 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3957 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3958 if (attributes_equal(tattr, attr))
3965 * test wether new_list contains any attributes not included in old_list
3967 static bool has_new_attributes(const attribute_t *old_list,
3968 const attribute_t *new_list)
3970 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3971 if (!contains_attribute(old_list, attr))
3978 * Merge in attributes from an attribute list (probably from a previous
3979 * declaration with the same name). Warning: destroys the old structure
3980 * of the attribute list - don't reuse attributes after this call.
3982 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3985 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3987 if (contains_attribute(decl->attributes, attr))
3990 /* move attribute to new declarations attributes list */
3991 attr->next = decl->attributes;
3992 decl->attributes = attr;
3997 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3998 * for various problems that occur for multiple definitions
4000 entity_t *record_entity(entity_t *entity, const bool is_definition)
4002 const symbol_t *const symbol = entity->base.symbol;
4003 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4004 const source_position_t *pos = &entity->base.source_position;
4006 /* can happen in error cases */
4010 entity_t *const previous_entity = get_entity(symbol, namespc);
4011 /* pushing the same entity twice will break the stack structure */
4012 assert(previous_entity != entity);
4014 if (entity->kind == ENTITY_FUNCTION) {
4015 type_t *const orig_type = entity->declaration.type;
4016 type_t *const type = skip_typeref(orig_type);
4018 assert(is_type_function(type));
4019 if (type->function.unspecified_parameters &&
4020 previous_entity == NULL &&
4021 !entity->declaration.implicit) {
4022 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4025 if (current_scope == file_scope && is_sym_main(symbol)) {
4030 if (is_declaration(entity) &&
4031 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4032 current_scope != file_scope &&
4033 !entity->declaration.implicit) {
4034 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4037 if (previous_entity != NULL) {
4038 source_position_t const *const ppos = &previous_entity->base.source_position;
4040 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4041 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4042 assert(previous_entity->kind == ENTITY_PARAMETER);
4043 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4047 if (previous_entity->base.parent_scope == current_scope) {
4048 if (previous_entity->kind != entity->kind) {
4049 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4050 error_redefined_as_different_kind(pos, previous_entity,
4055 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4056 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4059 if (previous_entity->kind == ENTITY_TYPEDEF) {
4060 type_t *const type = skip_typeref(entity->typedefe.type);
4061 type_t *const prev_type
4062 = skip_typeref(previous_entity->typedefe.type);
4063 if (c_mode & _CXX) {
4064 /* C++ allows double typedef if they are identical
4065 * (after skipping typedefs) */
4066 if (type == prev_type)
4069 /* GCC extension: redef in system headers is allowed */
4070 if ((pos->is_system_header || ppos->is_system_header) &&
4071 types_compatible(type, prev_type))
4074 errorf(pos, "redefinition of '%N' (declared %P)",
4079 /* at this point we should have only VARIABLES or FUNCTIONS */
4080 assert(is_declaration(previous_entity) && is_declaration(entity));
4082 declaration_t *const prev_decl = &previous_entity->declaration;
4083 declaration_t *const decl = &entity->declaration;
4085 /* can happen for K&R style declarations */
4086 if (prev_decl->type == NULL &&
4087 previous_entity->kind == ENTITY_PARAMETER &&
4088 entity->kind == ENTITY_PARAMETER) {
4089 prev_decl->type = decl->type;
4090 prev_decl->storage_class = decl->storage_class;
4091 prev_decl->declared_storage_class = decl->declared_storage_class;
4092 prev_decl->modifiers = decl->modifiers;
4093 return previous_entity;
4096 type_t *const type = skip_typeref(decl->type);
4097 type_t *const prev_type = skip_typeref(prev_decl->type);
4099 if (!types_compatible(type, prev_type)) {
4100 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4102 unsigned old_storage_class = prev_decl->storage_class;
4104 if (is_definition &&
4106 !(prev_decl->modifiers & DM_USED) &&
4107 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4108 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4111 storage_class_t new_storage_class = decl->storage_class;
4113 /* pretend no storage class means extern for function
4114 * declarations (except if the previous declaration is neither
4115 * none nor extern) */
4116 if (entity->kind == ENTITY_FUNCTION) {
4117 /* the previous declaration could have unspecified parameters or
4118 * be a typedef, so use the new type */
4119 if (prev_type->function.unspecified_parameters || is_definition)
4120 prev_decl->type = type;
4122 switch (old_storage_class) {
4123 case STORAGE_CLASS_NONE:
4124 old_storage_class = STORAGE_CLASS_EXTERN;
4127 case STORAGE_CLASS_EXTERN:
4128 if (is_definition) {
4129 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4130 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4132 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4133 new_storage_class = STORAGE_CLASS_EXTERN;
4140 } else if (is_type_incomplete(prev_type)) {
4141 prev_decl->type = type;
4144 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4145 new_storage_class == STORAGE_CLASS_EXTERN) {
4147 warn_redundant_declaration: ;
4149 = has_new_attributes(prev_decl->attributes,
4151 if (has_new_attrs) {
4152 merge_in_attributes(decl, prev_decl->attributes);
4153 } else if (!is_definition &&
4154 is_type_valid(prev_type) &&
4155 !pos->is_system_header) {
4156 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4158 } else if (current_function == NULL) {
4159 if (old_storage_class != STORAGE_CLASS_STATIC &&
4160 new_storage_class == STORAGE_CLASS_STATIC) {
4161 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4162 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4163 prev_decl->storage_class = STORAGE_CLASS_NONE;
4164 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4166 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4168 goto error_redeclaration;
4169 goto warn_redundant_declaration;
4171 } else if (is_type_valid(prev_type)) {
4172 if (old_storage_class == new_storage_class) {
4173 error_redeclaration:
4174 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4176 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4181 prev_decl->modifiers |= decl->modifiers;
4182 if (entity->kind == ENTITY_FUNCTION) {
4183 previous_entity->function.is_inline |= entity->function.is_inline;
4185 return previous_entity;
4189 if (is_warn_on(why = WARN_SHADOW) ||
4190 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4191 char const *const what = get_entity_kind_name(previous_entity->kind);
4192 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4196 if (entity->kind == ENTITY_FUNCTION) {
4197 if (is_definition &&
4198 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4199 !is_sym_main(symbol)) {
4200 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4201 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4203 goto warn_missing_declaration;
4206 } else if (entity->kind == ENTITY_VARIABLE) {
4207 if (current_scope == file_scope &&
4208 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4209 !entity->declaration.implicit) {
4210 warn_missing_declaration:
4211 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4216 assert(entity->base.parent_scope == NULL);
4217 assert(current_scope != NULL);
4219 entity->base.parent_scope = current_scope;
4220 environment_push(entity);
4221 append_entity(current_scope, entity);
4226 static void parser_error_multiple_definition(entity_t *entity,
4227 const source_position_t *source_position)
4229 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4230 entity->base.symbol, &entity->base.source_position);
4233 static bool is_declaration_specifier(const token_t *token)
4235 switch (token->kind) {
4239 return is_typedef_symbol(token->identifier.symbol);
4246 static void parse_init_declarator_rest(entity_t *entity)
4248 type_t *orig_type = type_error_type;
4250 if (entity->base.kind == ENTITY_TYPEDEF) {
4251 source_position_t const *const pos = &entity->base.source_position;
4252 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4254 assert(is_declaration(entity));
4255 orig_type = entity->declaration.type;
4258 type_t *type = skip_typeref(orig_type);
4260 if (entity->kind == ENTITY_VARIABLE
4261 && entity->variable.initializer != NULL) {
4262 parser_error_multiple_definition(entity, HERE);
4266 declaration_t *const declaration = &entity->declaration;
4267 bool must_be_constant = false;
4268 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4269 entity->base.parent_scope == file_scope) {
4270 must_be_constant = true;
4273 if (is_type_function(type)) {
4274 source_position_t const *const pos = &entity->base.source_position;
4275 errorf(pos, "'%N' is initialized like a variable", entity);
4276 orig_type = type_error_type;
4279 parse_initializer_env_t env;
4280 env.type = orig_type;
4281 env.must_be_constant = must_be_constant;
4282 env.entity = entity;
4284 initializer_t *initializer = parse_initializer(&env);
4286 if (entity->kind == ENTITY_VARIABLE) {
4287 /* §6.7.5:22 array initializers for arrays with unknown size
4288 * determine the array type size */
4289 declaration->type = env.type;
4290 entity->variable.initializer = initializer;
4294 /* parse rest of a declaration without any declarator */
4295 static void parse_anonymous_declaration_rest(
4296 const declaration_specifiers_t *specifiers)
4299 anonymous_entity = NULL;
4301 source_position_t const *const pos = &specifiers->source_position;
4302 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4303 specifiers->thread_local) {
4304 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4307 type_t *type = specifiers->type;
4308 switch (type->kind) {
4309 case TYPE_COMPOUND_STRUCT:
4310 case TYPE_COMPOUND_UNION: {
4311 if (type->compound.compound->base.symbol == NULL) {
4312 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4321 warningf(WARN_OTHER, pos, "empty declaration");
4326 static void check_variable_type_complete(entity_t *ent)
4328 if (ent->kind != ENTITY_VARIABLE)
4331 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4332 * type for the object shall be complete [...] */
4333 declaration_t *decl = &ent->declaration;
4334 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4335 decl->storage_class == STORAGE_CLASS_STATIC)
4338 type_t *const type = skip_typeref(decl->type);
4339 if (!is_type_incomplete(type))
4342 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4343 * are given length one. */
4344 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4345 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4349 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4353 static void parse_declaration_rest(entity_t *ndeclaration,
4354 const declaration_specifiers_t *specifiers,
4355 parsed_declaration_func finished_declaration,
4356 declarator_flags_t flags)
4358 add_anchor_token(';');
4359 add_anchor_token(',');
4361 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4363 if (token.kind == '=') {
4364 parse_init_declarator_rest(entity);
4365 } else if (entity->kind == ENTITY_VARIABLE) {
4366 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4367 * [...] where the extern specifier is explicitly used. */
4368 declaration_t *decl = &entity->declaration;
4369 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4370 is_type_reference(skip_typeref(decl->type))) {
4371 source_position_t const *const pos = &entity->base.source_position;
4372 errorf(pos, "reference '%#N' must be initialized", entity);
4376 check_variable_type_complete(entity);
4381 add_anchor_token('=');
4382 ndeclaration = parse_declarator(specifiers, flags);
4383 rem_anchor_token('=');
4385 rem_anchor_token(',');
4386 rem_anchor_token(';');
4389 anonymous_entity = NULL;
4392 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4394 symbol_t *symbol = entity->base.symbol;
4398 assert(entity->base.namespc == NAMESPACE_NORMAL);
4399 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4400 if (previous_entity == NULL
4401 || previous_entity->base.parent_scope != current_scope) {
4402 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4407 if (is_definition) {
4408 errorf(HERE, "'%N' is initialised", entity);
4411 return record_entity(entity, false);
4414 static void parse_declaration(parsed_declaration_func finished_declaration,
4415 declarator_flags_t flags)
4417 add_anchor_token(';');
4418 declaration_specifiers_t specifiers;
4419 parse_declaration_specifiers(&specifiers);
4420 rem_anchor_token(';');
4422 if (token.kind == ';') {
4423 parse_anonymous_declaration_rest(&specifiers);
4425 entity_t *entity = parse_declarator(&specifiers, flags);
4426 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4431 static type_t *get_default_promoted_type(type_t *orig_type)
4433 type_t *result = orig_type;
4435 type_t *type = skip_typeref(orig_type);
4436 if (is_type_integer(type)) {
4437 result = promote_integer(type);
4438 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4439 result = type_double;
4445 static void parse_kr_declaration_list(entity_t *entity)
4447 if (entity->kind != ENTITY_FUNCTION)
4450 type_t *type = skip_typeref(entity->declaration.type);
4451 assert(is_type_function(type));
4452 if (!type->function.kr_style_parameters)
4455 add_anchor_token('{');
4457 PUSH_SCOPE(&entity->function.parameters);
4459 entity_t *parameter = entity->function.parameters.entities;
4460 for ( ; parameter != NULL; parameter = parameter->base.next) {
4461 assert(parameter->base.parent_scope == NULL);
4462 parameter->base.parent_scope = current_scope;
4463 environment_push(parameter);
4466 /* parse declaration list */
4468 switch (token.kind) {
4470 /* This covers symbols, which are no type, too, and results in
4471 * better error messages. The typical cases are misspelled type
4472 * names and missing includes. */
4474 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4484 /* update function type */
4485 type_t *new_type = duplicate_type(type);
4487 function_parameter_t *parameters = NULL;
4488 function_parameter_t **anchor = ¶meters;
4490 /* did we have an earlier prototype? */
4491 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4492 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4495 function_parameter_t *proto_parameter = NULL;
4496 if (proto_type != NULL) {
4497 type_t *proto_type_type = proto_type->declaration.type;
4498 proto_parameter = proto_type_type->function.parameters;
4499 /* If a K&R function definition has a variadic prototype earlier, then
4500 * make the function definition variadic, too. This should conform to
4501 * §6.7.5.3:15 and §6.9.1:8. */
4502 new_type->function.variadic = proto_type_type->function.variadic;
4504 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4506 new_type->function.unspecified_parameters = true;
4509 bool need_incompatible_warning = false;
4510 parameter = entity->function.parameters.entities;
4511 for (; parameter != NULL; parameter = parameter->base.next,
4513 proto_parameter == NULL ? NULL : proto_parameter->next) {
4514 if (parameter->kind != ENTITY_PARAMETER)
4517 type_t *parameter_type = parameter->declaration.type;
4518 if (parameter_type == NULL) {
4519 source_position_t const* const pos = ¶meter->base.source_position;
4521 errorf(pos, "no type specified for function '%N'", parameter);
4522 parameter_type = type_error_type;
4524 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4525 parameter_type = type_int;
4527 parameter->declaration.type = parameter_type;
4530 semantic_parameter_incomplete(parameter);
4532 /* we need the default promoted types for the function type */
4533 type_t *not_promoted = parameter_type;
4534 parameter_type = get_default_promoted_type(parameter_type);
4536 /* gcc special: if the type of the prototype matches the unpromoted
4537 * type don't promote */
4538 if (!strict_mode && proto_parameter != NULL) {
4539 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4540 type_t *promo_skip = skip_typeref(parameter_type);
4541 type_t *param_skip = skip_typeref(not_promoted);
4542 if (!types_compatible(proto_p_type, promo_skip)
4543 && types_compatible(proto_p_type, param_skip)) {
4545 need_incompatible_warning = true;
4546 parameter_type = not_promoted;
4549 function_parameter_t *const function_parameter
4550 = allocate_parameter(parameter_type);
4552 *anchor = function_parameter;
4553 anchor = &function_parameter->next;
4556 new_type->function.parameters = parameters;
4557 new_type = identify_new_type(new_type);
4559 if (need_incompatible_warning) {
4560 symbol_t const *const sym = entity->base.symbol;
4561 source_position_t const *const pos = &entity->base.source_position;
4562 source_position_t const *const ppos = &proto_type->base.source_position;
4563 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4565 entity->declaration.type = new_type;
4567 rem_anchor_token('{');
4570 static bool first_err = true;
4573 * When called with first_err set, prints the name of the current function,
4576 static void print_in_function(void)
4580 char const *const file = current_function->base.base.source_position.input_name;
4581 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4586 * Check if all labels are defined in the current function.
4587 * Check if all labels are used in the current function.
4589 static void check_labels(void)
4591 for (const goto_statement_t *goto_statement = goto_first;
4592 goto_statement != NULL;
4593 goto_statement = goto_statement->next) {
4594 label_t *label = goto_statement->label;
4595 if (label->base.source_position.input_name == NULL) {
4596 print_in_function();
4597 source_position_t const *const pos = &goto_statement->base.source_position;
4598 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4602 if (is_warn_on(WARN_UNUSED_LABEL)) {
4603 for (const label_statement_t *label_statement = label_first;
4604 label_statement != NULL;
4605 label_statement = label_statement->next) {
4606 label_t *label = label_statement->label;
4608 if (! label->used) {
4609 print_in_function();
4610 source_position_t const *const pos = &label_statement->base.source_position;
4611 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4617 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4619 entity_t const *const end = last != NULL ? last->base.next : NULL;
4620 for (; entity != end; entity = entity->base.next) {
4621 if (!is_declaration(entity))
4624 declaration_t *declaration = &entity->declaration;
4625 if (declaration->implicit)
4628 if (!declaration->used) {
4629 print_in_function();
4630 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4631 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4632 print_in_function();
4633 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4638 static void check_unused_variables(statement_t *const stmt, void *const env)
4642 switch (stmt->kind) {
4643 case STATEMENT_DECLARATION: {
4644 declaration_statement_t const *const decls = &stmt->declaration;
4645 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4650 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4659 * Check declarations of current_function for unused entities.
4661 static void check_declarations(void)
4663 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4664 const scope_t *scope = ¤t_function->parameters;
4666 /* do not issue unused warnings for main */
4667 if (!is_sym_main(current_function->base.base.symbol)) {
4668 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4671 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4672 walk_statements(current_function->statement, check_unused_variables,
4677 static int determine_truth(expression_t const* const cond)
4680 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4681 fold_constant_to_bool(cond) ? 1 :
4685 static void check_reachable(statement_t *);
4686 static bool reaches_end;
4688 static bool expression_returns(expression_t const *const expr)
4690 switch (expr->kind) {
4692 expression_t const *const func = expr->call.function;
4693 type_t const *const type = skip_typeref(func->base.type);
4694 if (type->kind == TYPE_POINTER) {
4695 type_t const *const points_to
4696 = skip_typeref(type->pointer.points_to);
4697 if (points_to->kind == TYPE_FUNCTION
4698 && points_to->function.modifiers & DM_NORETURN)
4702 if (!expression_returns(func))
4705 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4706 if (!expression_returns(arg->expression))
4713 case EXPR_REFERENCE:
4714 case EXPR_ENUM_CONSTANT:
4715 case EXPR_LITERAL_CASES:
4716 case EXPR_STRING_LITERAL:
4717 case EXPR_WIDE_STRING_LITERAL:
4718 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4719 case EXPR_LABEL_ADDRESS:
4720 case EXPR_CLASSIFY_TYPE:
4721 case EXPR_SIZEOF: // TODO handle obscure VLA case
4724 case EXPR_BUILTIN_CONSTANT_P:
4725 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4730 case EXPR_STATEMENT: {
4731 bool old_reaches_end = reaches_end;
4732 reaches_end = false;
4733 check_reachable(expr->statement.statement);
4734 bool returns = reaches_end;
4735 reaches_end = old_reaches_end;
4739 case EXPR_CONDITIONAL:
4740 // TODO handle constant expression
4742 if (!expression_returns(expr->conditional.condition))
4745 if (expr->conditional.true_expression != NULL
4746 && expression_returns(expr->conditional.true_expression))
4749 return expression_returns(expr->conditional.false_expression);
4752 return expression_returns(expr->select.compound);
4754 case EXPR_ARRAY_ACCESS:
4756 expression_returns(expr->array_access.array_ref) &&
4757 expression_returns(expr->array_access.index);
4760 return expression_returns(expr->va_starte.ap);
4763 return expression_returns(expr->va_arge.ap);
4766 return expression_returns(expr->va_copye.src);
4768 case EXPR_UNARY_CASES_MANDATORY:
4769 return expression_returns(expr->unary.value);
4771 case EXPR_UNARY_THROW:
4774 case EXPR_BINARY_CASES:
4775 // TODO handle constant lhs of && and ||
4777 expression_returns(expr->binary.left) &&
4778 expression_returns(expr->binary.right);
4781 panic("unhandled expression");
4784 static bool initializer_returns(initializer_t const *const init)
4786 switch (init->kind) {
4787 case INITIALIZER_VALUE:
4788 return expression_returns(init->value.value);
4790 case INITIALIZER_LIST: {
4791 initializer_t * const* i = init->list.initializers;
4792 initializer_t * const* const end = i + init->list.len;
4793 bool returns = true;
4794 for (; i != end; ++i) {
4795 if (!initializer_returns(*i))
4801 case INITIALIZER_STRING:
4802 case INITIALIZER_WIDE_STRING:
4803 case INITIALIZER_DESIGNATOR: // designators have no payload
4806 panic("unhandled initializer");
4809 static bool noreturn_candidate;
4811 static void check_reachable(statement_t *const stmt)
4813 if (stmt->base.reachable)
4815 if (stmt->kind != STATEMENT_DO_WHILE)
4816 stmt->base.reachable = true;
4818 statement_t *last = stmt;
4820 switch (stmt->kind) {
4821 case STATEMENT_ERROR:
4822 case STATEMENT_EMPTY:
4824 next = stmt->base.next;
4827 case STATEMENT_DECLARATION: {
4828 declaration_statement_t const *const decl = &stmt->declaration;
4829 entity_t const * ent = decl->declarations_begin;
4830 entity_t const *const last_decl = decl->declarations_end;
4832 for (;; ent = ent->base.next) {
4833 if (ent->kind == ENTITY_VARIABLE &&
4834 ent->variable.initializer != NULL &&
4835 !initializer_returns(ent->variable.initializer)) {
4838 if (ent == last_decl)
4842 next = stmt->base.next;
4846 case STATEMENT_COMPOUND:
4847 next = stmt->compound.statements;
4849 next = stmt->base.next;
4852 case STATEMENT_RETURN: {
4853 expression_t const *const val = stmt->returns.value;
4854 if (val == NULL || expression_returns(val))
4855 noreturn_candidate = false;
4859 case STATEMENT_IF: {
4860 if_statement_t const *const ifs = &stmt->ifs;
4861 expression_t const *const cond = ifs->condition;
4863 if (!expression_returns(cond))
4866 int const val = determine_truth(cond);
4869 check_reachable(ifs->true_statement);
4874 if (ifs->false_statement != NULL) {
4875 check_reachable(ifs->false_statement);
4879 next = stmt->base.next;
4883 case STATEMENT_SWITCH: {
4884 switch_statement_t const *const switchs = &stmt->switchs;
4885 expression_t const *const expr = switchs->expression;
4887 if (!expression_returns(expr))
4890 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4891 long const val = fold_constant_to_int(expr);
4892 case_label_statement_t * defaults = NULL;
4893 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4894 if (i->expression == NULL) {
4899 if (i->first_case <= val && val <= i->last_case) {
4900 check_reachable((statement_t*)i);
4905 if (defaults != NULL) {
4906 check_reachable((statement_t*)defaults);
4910 bool has_default = false;
4911 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4912 if (i->expression == NULL)
4915 check_reachable((statement_t*)i);
4922 next = stmt->base.next;
4926 case STATEMENT_EXPRESSION: {
4927 /* Check for noreturn function call */
4928 expression_t const *const expr = stmt->expression.expression;
4929 if (!expression_returns(expr))
4932 next = stmt->base.next;
4936 case STATEMENT_CONTINUE:
4937 for (statement_t *parent = stmt;;) {
4938 parent = parent->base.parent;
4939 if (parent == NULL) /* continue not within loop */
4943 switch (parent->kind) {
4944 case STATEMENT_WHILE: goto continue_while;
4945 case STATEMENT_DO_WHILE: goto continue_do_while;
4946 case STATEMENT_FOR: goto continue_for;
4952 case STATEMENT_BREAK:
4953 for (statement_t *parent = stmt;;) {
4954 parent = parent->base.parent;
4955 if (parent == NULL) /* break not within loop/switch */
4958 switch (parent->kind) {
4959 case STATEMENT_SWITCH:
4960 case STATEMENT_WHILE:
4961 case STATEMENT_DO_WHILE:
4964 next = parent->base.next;
4965 goto found_break_parent;
4973 case STATEMENT_COMPUTED_GOTO: {
4974 if (!expression_returns(stmt->computed_goto.expression))
4977 statement_t *parent = stmt->base.parent;
4978 if (parent == NULL) /* top level goto */
4984 case STATEMENT_GOTO:
4985 next = stmt->gotos.label->statement;
4986 if (next == NULL) /* missing label */
4990 case STATEMENT_LABEL:
4991 next = stmt->label.statement;
4994 case STATEMENT_CASE_LABEL:
4995 next = stmt->case_label.statement;
4998 case STATEMENT_WHILE: {
4999 while_statement_t const *const whiles = &stmt->whiles;
5000 expression_t const *const cond = whiles->condition;
5002 if (!expression_returns(cond))
5005 int const val = determine_truth(cond);
5008 check_reachable(whiles->body);
5013 next = stmt->base.next;
5017 case STATEMENT_DO_WHILE:
5018 next = stmt->do_while.body;
5021 case STATEMENT_FOR: {
5022 for_statement_t *const fors = &stmt->fors;
5024 if (fors->condition_reachable)
5026 fors->condition_reachable = true;
5028 expression_t const *const cond = fors->condition;
5033 } else if (expression_returns(cond)) {
5034 val = determine_truth(cond);
5040 check_reachable(fors->body);
5045 next = stmt->base.next;
5049 case STATEMENT_MS_TRY: {
5050 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5051 check_reachable(ms_try->try_statement);
5052 next = ms_try->final_statement;
5056 case STATEMENT_LEAVE: {
5057 statement_t *parent = stmt;
5059 parent = parent->base.parent;
5060 if (parent == NULL) /* __leave not within __try */
5063 if (parent->kind == STATEMENT_MS_TRY) {
5065 next = parent->ms_try.final_statement;
5073 panic("invalid statement kind");
5076 while (next == NULL) {
5077 next = last->base.parent;
5079 noreturn_candidate = false;
5081 type_t *const type = skip_typeref(current_function->base.type);
5082 assert(is_type_function(type));
5083 type_t *const ret = skip_typeref(type->function.return_type);
5084 if (!is_type_void(ret) &&
5085 is_type_valid(ret) &&
5086 !is_sym_main(current_function->base.base.symbol)) {
5087 source_position_t const *const pos = &stmt->base.source_position;
5088 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5093 switch (next->kind) {
5094 case STATEMENT_ERROR:
5095 case STATEMENT_EMPTY:
5096 case STATEMENT_DECLARATION:
5097 case STATEMENT_EXPRESSION:
5099 case STATEMENT_RETURN:
5100 case STATEMENT_CONTINUE:
5101 case STATEMENT_BREAK:
5102 case STATEMENT_COMPUTED_GOTO:
5103 case STATEMENT_GOTO:
5104 case STATEMENT_LEAVE:
5105 panic("invalid control flow in function");
5107 case STATEMENT_COMPOUND:
5108 if (next->compound.stmt_expr) {
5114 case STATEMENT_SWITCH:
5115 case STATEMENT_LABEL:
5116 case STATEMENT_CASE_LABEL:
5118 next = next->base.next;
5121 case STATEMENT_WHILE: {
5123 if (next->base.reachable)
5125 next->base.reachable = true;
5127 while_statement_t const *const whiles = &next->whiles;
5128 expression_t const *const cond = whiles->condition;
5130 if (!expression_returns(cond))
5133 int const val = determine_truth(cond);
5136 check_reachable(whiles->body);
5142 next = next->base.next;
5146 case STATEMENT_DO_WHILE: {
5148 if (next->base.reachable)
5150 next->base.reachable = true;
5152 do_while_statement_t const *const dw = &next->do_while;
5153 expression_t const *const cond = dw->condition;
5155 if (!expression_returns(cond))
5158 int const val = determine_truth(cond);
5161 check_reachable(dw->body);
5167 next = next->base.next;
5171 case STATEMENT_FOR: {
5173 for_statement_t *const fors = &next->fors;
5175 fors->step_reachable = true;
5177 if (fors->condition_reachable)
5179 fors->condition_reachable = true;
5181 expression_t const *const cond = fors->condition;
5186 } else if (expression_returns(cond)) {
5187 val = determine_truth(cond);
5193 check_reachable(fors->body);
5199 next = next->base.next;
5203 case STATEMENT_MS_TRY:
5205 next = next->ms_try.final_statement;
5210 check_reachable(next);
5213 static void check_unreachable(statement_t* const stmt, void *const env)
5217 switch (stmt->kind) {
5218 case STATEMENT_DO_WHILE:
5219 if (!stmt->base.reachable) {
5220 expression_t const *const cond = stmt->do_while.condition;
5221 if (determine_truth(cond) >= 0) {
5222 source_position_t const *const pos = &cond->base.source_position;
5223 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5228 case STATEMENT_FOR: {
5229 for_statement_t const* const fors = &stmt->fors;
5231 // if init and step are unreachable, cond is unreachable, too
5232 if (!stmt->base.reachable && !fors->step_reachable) {
5233 goto warn_unreachable;
5235 if (!stmt->base.reachable && fors->initialisation != NULL) {
5236 source_position_t const *const pos = &fors->initialisation->base.source_position;
5237 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5240 if (!fors->condition_reachable && fors->condition != NULL) {
5241 source_position_t const *const pos = &fors->condition->base.source_position;
5242 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5245 if (!fors->step_reachable && fors->step != NULL) {
5246 source_position_t const *const pos = &fors->step->base.source_position;
5247 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5253 case STATEMENT_COMPOUND:
5254 if (stmt->compound.statements != NULL)
5256 goto warn_unreachable;
5258 case STATEMENT_DECLARATION: {
5259 /* Only warn if there is at least one declarator with an initializer.
5260 * This typically occurs in switch statements. */
5261 declaration_statement_t const *const decl = &stmt->declaration;
5262 entity_t const * ent = decl->declarations_begin;
5263 entity_t const *const last = decl->declarations_end;
5265 for (;; ent = ent->base.next) {
5266 if (ent->kind == ENTITY_VARIABLE &&
5267 ent->variable.initializer != NULL) {
5268 goto warn_unreachable;
5278 if (!stmt->base.reachable) {
5279 source_position_t const *const pos = &stmt->base.source_position;
5280 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5286 static bool is_main(entity_t *entity)
5288 static symbol_t *sym_main = NULL;
5289 if (sym_main == NULL) {
5290 sym_main = symbol_table_insert("main");
5293 if (entity->base.symbol != sym_main)
5295 /* must be in outermost scope */
5296 if (entity->base.parent_scope != file_scope)
5302 static void parse_external_declaration(void)
5304 /* function-definitions and declarations both start with declaration
5306 add_anchor_token(';');
5307 declaration_specifiers_t specifiers;
5308 parse_declaration_specifiers(&specifiers);
5309 rem_anchor_token(';');
5311 /* must be a declaration */
5312 if (token.kind == ';') {
5313 parse_anonymous_declaration_rest(&specifiers);
5317 add_anchor_token(',');
5318 add_anchor_token('=');
5319 add_anchor_token(';');
5320 add_anchor_token('{');
5322 /* declarator is common to both function-definitions and declarations */
5323 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5325 rem_anchor_token('{');
5326 rem_anchor_token(';');
5327 rem_anchor_token('=');
5328 rem_anchor_token(',');
5330 /* must be a declaration */
5331 switch (token.kind) {
5335 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5340 /* must be a function definition */
5341 parse_kr_declaration_list(ndeclaration);
5343 if (token.kind != '{') {
5344 parse_error_expected("while parsing function definition", '{', NULL);
5345 eat_until_matching_token(';');
5349 assert(is_declaration(ndeclaration));
5350 type_t *const orig_type = ndeclaration->declaration.type;
5351 type_t * type = skip_typeref(orig_type);
5353 if (!is_type_function(type)) {
5354 if (is_type_valid(type)) {
5355 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5361 source_position_t const *const pos = &ndeclaration->base.source_position;
5362 if (is_typeref(orig_type)) {
5364 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5367 if (is_type_compound(skip_typeref(type->function.return_type))) {
5368 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5370 if (type->function.unspecified_parameters) {
5371 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5373 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5376 /* §6.7.5.3:14 a function definition with () means no
5377 * parameters (and not unspecified parameters) */
5378 if (type->function.unspecified_parameters &&
5379 type->function.parameters == NULL) {
5380 type_t *copy = duplicate_type(type);
5381 copy->function.unspecified_parameters = false;
5382 type = identify_new_type(copy);
5384 ndeclaration->declaration.type = type;
5387 entity_t *const entity = record_entity(ndeclaration, true);
5388 assert(entity->kind == ENTITY_FUNCTION);
5389 assert(ndeclaration->kind == ENTITY_FUNCTION);
5391 function_t *const function = &entity->function;
5392 if (ndeclaration != entity) {
5393 function->parameters = ndeclaration->function.parameters;
5395 assert(is_declaration(entity));
5396 type = skip_typeref(entity->declaration.type);
5398 PUSH_SCOPE(&function->parameters);
5400 entity_t *parameter = function->parameters.entities;
5401 for (; parameter != NULL; parameter = parameter->base.next) {
5402 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5403 parameter->base.parent_scope = current_scope;
5405 assert(parameter->base.parent_scope == NULL
5406 || parameter->base.parent_scope == current_scope);
5407 parameter->base.parent_scope = current_scope;
5408 if (parameter->base.symbol == NULL) {
5409 errorf(¶meter->base.source_position, "parameter name omitted");
5412 environment_push(parameter);
5415 if (function->statement != NULL) {
5416 parser_error_multiple_definition(entity, HERE);
5419 /* parse function body */
5420 int label_stack_top = label_top();
5421 function_t *old_current_function = current_function;
5422 entity_t *old_current_entity = current_entity;
5423 current_function = function;
5424 current_entity = entity;
5428 goto_anchor = &goto_first;
5430 label_anchor = &label_first;
5432 statement_t *const body = parse_compound_statement(false);
5433 function->statement = body;
5436 check_declarations();
5437 if (is_warn_on(WARN_RETURN_TYPE) ||
5438 is_warn_on(WARN_UNREACHABLE_CODE) ||
5439 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5440 noreturn_candidate = true;
5441 check_reachable(body);
5442 if (is_warn_on(WARN_UNREACHABLE_CODE))
5443 walk_statements(body, check_unreachable, NULL);
5444 if (noreturn_candidate &&
5445 !(function->base.modifiers & DM_NORETURN)) {
5446 source_position_t const *const pos = &body->base.source_position;
5447 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5451 if (is_main(entity) && enable_main_collect2_hack)
5452 prepare_main_collect2(entity);
5455 assert(current_function == function);
5456 assert(current_entity == entity);
5457 current_entity = old_current_entity;
5458 current_function = old_current_function;
5459 label_pop_to(label_stack_top);
5465 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5467 entity_t *iter = compound->members.entities;
5468 for (; iter != NULL; iter = iter->base.next) {
5469 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5472 if (iter->base.symbol == symbol) {
5474 } else if (iter->base.symbol == NULL) {
5475 /* search in anonymous structs and unions */
5476 type_t *type = skip_typeref(iter->declaration.type);
5477 if (is_type_compound(type)) {
5478 if (find_compound_entry(type->compound.compound, symbol)
5489 static void check_deprecated(const source_position_t *source_position,
5490 const entity_t *entity)
5492 if (!is_declaration(entity))
5494 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5497 source_position_t const *const epos = &entity->base.source_position;
5498 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5500 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5502 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5507 static expression_t *create_select(const source_position_t *pos,
5509 type_qualifiers_t qualifiers,
5512 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5514 check_deprecated(pos, entry);
5516 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5517 select->select.compound = addr;
5518 select->select.compound_entry = entry;
5520 type_t *entry_type = entry->declaration.type;
5521 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5523 /* bitfields need special treatment */
5524 if (entry->compound_member.bitfield) {
5525 unsigned bit_size = entry->compound_member.bit_size;
5526 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5527 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5528 res_type = type_int;
5532 /* we always do the auto-type conversions; the & and sizeof parser contains
5533 * code to revert this! */
5534 select->base.type = automatic_type_conversion(res_type);
5541 * Find entry with symbol in compound. Search anonymous structs and unions and
5542 * creates implicit select expressions for them.
5543 * Returns the adress for the innermost compound.
5545 static expression_t *find_create_select(const source_position_t *pos,
5547 type_qualifiers_t qualifiers,
5548 compound_t *compound, symbol_t *symbol)
5550 entity_t *iter = compound->members.entities;
5551 for (; iter != NULL; iter = iter->base.next) {
5552 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5555 symbol_t *iter_symbol = iter->base.symbol;
5556 if (iter_symbol == NULL) {
5557 type_t *type = iter->declaration.type;
5558 if (type->kind != TYPE_COMPOUND_STRUCT
5559 && type->kind != TYPE_COMPOUND_UNION)
5562 compound_t *sub_compound = type->compound.compound;
5564 if (find_compound_entry(sub_compound, symbol) == NULL)
5567 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5568 sub_addr->base.source_position = *pos;
5569 sub_addr->base.implicit = true;
5570 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5574 if (iter_symbol == symbol) {
5575 return create_select(pos, addr, qualifiers, iter);
5582 static void parse_bitfield_member(entity_t *entity)
5586 expression_t *size = parse_constant_expression();
5589 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5590 type_t *type = entity->declaration.type;
5591 if (!is_type_integer(skip_typeref(type))) {
5592 errorf(HERE, "bitfield base type '%T' is not an integer type",
5596 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5597 /* error already reported by parse_constant_expression */
5598 size_long = get_type_size(type) * 8;
5600 size_long = fold_constant_to_int(size);
5602 const symbol_t *symbol = entity->base.symbol;
5603 const symbol_t *user_symbol
5604 = symbol == NULL ? sym_anonymous : symbol;
5605 unsigned bit_size = get_type_size(type) * 8;
5606 if (size_long < 0) {
5607 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5608 } else if (size_long == 0 && symbol != NULL) {
5609 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5610 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5611 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5614 /* hope that people don't invent crazy types with more bits
5615 * than our struct can hold */
5617 (1 << sizeof(entity->compound_member.bit_size)*8));
5621 entity->compound_member.bitfield = true;
5622 entity->compound_member.bit_size = (unsigned char)size_long;
5625 static void parse_compound_declarators(compound_t *compound,
5626 const declaration_specifiers_t *specifiers)
5628 add_anchor_token(';');
5629 add_anchor_token(',');
5633 if (token.kind == ':') {
5634 /* anonymous bitfield */
5635 type_t *type = specifiers->type;
5636 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5637 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5638 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5639 entity->declaration.type = type;
5641 parse_bitfield_member(entity);
5643 attribute_t *attributes = parse_attributes(NULL);
5644 attribute_t **anchor = &attributes;
5645 while (*anchor != NULL)
5646 anchor = &(*anchor)->next;
5647 *anchor = specifiers->attributes;
5648 if (attributes != NULL) {
5649 handle_entity_attributes(attributes, entity);
5651 entity->declaration.attributes = attributes;
5653 append_entity(&compound->members, entity);
5655 entity = parse_declarator(specifiers,
5656 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5657 source_position_t const *const pos = &entity->base.source_position;
5658 if (entity->kind == ENTITY_TYPEDEF) {
5659 errorf(pos, "typedef not allowed as compound member");
5661 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5663 /* make sure we don't define a symbol multiple times */
5664 symbol_t *symbol = entity->base.symbol;
5665 if (symbol != NULL) {
5666 entity_t *prev = find_compound_entry(compound, symbol);
5668 source_position_t const *const ppos = &prev->base.source_position;
5669 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5673 if (token.kind == ':') {
5674 parse_bitfield_member(entity);
5676 attribute_t *attributes = parse_attributes(NULL);
5677 handle_entity_attributes(attributes, entity);
5679 type_t *orig_type = entity->declaration.type;
5680 type_t *type = skip_typeref(orig_type);
5681 if (is_type_function(type)) {
5682 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5683 } else if (is_type_incomplete(type)) {
5684 /* §6.7.2.1:16 flexible array member */
5685 if (!is_type_array(type) ||
5686 token.kind != ';' ||
5687 look_ahead(1)->kind != '}') {
5688 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5689 } else if (compound->members.entities == NULL) {
5690 errorf(pos, "flexible array member in otherwise empty struct");
5695 append_entity(&compound->members, entity);
5698 } while (next_if(','));
5699 rem_anchor_token(',');
5700 rem_anchor_token(';');
5703 anonymous_entity = NULL;
5706 static void parse_compound_type_entries(compound_t *compound)
5709 add_anchor_token('}');
5712 switch (token.kind) {
5714 case T___extension__:
5715 case T_IDENTIFIER: {
5717 declaration_specifiers_t specifiers;
5718 parse_declaration_specifiers(&specifiers);
5719 parse_compound_declarators(compound, &specifiers);
5725 rem_anchor_token('}');
5728 compound->complete = true;
5734 static type_t *parse_typename(void)
5736 declaration_specifiers_t specifiers;
5737 parse_declaration_specifiers(&specifiers);
5738 if (specifiers.storage_class != STORAGE_CLASS_NONE
5739 || specifiers.thread_local) {
5740 /* TODO: improve error message, user does probably not know what a
5741 * storage class is...
5743 errorf(&specifiers.source_position, "typename must not have a storage class");
5746 type_t *result = parse_abstract_declarator(specifiers.type);
5754 typedef expression_t* (*parse_expression_function)(void);
5755 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5757 typedef struct expression_parser_function_t expression_parser_function_t;
5758 struct expression_parser_function_t {
5759 parse_expression_function parser;
5760 precedence_t infix_precedence;
5761 parse_expression_infix_function infix_parser;
5764 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5767 * Prints an error message if an expression was expected but not read
5769 static expression_t *expected_expression_error(void)
5771 /* skip the error message if the error token was read */
5772 if (token.kind != T_ERROR) {
5773 errorf(HERE, "expected expression, got token %K", &token);
5777 return create_error_expression();
5780 static type_t *get_string_type(void)
5782 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5785 static type_t *get_wide_string_type(void)
5787 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5791 * Parse a string constant.
5793 static expression_t *parse_string_literal(void)
5795 source_position_t begin = token.base.source_position;
5796 string_t res = token.string.string;
5797 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5800 while (token.kind == T_STRING_LITERAL
5801 || token.kind == T_WIDE_STRING_LITERAL) {
5802 warn_string_concat(&token.base.source_position);
5803 res = concat_strings(&res, &token.string.string);
5805 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5808 expression_t *literal;
5810 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5811 literal->base.type = get_wide_string_type();
5813 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5814 literal->base.type = get_string_type();
5816 literal->base.source_position = begin;
5817 literal->literal.value = res;
5823 * Parse a boolean constant.
5825 static expression_t *parse_boolean_literal(bool value)
5827 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5828 literal->base.type = type_bool;
5829 literal->literal.value.begin = value ? "true" : "false";
5830 literal->literal.value.size = value ? 4 : 5;
5836 static void warn_traditional_suffix(void)
5838 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5839 &token.number.suffix);
5842 static void check_integer_suffix(void)
5844 const string_t *suffix = &token.number.suffix;
5845 if (suffix->size == 0)
5848 bool not_traditional = false;
5849 const char *c = suffix->begin;
5850 if (*c == 'l' || *c == 'L') {
5853 not_traditional = true;
5855 if (*c == 'u' || *c == 'U') {
5858 } else if (*c == 'u' || *c == 'U') {
5859 not_traditional = true;
5862 } else if (*c == 'u' || *c == 'U') {
5863 not_traditional = true;
5865 if (*c == 'l' || *c == 'L') {
5873 errorf(&token.base.source_position,
5874 "invalid suffix '%S' on integer constant", suffix);
5875 } else if (not_traditional) {
5876 warn_traditional_suffix();
5880 static type_t *check_floatingpoint_suffix(void)
5882 const string_t *suffix = &token.number.suffix;
5883 type_t *type = type_double;
5884 if (suffix->size == 0)
5887 bool not_traditional = false;
5888 const char *c = suffix->begin;
5889 if (*c == 'f' || *c == 'F') {
5892 } else if (*c == 'l' || *c == 'L') {
5894 type = type_long_double;
5897 errorf(&token.base.source_position,
5898 "invalid suffix '%S' on floatingpoint constant", suffix);
5899 } else if (not_traditional) {
5900 warn_traditional_suffix();
5907 * Parse an integer constant.
5909 static expression_t *parse_number_literal(void)
5911 expression_kind_t kind;
5914 switch (token.kind) {
5916 kind = EXPR_LITERAL_INTEGER;
5917 check_integer_suffix();
5920 case T_INTEGER_OCTAL:
5921 kind = EXPR_LITERAL_INTEGER_OCTAL;
5922 check_integer_suffix();
5925 case T_INTEGER_HEXADECIMAL:
5926 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5927 check_integer_suffix();
5930 case T_FLOATINGPOINT:
5931 kind = EXPR_LITERAL_FLOATINGPOINT;
5932 type = check_floatingpoint_suffix();
5934 case T_FLOATINGPOINT_HEXADECIMAL:
5935 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5936 type = check_floatingpoint_suffix();
5939 panic("unexpected token type in parse_number_literal");
5942 expression_t *literal = allocate_expression_zero(kind);
5943 literal->base.type = type;
5944 literal->literal.value = token.number.number;
5945 literal->literal.suffix = token.number.suffix;
5948 /* integer type depends on the size of the number and the size
5949 * representable by the types. The backend/codegeneration has to determine
5952 determine_literal_type(&literal->literal);
5957 * Parse a character constant.
5959 static expression_t *parse_character_constant(void)
5961 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5962 literal->base.type = c_mode & _CXX ? type_char : type_int;
5963 literal->literal.value = token.string.string;
5965 size_t len = literal->literal.value.size;
5967 if (!GNU_MODE && !(c_mode & _C99)) {
5968 errorf(HERE, "more than 1 character in character constant");
5970 literal->base.type = type_int;
5971 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5980 * Parse a wide character constant.
5982 static expression_t *parse_wide_character_constant(void)
5984 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5985 literal->base.type = type_int;
5986 literal->literal.value = token.string.string;
5988 size_t len = wstrlen(&literal->literal.value);
5990 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5997 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5999 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6000 ntype->function.return_type = type_int;
6001 ntype->function.unspecified_parameters = true;
6002 ntype->function.linkage = LINKAGE_C;
6003 type_t *type = identify_new_type(ntype);
6005 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
6006 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6007 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6008 entity->declaration.type = type;
6009 entity->declaration.implicit = true;
6011 if (current_scope != NULL)
6012 record_entity(entity, false);
6018 * Performs automatic type cast as described in §6.3.2.1.
6020 * @param orig_type the original type
6022 static type_t *automatic_type_conversion(type_t *orig_type)
6024 type_t *type = skip_typeref(orig_type);
6025 if (is_type_array(type)) {
6026 array_type_t *array_type = &type->array;
6027 type_t *element_type = array_type->element_type;
6028 unsigned qualifiers = array_type->base.qualifiers;
6030 return make_pointer_type(element_type, qualifiers);
6033 if (is_type_function(type)) {
6034 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6041 * reverts the automatic casts of array to pointer types and function
6042 * to function-pointer types as defined §6.3.2.1
6044 type_t *revert_automatic_type_conversion(const expression_t *expression)
6046 switch (expression->kind) {
6047 case EXPR_REFERENCE: {
6048 entity_t *entity = expression->reference.entity;
6049 if (is_declaration(entity)) {
6050 return entity->declaration.type;
6051 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6052 return entity->enum_value.enum_type;
6054 panic("no declaration or enum in reference");
6059 entity_t *entity = expression->select.compound_entry;
6060 assert(is_declaration(entity));
6061 type_t *type = entity->declaration.type;
6062 return get_qualified_type(type, expression->base.type->base.qualifiers);
6065 case EXPR_UNARY_DEREFERENCE: {
6066 const expression_t *const value = expression->unary.value;
6067 type_t *const type = skip_typeref(value->base.type);
6068 if (!is_type_pointer(type))
6069 return type_error_type;
6070 return type->pointer.points_to;
6073 case EXPR_ARRAY_ACCESS: {
6074 const expression_t *array_ref = expression->array_access.array_ref;
6075 type_t *type_left = skip_typeref(array_ref->base.type);
6076 if (!is_type_pointer(type_left))
6077 return type_error_type;
6078 return type_left->pointer.points_to;
6081 case EXPR_STRING_LITERAL: {
6082 size_t size = expression->string_literal.value.size;
6083 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6086 case EXPR_WIDE_STRING_LITERAL: {
6087 size_t size = wstrlen(&expression->string_literal.value);
6088 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6091 case EXPR_COMPOUND_LITERAL:
6092 return expression->compound_literal.type;
6097 return expression->base.type;
6101 * Find an entity matching a symbol in a scope.
6102 * Uses current scope if scope is NULL
6104 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6105 namespace_tag_t namespc)
6107 if (scope == NULL) {
6108 return get_entity(symbol, namespc);
6111 /* we should optimize here, if scope grows above a certain size we should
6112 construct a hashmap here... */
6113 entity_t *entity = scope->entities;
6114 for ( ; entity != NULL; entity = entity->base.next) {
6115 if (entity->base.symbol == symbol
6116 && (namespace_tag_t)entity->base.namespc == namespc)
6123 static entity_t *parse_qualified_identifier(void)
6125 /* namespace containing the symbol */
6127 source_position_t pos;
6128 const scope_t *lookup_scope = NULL;
6130 if (next_if(T_COLONCOLON))
6131 lookup_scope = &unit->scope;
6135 symbol = expect_identifier("while parsing identifier", &pos);
6137 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6140 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6142 if (!next_if(T_COLONCOLON))
6145 switch (entity->kind) {
6146 case ENTITY_NAMESPACE:
6147 lookup_scope = &entity->namespacee.members;
6152 lookup_scope = &entity->compound.members;
6155 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6156 symbol, get_entity_kind_name(entity->kind));
6158 /* skip further qualifications */
6159 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6161 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6165 if (entity == NULL) {
6166 if (!strict_mode && token.kind == '(') {
6167 /* an implicitly declared function */
6168 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6169 "implicit declaration of function '%Y'", symbol);
6170 entity = create_implicit_function(symbol, &pos);
6172 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6173 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6180 static expression_t *parse_reference(void)
6182 source_position_t const pos = token.base.source_position;
6183 entity_t *const entity = parse_qualified_identifier();
6186 if (is_declaration(entity)) {
6187 orig_type = entity->declaration.type;
6188 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6189 orig_type = entity->enum_value.enum_type;
6191 panic("expected declaration or enum value in reference");
6194 /* we always do the auto-type conversions; the & and sizeof parser contains
6195 * code to revert this! */
6196 type_t *type = automatic_type_conversion(orig_type);
6198 expression_kind_t kind = EXPR_REFERENCE;
6199 if (entity->kind == ENTITY_ENUM_VALUE)
6200 kind = EXPR_ENUM_CONSTANT;
6202 expression_t *expression = allocate_expression_zero(kind);
6203 expression->base.source_position = pos;
6204 expression->base.type = type;
6205 expression->reference.entity = entity;
6207 /* this declaration is used */
6208 if (is_declaration(entity)) {
6209 entity->declaration.used = true;
6212 if (entity->base.parent_scope != file_scope
6213 && (current_function != NULL
6214 && entity->base.parent_scope->depth < current_function->parameters.depth)
6215 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6216 if (entity->kind == ENTITY_VARIABLE) {
6217 /* access of a variable from an outer function */
6218 entity->variable.address_taken = true;
6219 } else if (entity->kind == ENTITY_PARAMETER) {
6220 entity->parameter.address_taken = true;
6222 current_function->need_closure = true;
6225 check_deprecated(&pos, entity);
6230 static bool semantic_cast(expression_t *cast)
6232 expression_t *expression = cast->unary.value;
6233 type_t *orig_dest_type = cast->base.type;
6234 type_t *orig_type_right = expression->base.type;
6235 type_t const *dst_type = skip_typeref(orig_dest_type);
6236 type_t const *src_type = skip_typeref(orig_type_right);
6237 source_position_t const *pos = &cast->base.source_position;
6239 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6240 if (is_type_void(dst_type))
6243 /* only integer and pointer can be casted to pointer */
6244 if (is_type_pointer(dst_type) &&
6245 !is_type_pointer(src_type) &&
6246 !is_type_integer(src_type) &&
6247 is_type_valid(src_type)) {
6248 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6252 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6253 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6257 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6258 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6262 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6263 type_t *src = skip_typeref(src_type->pointer.points_to);
6264 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6265 unsigned missing_qualifiers =
6266 src->base.qualifiers & ~dst->base.qualifiers;
6267 if (missing_qualifiers != 0) {
6268 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6274 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6276 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6277 expression->base.source_position = *pos;
6279 parse_initializer_env_t env;
6282 env.must_be_constant = false;
6283 initializer_t *initializer = parse_initializer(&env);
6286 expression->compound_literal.initializer = initializer;
6287 expression->compound_literal.type = type;
6288 expression->base.type = automatic_type_conversion(type);
6294 * Parse a cast expression.
6296 static expression_t *parse_cast(void)
6298 source_position_t const pos = *HERE;
6301 add_anchor_token(')');
6303 type_t *type = parse_typename();
6305 rem_anchor_token(')');
6308 if (token.kind == '{') {
6309 return parse_compound_literal(&pos, type);
6312 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6313 cast->base.source_position = pos;
6315 expression_t *value = parse_subexpression(PREC_CAST);
6316 cast->base.type = type;
6317 cast->unary.value = value;
6319 if (! semantic_cast(cast)) {
6320 /* TODO: record the error in the AST. else it is impossible to detect it */
6327 * Parse a statement expression.
6329 static expression_t *parse_statement_expression(void)
6331 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6334 add_anchor_token(')');
6336 statement_t *statement = parse_compound_statement(true);
6337 statement->compound.stmt_expr = true;
6338 expression->statement.statement = statement;
6340 /* find last statement and use its type */
6341 type_t *type = type_void;
6342 const statement_t *stmt = statement->compound.statements;
6344 while (stmt->base.next != NULL)
6345 stmt = stmt->base.next;
6347 if (stmt->kind == STATEMENT_EXPRESSION) {
6348 type = stmt->expression.expression->base.type;
6351 source_position_t const *const pos = &expression->base.source_position;
6352 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6354 expression->base.type = type;
6356 rem_anchor_token(')');
6362 * Parse a parenthesized expression.
6364 static expression_t *parse_parenthesized_expression(void)
6366 token_t const* const la1 = look_ahead(1);
6367 switch (la1->kind) {
6369 /* gcc extension: a statement expression */
6370 return parse_statement_expression();
6373 if (is_typedef_symbol(la1->identifier.symbol)) {
6375 return parse_cast();
6380 add_anchor_token(')');
6381 expression_t *result = parse_expression();
6382 result->base.parenthesized = true;
6383 rem_anchor_token(')');
6389 static expression_t *parse_function_keyword(void)
6393 if (current_function == NULL) {
6394 errorf(HERE, "'__func__' used outside of a function");
6397 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6398 expression->base.type = type_char_ptr;
6399 expression->funcname.kind = FUNCNAME_FUNCTION;
6406 static expression_t *parse_pretty_function_keyword(void)
6408 if (current_function == NULL) {
6409 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6412 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6413 expression->base.type = type_char_ptr;
6414 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6416 eat(T___PRETTY_FUNCTION__);
6421 static expression_t *parse_funcsig_keyword(void)
6423 if (current_function == NULL) {
6424 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6427 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6428 expression->base.type = type_char_ptr;
6429 expression->funcname.kind = FUNCNAME_FUNCSIG;
6436 static expression_t *parse_funcdname_keyword(void)
6438 if (current_function == NULL) {
6439 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6442 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6443 expression->base.type = type_char_ptr;
6444 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6446 eat(T___FUNCDNAME__);
6451 static designator_t *parse_designator(void)
6453 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6454 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6455 if (!result->symbol)
6458 designator_t *last_designator = result;
6461 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6462 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6463 if (!designator->symbol)
6466 last_designator->next = designator;
6467 last_designator = designator;
6471 add_anchor_token(']');
6472 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6473 designator->source_position = *HERE;
6474 designator->array_index = parse_expression();
6475 rem_anchor_token(']');
6477 if (designator->array_index == NULL) {
6481 last_designator->next = designator;
6482 last_designator = designator;
6492 * Parse the __builtin_offsetof() expression.
6494 static expression_t *parse_offsetof(void)
6496 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6497 expression->base.type = type_size_t;
6499 eat(T___builtin_offsetof);
6502 add_anchor_token(')');
6503 add_anchor_token(',');
6504 type_t *type = parse_typename();
6505 rem_anchor_token(',');
6507 designator_t *designator = parse_designator();
6508 rem_anchor_token(')');
6511 expression->offsetofe.type = type;
6512 expression->offsetofe.designator = designator;
6515 memset(&path, 0, sizeof(path));
6516 path.top_type = type;
6517 path.path = NEW_ARR_F(type_path_entry_t, 0);
6519 descend_into_subtype(&path);
6521 if (!walk_designator(&path, designator, true)) {
6522 return create_error_expression();
6525 DEL_ARR_F(path.path);
6531 * Parses a _builtin_va_start() expression.
6533 static expression_t *parse_va_start(void)
6535 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6537 eat(T___builtin_va_start);
6540 add_anchor_token(')');
6541 add_anchor_token(',');
6542 expression->va_starte.ap = parse_assignment_expression();
6543 rem_anchor_token(',');
6545 expression_t *const expr = parse_assignment_expression();
6546 if (expr->kind == EXPR_REFERENCE) {
6547 entity_t *const entity = expr->reference.entity;
6548 if (!current_function->base.type->function.variadic) {
6549 errorf(&expr->base.source_position,
6550 "'va_start' used in non-variadic function");
6551 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6552 entity->base.next != NULL ||
6553 entity->kind != ENTITY_PARAMETER) {
6554 errorf(&expr->base.source_position,
6555 "second argument of 'va_start' must be last parameter of the current function");
6557 expression->va_starte.parameter = &entity->variable;
6560 expression = create_error_expression();
6562 rem_anchor_token(')');
6568 * Parses a __builtin_va_arg() expression.
6570 static expression_t *parse_va_arg(void)
6572 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6574 eat(T___builtin_va_arg);
6577 add_anchor_token(')');
6578 add_anchor_token(',');
6580 ap.expression = parse_assignment_expression();
6581 expression->va_arge.ap = ap.expression;
6582 check_call_argument(type_valist, &ap, 1);
6584 rem_anchor_token(',');
6586 expression->base.type = parse_typename();
6587 rem_anchor_token(')');
6594 * Parses a __builtin_va_copy() expression.
6596 static expression_t *parse_va_copy(void)
6598 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6600 eat(T___builtin_va_copy);
6603 add_anchor_token(')');
6604 add_anchor_token(',');
6605 expression_t *dst = parse_assignment_expression();
6606 assign_error_t error = semantic_assign(type_valist, dst);
6607 report_assign_error(error, type_valist, dst, "call argument 1",
6608 &dst->base.source_position);
6609 expression->va_copye.dst = dst;
6611 rem_anchor_token(',');
6614 call_argument_t src;
6615 src.expression = parse_assignment_expression();
6616 check_call_argument(type_valist, &src, 2);
6617 expression->va_copye.src = src.expression;
6618 rem_anchor_token(')');
6625 * Parses a __builtin_constant_p() expression.
6627 static expression_t *parse_builtin_constant(void)
6629 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6631 eat(T___builtin_constant_p);
6634 add_anchor_token(')');
6635 expression->builtin_constant.value = parse_assignment_expression();
6636 rem_anchor_token(')');
6638 expression->base.type = type_int;
6644 * Parses a __builtin_types_compatible_p() expression.
6646 static expression_t *parse_builtin_types_compatible(void)
6648 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6650 eat(T___builtin_types_compatible_p);
6653 add_anchor_token(')');
6654 add_anchor_token(',');
6655 expression->builtin_types_compatible.left = parse_typename();
6656 rem_anchor_token(',');
6658 expression->builtin_types_compatible.right = parse_typename();
6659 rem_anchor_token(')');
6661 expression->base.type = type_int;
6667 * Parses a __builtin_is_*() compare expression.
6669 static expression_t *parse_compare_builtin(void)
6671 expression_t *expression;
6673 switch (token.kind) {
6674 case T___builtin_isgreater:
6675 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6677 case T___builtin_isgreaterequal:
6678 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6680 case T___builtin_isless:
6681 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6683 case T___builtin_islessequal:
6684 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6686 case T___builtin_islessgreater:
6687 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6689 case T___builtin_isunordered:
6690 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6693 internal_errorf(HERE, "invalid compare builtin found");
6695 expression->base.source_position = *HERE;
6699 add_anchor_token(')');
6700 add_anchor_token(',');
6701 expression->binary.left = parse_assignment_expression();
6702 rem_anchor_token(',');
6704 expression->binary.right = parse_assignment_expression();
6705 rem_anchor_token(')');
6708 type_t *const orig_type_left = expression->binary.left->base.type;
6709 type_t *const orig_type_right = expression->binary.right->base.type;
6711 type_t *const type_left = skip_typeref(orig_type_left);
6712 type_t *const type_right = skip_typeref(orig_type_right);
6713 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6714 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6715 type_error_incompatible("invalid operands in comparison",
6716 &expression->base.source_position, orig_type_left, orig_type_right);
6719 semantic_comparison(&expression->binary);
6726 * Parses a MS assume() expression.
6728 static expression_t *parse_assume(void)
6730 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6735 add_anchor_token(')');
6736 expression->unary.value = parse_assignment_expression();
6737 rem_anchor_token(')');
6740 expression->base.type = type_void;
6745 * Return the label for the current symbol or create a new one.
6747 static label_t *get_label(void)
6749 assert(token.kind == T_IDENTIFIER);
6750 assert(current_function != NULL);
6752 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6753 /* If we find a local label, we already created the declaration. */
6754 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6755 if (label->base.parent_scope != current_scope) {
6756 assert(label->base.parent_scope->depth < current_scope->depth);
6757 current_function->goto_to_outer = true;
6759 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6760 /* There is no matching label in the same function, so create a new one. */
6761 source_position_t const nowhere = { NULL, 0, 0, false };
6762 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6767 return &label->label;
6771 * Parses a GNU && label address expression.
6773 static expression_t *parse_label_address(void)
6775 source_position_t source_position = token.base.source_position;
6777 if (token.kind != T_IDENTIFIER) {
6778 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6779 return create_error_expression();
6782 label_t *const label = get_label();
6784 label->address_taken = true;
6786 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6787 expression->base.source_position = source_position;
6789 /* label address is treated as a void pointer */
6790 expression->base.type = type_void_ptr;
6791 expression->label_address.label = label;
6796 * Parse a microsoft __noop expression.
6798 static expression_t *parse_noop_expression(void)
6800 /* the result is a (int)0 */
6801 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6802 literal->base.type = type_int;
6803 literal->literal.value.begin = "__noop";
6804 literal->literal.value.size = 6;
6808 if (token.kind == '(') {
6809 /* parse arguments */
6811 add_anchor_token(')');
6812 add_anchor_token(',');
6814 if (token.kind != ')') do {
6815 (void)parse_assignment_expression();
6816 } while (next_if(','));
6818 rem_anchor_token(',');
6819 rem_anchor_token(')');
6827 * Parses a primary expression.
6829 static expression_t *parse_primary_expression(void)
6831 switch (token.kind) {
6832 case T_false: return parse_boolean_literal(false);
6833 case T_true: return parse_boolean_literal(true);
6835 case T_INTEGER_OCTAL:
6836 case T_INTEGER_HEXADECIMAL:
6837 case T_FLOATINGPOINT:
6838 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6839 case T_CHARACTER_CONSTANT: return parse_character_constant();
6840 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6841 case T_STRING_LITERAL:
6842 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6843 case T___FUNCTION__:
6844 case T___func__: return parse_function_keyword();
6845 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6846 case T___FUNCSIG__: return parse_funcsig_keyword();
6847 case T___FUNCDNAME__: return parse_funcdname_keyword();
6848 case T___builtin_offsetof: return parse_offsetof();
6849 case T___builtin_va_start: return parse_va_start();
6850 case T___builtin_va_arg: return parse_va_arg();
6851 case T___builtin_va_copy: return parse_va_copy();
6852 case T___builtin_isgreater:
6853 case T___builtin_isgreaterequal:
6854 case T___builtin_isless:
6855 case T___builtin_islessequal:
6856 case T___builtin_islessgreater:
6857 case T___builtin_isunordered: return parse_compare_builtin();
6858 case T___builtin_constant_p: return parse_builtin_constant();
6859 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6860 case T__assume: return parse_assume();
6863 return parse_label_address();
6866 case '(': return parse_parenthesized_expression();
6867 case T___noop: return parse_noop_expression();
6869 /* Gracefully handle type names while parsing expressions. */
6871 return parse_reference();
6873 if (!is_typedef_symbol(token.identifier.symbol)) {
6874 return parse_reference();
6878 source_position_t const pos = *HERE;
6879 declaration_specifiers_t specifiers;
6880 parse_declaration_specifiers(&specifiers);
6881 type_t const *const type = parse_abstract_declarator(specifiers.type);
6882 errorf(&pos, "encountered type '%T' while parsing expression", type);
6883 return create_error_expression();
6887 errorf(HERE, "unexpected token %K, expected an expression", &token);
6889 return create_error_expression();
6892 static expression_t *parse_array_expression(expression_t *left)
6894 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6895 array_access_expression_t *const arr = &expr->array_access;
6898 add_anchor_token(']');
6900 expression_t *const inside = parse_expression();
6902 type_t *const orig_type_left = left->base.type;
6903 type_t *const orig_type_inside = inside->base.type;
6905 type_t *const type_left = skip_typeref(orig_type_left);
6906 type_t *const type_inside = skip_typeref(orig_type_inside);
6912 if (is_type_pointer(type_left)) {
6915 idx_type = type_inside;
6916 res_type = type_left->pointer.points_to;
6918 } else if (is_type_pointer(type_inside)) {
6919 arr->flipped = true;
6922 idx_type = type_left;
6923 res_type = type_inside->pointer.points_to;
6925 res_type = automatic_type_conversion(res_type);
6926 if (!is_type_integer(idx_type)) {
6927 errorf(&idx->base.source_position, "array subscript must have integer type");
6928 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6929 source_position_t const *const pos = &idx->base.source_position;
6930 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6933 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6934 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6936 res_type = type_error_type;
6941 arr->array_ref = ref;
6943 arr->base.type = res_type;
6945 rem_anchor_token(']');
6950 static bool is_bitfield(const expression_t *expression)
6952 return expression->kind == EXPR_SELECT
6953 && expression->select.compound_entry->compound_member.bitfield;
6956 static expression_t *parse_typeprop(expression_kind_t const kind)
6958 expression_t *tp_expression = allocate_expression_zero(kind);
6959 tp_expression->base.type = type_size_t;
6961 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6964 expression_t *expression;
6965 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6966 source_position_t const pos = *HERE;
6968 add_anchor_token(')');
6969 orig_type = parse_typename();
6970 rem_anchor_token(')');
6973 if (token.kind == '{') {
6974 /* It was not sizeof(type) after all. It is sizeof of an expression
6975 * starting with a compound literal */
6976 expression = parse_compound_literal(&pos, orig_type);
6977 goto typeprop_expression;
6980 expression = parse_subexpression(PREC_UNARY);
6982 typeprop_expression:
6983 if (is_bitfield(expression)) {
6984 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6985 errorf(&tp_expression->base.source_position,
6986 "operand of %s expression must not be a bitfield", what);
6989 tp_expression->typeprop.tp_expression = expression;
6991 orig_type = revert_automatic_type_conversion(expression);
6992 expression->base.type = orig_type;
6995 tp_expression->typeprop.type = orig_type;
6996 type_t const* const type = skip_typeref(orig_type);
6997 char const* wrong_type = NULL;
6998 if (is_type_incomplete(type)) {
6999 if (!is_type_void(type) || !GNU_MODE)
7000 wrong_type = "incomplete";
7001 } else if (type->kind == TYPE_FUNCTION) {
7003 /* function types are allowed (and return 1) */
7004 source_position_t const *const pos = &tp_expression->base.source_position;
7005 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7006 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7008 wrong_type = "function";
7012 if (wrong_type != NULL) {
7013 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7014 errorf(&tp_expression->base.source_position,
7015 "operand of %s expression must not be of %s type '%T'",
7016 what, wrong_type, orig_type);
7019 return tp_expression;
7022 static expression_t *parse_sizeof(void)
7024 return parse_typeprop(EXPR_SIZEOF);
7027 static expression_t *parse_alignof(void)
7029 return parse_typeprop(EXPR_ALIGNOF);
7032 static expression_t *parse_select_expression(expression_t *addr)
7034 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7035 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7036 source_position_t const pos = *HERE;
7039 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
7041 return create_error_expression();
7043 type_t *const orig_type = addr->base.type;
7044 type_t *const type = skip_typeref(orig_type);
7047 bool saw_error = false;
7048 if (is_type_pointer(type)) {
7049 if (!select_left_arrow) {
7051 "request for member '%Y' in something not a struct or union, but '%T'",
7055 type_left = skip_typeref(type->pointer.points_to);
7057 if (select_left_arrow && is_type_valid(type)) {
7058 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7064 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7065 type_left->kind != TYPE_COMPOUND_UNION) {
7067 if (is_type_valid(type_left) && !saw_error) {
7069 "request for member '%Y' in something not a struct or union, but '%T'",
7072 return create_error_expression();
7075 compound_t *compound = type_left->compound.compound;
7076 if (!compound->complete) {
7077 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7079 return create_error_expression();
7082 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7083 expression_t *result =
7084 find_create_select(&pos, addr, qualifiers, compound, symbol);
7086 if (result == NULL) {
7087 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7088 return create_error_expression();
7094 static void check_call_argument(type_t *expected_type,
7095 call_argument_t *argument, unsigned pos)
7097 type_t *expected_type_skip = skip_typeref(expected_type);
7098 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7099 expression_t *arg_expr = argument->expression;
7100 type_t *arg_type = skip_typeref(arg_expr->base.type);
7102 /* handle transparent union gnu extension */
7103 if (is_type_union(expected_type_skip)
7104 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7105 compound_t *union_decl = expected_type_skip->compound.compound;
7106 type_t *best_type = NULL;
7107 entity_t *entry = union_decl->members.entities;
7108 for ( ; entry != NULL; entry = entry->base.next) {
7109 assert(is_declaration(entry));
7110 type_t *decl_type = entry->declaration.type;
7111 error = semantic_assign(decl_type, arg_expr);
7112 if (error == ASSIGN_ERROR_INCOMPATIBLE
7113 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7116 if (error == ASSIGN_SUCCESS) {
7117 best_type = decl_type;
7118 } else if (best_type == NULL) {
7119 best_type = decl_type;
7123 if (best_type != NULL) {
7124 expected_type = best_type;
7128 error = semantic_assign(expected_type, arg_expr);
7129 argument->expression = create_implicit_cast(arg_expr, expected_type);
7131 if (error != ASSIGN_SUCCESS) {
7132 /* report exact scope in error messages (like "in argument 3") */
7134 snprintf(buf, sizeof(buf), "call argument %u", pos);
7135 report_assign_error(error, expected_type, arg_expr, buf,
7136 &arg_expr->base.source_position);
7138 type_t *const promoted_type = get_default_promoted_type(arg_type);
7139 if (!types_compatible(expected_type_skip, promoted_type) &&
7140 !types_compatible(expected_type_skip, type_void_ptr) &&
7141 !types_compatible(type_void_ptr, promoted_type)) {
7142 /* Deliberately show the skipped types in this warning */
7143 source_position_t const *const apos = &arg_expr->base.source_position;
7144 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7150 * Handle the semantic restrictions of builtin calls
7152 static void handle_builtin_argument_restrictions(call_expression_t *call)
7154 entity_t *entity = call->function->reference.entity;
7155 switch (entity->function.btk) {
7157 switch (entity->function.b.firm_builtin_kind) {
7158 case ir_bk_return_address:
7159 case ir_bk_frame_address: {
7160 /* argument must be constant */
7161 call_argument_t *argument = call->arguments;
7163 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7164 errorf(&call->base.source_position,
7165 "argument of '%Y' must be a constant expression",
7166 call->function->reference.entity->base.symbol);
7170 case ir_bk_prefetch:
7171 /* second and third argument must be constant if existent */
7172 if (call->arguments == NULL)
7174 call_argument_t *rw = call->arguments->next;
7175 call_argument_t *locality = NULL;
7178 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7179 errorf(&call->base.source_position,
7180 "second argument of '%Y' must be a constant expression",
7181 call->function->reference.entity->base.symbol);
7183 locality = rw->next;
7185 if (locality != NULL) {
7186 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7187 errorf(&call->base.source_position,
7188 "third argument of '%Y' must be a constant expression",
7189 call->function->reference.entity->base.symbol);
7191 locality = rw->next;
7198 case BUILTIN_OBJECT_SIZE:
7199 if (call->arguments == NULL)
7202 call_argument_t *arg = call->arguments->next;
7203 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7204 errorf(&call->base.source_position,
7205 "second argument of '%Y' must be a constant expression",
7206 call->function->reference.entity->base.symbol);
7215 * Parse a call expression, ie. expression '( ... )'.
7217 * @param expression the function address
7219 static expression_t *parse_call_expression(expression_t *expression)
7221 expression_t *result = allocate_expression_zero(EXPR_CALL);
7222 call_expression_t *call = &result->call;
7223 call->function = expression;
7225 type_t *const orig_type = expression->base.type;
7226 type_t *const type = skip_typeref(orig_type);
7228 function_type_t *function_type = NULL;
7229 if (is_type_pointer(type)) {
7230 type_t *const to_type = skip_typeref(type->pointer.points_to);
7232 if (is_type_function(to_type)) {
7233 function_type = &to_type->function;
7234 call->base.type = function_type->return_type;
7238 if (function_type == NULL && is_type_valid(type)) {
7240 "called object '%E' (type '%T') is not a pointer to a function",
7241 expression, orig_type);
7244 /* parse arguments */
7246 add_anchor_token(')');
7247 add_anchor_token(',');
7249 if (token.kind != ')') {
7250 call_argument_t **anchor = &call->arguments;
7252 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7253 argument->expression = parse_assignment_expression();
7256 anchor = &argument->next;
7257 } while (next_if(','));
7259 rem_anchor_token(',');
7260 rem_anchor_token(')');
7263 if (function_type == NULL)
7266 /* check type and count of call arguments */
7267 function_parameter_t *parameter = function_type->parameters;
7268 call_argument_t *argument = call->arguments;
7269 if (!function_type->unspecified_parameters) {
7270 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7271 parameter = parameter->next, argument = argument->next) {
7272 check_call_argument(parameter->type, argument, ++pos);
7275 if (parameter != NULL) {
7276 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7277 } else if (argument != NULL && !function_type->variadic) {
7278 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7282 /* do default promotion for other arguments */
7283 for (; argument != NULL; argument = argument->next) {
7284 type_t *argument_type = argument->expression->base.type;
7285 if (!is_type_object(skip_typeref(argument_type))) {
7286 errorf(&argument->expression->base.source_position,
7287 "call argument '%E' must not be void", argument->expression);
7290 argument_type = get_default_promoted_type(argument_type);
7292 argument->expression
7293 = create_implicit_cast(argument->expression, argument_type);
7298 if (is_type_compound(skip_typeref(function_type->return_type))) {
7299 source_position_t const *const pos = &expression->base.source_position;
7300 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7303 if (expression->kind == EXPR_REFERENCE) {
7304 reference_expression_t *reference = &expression->reference;
7305 if (reference->entity->kind == ENTITY_FUNCTION &&
7306 reference->entity->function.btk != BUILTIN_NONE)
7307 handle_builtin_argument_restrictions(call);
7313 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7315 static bool same_compound_type(const type_t *type1, const type_t *type2)
7318 is_type_compound(type1) &&
7319 type1->kind == type2->kind &&
7320 type1->compound.compound == type2->compound.compound;
7323 static expression_t const *get_reference_address(expression_t const *expr)
7325 bool regular_take_address = true;
7327 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7328 expr = expr->unary.value;
7330 regular_take_address = false;
7333 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7336 expr = expr->unary.value;
7339 if (expr->kind != EXPR_REFERENCE)
7342 /* special case for functions which are automatically converted to a
7343 * pointer to function without an extra TAKE_ADDRESS operation */
7344 if (!regular_take_address &&
7345 expr->reference.entity->kind != ENTITY_FUNCTION) {
7352 static void warn_reference_address_as_bool(expression_t const* expr)
7354 expr = get_reference_address(expr);
7356 source_position_t const *const pos = &expr->base.source_position;
7357 entity_t const *const ent = expr->reference.entity;
7358 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7362 static void warn_assignment_in_condition(const expression_t *const expr)
7364 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7366 if (expr->base.parenthesized)
7368 source_position_t const *const pos = &expr->base.source_position;
7369 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7372 static void semantic_condition(expression_t const *const expr,
7373 char const *const context)
7375 type_t *const type = skip_typeref(expr->base.type);
7376 if (is_type_scalar(type)) {
7377 warn_reference_address_as_bool(expr);
7378 warn_assignment_in_condition(expr);
7379 } else if (is_type_valid(type)) {
7380 errorf(&expr->base.source_position,
7381 "%s must have scalar type", context);
7386 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7388 * @param expression the conditional expression
7390 static expression_t *parse_conditional_expression(expression_t *expression)
7392 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7394 conditional_expression_t *conditional = &result->conditional;
7395 conditional->condition = expression;
7398 add_anchor_token(':');
7400 /* §6.5.15:2 The first operand shall have scalar type. */
7401 semantic_condition(expression, "condition of conditional operator");
7403 expression_t *true_expression = expression;
7404 bool gnu_cond = false;
7405 if (GNU_MODE && token.kind == ':') {
7408 true_expression = parse_expression();
7410 rem_anchor_token(':');
7412 expression_t *false_expression =
7413 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7415 type_t *const orig_true_type = true_expression->base.type;
7416 type_t *const orig_false_type = false_expression->base.type;
7417 type_t *const true_type = skip_typeref(orig_true_type);
7418 type_t *const false_type = skip_typeref(orig_false_type);
7421 source_position_t const *const pos = &conditional->base.source_position;
7422 type_t *result_type;
7423 if (is_type_void(true_type) || is_type_void(false_type)) {
7424 /* ISO/IEC 14882:1998(E) §5.16:2 */
7425 if (true_expression->kind == EXPR_UNARY_THROW) {
7426 result_type = false_type;
7427 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7428 result_type = true_type;
7430 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7431 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7433 result_type = type_void;
7435 } else if (is_type_arithmetic(true_type)
7436 && is_type_arithmetic(false_type)) {
7437 result_type = semantic_arithmetic(true_type, false_type);
7438 } else if (same_compound_type(true_type, false_type)) {
7439 /* just take 1 of the 2 types */
7440 result_type = true_type;
7441 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7442 type_t *pointer_type;
7444 expression_t *other_expression;
7445 if (is_type_pointer(true_type) &&
7446 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7447 pointer_type = true_type;
7448 other_type = false_type;
7449 other_expression = false_expression;
7451 pointer_type = false_type;
7452 other_type = true_type;
7453 other_expression = true_expression;
7456 if (is_null_pointer_constant(other_expression)) {
7457 result_type = pointer_type;
7458 } else if (is_type_pointer(other_type)) {
7459 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7460 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7463 if (is_type_void(to1) || is_type_void(to2)) {
7465 } else if (types_compatible(get_unqualified_type(to1),
7466 get_unqualified_type(to2))) {
7469 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7473 type_t *const type =
7474 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7475 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7476 } else if (is_type_integer(other_type)) {
7477 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7478 result_type = pointer_type;
7480 goto types_incompatible;
7484 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7485 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7487 result_type = type_error_type;
7490 conditional->true_expression
7491 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7492 conditional->false_expression
7493 = create_implicit_cast(false_expression, result_type);
7494 conditional->base.type = result_type;
7499 * Parse an extension expression.
7501 static expression_t *parse_extension(void)
7504 expression_t *expression = parse_subexpression(PREC_UNARY);
7510 * Parse a __builtin_classify_type() expression.
7512 static expression_t *parse_builtin_classify_type(void)
7514 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7515 result->base.type = type_int;
7517 eat(T___builtin_classify_type);
7520 add_anchor_token(')');
7521 expression_t *expression = parse_expression();
7522 rem_anchor_token(')');
7524 result->classify_type.type_expression = expression;
7530 * Parse a delete expression
7531 * ISO/IEC 14882:1998(E) §5.3.5
7533 static expression_t *parse_delete(void)
7535 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7536 result->base.type = type_void;
7541 result->kind = EXPR_UNARY_DELETE_ARRAY;
7545 expression_t *const value = parse_subexpression(PREC_CAST);
7546 result->unary.value = value;
7548 type_t *const type = skip_typeref(value->base.type);
7549 if (!is_type_pointer(type)) {
7550 if (is_type_valid(type)) {
7551 errorf(&value->base.source_position,
7552 "operand of delete must have pointer type");
7554 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7555 source_position_t const *const pos = &value->base.source_position;
7556 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7563 * Parse a throw expression
7564 * ISO/IEC 14882:1998(E) §15:1
7566 static expression_t *parse_throw(void)
7568 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7569 result->base.type = type_void;
7573 expression_t *value = NULL;
7574 switch (token.kind) {
7576 value = parse_assignment_expression();
7577 /* ISO/IEC 14882:1998(E) §15.1:3 */
7578 type_t *const orig_type = value->base.type;
7579 type_t *const type = skip_typeref(orig_type);
7580 if (is_type_incomplete(type)) {
7581 errorf(&value->base.source_position,
7582 "cannot throw object of incomplete type '%T'", orig_type);
7583 } else if (is_type_pointer(type)) {
7584 type_t *const points_to = skip_typeref(type->pointer.points_to);
7585 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7586 errorf(&value->base.source_position,
7587 "cannot throw pointer to incomplete type '%T'", orig_type);
7595 result->unary.value = value;
7600 static bool check_pointer_arithmetic(const source_position_t *source_position,
7601 type_t *pointer_type,
7602 type_t *orig_pointer_type)
7604 type_t *points_to = pointer_type->pointer.points_to;
7605 points_to = skip_typeref(points_to);
7607 if (is_type_incomplete(points_to)) {
7608 if (!GNU_MODE || !is_type_void(points_to)) {
7609 errorf(source_position,
7610 "arithmetic with pointer to incomplete type '%T' not allowed",
7614 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7616 } else if (is_type_function(points_to)) {
7618 errorf(source_position,
7619 "arithmetic with pointer to function type '%T' not allowed",
7623 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7629 static bool is_lvalue(const expression_t *expression)
7631 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7632 switch (expression->kind) {
7633 case EXPR_ARRAY_ACCESS:
7634 case EXPR_COMPOUND_LITERAL:
7635 case EXPR_REFERENCE:
7637 case EXPR_UNARY_DEREFERENCE:
7641 type_t *type = skip_typeref(expression->base.type);
7643 /* ISO/IEC 14882:1998(E) §3.10:3 */
7644 is_type_reference(type) ||
7645 /* Claim it is an lvalue, if the type is invalid. There was a parse
7646 * error before, which maybe prevented properly recognizing it as
7648 !is_type_valid(type);
7653 static void semantic_incdec(unary_expression_t *expression)
7655 type_t *const orig_type = expression->value->base.type;
7656 type_t *const type = skip_typeref(orig_type);
7657 if (is_type_pointer(type)) {
7658 if (!check_pointer_arithmetic(&expression->base.source_position,
7662 } else if (!is_type_real(type) && is_type_valid(type)) {
7663 /* TODO: improve error message */
7664 errorf(&expression->base.source_position,
7665 "operation needs an arithmetic or pointer type");
7668 if (!is_lvalue(expression->value)) {
7669 /* TODO: improve error message */
7670 errorf(&expression->base.source_position, "lvalue required as operand");
7672 expression->base.type = orig_type;
7675 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7677 type_t *const res_type = promote_integer(type);
7678 expr->base.type = res_type;
7679 expr->value = create_implicit_cast(expr->value, res_type);
7682 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7684 type_t *const orig_type = expression->value->base.type;
7685 type_t *const type = skip_typeref(orig_type);
7686 if (!is_type_arithmetic(type)) {
7687 if (is_type_valid(type)) {
7688 /* TODO: improve error message */
7689 errorf(&expression->base.source_position,
7690 "operation needs an arithmetic type");
7693 } else if (is_type_integer(type)) {
7694 promote_unary_int_expr(expression, type);
7696 expression->base.type = orig_type;
7700 static void semantic_unexpr_plus(unary_expression_t *expression)
7702 semantic_unexpr_arithmetic(expression);
7703 source_position_t const *const pos = &expression->base.source_position;
7704 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7707 static void semantic_not(unary_expression_t *expression)
7709 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7710 semantic_condition(expression->value, "operand of !");
7711 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7714 static void semantic_unexpr_integer(unary_expression_t *expression)
7716 type_t *const orig_type = expression->value->base.type;
7717 type_t *const type = skip_typeref(orig_type);
7718 if (!is_type_integer(type)) {
7719 if (is_type_valid(type)) {
7720 errorf(&expression->base.source_position,
7721 "operand of ~ must be of integer type");
7726 promote_unary_int_expr(expression, type);
7729 static void semantic_dereference(unary_expression_t *expression)
7731 type_t *const orig_type = expression->value->base.type;
7732 type_t *const type = skip_typeref(orig_type);
7733 if (!is_type_pointer(type)) {
7734 if (is_type_valid(type)) {
7735 errorf(&expression->base.source_position,
7736 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7741 type_t *result_type = type->pointer.points_to;
7742 result_type = automatic_type_conversion(result_type);
7743 expression->base.type = result_type;
7747 * Record that an address is taken (expression represents an lvalue).
7749 * @param expression the expression
7750 * @param may_be_register if true, the expression might be an register
7752 static void set_address_taken(expression_t *expression, bool may_be_register)
7754 if (expression->kind != EXPR_REFERENCE)
7757 entity_t *const entity = expression->reference.entity;
7759 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7762 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7763 && !may_be_register) {
7764 source_position_t const *const pos = &expression->base.source_position;
7765 errorf(pos, "address of register '%N' requested", entity);
7768 if (entity->kind == ENTITY_VARIABLE) {
7769 entity->variable.address_taken = true;
7771 assert(entity->kind == ENTITY_PARAMETER);
7772 entity->parameter.address_taken = true;
7777 * Check the semantic of the address taken expression.
7779 static void semantic_take_addr(unary_expression_t *expression)
7781 expression_t *value = expression->value;
7782 value->base.type = revert_automatic_type_conversion(value);
7784 type_t *orig_type = value->base.type;
7785 type_t *type = skip_typeref(orig_type);
7786 if (!is_type_valid(type))
7790 if (!is_lvalue(value)) {
7791 errorf(&expression->base.source_position, "'&' requires an lvalue");
7793 if (is_bitfield(value)) {
7794 errorf(&expression->base.source_position,
7795 "'&' not allowed on bitfield");
7798 set_address_taken(value, false);
7800 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7803 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7804 static expression_t *parse_##unexpression_type(void) \
7806 expression_t *unary_expression \
7807 = allocate_expression_zero(unexpression_type); \
7809 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7811 sfunc(&unary_expression->unary); \
7813 return unary_expression; \
7816 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7817 semantic_unexpr_arithmetic)
7818 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7819 semantic_unexpr_plus)
7820 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7822 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7823 semantic_dereference)
7824 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7826 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7827 semantic_unexpr_integer)
7828 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7830 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7833 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7835 static expression_t *parse_##unexpression_type(expression_t *left) \
7837 expression_t *unary_expression \
7838 = allocate_expression_zero(unexpression_type); \
7840 unary_expression->unary.value = left; \
7842 sfunc(&unary_expression->unary); \
7844 return unary_expression; \
7847 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7848 EXPR_UNARY_POSTFIX_INCREMENT,
7850 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7851 EXPR_UNARY_POSTFIX_DECREMENT,
7854 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7856 /* TODO: handle complex + imaginary types */
7858 type_left = get_unqualified_type(type_left);
7859 type_right = get_unqualified_type(type_right);
7861 /* §6.3.1.8 Usual arithmetic conversions */
7862 if (type_left == type_long_double || type_right == type_long_double) {
7863 return type_long_double;
7864 } else if (type_left == type_double || type_right == type_double) {
7866 } else if (type_left == type_float || type_right == type_float) {
7870 type_left = promote_integer(type_left);
7871 type_right = promote_integer(type_right);
7873 if (type_left == type_right)
7876 bool const signed_left = is_type_signed(type_left);
7877 bool const signed_right = is_type_signed(type_right);
7878 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7879 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7881 if (signed_left == signed_right)
7882 return rank_left >= rank_right ? type_left : type_right;
7886 atomic_type_kind_t s_akind;
7887 atomic_type_kind_t u_akind;
7892 u_type = type_right;
7894 s_type = type_right;
7897 s_akind = get_akind(s_type);
7898 u_akind = get_akind(u_type);
7899 s_rank = get_akind_rank(s_akind);
7900 u_rank = get_akind_rank(u_akind);
7902 if (u_rank >= s_rank)
7905 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7909 case ATOMIC_TYPE_INT: return type_unsigned_int;
7910 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7911 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7913 default: panic("invalid atomic type");
7918 * Check the semantic restrictions for a binary expression.
7920 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7922 expression_t *const left = expression->left;
7923 expression_t *const right = expression->right;
7924 type_t *const orig_type_left = left->base.type;
7925 type_t *const orig_type_right = right->base.type;
7926 type_t *const type_left = skip_typeref(orig_type_left);
7927 type_t *const type_right = skip_typeref(orig_type_right);
7929 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7930 /* TODO: improve error message */
7931 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7932 errorf(&expression->base.source_position,
7933 "operation needs arithmetic types");
7938 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7939 expression->left = create_implicit_cast(left, arithmetic_type);
7940 expression->right = create_implicit_cast(right, arithmetic_type);
7941 expression->base.type = arithmetic_type;
7944 static void semantic_binexpr_integer(binary_expression_t *const expression)
7946 expression_t *const left = expression->left;
7947 expression_t *const right = expression->right;
7948 type_t *const orig_type_left = left->base.type;
7949 type_t *const orig_type_right = right->base.type;
7950 type_t *const type_left = skip_typeref(orig_type_left);
7951 type_t *const type_right = skip_typeref(orig_type_right);
7953 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7954 /* TODO: improve error message */
7955 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7956 errorf(&expression->base.source_position,
7957 "operation needs integer types");
7962 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7963 expression->left = create_implicit_cast(left, result_type);
7964 expression->right = create_implicit_cast(right, result_type);
7965 expression->base.type = result_type;
7968 static void warn_div_by_zero(binary_expression_t const *const expression)
7970 if (!is_type_integer(expression->base.type))
7973 expression_t const *const right = expression->right;
7974 /* The type of the right operand can be different for /= */
7975 if (is_type_integer(right->base.type) &&
7976 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7977 !fold_constant_to_bool(right)) {
7978 source_position_t const *const pos = &expression->base.source_position;
7979 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7984 * Check the semantic restrictions for a div/mod expression.
7986 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7988 semantic_binexpr_arithmetic(expression);
7989 warn_div_by_zero(expression);
7992 static void warn_addsub_in_shift(const expression_t *const expr)
7994 if (expr->base.parenthesized)
7998 switch (expr->kind) {
7999 case EXPR_BINARY_ADD: op = '+'; break;
8000 case EXPR_BINARY_SUB: op = '-'; break;
8004 source_position_t const *const pos = &expr->base.source_position;
8005 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8008 static bool semantic_shift(binary_expression_t *expression)
8010 expression_t *const left = expression->left;
8011 expression_t *const right = expression->right;
8012 type_t *const orig_type_left = left->base.type;
8013 type_t *const orig_type_right = right->base.type;
8014 type_t * type_left = skip_typeref(orig_type_left);
8015 type_t * type_right = skip_typeref(orig_type_right);
8017 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8018 /* TODO: improve error message */
8019 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8020 errorf(&expression->base.source_position,
8021 "operands of shift operation must have integer types");
8026 type_left = promote_integer(type_left);
8028 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8029 source_position_t const *const pos = &right->base.source_position;
8030 long const count = fold_constant_to_int(right);
8032 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8033 } else if ((unsigned long)count >=
8034 get_atomic_type_size(type_left->atomic.akind) * 8) {
8035 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8039 type_right = promote_integer(type_right);
8040 expression->right = create_implicit_cast(right, type_right);
8045 static void semantic_shift_op(binary_expression_t *expression)
8047 expression_t *const left = expression->left;
8048 expression_t *const right = expression->right;
8050 if (!semantic_shift(expression))
8053 warn_addsub_in_shift(left);
8054 warn_addsub_in_shift(right);
8056 type_t *const orig_type_left = left->base.type;
8057 type_t * type_left = skip_typeref(orig_type_left);
8059 type_left = promote_integer(type_left);
8060 expression->left = create_implicit_cast(left, type_left);
8061 expression->base.type = type_left;
8064 static void semantic_add(binary_expression_t *expression)
8066 expression_t *const left = expression->left;
8067 expression_t *const right = expression->right;
8068 type_t *const orig_type_left = left->base.type;
8069 type_t *const orig_type_right = right->base.type;
8070 type_t *const type_left = skip_typeref(orig_type_left);
8071 type_t *const type_right = skip_typeref(orig_type_right);
8074 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8075 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8076 expression->left = create_implicit_cast(left, arithmetic_type);
8077 expression->right = create_implicit_cast(right, arithmetic_type);
8078 expression->base.type = arithmetic_type;
8079 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8080 check_pointer_arithmetic(&expression->base.source_position,
8081 type_left, orig_type_left);
8082 expression->base.type = type_left;
8083 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8084 check_pointer_arithmetic(&expression->base.source_position,
8085 type_right, orig_type_right);
8086 expression->base.type = type_right;
8087 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8088 errorf(&expression->base.source_position,
8089 "invalid operands to binary + ('%T', '%T')",
8090 orig_type_left, orig_type_right);
8094 static void semantic_sub(binary_expression_t *expression)
8096 expression_t *const left = expression->left;
8097 expression_t *const right = expression->right;
8098 type_t *const orig_type_left = left->base.type;
8099 type_t *const orig_type_right = right->base.type;
8100 type_t *const type_left = skip_typeref(orig_type_left);
8101 type_t *const type_right = skip_typeref(orig_type_right);
8102 source_position_t const *const pos = &expression->base.source_position;
8105 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8106 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8107 expression->left = create_implicit_cast(left, arithmetic_type);
8108 expression->right = create_implicit_cast(right, arithmetic_type);
8109 expression->base.type = arithmetic_type;
8110 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8111 check_pointer_arithmetic(&expression->base.source_position,
8112 type_left, orig_type_left);
8113 expression->base.type = type_left;
8114 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8115 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8116 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8117 if (!types_compatible(unqual_left, unqual_right)) {
8119 "subtracting pointers to incompatible types '%T' and '%T'",
8120 orig_type_left, orig_type_right);
8121 } else if (!is_type_object(unqual_left)) {
8122 if (!is_type_void(unqual_left)) {
8123 errorf(pos, "subtracting pointers to non-object types '%T'",
8126 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8129 expression->base.type = type_ptrdiff_t;
8130 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8131 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8132 orig_type_left, orig_type_right);
8136 static void warn_string_literal_address(expression_t const* expr)
8138 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8139 expr = expr->unary.value;
8140 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8142 expr = expr->unary.value;
8145 if (expr->kind == EXPR_STRING_LITERAL
8146 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8147 source_position_t const *const pos = &expr->base.source_position;
8148 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8152 static bool maybe_negative(expression_t const *const expr)
8154 switch (is_constant_expression(expr)) {
8155 case EXPR_CLASS_ERROR: return false;
8156 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8157 default: return true;
8161 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8163 warn_string_literal_address(expr);
8165 expression_t const* const ref = get_reference_address(expr);
8166 if (ref != NULL && is_null_pointer_constant(other)) {
8167 entity_t const *const ent = ref->reference.entity;
8168 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8171 if (!expr->base.parenthesized) {
8172 switch (expr->base.kind) {
8173 case EXPR_BINARY_LESS:
8174 case EXPR_BINARY_GREATER:
8175 case EXPR_BINARY_LESSEQUAL:
8176 case EXPR_BINARY_GREATEREQUAL:
8177 case EXPR_BINARY_NOTEQUAL:
8178 case EXPR_BINARY_EQUAL:
8179 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8188 * Check the semantics of comparison expressions.
8190 * @param expression The expression to check.
8192 static void semantic_comparison(binary_expression_t *expression)
8194 source_position_t const *const pos = &expression->base.source_position;
8195 expression_t *const left = expression->left;
8196 expression_t *const right = expression->right;
8198 warn_comparison(pos, left, right);
8199 warn_comparison(pos, right, left);
8201 type_t *orig_type_left = left->base.type;
8202 type_t *orig_type_right = right->base.type;
8203 type_t *type_left = skip_typeref(orig_type_left);
8204 type_t *type_right = skip_typeref(orig_type_right);
8206 /* TODO non-arithmetic types */
8207 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8208 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8210 /* test for signed vs unsigned compares */
8211 if (is_type_integer(arithmetic_type)) {
8212 bool const signed_left = is_type_signed(type_left);
8213 bool const signed_right = is_type_signed(type_right);
8214 if (signed_left != signed_right) {
8215 /* FIXME long long needs better const folding magic */
8216 /* TODO check whether constant value can be represented by other type */
8217 if ((signed_left && maybe_negative(left)) ||
8218 (signed_right && maybe_negative(right))) {
8219 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8224 expression->left = create_implicit_cast(left, arithmetic_type);
8225 expression->right = create_implicit_cast(right, arithmetic_type);
8226 expression->base.type = arithmetic_type;
8227 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8228 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8229 is_type_float(arithmetic_type)) {
8230 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8232 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8233 /* TODO check compatibility */
8234 } else if (is_type_pointer(type_left)) {
8235 expression->right = create_implicit_cast(right, type_left);
8236 } else if (is_type_pointer(type_right)) {
8237 expression->left = create_implicit_cast(left, type_right);
8238 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8239 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8241 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8245 * Checks if a compound type has constant fields.
8247 static bool has_const_fields(const compound_type_t *type)
8249 compound_t *compound = type->compound;
8250 entity_t *entry = compound->members.entities;
8252 for (; entry != NULL; entry = entry->base.next) {
8253 if (!is_declaration(entry))
8256 const type_t *decl_type = skip_typeref(entry->declaration.type);
8257 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8264 static bool is_valid_assignment_lhs(expression_t const* const left)
8266 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8267 type_t *const type_left = skip_typeref(orig_type_left);
8269 if (!is_lvalue(left)) {
8270 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8275 if (left->kind == EXPR_REFERENCE
8276 && left->reference.entity->kind == ENTITY_FUNCTION) {
8277 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8281 if (is_type_array(type_left)) {
8282 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8285 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8286 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8290 if (is_type_incomplete(type_left)) {
8291 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8292 left, orig_type_left);
8295 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8296 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8297 left, orig_type_left);
8304 static void semantic_arithmetic_assign(binary_expression_t *expression)
8306 expression_t *left = expression->left;
8307 expression_t *right = expression->right;
8308 type_t *orig_type_left = left->base.type;
8309 type_t *orig_type_right = right->base.type;
8311 if (!is_valid_assignment_lhs(left))
8314 type_t *type_left = skip_typeref(orig_type_left);
8315 type_t *type_right = skip_typeref(orig_type_right);
8317 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8318 /* TODO: improve error message */
8319 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8320 errorf(&expression->base.source_position,
8321 "operation needs arithmetic types");
8326 /* combined instructions are tricky. We can't create an implicit cast on
8327 * the left side, because we need the uncasted form for the store.
8328 * The ast2firm pass has to know that left_type must be right_type
8329 * for the arithmetic operation and create a cast by itself */
8330 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8331 expression->right = create_implicit_cast(right, arithmetic_type);
8332 expression->base.type = type_left;
8335 static void semantic_divmod_assign(binary_expression_t *expression)
8337 semantic_arithmetic_assign(expression);
8338 warn_div_by_zero(expression);
8341 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8343 expression_t *const left = expression->left;
8344 expression_t *const right = expression->right;
8345 type_t *const orig_type_left = left->base.type;
8346 type_t *const orig_type_right = right->base.type;
8347 type_t *const type_left = skip_typeref(orig_type_left);
8348 type_t *const type_right = skip_typeref(orig_type_right);
8350 if (!is_valid_assignment_lhs(left))
8353 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8354 /* combined instructions are tricky. We can't create an implicit cast on
8355 * the left side, because we need the uncasted form for the store.
8356 * The ast2firm pass has to know that left_type must be right_type
8357 * for the arithmetic operation and create a cast by itself */
8358 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8359 expression->right = create_implicit_cast(right, arithmetic_type);
8360 expression->base.type = type_left;
8361 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8362 check_pointer_arithmetic(&expression->base.source_position,
8363 type_left, orig_type_left);
8364 expression->base.type = type_left;
8365 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8366 errorf(&expression->base.source_position,
8367 "incompatible types '%T' and '%T' in assignment",
8368 orig_type_left, orig_type_right);
8372 static void semantic_integer_assign(binary_expression_t *expression)
8374 expression_t *left = expression->left;
8375 expression_t *right = expression->right;
8376 type_t *orig_type_left = left->base.type;
8377 type_t *orig_type_right = right->base.type;
8379 if (!is_valid_assignment_lhs(left))
8382 type_t *type_left = skip_typeref(orig_type_left);
8383 type_t *type_right = skip_typeref(orig_type_right);
8385 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8386 /* TODO: improve error message */
8387 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8388 errorf(&expression->base.source_position,
8389 "operation needs integer types");
8394 /* combined instructions are tricky. We can't create an implicit cast on
8395 * the left side, because we need the uncasted form for the store.
8396 * The ast2firm pass has to know that left_type must be right_type
8397 * for the arithmetic operation and create a cast by itself */
8398 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8399 expression->right = create_implicit_cast(right, arithmetic_type);
8400 expression->base.type = type_left;
8403 static void semantic_shift_assign(binary_expression_t *expression)
8405 expression_t *left = expression->left;
8407 if (!is_valid_assignment_lhs(left))
8410 if (!semantic_shift(expression))
8413 expression->base.type = skip_typeref(left->base.type);
8416 static void warn_logical_and_within_or(const expression_t *const expr)
8418 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8420 if (expr->base.parenthesized)
8422 source_position_t const *const pos = &expr->base.source_position;
8423 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8427 * Check the semantic restrictions of a logical expression.
8429 static void semantic_logical_op(binary_expression_t *expression)
8431 /* §6.5.13:2 Each of the operands shall have scalar type.
8432 * §6.5.14:2 Each of the operands shall have scalar type. */
8433 semantic_condition(expression->left, "left operand of logical operator");
8434 semantic_condition(expression->right, "right operand of logical operator");
8435 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8436 warn_logical_and_within_or(expression->left);
8437 warn_logical_and_within_or(expression->right);
8439 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8443 * Check the semantic restrictions of a binary assign expression.
8445 static void semantic_binexpr_assign(binary_expression_t *expression)
8447 expression_t *left = expression->left;
8448 type_t *orig_type_left = left->base.type;
8450 if (!is_valid_assignment_lhs(left))
8453 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8454 report_assign_error(error, orig_type_left, expression->right,
8455 "assignment", &left->base.source_position);
8456 expression->right = create_implicit_cast(expression->right, orig_type_left);
8457 expression->base.type = orig_type_left;
8461 * Determine if the outermost operation (or parts thereof) of the given
8462 * expression has no effect in order to generate a warning about this fact.
8463 * Therefore in some cases this only examines some of the operands of the
8464 * expression (see comments in the function and examples below).
8466 * f() + 23; // warning, because + has no effect
8467 * x || f(); // no warning, because x controls execution of f()
8468 * x ? y : f(); // warning, because y has no effect
8469 * (void)x; // no warning to be able to suppress the warning
8470 * This function can NOT be used for an "expression has definitely no effect"-
8472 static bool expression_has_effect(const expression_t *const expr)
8474 switch (expr->kind) {
8475 case EXPR_ERROR: return true; /* do NOT warn */
8476 case EXPR_REFERENCE: return false;
8477 case EXPR_ENUM_CONSTANT: return false;
8478 case EXPR_LABEL_ADDRESS: return false;
8480 /* suppress the warning for microsoft __noop operations */
8481 case EXPR_LITERAL_MS_NOOP: return true;
8482 case EXPR_LITERAL_BOOLEAN:
8483 case EXPR_LITERAL_CHARACTER:
8484 case EXPR_LITERAL_WIDE_CHARACTER:
8485 case EXPR_LITERAL_INTEGER:
8486 case EXPR_LITERAL_INTEGER_OCTAL:
8487 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8488 case EXPR_LITERAL_FLOATINGPOINT:
8489 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8490 case EXPR_STRING_LITERAL: return false;
8491 case EXPR_WIDE_STRING_LITERAL: return false;
8494 const call_expression_t *const call = &expr->call;
8495 if (call->function->kind != EXPR_REFERENCE)
8498 switch (call->function->reference.entity->function.btk) {
8499 /* FIXME: which builtins have no effect? */
8500 default: return true;
8504 /* Generate the warning if either the left or right hand side of a
8505 * conditional expression has no effect */
8506 case EXPR_CONDITIONAL: {
8507 conditional_expression_t const *const cond = &expr->conditional;
8508 expression_t const *const t = cond->true_expression;
8510 (t == NULL || expression_has_effect(t)) &&
8511 expression_has_effect(cond->false_expression);
8514 case EXPR_SELECT: return false;
8515 case EXPR_ARRAY_ACCESS: return false;
8516 case EXPR_SIZEOF: return false;
8517 case EXPR_CLASSIFY_TYPE: return false;
8518 case EXPR_ALIGNOF: return false;
8520 case EXPR_FUNCNAME: return false;
8521 case EXPR_BUILTIN_CONSTANT_P: return false;
8522 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8523 case EXPR_OFFSETOF: return false;
8524 case EXPR_VA_START: return true;
8525 case EXPR_VA_ARG: return true;
8526 case EXPR_VA_COPY: return true;
8527 case EXPR_STATEMENT: return true; // TODO
8528 case EXPR_COMPOUND_LITERAL: return false;
8530 case EXPR_UNARY_NEGATE: return false;
8531 case EXPR_UNARY_PLUS: return false;
8532 case EXPR_UNARY_BITWISE_NEGATE: return false;
8533 case EXPR_UNARY_NOT: return false;
8534 case EXPR_UNARY_DEREFERENCE: return false;
8535 case EXPR_UNARY_TAKE_ADDRESS: return false;
8536 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8537 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8538 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8539 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8541 /* Treat void casts as if they have an effect in order to being able to
8542 * suppress the warning */
8543 case EXPR_UNARY_CAST: {
8544 type_t *const type = skip_typeref(expr->base.type);
8545 return is_type_void(type);
8548 case EXPR_UNARY_ASSUME: return true;
8549 case EXPR_UNARY_DELETE: return true;
8550 case EXPR_UNARY_DELETE_ARRAY: return true;
8551 case EXPR_UNARY_THROW: return true;
8553 case EXPR_BINARY_ADD: return false;
8554 case EXPR_BINARY_SUB: return false;
8555 case EXPR_BINARY_MUL: return false;
8556 case EXPR_BINARY_DIV: return false;
8557 case EXPR_BINARY_MOD: return false;
8558 case EXPR_BINARY_EQUAL: return false;
8559 case EXPR_BINARY_NOTEQUAL: return false;
8560 case EXPR_BINARY_LESS: return false;
8561 case EXPR_BINARY_LESSEQUAL: return false;
8562 case EXPR_BINARY_GREATER: return false;
8563 case EXPR_BINARY_GREATEREQUAL: return false;
8564 case EXPR_BINARY_BITWISE_AND: return false;
8565 case EXPR_BINARY_BITWISE_OR: return false;
8566 case EXPR_BINARY_BITWISE_XOR: return false;
8567 case EXPR_BINARY_SHIFTLEFT: return false;
8568 case EXPR_BINARY_SHIFTRIGHT: return false;
8569 case EXPR_BINARY_ASSIGN: return true;
8570 case EXPR_BINARY_MUL_ASSIGN: return true;
8571 case EXPR_BINARY_DIV_ASSIGN: return true;
8572 case EXPR_BINARY_MOD_ASSIGN: return true;
8573 case EXPR_BINARY_ADD_ASSIGN: return true;
8574 case EXPR_BINARY_SUB_ASSIGN: return true;
8575 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8576 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8577 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8578 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8579 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8581 /* Only examine the right hand side of && and ||, because the left hand
8582 * side already has the effect of controlling the execution of the right
8584 case EXPR_BINARY_LOGICAL_AND:
8585 case EXPR_BINARY_LOGICAL_OR:
8586 /* Only examine the right hand side of a comma expression, because the left
8587 * hand side has a separate warning */
8588 case EXPR_BINARY_COMMA:
8589 return expression_has_effect(expr->binary.right);
8591 case EXPR_BINARY_ISGREATER: return false;
8592 case EXPR_BINARY_ISGREATEREQUAL: return false;
8593 case EXPR_BINARY_ISLESS: return false;
8594 case EXPR_BINARY_ISLESSEQUAL: return false;
8595 case EXPR_BINARY_ISLESSGREATER: return false;
8596 case EXPR_BINARY_ISUNORDERED: return false;
8599 internal_errorf(HERE, "unexpected expression");
8602 static void semantic_comma(binary_expression_t *expression)
8604 const expression_t *const left = expression->left;
8605 if (!expression_has_effect(left)) {
8606 source_position_t const *const pos = &left->base.source_position;
8607 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8609 expression->base.type = expression->right->base.type;
8613 * @param prec_r precedence of the right operand
8615 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8616 static expression_t *parse_##binexpression_type(expression_t *left) \
8618 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8619 binexpr->binary.left = left; \
8622 expression_t *right = parse_subexpression(prec_r); \
8624 binexpr->binary.right = right; \
8625 sfunc(&binexpr->binary); \
8630 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8631 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8632 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8633 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8634 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8635 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8636 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8637 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8638 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8639 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8640 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8641 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8642 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8643 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8644 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8645 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8646 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8647 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8648 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8649 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8650 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8651 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8652 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8653 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8654 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8655 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8656 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8657 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8658 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8659 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8662 static expression_t *parse_subexpression(precedence_t precedence)
8664 if (token.kind < 0) {
8665 return expected_expression_error();
8668 expression_parser_function_t *parser
8669 = &expression_parsers[token.kind];
8672 if (parser->parser != NULL) {
8673 left = parser->parser();
8675 left = parse_primary_expression();
8677 assert(left != NULL);
8680 if (token.kind < 0) {
8681 return expected_expression_error();
8684 parser = &expression_parsers[token.kind];
8685 if (parser->infix_parser == NULL)
8687 if (parser->infix_precedence < precedence)
8690 left = parser->infix_parser(left);
8692 assert(left != NULL);
8699 * Parse an expression.
8701 static expression_t *parse_expression(void)
8703 return parse_subexpression(PREC_EXPRESSION);
8707 * Register a parser for a prefix-like operator.
8709 * @param parser the parser function
8710 * @param token_kind the token type of the prefix token
8712 static void register_expression_parser(parse_expression_function parser,
8715 expression_parser_function_t *entry = &expression_parsers[token_kind];
8717 if (entry->parser != NULL) {
8718 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8719 panic("trying to register multiple expression parsers for a token");
8721 entry->parser = parser;
8725 * Register a parser for an infix operator with given precedence.
8727 * @param parser the parser function
8728 * @param token_kind the token type of the infix operator
8729 * @param precedence the precedence of the operator
8731 static void register_infix_parser(parse_expression_infix_function parser,
8732 int token_kind, precedence_t precedence)
8734 expression_parser_function_t *entry = &expression_parsers[token_kind];
8736 if (entry->infix_parser != NULL) {
8737 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8738 panic("trying to register multiple infix expression parsers for a "
8741 entry->infix_parser = parser;
8742 entry->infix_precedence = precedence;
8746 * Initialize the expression parsers.
8748 static void init_expression_parsers(void)
8750 memset(&expression_parsers, 0, sizeof(expression_parsers));
8752 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8753 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8754 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8755 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8756 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8757 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8758 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8759 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8760 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8761 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8762 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8763 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8764 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8765 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8766 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8767 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8768 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8769 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8770 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8771 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8772 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8773 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8774 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8775 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8776 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8777 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8778 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8779 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8780 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8781 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8782 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8783 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8784 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8785 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8786 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8787 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8788 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8790 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8791 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8792 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8793 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8794 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8795 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8796 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8797 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8798 register_expression_parser(parse_sizeof, T_sizeof);
8799 register_expression_parser(parse_alignof, T___alignof__);
8800 register_expression_parser(parse_extension, T___extension__);
8801 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8802 register_expression_parser(parse_delete, T_delete);
8803 register_expression_parser(parse_throw, T_throw);
8807 * Parse a asm statement arguments specification.
8809 static asm_argument_t *parse_asm_arguments(bool is_out)
8811 asm_argument_t *result = NULL;
8812 asm_argument_t **anchor = &result;
8814 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8815 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8818 add_anchor_token(']');
8819 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8820 rem_anchor_token(']');
8822 if (!argument->symbol)
8826 argument->constraints = parse_string_literals();
8828 add_anchor_token(')');
8829 expression_t *expression = parse_expression();
8830 rem_anchor_token(')');
8832 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8833 * change size or type representation (e.g. int -> long is ok, but
8834 * int -> float is not) */
8835 if (expression->kind == EXPR_UNARY_CAST) {
8836 type_t *const type = expression->base.type;
8837 type_kind_t const kind = type->kind;
8838 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8841 if (kind == TYPE_ATOMIC) {
8842 atomic_type_kind_t const akind = type->atomic.akind;
8843 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8844 size = get_atomic_type_size(akind);
8846 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8847 size = get_type_size(type_void_ptr);
8851 expression_t *const value = expression->unary.value;
8852 type_t *const value_type = value->base.type;
8853 type_kind_t const value_kind = value_type->kind;
8855 unsigned value_flags;
8856 unsigned value_size;
8857 if (value_kind == TYPE_ATOMIC) {
8858 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8859 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8860 value_size = get_atomic_type_size(value_akind);
8861 } else if (value_kind == TYPE_POINTER) {
8862 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8863 value_size = get_type_size(type_void_ptr);
8868 if (value_flags != flags || value_size != size)
8872 } while (expression->kind == EXPR_UNARY_CAST);
8876 if (!is_lvalue(expression)) {
8877 errorf(&expression->base.source_position,
8878 "asm output argument is not an lvalue");
8881 if (argument->constraints.begin[0] == '=')
8882 determine_lhs_ent(expression, NULL);
8884 mark_vars_read(expression, NULL);
8886 mark_vars_read(expression, NULL);
8888 argument->expression = expression;
8891 set_address_taken(expression, true);
8894 anchor = &argument->next;
8904 * Parse a asm statement clobber specification.
8906 static asm_clobber_t *parse_asm_clobbers(void)
8908 asm_clobber_t *result = NULL;
8909 asm_clobber_t **anchor = &result;
8911 while (token.kind == T_STRING_LITERAL) {
8912 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8913 clobber->clobber = parse_string_literals();
8916 anchor = &clobber->next;
8926 * Parse an asm statement.
8928 static statement_t *parse_asm_statement(void)
8930 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8931 asm_statement_t *asm_statement = &statement->asms;
8935 if (next_if(T_volatile))
8936 asm_statement->is_volatile = true;
8939 add_anchor_token(')');
8940 if (token.kind != T_STRING_LITERAL) {
8941 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8944 asm_statement->asm_text = parse_string_literals();
8946 add_anchor_token(':');
8947 if (!next_if(':')) {
8948 rem_anchor_token(':');
8952 asm_statement->outputs = parse_asm_arguments(true);
8953 if (!next_if(':')) {
8954 rem_anchor_token(':');
8958 asm_statement->inputs = parse_asm_arguments(false);
8959 if (!next_if(':')) {
8960 rem_anchor_token(':');
8963 rem_anchor_token(':');
8965 asm_statement->clobbers = parse_asm_clobbers();
8968 rem_anchor_token(')');
8972 if (asm_statement->outputs == NULL) {
8973 /* GCC: An 'asm' instruction without any output operands will be treated
8974 * identically to a volatile 'asm' instruction. */
8975 asm_statement->is_volatile = true;
8981 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8983 statement_t *inner_stmt;
8984 switch (token.kind) {
8986 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8987 inner_stmt = create_error_statement();
8991 if (label->kind == STATEMENT_LABEL) {
8992 /* Eat an empty statement here, to avoid the warning about an empty
8993 * statement after a label. label:; is commonly used to have a label
8994 * before a closing brace. */
8995 inner_stmt = create_empty_statement();
9002 inner_stmt = parse_statement();
9003 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9004 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9005 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9006 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9014 * Parse a case statement.
9016 static statement_t *parse_case_statement(void)
9018 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9019 source_position_t *const pos = &statement->base.source_position;
9022 add_anchor_token(':');
9024 expression_t *expression = parse_expression();
9025 type_t *expression_type = expression->base.type;
9026 type_t *skipped = skip_typeref(expression_type);
9027 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9028 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9029 expression, expression_type);
9032 type_t *type = expression_type;
9033 if (current_switch != NULL) {
9034 type_t *switch_type = current_switch->expression->base.type;
9035 if (is_type_valid(switch_type)) {
9036 expression = create_implicit_cast(expression, switch_type);
9040 statement->case_label.expression = expression;
9041 expression_classification_t const expr_class = is_constant_expression(expression);
9042 if (expr_class != EXPR_CLASS_CONSTANT) {
9043 if (expr_class != EXPR_CLASS_ERROR) {
9044 errorf(pos, "case label does not reduce to an integer constant");
9046 statement->case_label.is_bad = true;
9048 long const val = fold_constant_to_int(expression);
9049 statement->case_label.first_case = val;
9050 statement->case_label.last_case = val;
9054 if (next_if(T_DOTDOTDOT)) {
9055 expression_t *end_range = parse_expression();
9056 expression_type = expression->base.type;
9057 skipped = skip_typeref(expression_type);
9058 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9059 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9060 expression, expression_type);
9063 end_range = create_implicit_cast(end_range, type);
9064 statement->case_label.end_range = end_range;
9065 expression_classification_t const end_class = is_constant_expression(end_range);
9066 if (end_class != EXPR_CLASS_CONSTANT) {
9067 if (end_class != EXPR_CLASS_ERROR) {
9068 errorf(pos, "case range does not reduce to an integer constant");
9070 statement->case_label.is_bad = true;
9072 long const val = fold_constant_to_int(end_range);
9073 statement->case_label.last_case = val;
9075 if (val < statement->case_label.first_case) {
9076 statement->case_label.is_empty_range = true;
9077 warningf(WARN_OTHER, pos, "empty range specified");
9083 PUSH_PARENT(statement);
9085 rem_anchor_token(':');
9088 if (current_switch != NULL) {
9089 if (! statement->case_label.is_bad) {
9090 /* Check for duplicate case values */
9091 case_label_statement_t *c = &statement->case_label;
9092 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9093 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9096 if (c->last_case < l->first_case || c->first_case > l->last_case)
9099 errorf(pos, "duplicate case value (previously used %P)",
9100 &l->base.source_position);
9104 /* link all cases into the switch statement */
9105 if (current_switch->last_case == NULL) {
9106 current_switch->first_case = &statement->case_label;
9108 current_switch->last_case->next = &statement->case_label;
9110 current_switch->last_case = &statement->case_label;
9112 errorf(pos, "case label not within a switch statement");
9115 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9122 * Parse a default statement.
9124 static statement_t *parse_default_statement(void)
9126 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9130 PUSH_PARENT(statement);
9134 if (current_switch != NULL) {
9135 const case_label_statement_t *def_label = current_switch->default_label;
9136 if (def_label != NULL) {
9137 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9139 current_switch->default_label = &statement->case_label;
9141 /* link all cases into the switch statement */
9142 if (current_switch->last_case == NULL) {
9143 current_switch->first_case = &statement->case_label;
9145 current_switch->last_case->next = &statement->case_label;
9147 current_switch->last_case = &statement->case_label;
9150 errorf(&statement->base.source_position,
9151 "'default' label not within a switch statement");
9154 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9161 * Parse a label statement.
9163 static statement_t *parse_label_statement(void)
9165 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9166 label_t *const label = get_label();
9167 statement->label.label = label;
9169 PUSH_PARENT(statement);
9171 /* if statement is already set then the label is defined twice,
9172 * otherwise it was just mentioned in a goto/local label declaration so far
9174 source_position_t const* const pos = &statement->base.source_position;
9175 if (label->statement != NULL) {
9176 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9178 label->base.source_position = *pos;
9179 label->statement = statement;
9184 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9185 parse_attributes(NULL); // TODO process attributes
9188 statement->label.statement = parse_label_inner_statement(statement, "label");
9190 /* remember the labels in a list for later checking */
9191 *label_anchor = &statement->label;
9192 label_anchor = &statement->label.next;
9198 static statement_t *parse_inner_statement(void)
9200 statement_t *const stmt = parse_statement();
9201 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9202 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9203 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9204 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9210 * Parse an expression in parentheses and mark its variables as read.
9212 static expression_t *parse_condition(void)
9215 add_anchor_token(')');
9216 expression_t *const expr = parse_expression();
9217 mark_vars_read(expr, NULL);
9218 rem_anchor_token(')');
9224 * Parse an if statement.
9226 static statement_t *parse_if(void)
9228 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9232 PUSH_PARENT(statement);
9234 add_anchor_token('{');
9236 expression_t *const expr = parse_condition();
9237 statement->ifs.condition = expr;
9238 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9240 semantic_condition(expr, "condition of 'if'-statment");
9242 rem_anchor_token('{');
9244 add_anchor_token(T_else);
9245 statement_t *const true_stmt = parse_inner_statement();
9246 statement->ifs.true_statement = true_stmt;
9247 rem_anchor_token(T_else);
9249 if (true_stmt->kind == STATEMENT_EMPTY) {
9250 warningf(WARN_EMPTY_BODY, HERE,
9251 "suggest braces around empty body in an ‘if’ statement");
9254 if (next_if(T_else)) {
9255 statement->ifs.false_statement = parse_inner_statement();
9257 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9258 warningf(WARN_EMPTY_BODY, HERE,
9259 "suggest braces around empty body in an ‘if’ statement");
9261 } else if (true_stmt->kind == STATEMENT_IF &&
9262 true_stmt->ifs.false_statement != NULL) {
9263 source_position_t const *const pos = &true_stmt->base.source_position;
9264 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9272 * Check that all enums are handled in a switch.
9274 * @param statement the switch statement to check
9276 static void check_enum_cases(const switch_statement_t *statement)
9278 if (!is_warn_on(WARN_SWITCH_ENUM))
9280 const type_t *type = skip_typeref(statement->expression->base.type);
9281 if (! is_type_enum(type))
9283 const enum_type_t *enumt = &type->enumt;
9285 /* if we have a default, no warnings */
9286 if (statement->default_label != NULL)
9289 /* FIXME: calculation of value should be done while parsing */
9290 /* TODO: quadratic algorithm here. Change to an n log n one */
9291 long last_value = -1;
9292 const entity_t *entry = enumt->enume->base.next;
9293 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9294 entry = entry->base.next) {
9295 const expression_t *expression = entry->enum_value.value;
9296 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9298 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9299 if (l->expression == NULL)
9301 if (l->first_case <= value && value <= l->last_case) {
9307 source_position_t const *const pos = &statement->base.source_position;
9308 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9315 * Parse a switch statement.
9317 static statement_t *parse_switch(void)
9319 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9323 PUSH_PARENT(statement);
9325 expression_t *const expr = parse_condition();
9326 type_t * type = skip_typeref(expr->base.type);
9327 if (is_type_integer(type)) {
9328 type = promote_integer(type);
9329 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9330 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9332 } else if (is_type_valid(type)) {
9333 errorf(&expr->base.source_position,
9334 "switch quantity is not an integer, but '%T'", type);
9335 type = type_error_type;
9337 statement->switchs.expression = create_implicit_cast(expr, type);
9339 switch_statement_t *rem = current_switch;
9340 current_switch = &statement->switchs;
9341 statement->switchs.body = parse_inner_statement();
9342 current_switch = rem;
9344 if (statement->switchs.default_label == NULL) {
9345 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9347 check_enum_cases(&statement->switchs);
9353 static statement_t *parse_loop_body(statement_t *const loop)
9355 statement_t *const rem = current_loop;
9356 current_loop = loop;
9358 statement_t *const body = parse_inner_statement();
9365 * Parse a while statement.
9367 static statement_t *parse_while(void)
9369 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9373 PUSH_PARENT(statement);
9375 expression_t *const cond = parse_condition();
9376 statement->whiles.condition = cond;
9377 /* §6.8.5:2 The controlling expression of an iteration statement shall
9378 * have scalar type. */
9379 semantic_condition(cond, "condition of 'while'-statement");
9381 statement->whiles.body = parse_loop_body(statement);
9388 * Parse a do statement.
9390 static statement_t *parse_do(void)
9392 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9396 PUSH_PARENT(statement);
9398 add_anchor_token(T_while);
9399 statement->do_while.body = parse_loop_body(statement);
9400 rem_anchor_token(T_while);
9403 expression_t *const cond = parse_condition();
9404 statement->do_while.condition = cond;
9405 /* §6.8.5:2 The controlling expression of an iteration statement shall
9406 * have scalar type. */
9407 semantic_condition(cond, "condition of 'do-while'-statement");
9415 * Parse a for statement.
9417 static statement_t *parse_for(void)
9419 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9423 PUSH_PARENT(statement);
9424 PUSH_SCOPE(&statement->fors.scope);
9427 add_anchor_token(')');
9432 } else if (is_declaration_specifier(&token)) {
9433 parse_declaration(record_entity, DECL_FLAGS_NONE);
9435 add_anchor_token(';');
9436 expression_t *const init = parse_expression();
9437 statement->fors.initialisation = init;
9438 mark_vars_read(init, ENT_ANY);
9439 if (!expression_has_effect(init)) {
9440 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9442 rem_anchor_token(';');
9448 if (token.kind != ';') {
9449 add_anchor_token(';');
9450 expression_t *const cond = parse_expression();
9451 statement->fors.condition = cond;
9452 /* §6.8.5:2 The controlling expression of an iteration statement
9453 * shall have scalar type. */
9454 semantic_condition(cond, "condition of 'for'-statement");
9455 mark_vars_read(cond, NULL);
9456 rem_anchor_token(';');
9459 if (token.kind != ')') {
9460 expression_t *const step = parse_expression();
9461 statement->fors.step = step;
9462 mark_vars_read(step, ENT_ANY);
9463 if (!expression_has_effect(step)) {
9464 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9467 rem_anchor_token(')');
9469 statement->fors.body = parse_loop_body(statement);
9477 * Parse a goto statement.
9479 static statement_t *parse_goto(void)
9481 statement_t *statement;
9482 if (GNU_MODE && look_ahead(1)->kind == '*') {
9483 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9487 expression_t *expression = parse_expression();
9488 mark_vars_read(expression, NULL);
9490 /* Argh: although documentation says the expression must be of type void*,
9491 * gcc accepts anything that can be casted into void* without error */
9492 type_t *type = expression->base.type;
9494 if (type != type_error_type) {
9495 if (!is_type_pointer(type) && !is_type_integer(type)) {
9496 errorf(&expression->base.source_position,
9497 "cannot convert to a pointer type");
9498 } else if (type != type_void_ptr) {
9499 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9501 expression = create_implicit_cast(expression, type_void_ptr);
9504 statement->computed_goto.expression = expression;
9506 statement = allocate_statement_zero(STATEMENT_GOTO);
9508 if (token.kind == T_IDENTIFIER) {
9509 label_t *const label = get_label();
9511 statement->gotos.label = label;
9513 /* remember the goto's in a list for later checking */
9514 *goto_anchor = &statement->gotos;
9515 goto_anchor = &statement->gotos.next;
9518 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9520 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9522 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9531 * Parse a continue statement.
9533 static statement_t *parse_continue(void)
9535 if (current_loop == NULL) {
9536 errorf(HERE, "continue statement not within loop");
9539 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9547 * Parse a break statement.
9549 static statement_t *parse_break(void)
9551 if (current_switch == NULL && current_loop == NULL) {
9552 errorf(HERE, "break statement not within loop or switch");
9555 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9563 * Parse a __leave statement.
9565 static statement_t *parse_leave_statement(void)
9567 if (current_try == NULL) {
9568 errorf(HERE, "__leave statement not within __try");
9571 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9579 * Check if a given entity represents a local variable.
9581 static bool is_local_variable(const entity_t *entity)
9583 if (entity->kind != ENTITY_VARIABLE)
9586 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9587 case STORAGE_CLASS_AUTO:
9588 case STORAGE_CLASS_REGISTER: {
9589 const type_t *type = skip_typeref(entity->declaration.type);
9590 if (is_type_function(type)) {
9602 * Check if a given expression represents a local variable.
9604 static bool expression_is_local_variable(const expression_t *expression)
9606 if (expression->base.kind != EXPR_REFERENCE) {
9609 const entity_t *entity = expression->reference.entity;
9610 return is_local_variable(entity);
9614 * Check if a given expression represents a local variable and
9615 * return its declaration then, else return NULL.
9617 entity_t *expression_is_variable(const expression_t *expression)
9619 if (expression->base.kind != EXPR_REFERENCE) {
9622 entity_t *entity = expression->reference.entity;
9623 if (entity->kind != ENTITY_VARIABLE)
9629 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9631 if (c_mode & _CXX || strict_mode) {
9634 warningf(WARN_OTHER, pos, msg);
9639 * Parse a return statement.
9641 static statement_t *parse_return(void)
9643 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9646 expression_t *return_value = NULL;
9647 if (token.kind != ';') {
9648 return_value = parse_expression();
9649 mark_vars_read(return_value, NULL);
9652 const type_t *const func_type = skip_typeref(current_function->base.type);
9653 assert(is_type_function(func_type));
9654 type_t *const return_type = skip_typeref(func_type->function.return_type);
9656 source_position_t const *const pos = &statement->base.source_position;
9657 if (return_value != NULL) {
9658 type_t *return_value_type = skip_typeref(return_value->base.type);
9660 if (is_type_void(return_type)) {
9661 if (!is_type_void(return_value_type)) {
9662 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9663 /* Only warn in C mode, because GCC does the same */
9664 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9665 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9666 /* Only warn in C mode, because GCC does the same */
9667 err_or_warn(pos, "'return' with expression in function returning 'void'");
9670 assign_error_t error = semantic_assign(return_type, return_value);
9671 report_assign_error(error, return_type, return_value, "'return'",
9674 return_value = create_implicit_cast(return_value, return_type);
9675 /* check for returning address of a local var */
9676 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9677 const expression_t *expression = return_value->unary.value;
9678 if (expression_is_local_variable(expression)) {
9679 warningf(WARN_OTHER, pos, "function returns address of local variable");
9682 } else if (!is_type_void(return_type)) {
9683 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9684 err_or_warn(pos, "'return' without value, in function returning non-void");
9686 statement->returns.value = return_value;
9693 * Parse a declaration statement.
9695 static statement_t *parse_declaration_statement(void)
9697 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9699 entity_t *before = current_scope->last_entity;
9701 parse_external_declaration();
9703 parse_declaration(record_entity, DECL_FLAGS_NONE);
9706 declaration_statement_t *const decl = &statement->declaration;
9707 entity_t *const begin =
9708 before != NULL ? before->base.next : current_scope->entities;
9709 decl->declarations_begin = begin;
9710 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9716 * Parse an expression statement, ie. expr ';'.
9718 static statement_t *parse_expression_statement(void)
9720 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9722 expression_t *const expr = parse_expression();
9723 statement->expression.expression = expr;
9724 mark_vars_read(expr, ENT_ANY);
9731 * Parse a microsoft __try { } __finally { } or
9732 * __try{ } __except() { }
9734 static statement_t *parse_ms_try_statment(void)
9736 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9739 PUSH_PARENT(statement);
9741 ms_try_statement_t *rem = current_try;
9742 current_try = &statement->ms_try;
9743 statement->ms_try.try_statement = parse_compound_statement(false);
9748 if (next_if(T___except)) {
9749 expression_t *const expr = parse_condition();
9750 type_t * type = skip_typeref(expr->base.type);
9751 if (is_type_integer(type)) {
9752 type = promote_integer(type);
9753 } else if (is_type_valid(type)) {
9754 errorf(&expr->base.source_position,
9755 "__expect expression is not an integer, but '%T'", type);
9756 type = type_error_type;
9758 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9759 } else if (!next_if(T__finally)) {
9760 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9762 statement->ms_try.final_statement = parse_compound_statement(false);
9766 static statement_t *parse_empty_statement(void)
9768 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9769 statement_t *const statement = create_empty_statement();
9774 static statement_t *parse_local_label_declaration(void)
9776 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9780 entity_t *begin = NULL;
9781 entity_t *end = NULL;
9782 entity_t **anchor = &begin;
9784 source_position_t pos;
9785 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9789 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9790 if (entity != NULL && entity->base.parent_scope == current_scope) {
9791 source_position_t const *const ppos = &entity->base.source_position;
9792 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9794 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9795 entity->base.parent_scope = current_scope;
9798 anchor = &entity->base.next;
9801 environment_push(entity);
9803 } while (next_if(','));
9806 statement->declaration.declarations_begin = begin;
9807 statement->declaration.declarations_end = end;
9811 static void parse_namespace_definition(void)
9815 entity_t *entity = NULL;
9816 symbol_t *symbol = NULL;
9818 if (token.kind == T_IDENTIFIER) {
9819 symbol = token.identifier.symbol;
9822 entity = get_entity(symbol, NAMESPACE_NORMAL);
9824 && entity->kind != ENTITY_NAMESPACE
9825 && entity->base.parent_scope == current_scope) {
9826 if (is_entity_valid(entity)) {
9827 error_redefined_as_different_kind(&token.base.source_position,
9828 entity, ENTITY_NAMESPACE);
9834 if (entity == NULL) {
9835 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9836 entity->base.parent_scope = current_scope;
9839 if (token.kind == '=') {
9840 /* TODO: parse namespace alias */
9841 panic("namespace alias definition not supported yet");
9844 environment_push(entity);
9845 append_entity(current_scope, entity);
9847 PUSH_SCOPE(&entity->namespacee.members);
9849 entity_t *old_current_entity = current_entity;
9850 current_entity = entity;
9852 add_anchor_token('}');
9855 rem_anchor_token('}');
9858 assert(current_entity == entity);
9859 current_entity = old_current_entity;
9864 * Parse a statement.
9865 * There's also parse_statement() which additionally checks for
9866 * "statement has no effect" warnings
9868 static statement_t *intern_parse_statement(void)
9870 /* declaration or statement */
9871 statement_t *statement;
9872 switch (token.kind) {
9873 case T_IDENTIFIER: {
9874 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9875 if (la1_type == ':') {
9876 statement = parse_label_statement();
9877 } else if (is_typedef_symbol(token.identifier.symbol)) {
9878 statement = parse_declaration_statement();
9880 /* it's an identifier, the grammar says this must be an
9881 * expression statement. However it is common that users mistype
9882 * declaration types, so we guess a bit here to improve robustness
9883 * for incorrect programs */
9887 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9889 statement = parse_expression_statement();
9893 statement = parse_declaration_statement();
9901 case T___extension__: {
9902 /* This can be a prefix to a declaration or an expression statement.
9903 * We simply eat it now and parse the rest with tail recursion. */
9905 statement = intern_parse_statement();
9911 statement = parse_declaration_statement();
9915 statement = parse_local_label_declaration();
9918 case ';': statement = parse_empty_statement(); break;
9919 case '{': statement = parse_compound_statement(false); break;
9920 case T___leave: statement = parse_leave_statement(); break;
9921 case T___try: statement = parse_ms_try_statment(); break;
9922 case T_asm: statement = parse_asm_statement(); break;
9923 case T_break: statement = parse_break(); break;
9924 case T_case: statement = parse_case_statement(); break;
9925 case T_continue: statement = parse_continue(); break;
9926 case T_default: statement = parse_default_statement(); break;
9927 case T_do: statement = parse_do(); break;
9928 case T_for: statement = parse_for(); break;
9929 case T_goto: statement = parse_goto(); break;
9930 case T_if: statement = parse_if(); break;
9931 case T_return: statement = parse_return(); break;
9932 case T_switch: statement = parse_switch(); break;
9933 case T_while: statement = parse_while(); break;
9936 statement = parse_expression_statement();
9940 errorf(HERE, "unexpected token %K while parsing statement", &token);
9941 statement = create_error_statement();
9950 * parse a statement and emits "statement has no effect" warning if needed
9951 * (This is really a wrapper around intern_parse_statement with check for 1
9952 * single warning. It is needed, because for statement expressions we have
9953 * to avoid the warning on the last statement)
9955 static statement_t *parse_statement(void)
9957 statement_t *statement = intern_parse_statement();
9959 if (statement->kind == STATEMENT_EXPRESSION) {
9960 expression_t *expression = statement->expression.expression;
9961 if (!expression_has_effect(expression)) {
9962 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9970 * Parse a compound statement.
9972 static statement_t *parse_compound_statement(bool inside_expression_statement)
9974 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9976 PUSH_PARENT(statement);
9977 PUSH_SCOPE(&statement->compound.scope);
9980 add_anchor_token('}');
9981 /* tokens, which can start a statement */
9982 /* TODO MS, __builtin_FOO */
9983 add_anchor_token('!');
9984 add_anchor_token('&');
9985 add_anchor_token('(');
9986 add_anchor_token('*');
9987 add_anchor_token('+');
9988 add_anchor_token('-');
9989 add_anchor_token(';');
9990 add_anchor_token('{');
9991 add_anchor_token('~');
9992 add_anchor_token(T_CHARACTER_CONSTANT);
9993 add_anchor_token(T_COLONCOLON);
9994 add_anchor_token(T_FLOATINGPOINT);
9995 add_anchor_token(T_IDENTIFIER);
9996 add_anchor_token(T_INTEGER);
9997 add_anchor_token(T_MINUSMINUS);
9998 add_anchor_token(T_PLUSPLUS);
9999 add_anchor_token(T_STRING_LITERAL);
10000 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10001 add_anchor_token(T_WIDE_STRING_LITERAL);
10002 add_anchor_token(T__Bool);
10003 add_anchor_token(T__Complex);
10004 add_anchor_token(T__Imaginary);
10005 add_anchor_token(T___FUNCTION__);
10006 add_anchor_token(T___PRETTY_FUNCTION__);
10007 add_anchor_token(T___alignof__);
10008 add_anchor_token(T___attribute__);
10009 add_anchor_token(T___builtin_va_start);
10010 add_anchor_token(T___extension__);
10011 add_anchor_token(T___func__);
10012 add_anchor_token(T___imag__);
10013 add_anchor_token(T___label__);
10014 add_anchor_token(T___real__);
10015 add_anchor_token(T___thread);
10016 add_anchor_token(T_asm);
10017 add_anchor_token(T_auto);
10018 add_anchor_token(T_bool);
10019 add_anchor_token(T_break);
10020 add_anchor_token(T_case);
10021 add_anchor_token(T_char);
10022 add_anchor_token(T_class);
10023 add_anchor_token(T_const);
10024 add_anchor_token(T_const_cast);
10025 add_anchor_token(T_continue);
10026 add_anchor_token(T_default);
10027 add_anchor_token(T_delete);
10028 add_anchor_token(T_double);
10029 add_anchor_token(T_do);
10030 add_anchor_token(T_dynamic_cast);
10031 add_anchor_token(T_enum);
10032 add_anchor_token(T_extern);
10033 add_anchor_token(T_false);
10034 add_anchor_token(T_float);
10035 add_anchor_token(T_for);
10036 add_anchor_token(T_goto);
10037 add_anchor_token(T_if);
10038 add_anchor_token(T_inline);
10039 add_anchor_token(T_int);
10040 add_anchor_token(T_long);
10041 add_anchor_token(T_new);
10042 add_anchor_token(T_operator);
10043 add_anchor_token(T_register);
10044 add_anchor_token(T_reinterpret_cast);
10045 add_anchor_token(T_restrict);
10046 add_anchor_token(T_return);
10047 add_anchor_token(T_short);
10048 add_anchor_token(T_signed);
10049 add_anchor_token(T_sizeof);
10050 add_anchor_token(T_static);
10051 add_anchor_token(T_static_cast);
10052 add_anchor_token(T_struct);
10053 add_anchor_token(T_switch);
10054 add_anchor_token(T_template);
10055 add_anchor_token(T_this);
10056 add_anchor_token(T_throw);
10057 add_anchor_token(T_true);
10058 add_anchor_token(T_try);
10059 add_anchor_token(T_typedef);
10060 add_anchor_token(T_typeid);
10061 add_anchor_token(T_typename);
10062 add_anchor_token(T_typeof);
10063 add_anchor_token(T_union);
10064 add_anchor_token(T_unsigned);
10065 add_anchor_token(T_using);
10066 add_anchor_token(T_void);
10067 add_anchor_token(T_volatile);
10068 add_anchor_token(T_wchar_t);
10069 add_anchor_token(T_while);
10071 statement_t **anchor = &statement->compound.statements;
10072 bool only_decls_so_far = true;
10073 while (token.kind != '}' && token.kind != T_EOF) {
10074 statement_t *sub_statement = intern_parse_statement();
10075 if (sub_statement->kind == STATEMENT_ERROR) {
10079 if (sub_statement->kind != STATEMENT_DECLARATION) {
10080 only_decls_so_far = false;
10081 } else if (!only_decls_so_far) {
10082 source_position_t const *const pos = &sub_statement->base.source_position;
10083 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10086 *anchor = sub_statement;
10087 anchor = &sub_statement->base.next;
10091 /* look over all statements again to produce no effect warnings */
10092 if (is_warn_on(WARN_UNUSED_VALUE)) {
10093 statement_t *sub_statement = statement->compound.statements;
10094 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10095 if (sub_statement->kind != STATEMENT_EXPRESSION)
10097 /* don't emit a warning for the last expression in an expression
10098 * statement as it has always an effect */
10099 if (inside_expression_statement && sub_statement->base.next == NULL)
10102 expression_t *expression = sub_statement->expression.expression;
10103 if (!expression_has_effect(expression)) {
10104 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10109 rem_anchor_token(T_while);
10110 rem_anchor_token(T_wchar_t);
10111 rem_anchor_token(T_volatile);
10112 rem_anchor_token(T_void);
10113 rem_anchor_token(T_using);
10114 rem_anchor_token(T_unsigned);
10115 rem_anchor_token(T_union);
10116 rem_anchor_token(T_typeof);
10117 rem_anchor_token(T_typename);
10118 rem_anchor_token(T_typeid);
10119 rem_anchor_token(T_typedef);
10120 rem_anchor_token(T_try);
10121 rem_anchor_token(T_true);
10122 rem_anchor_token(T_throw);
10123 rem_anchor_token(T_this);
10124 rem_anchor_token(T_template);
10125 rem_anchor_token(T_switch);
10126 rem_anchor_token(T_struct);
10127 rem_anchor_token(T_static_cast);
10128 rem_anchor_token(T_static);
10129 rem_anchor_token(T_sizeof);
10130 rem_anchor_token(T_signed);
10131 rem_anchor_token(T_short);
10132 rem_anchor_token(T_return);
10133 rem_anchor_token(T_restrict);
10134 rem_anchor_token(T_reinterpret_cast);
10135 rem_anchor_token(T_register);
10136 rem_anchor_token(T_operator);
10137 rem_anchor_token(T_new);
10138 rem_anchor_token(T_long);
10139 rem_anchor_token(T_int);
10140 rem_anchor_token(T_inline);
10141 rem_anchor_token(T_if);
10142 rem_anchor_token(T_goto);
10143 rem_anchor_token(T_for);
10144 rem_anchor_token(T_float);
10145 rem_anchor_token(T_false);
10146 rem_anchor_token(T_extern);
10147 rem_anchor_token(T_enum);
10148 rem_anchor_token(T_dynamic_cast);
10149 rem_anchor_token(T_do);
10150 rem_anchor_token(T_double);
10151 rem_anchor_token(T_delete);
10152 rem_anchor_token(T_default);
10153 rem_anchor_token(T_continue);
10154 rem_anchor_token(T_const_cast);
10155 rem_anchor_token(T_const);
10156 rem_anchor_token(T_class);
10157 rem_anchor_token(T_char);
10158 rem_anchor_token(T_case);
10159 rem_anchor_token(T_break);
10160 rem_anchor_token(T_bool);
10161 rem_anchor_token(T_auto);
10162 rem_anchor_token(T_asm);
10163 rem_anchor_token(T___thread);
10164 rem_anchor_token(T___real__);
10165 rem_anchor_token(T___label__);
10166 rem_anchor_token(T___imag__);
10167 rem_anchor_token(T___func__);
10168 rem_anchor_token(T___extension__);
10169 rem_anchor_token(T___builtin_va_start);
10170 rem_anchor_token(T___attribute__);
10171 rem_anchor_token(T___alignof__);
10172 rem_anchor_token(T___PRETTY_FUNCTION__);
10173 rem_anchor_token(T___FUNCTION__);
10174 rem_anchor_token(T__Imaginary);
10175 rem_anchor_token(T__Complex);
10176 rem_anchor_token(T__Bool);
10177 rem_anchor_token(T_WIDE_STRING_LITERAL);
10178 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10179 rem_anchor_token(T_STRING_LITERAL);
10180 rem_anchor_token(T_PLUSPLUS);
10181 rem_anchor_token(T_MINUSMINUS);
10182 rem_anchor_token(T_INTEGER);
10183 rem_anchor_token(T_IDENTIFIER);
10184 rem_anchor_token(T_FLOATINGPOINT);
10185 rem_anchor_token(T_COLONCOLON);
10186 rem_anchor_token(T_CHARACTER_CONSTANT);
10187 rem_anchor_token('~');
10188 rem_anchor_token('{');
10189 rem_anchor_token(';');
10190 rem_anchor_token('-');
10191 rem_anchor_token('+');
10192 rem_anchor_token('*');
10193 rem_anchor_token('(');
10194 rem_anchor_token('&');
10195 rem_anchor_token('!');
10196 rem_anchor_token('}');
10204 * Check for unused global static functions and variables
10206 static void check_unused_globals(void)
10208 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10211 for (const entity_t *entity = file_scope->entities; entity != NULL;
10212 entity = entity->base.next) {
10213 if (!is_declaration(entity))
10216 const declaration_t *declaration = &entity->declaration;
10217 if (declaration->used ||
10218 declaration->modifiers & DM_UNUSED ||
10219 declaration->modifiers & DM_USED ||
10220 declaration->storage_class != STORAGE_CLASS_STATIC)
10225 if (entity->kind == ENTITY_FUNCTION) {
10226 /* inhibit warning for static inline functions */
10227 if (entity->function.is_inline)
10230 why = WARN_UNUSED_FUNCTION;
10231 s = entity->function.statement != NULL ? "defined" : "declared";
10233 why = WARN_UNUSED_VARIABLE;
10237 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10241 static void parse_global_asm(void)
10243 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10246 add_anchor_token(';');
10247 add_anchor_token(')');
10248 add_anchor_token(T_STRING_LITERAL);
10251 rem_anchor_token(T_STRING_LITERAL);
10252 statement->asms.asm_text = parse_string_literals();
10253 statement->base.next = unit->global_asm;
10254 unit->global_asm = statement;
10256 rem_anchor_token(')');
10258 rem_anchor_token(';');
10262 static void parse_linkage_specification(void)
10266 source_position_t const pos = *HERE;
10267 char const *const linkage = parse_string_literals().begin;
10269 linkage_kind_t old_linkage = current_linkage;
10270 linkage_kind_t new_linkage;
10271 if (streq(linkage, "C")) {
10272 new_linkage = LINKAGE_C;
10273 } else if (streq(linkage, "C++")) {
10274 new_linkage = LINKAGE_CXX;
10276 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10277 new_linkage = LINKAGE_C;
10279 current_linkage = new_linkage;
10281 if (next_if('{')) {
10288 assert(current_linkage == new_linkage);
10289 current_linkage = old_linkage;
10292 static void parse_external(void)
10294 switch (token.kind) {
10296 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10297 parse_linkage_specification();
10299 DECLARATION_START_NO_EXTERN
10301 case T___extension__:
10302 /* tokens below are for implicit int */
10303 case '&': /* & x; -> int& x; (and error later, because C++ has no
10305 case '*': /* * x; -> int* x; */
10306 case '(': /* (x); -> int (x); */
10308 parse_external_declaration();
10314 parse_global_asm();
10318 parse_namespace_definition();
10322 if (!strict_mode) {
10323 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10330 errorf(HERE, "stray %K outside of function", &token);
10331 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10332 eat_until_matching_token(token.kind);
10338 static void parse_externals(void)
10340 add_anchor_token('}');
10341 add_anchor_token(T_EOF);
10344 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10345 unsigned short token_anchor_copy[T_LAST_TOKEN];
10346 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10349 while (token.kind != T_EOF && token.kind != '}') {
10351 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10352 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10354 /* the anchor set and its copy differs */
10355 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10358 if (in_gcc_extension) {
10359 /* an gcc extension scope was not closed */
10360 internal_errorf(HERE, "Leaked __extension__");
10367 rem_anchor_token(T_EOF);
10368 rem_anchor_token('}');
10372 * Parse a translation unit.
10374 static void parse_translation_unit(void)
10376 add_anchor_token(T_EOF);
10381 if (token.kind == T_EOF)
10384 errorf(HERE, "stray %K outside of function", &token);
10385 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10386 eat_until_matching_token(token.kind);
10391 void set_default_visibility(elf_visibility_tag_t visibility)
10393 default_visibility = visibility;
10399 * @return the translation unit or NULL if errors occurred.
10401 void start_parsing(void)
10403 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10404 label_stack = NEW_ARR_F(stack_entry_t, 0);
10405 diagnostic_count = 0;
10409 print_to_file(stderr);
10411 assert(unit == NULL);
10412 unit = allocate_ast_zero(sizeof(unit[0]));
10414 assert(file_scope == NULL);
10415 file_scope = &unit->scope;
10417 assert(current_scope == NULL);
10418 scope_push(&unit->scope);
10420 create_gnu_builtins();
10422 create_microsoft_intrinsics();
10425 translation_unit_t *finish_parsing(void)
10427 assert(current_scope == &unit->scope);
10430 assert(file_scope == &unit->scope);
10431 check_unused_globals();
10434 DEL_ARR_F(environment_stack);
10435 DEL_ARR_F(label_stack);
10437 translation_unit_t *result = unit;
10442 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10443 * are given length one. */
10444 static void complete_incomplete_arrays(void)
10446 size_t n = ARR_LEN(incomplete_arrays);
10447 for (size_t i = 0; i != n; ++i) {
10448 declaration_t *const decl = incomplete_arrays[i];
10449 type_t *const type = skip_typeref(decl->type);
10451 if (!is_type_incomplete(type))
10454 source_position_t const *const pos = &decl->base.source_position;
10455 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10457 type_t *const new_type = duplicate_type(type);
10458 new_type->array.size_constant = true;
10459 new_type->array.has_implicit_size = true;
10460 new_type->array.size = 1;
10462 type_t *const result = identify_new_type(new_type);
10464 decl->type = result;
10468 void prepare_main_collect2(entity_t *entity)
10470 PUSH_SCOPE(&entity->function.statement->compound.scope);
10472 // create call to __main
10473 symbol_t *symbol = symbol_table_insert("__main");
10474 entity_t *subsubmain_ent
10475 = create_implicit_function(symbol, &builtin_source_position);
10477 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10478 type_t *ftype = subsubmain_ent->declaration.type;
10479 ref->base.source_position = builtin_source_position;
10480 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10481 ref->reference.entity = subsubmain_ent;
10483 expression_t *call = allocate_expression_zero(EXPR_CALL);
10484 call->base.source_position = builtin_source_position;
10485 call->base.type = type_void;
10486 call->call.function = ref;
10488 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10489 expr_statement->base.source_position = builtin_source_position;
10490 expr_statement->expression.expression = call;
10492 statement_t *statement = entity->function.statement;
10493 assert(statement->kind == STATEMENT_COMPOUND);
10494 compound_statement_t *compounds = &statement->compound;
10496 expr_statement->base.next = compounds->statements;
10497 compounds->statements = expr_statement;
10504 lookahead_bufpos = 0;
10505 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10508 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10509 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10510 parse_translation_unit();
10511 complete_incomplete_arrays();
10512 DEL_ARR_F(incomplete_arrays);
10513 incomplete_arrays = NULL;
10517 * Initialize the parser.
10519 void init_parser(void)
10521 sym_anonymous = symbol_table_insert("<anonymous>");
10523 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10525 init_expression_parsers();
10526 obstack_init(&temp_obst);
10530 * Terminate the parser.
10532 void exit_parser(void)
10534 obstack_free(&temp_obst, NULL);