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 = (new_scope ? scope_push(new_scope) : NULL)
122 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
123 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
125 #define PUSH_EXTENSION() \
127 bool const old_gcc_extension = in_gcc_extension; \
128 while (next_if(T___extension__)) { \
129 in_gcc_extension = true; \
132 #define POP_EXTENSION() \
133 ((void)(in_gcc_extension = old_gcc_extension))
135 /** special symbol used for anonymous entities. */
136 static symbol_t *sym_anonymous = NULL;
138 /** The token anchor set */
139 static unsigned short token_anchor_set[T_LAST_TOKEN];
141 /** The current source position. */
142 #define HERE (&token.base.source_position)
144 /** true if we are in GCC mode. */
145 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
147 static statement_t *parse_compound_statement(bool inside_expression_statement);
148 static statement_t *parse_statement(void);
150 static expression_t *parse_subexpression(precedence_t);
151 static expression_t *parse_expression(void);
152 static type_t *parse_typename(void);
153 static void parse_externals(void);
154 static void parse_external(void);
156 static void parse_compound_type_entries(compound_t *compound_declaration);
158 static void check_call_argument(type_t *expected_type,
159 call_argument_t *argument, unsigned pos);
161 typedef enum declarator_flags_t {
163 DECL_MAY_BE_ABSTRACT = 1U << 0,
164 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
165 DECL_IS_PARAMETER = 1U << 2
166 } declarator_flags_t;
168 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
169 declarator_flags_t flags);
171 static void semantic_comparison(binary_expression_t *expression);
173 #define STORAGE_CLASSES \
174 STORAGE_CLASSES_NO_EXTERN \
177 #define STORAGE_CLASSES_NO_EXTERN \
184 #define TYPE_QUALIFIERS \
189 case T__forceinline: \
190 case T___attribute__:
192 #define COMPLEX_SPECIFIERS \
194 #define IMAGINARY_SPECIFIERS \
197 #define TYPE_SPECIFIERS \
199 case T___builtin_va_list: \
224 #define DECLARATION_START \
229 #define DECLARATION_START_NO_EXTERN \
230 STORAGE_CLASSES_NO_EXTERN \
234 #define EXPRESSION_START \
243 case T_CHARACTER_CONSTANT: \
244 case T_FLOATINGPOINT: \
245 case T_FLOATINGPOINT_HEXADECIMAL: \
247 case T_INTEGER_HEXADECIMAL: \
248 case T_INTEGER_OCTAL: \
251 case T_STRING_LITERAL: \
252 case T_WIDE_CHARACTER_CONSTANT: \
253 case T_WIDE_STRING_LITERAL: \
254 case T___FUNCDNAME__: \
255 case T___FUNCSIG__: \
256 case T___FUNCTION__: \
257 case T___PRETTY_FUNCTION__: \
258 case T___alignof__: \
259 case T___builtin_classify_type: \
260 case T___builtin_constant_p: \
261 case T___builtin_isgreater: \
262 case T___builtin_isgreaterequal: \
263 case T___builtin_isless: \
264 case T___builtin_islessequal: \
265 case T___builtin_islessgreater: \
266 case T___builtin_isunordered: \
267 case T___builtin_offsetof: \
268 case T___builtin_va_arg: \
269 case T___builtin_va_copy: \
270 case T___builtin_va_start: \
281 * Returns the size of a statement node.
283 * @param kind the statement kind
285 static size_t get_statement_struct_size(statement_kind_t kind)
287 static const size_t sizes[] = {
288 [STATEMENT_ERROR] = sizeof(statement_base_t),
289 [STATEMENT_EMPTY] = sizeof(statement_base_t),
290 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
291 [STATEMENT_RETURN] = sizeof(return_statement_t),
292 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
293 [STATEMENT_IF] = sizeof(if_statement_t),
294 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
295 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
296 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
297 [STATEMENT_BREAK] = sizeof(statement_base_t),
298 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
299 [STATEMENT_GOTO] = sizeof(goto_statement_t),
300 [STATEMENT_LABEL] = sizeof(label_statement_t),
301 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
302 [STATEMENT_WHILE] = sizeof(while_statement_t),
303 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
304 [STATEMENT_FOR] = sizeof(for_statement_t),
305 [STATEMENT_ASM] = sizeof(asm_statement_t),
306 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
307 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
309 assert((size_t)kind < lengthof(sizes));
310 assert(sizes[kind] != 0);
315 * Returns the size of an expression node.
317 * @param kind the expression kind
319 static size_t get_expression_struct_size(expression_kind_t kind)
321 static const size_t sizes[] = {
322 [EXPR_ERROR] = sizeof(expression_base_t),
323 [EXPR_REFERENCE] = sizeof(reference_expression_t),
324 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
325 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
329 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
332 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
333 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
334 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
335 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
336 [EXPR_CALL] = sizeof(call_expression_t),
337 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
338 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
339 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
340 [EXPR_SELECT] = sizeof(select_expression_t),
341 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
342 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
343 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
344 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
345 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
346 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
347 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
348 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
349 [EXPR_VA_START] = sizeof(va_start_expression_t),
350 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
351 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
352 [EXPR_STATEMENT] = sizeof(statement_expression_t),
353 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
355 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
356 return sizes[EXPR_UNARY_FIRST];
358 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
359 return sizes[EXPR_BINARY_FIRST];
361 assert((size_t)kind < lengthof(sizes));
362 assert(sizes[kind] != 0);
367 * Allocate a statement node of given kind and initialize all
368 * fields with zero. Sets its source position to the position
369 * of the current token.
371 static statement_t *allocate_statement_zero(statement_kind_t kind)
373 size_t size = get_statement_struct_size(kind);
374 statement_t *res = allocate_ast_zero(size);
376 res->base.kind = kind;
377 res->base.parent = current_parent;
378 res->base.source_position = token.base.source_position;
383 * Allocate an expression node of given kind and initialize all
386 * @param kind the kind of the expression to allocate
388 static expression_t *allocate_expression_zero(expression_kind_t kind)
390 size_t size = get_expression_struct_size(kind);
391 expression_t *res = allocate_ast_zero(size);
393 res->base.kind = kind;
394 res->base.type = type_error_type;
395 res->base.source_position = token.base.source_position;
400 * Creates a new invalid expression at the source position
401 * of the current token.
403 static expression_t *create_error_expression(void)
405 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
406 expression->base.type = type_error_type;
411 * Creates a new invalid statement.
413 static statement_t *create_error_statement(void)
415 return allocate_statement_zero(STATEMENT_ERROR);
419 * Allocate a new empty statement.
421 static statement_t *create_empty_statement(void)
423 return allocate_statement_zero(STATEMENT_EMPTY);
427 * Returns the size of an initializer node.
429 * @param kind the initializer kind
431 static size_t get_initializer_size(initializer_kind_t kind)
433 static const size_t sizes[] = {
434 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
435 [INITIALIZER_STRING] = sizeof(initializer_string_t),
436 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
437 [INITIALIZER_LIST] = sizeof(initializer_list_t),
438 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
440 assert((size_t)kind < lengthof(sizes));
441 assert(sizes[kind] != 0);
446 * Allocate an initializer node of given kind and initialize all
449 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
451 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
458 * Returns the index of the top element of the environment stack.
460 static size_t environment_top(void)
462 return ARR_LEN(environment_stack);
466 * Returns the index of the top element of the global label stack.
468 static size_t label_top(void)
470 return ARR_LEN(label_stack);
474 * Return the next token.
476 static inline void next_token(void)
478 token = lookahead_buffer[lookahead_bufpos];
479 lookahead_buffer[lookahead_bufpos] = lexer_token;
482 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
485 print_token(stderr, &token);
486 fprintf(stderr, "\n");
490 static inline bool next_if(int const type)
492 if (token.kind == type) {
501 * Return the next token with a given lookahead.
503 static inline const token_t *look_ahead(size_t num)
505 assert(0 < num && num <= MAX_LOOKAHEAD);
506 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
507 return &lookahead_buffer[pos];
511 * Adds a token type to the token type anchor set (a multi-set).
513 static void add_anchor_token(int token_kind)
515 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
516 ++token_anchor_set[token_kind];
520 * Set the number of tokens types of the given type
521 * to zero and return the old count.
523 static int save_and_reset_anchor_state(int token_kind)
525 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
526 int count = token_anchor_set[token_kind];
527 token_anchor_set[token_kind] = 0;
532 * Restore the number of token types to the given count.
534 static void restore_anchor_state(int token_kind, int count)
536 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
537 token_anchor_set[token_kind] = count;
541 * Remove a token type from the token type anchor set (a multi-set).
543 static void rem_anchor_token(int token_kind)
545 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
546 assert(token_anchor_set[token_kind] != 0);
547 --token_anchor_set[token_kind];
551 * Eat tokens until a matching token type is found.
553 static void eat_until_matching_token(int type)
557 case '(': end_token = ')'; break;
558 case '{': end_token = '}'; break;
559 case '[': end_token = ']'; break;
560 default: end_token = type; break;
563 unsigned parenthesis_count = 0;
564 unsigned brace_count = 0;
565 unsigned bracket_count = 0;
566 while (token.kind != end_token ||
567 parenthesis_count != 0 ||
569 bracket_count != 0) {
570 switch (token.kind) {
572 case '(': ++parenthesis_count; break;
573 case '{': ++brace_count; break;
574 case '[': ++bracket_count; break;
577 if (parenthesis_count > 0)
587 if (bracket_count > 0)
590 if (token.kind == end_token &&
591 parenthesis_count == 0 &&
605 * Eat input tokens until an anchor is found.
607 static void eat_until_anchor(void)
609 while (token_anchor_set[token.kind] == 0) {
610 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
611 eat_until_matching_token(token.kind);
617 * Eat a whole block from input tokens.
619 static void eat_block(void)
621 eat_until_matching_token('{');
625 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
628 * Report a parse error because an expected token was not found.
631 #if defined __GNUC__ && __GNUC__ >= 4
632 __attribute__((sentinel))
634 void parse_error_expected(const char *message, ...)
636 if (message != NULL) {
637 errorf(HERE, "%s", message);
640 va_start(ap, message);
641 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
646 * Report an incompatible type.
648 static void type_error_incompatible(const char *msg,
649 const source_position_t *source_position, type_t *type1, type_t *type2)
651 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
656 * Expect the current token is the expected token.
657 * If not, generate an error and skip until the next anchor.
659 static void expect(token_kind_t const expected)
661 if (UNLIKELY(token.kind != expected)) {
662 parse_error_expected(NULL, expected, NULL);
663 add_anchor_token(expected);
665 rem_anchor_token(expected);
666 if (token.kind != expected)
672 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
674 if (token.kind != T_IDENTIFIER) {
675 parse_error_expected(context, T_IDENTIFIER, NULL);
676 add_anchor_token(T_IDENTIFIER);
678 rem_anchor_token(T_IDENTIFIER);
679 if (token.kind != T_IDENTIFIER)
682 symbol_t *const sym = token.identifier.symbol;
690 * Push a given scope on the scope stack and make it the
693 static scope_t *scope_push(scope_t *new_scope)
695 if (current_scope != NULL) {
696 new_scope->depth = current_scope->depth + 1;
699 scope_t *old_scope = current_scope;
700 current_scope = new_scope;
705 * Pop the current scope from the scope stack.
707 static void scope_pop(scope_t *old_scope)
709 current_scope = old_scope;
713 * Search an entity by its symbol in a given namespace.
715 static entity_t *get_entity(const symbol_t *const symbol,
716 namespace_tag_t namespc)
718 entity_t *entity = symbol->entity;
719 for (; entity != NULL; entity = entity->base.symbol_next) {
720 if ((namespace_tag_t)entity->base.namespc == namespc)
727 /* §6.2.3:1 24) There is only one name space for tags even though three are
729 static entity_t *get_tag(symbol_t const *const symbol,
730 entity_kind_tag_t const kind)
732 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
733 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
735 "'%Y' defined as wrong kind of tag (previous definition %P)",
736 symbol, &entity->base.source_position);
743 * pushs an entity on the environment stack and links the corresponding symbol
746 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
748 symbol_t *symbol = entity->base.symbol;
749 entity_namespace_t namespc = entity->base.namespc;
750 assert(namespc != 0);
752 /* replace/add entity into entity list of the symbol */
755 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
760 /* replace an entry? */
761 if (iter->base.namespc == namespc) {
762 entity->base.symbol_next = iter->base.symbol_next;
768 /* remember old declaration */
770 entry.symbol = symbol;
771 entry.old_entity = iter;
772 entry.namespc = namespc;
773 ARR_APP1(stack_entry_t, *stack_ptr, entry);
777 * Push an entity on the environment stack.
779 static void environment_push(entity_t *entity)
781 assert(entity->base.source_position.input_name != NULL);
782 assert(entity->base.parent_scope != NULL);
783 stack_push(&environment_stack, entity);
787 * Push a declaration on the global label stack.
789 * @param declaration the declaration
791 static void label_push(entity_t *label)
793 /* we abuse the parameters scope as parent for the labels */
794 label->base.parent_scope = ¤t_function->parameters;
795 stack_push(&label_stack, label);
799 * pops symbols from the environment stack until @p new_top is the top element
801 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
803 stack_entry_t *stack = *stack_ptr;
804 size_t top = ARR_LEN(stack);
807 assert(new_top <= top);
811 for (i = top; i > new_top; --i) {
812 stack_entry_t *entry = &stack[i - 1];
814 entity_t *old_entity = entry->old_entity;
815 symbol_t *symbol = entry->symbol;
816 entity_namespace_t namespc = entry->namespc;
818 /* replace with old_entity/remove */
821 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
823 assert(iter != NULL);
824 /* replace an entry? */
825 if (iter->base.namespc == namespc)
829 /* restore definition from outer scopes (if there was one) */
830 if (old_entity != NULL) {
831 old_entity->base.symbol_next = iter->base.symbol_next;
832 *anchor = old_entity;
834 /* remove entry from list */
835 *anchor = iter->base.symbol_next;
839 ARR_SHRINKLEN(*stack_ptr, new_top);
843 * Pop all entries from the environment stack until the new_top
846 * @param new_top the new stack top
848 static void environment_pop_to(size_t new_top)
850 stack_pop_to(&environment_stack, new_top);
854 * Pop all entries from the global label stack until the new_top
857 * @param new_top the new stack top
859 static void label_pop_to(size_t new_top)
861 stack_pop_to(&label_stack, new_top);
864 static atomic_type_kind_t get_akind(const type_t *type)
866 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
867 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
868 return type->atomic.akind;
872 * §6.3.1.1:2 Do integer promotion for a given type.
874 * @param type the type to promote
875 * @return the promoted type
877 static type_t *promote_integer(type_t *type)
879 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
886 * Check if a given expression represents a null pointer constant.
888 * @param expression the expression to check
890 static bool is_null_pointer_constant(const expression_t *expression)
892 /* skip void* cast */
893 if (expression->kind == EXPR_UNARY_CAST) {
894 type_t *const type = skip_typeref(expression->base.type);
895 if (types_compatible(type, type_void_ptr))
896 expression = expression->unary.value;
899 type_t *const type = skip_typeref(expression->base.type);
900 if (!is_type_integer(type))
902 switch (is_constant_expression(expression)) {
903 case EXPR_CLASS_ERROR: return true;
904 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
905 default: return false;
910 * Create an implicit cast expression.
912 * @param expression the expression to cast
913 * @param dest_type the destination type
915 static expression_t *create_implicit_cast(expression_t *expression,
918 type_t *const source_type = expression->base.type;
920 if (source_type == dest_type)
923 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
924 cast->unary.value = expression;
925 cast->base.type = dest_type;
926 cast->base.implicit = true;
931 typedef enum assign_error_t {
933 ASSIGN_ERROR_INCOMPATIBLE,
934 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
935 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
936 ASSIGN_WARNING_POINTER_FROM_INT,
937 ASSIGN_WARNING_INT_FROM_POINTER
940 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)
942 type_t *const orig_type_right = right->base.type;
943 type_t *const type_left = skip_typeref(orig_type_left);
944 type_t *const type_right = skip_typeref(orig_type_right);
949 case ASSIGN_ERROR_INCOMPATIBLE:
950 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
953 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
954 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
955 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
957 /* the left type has all qualifiers from the right type */
958 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
959 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);
963 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
964 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
967 case ASSIGN_WARNING_POINTER_FROM_INT:
968 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
971 case ASSIGN_WARNING_INT_FROM_POINTER:
972 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
976 panic("invalid error value");
980 /** Implements the rules from §6.5.16.1 */
981 static assign_error_t semantic_assign(type_t *orig_type_left,
982 const expression_t *const right)
984 type_t *const orig_type_right = right->base.type;
985 type_t *const type_left = skip_typeref(orig_type_left);
986 type_t *const type_right = skip_typeref(orig_type_right);
988 if (is_type_pointer(type_left)) {
989 if (is_null_pointer_constant(right)) {
990 return ASSIGN_SUCCESS;
991 } else if (is_type_pointer(type_right)) {
992 type_t *points_to_left
993 = skip_typeref(type_left->pointer.points_to);
994 type_t *points_to_right
995 = skip_typeref(type_right->pointer.points_to);
996 assign_error_t res = ASSIGN_SUCCESS;
998 /* the left type has all qualifiers from the right type */
999 unsigned missing_qualifiers
1000 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1001 if (missing_qualifiers != 0) {
1002 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1005 points_to_left = get_unqualified_type(points_to_left);
1006 points_to_right = get_unqualified_type(points_to_right);
1008 if (is_type_void(points_to_left))
1011 if (is_type_void(points_to_right)) {
1012 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1013 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1016 if (!types_compatible(points_to_left, points_to_right)) {
1017 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1021 } else if (is_type_integer(type_right)) {
1022 return ASSIGN_WARNING_POINTER_FROM_INT;
1024 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1025 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1026 && is_type_pointer(type_right))) {
1027 return ASSIGN_SUCCESS;
1028 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1029 type_t *const unqual_type_left = get_unqualified_type(type_left);
1030 type_t *const unqual_type_right = get_unqualified_type(type_right);
1031 if (types_compatible(unqual_type_left, unqual_type_right)) {
1032 return ASSIGN_SUCCESS;
1034 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1035 return ASSIGN_WARNING_INT_FROM_POINTER;
1038 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1039 return ASSIGN_SUCCESS;
1041 return ASSIGN_ERROR_INCOMPATIBLE;
1044 static expression_t *parse_constant_expression(void)
1046 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1048 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1049 errorf(&result->base.source_position,
1050 "expression '%E' is not constant", result);
1056 static expression_t *parse_assignment_expression(void)
1058 return parse_subexpression(PREC_ASSIGNMENT);
1061 static void warn_string_concat(const source_position_t *pos)
1063 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1066 static string_t parse_string_literals(void)
1068 assert(token.kind == T_STRING_LITERAL);
1069 string_t result = token.string.string;
1073 while (token.kind == T_STRING_LITERAL) {
1074 warn_string_concat(&token.base.source_position);
1075 result = concat_strings(&result, &token.string.string);
1082 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1084 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1085 attribute->kind = kind;
1086 attribute->source_position = *HERE;
1091 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1094 * __attribute__ ( ( attribute-list ) )
1098 * attribute_list , attrib
1103 * any-word ( identifier )
1104 * any-word ( identifier , nonempty-expr-list )
1105 * any-word ( expr-list )
1107 * where the "identifier" must not be declared as a type, and
1108 * "any-word" may be any identifier (including one declared as a
1109 * type), a reserved word storage class specifier, type specifier or
1110 * type qualifier. ??? This still leaves out most reserved keywords
1111 * (following the old parser), shouldn't we include them, and why not
1112 * allow identifiers declared as types to start the arguments?
1114 * Matze: this all looks confusing and little systematic, so we're even less
1115 * strict and parse any list of things which are identifiers or
1116 * (assignment-)expressions.
1118 static attribute_argument_t *parse_attribute_arguments(void)
1120 attribute_argument_t *first = NULL;
1121 attribute_argument_t **anchor = &first;
1122 if (token.kind != ')') do {
1123 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1125 /* is it an identifier */
1126 if (token.kind == T_IDENTIFIER
1127 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1128 symbol_t *symbol = token.identifier.symbol;
1129 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1130 argument->v.symbol = symbol;
1133 /* must be an expression */
1134 expression_t *expression = parse_assignment_expression();
1136 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1137 argument->v.expression = expression;
1140 /* append argument */
1142 anchor = &argument->next;
1143 } while (next_if(','));
1148 static attribute_t *parse_attribute_asm(void)
1150 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1153 attribute->a.arguments = parse_attribute_arguments();
1157 static symbol_t *get_symbol_from_token(void)
1159 switch(token.kind) {
1161 return token.identifier.symbol;
1190 /* maybe we need more tokens ... add them on demand */
1191 return get_token_kind_symbol(token.kind);
1197 static attribute_t *parse_attribute_gnu_single(void)
1199 /* parse "any-word" */
1200 symbol_t *symbol = get_symbol_from_token();
1201 if (symbol == NULL) {
1202 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1206 attribute_kind_t kind;
1207 char const *const name = symbol->string;
1208 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1209 if (kind > ATTRIBUTE_GNU_LAST) {
1210 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1211 /* TODO: we should still save the attribute in the list... */
1212 kind = ATTRIBUTE_UNKNOWN;
1216 const char *attribute_name = get_attribute_name(kind);
1217 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1221 attribute_t *attribute = allocate_attribute_zero(kind);
1224 /* parse arguments */
1226 attribute->a.arguments = parse_attribute_arguments();
1231 static attribute_t *parse_attribute_gnu(void)
1233 attribute_t *first = NULL;
1234 attribute_t **anchor = &first;
1236 eat(T___attribute__);
1240 add_anchor_token(')');
1241 add_anchor_token(',');
1242 if (token.kind != ')') do {
1243 attribute_t *attribute = parse_attribute_gnu_single();
1245 *anchor = attribute;
1246 anchor = &attribute->next;
1248 } while (next_if(','));
1249 rem_anchor_token(',');
1250 rem_anchor_token(')');
1257 /** Parse attributes. */
1258 static attribute_t *parse_attributes(attribute_t *first)
1260 attribute_t **anchor = &first;
1262 while (*anchor != NULL)
1263 anchor = &(*anchor)->next;
1265 attribute_t *attribute;
1266 switch (token.kind) {
1267 case T___attribute__:
1268 attribute = parse_attribute_gnu();
1269 if (attribute == NULL)
1274 attribute = parse_attribute_asm();
1278 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1283 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1287 case T__forceinline:
1288 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1289 eat(T__forceinline);
1293 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1298 /* TODO record modifier */
1299 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1300 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1308 *anchor = attribute;
1309 anchor = &attribute->next;
1313 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1315 static entity_t *determine_lhs_ent(expression_t *const expr,
1318 switch (expr->kind) {
1319 case EXPR_REFERENCE: {
1320 entity_t *const entity = expr->reference.entity;
1321 /* we should only find variables as lvalues... */
1322 if (entity->base.kind != ENTITY_VARIABLE
1323 && entity->base.kind != ENTITY_PARAMETER)
1329 case EXPR_ARRAY_ACCESS: {
1330 expression_t *const ref = expr->array_access.array_ref;
1331 entity_t * ent = NULL;
1332 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1333 ent = determine_lhs_ent(ref, lhs_ent);
1336 mark_vars_read(ref, lhs_ent);
1338 mark_vars_read(expr->array_access.index, lhs_ent);
1343 mark_vars_read(expr->select.compound, lhs_ent);
1344 if (is_type_compound(skip_typeref(expr->base.type)))
1345 return determine_lhs_ent(expr->select.compound, lhs_ent);
1349 case EXPR_UNARY_DEREFERENCE: {
1350 expression_t *const val = expr->unary.value;
1351 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1353 return determine_lhs_ent(val->unary.value, lhs_ent);
1355 mark_vars_read(val, NULL);
1361 mark_vars_read(expr, NULL);
1366 #define ENT_ANY ((entity_t*)-1)
1369 * Mark declarations, which are read. This is used to detect variables, which
1373 * x is not marked as "read", because it is only read to calculate its own new
1377 * x and y are not detected as "not read", because multiple variables are
1380 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1382 switch (expr->kind) {
1383 case EXPR_REFERENCE: {
1384 entity_t *const entity = expr->reference.entity;
1385 if (entity->kind != ENTITY_VARIABLE
1386 && entity->kind != ENTITY_PARAMETER)
1389 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1390 if (entity->kind == ENTITY_VARIABLE) {
1391 entity->variable.read = true;
1393 entity->parameter.read = true;
1400 // TODO respect pure/const
1401 mark_vars_read(expr->call.function, NULL);
1402 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1403 mark_vars_read(arg->expression, NULL);
1407 case EXPR_CONDITIONAL:
1408 // TODO lhs_decl should depend on whether true/false have an effect
1409 mark_vars_read(expr->conditional.condition, NULL);
1410 if (expr->conditional.true_expression != NULL)
1411 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1412 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1416 if (lhs_ent == ENT_ANY
1417 && !is_type_compound(skip_typeref(expr->base.type)))
1419 mark_vars_read(expr->select.compound, lhs_ent);
1422 case EXPR_ARRAY_ACCESS: {
1423 mark_vars_read(expr->array_access.index, lhs_ent);
1424 expression_t *const ref = expr->array_access.array_ref;
1425 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1426 if (lhs_ent == ENT_ANY)
1429 mark_vars_read(ref, lhs_ent);
1434 mark_vars_read(expr->va_arge.ap, lhs_ent);
1438 mark_vars_read(expr->va_copye.src, lhs_ent);
1441 case EXPR_UNARY_CAST:
1442 /* Special case: Use void cast to mark a variable as "read" */
1443 if (is_type_void(skip_typeref(expr->base.type)))
1448 case EXPR_UNARY_THROW:
1449 if (expr->unary.value == NULL)
1452 case EXPR_UNARY_DEREFERENCE:
1453 case EXPR_UNARY_DELETE:
1454 case EXPR_UNARY_DELETE_ARRAY:
1455 if (lhs_ent == ENT_ANY)
1459 case EXPR_UNARY_NEGATE:
1460 case EXPR_UNARY_PLUS:
1461 case EXPR_UNARY_BITWISE_NEGATE:
1462 case EXPR_UNARY_NOT:
1463 case EXPR_UNARY_TAKE_ADDRESS:
1464 case EXPR_UNARY_POSTFIX_INCREMENT:
1465 case EXPR_UNARY_POSTFIX_DECREMENT:
1466 case EXPR_UNARY_PREFIX_INCREMENT:
1467 case EXPR_UNARY_PREFIX_DECREMENT:
1468 case EXPR_UNARY_ASSUME:
1470 mark_vars_read(expr->unary.value, lhs_ent);
1473 case EXPR_BINARY_ADD:
1474 case EXPR_BINARY_SUB:
1475 case EXPR_BINARY_MUL:
1476 case EXPR_BINARY_DIV:
1477 case EXPR_BINARY_MOD:
1478 case EXPR_BINARY_EQUAL:
1479 case EXPR_BINARY_NOTEQUAL:
1480 case EXPR_BINARY_LESS:
1481 case EXPR_BINARY_LESSEQUAL:
1482 case EXPR_BINARY_GREATER:
1483 case EXPR_BINARY_GREATEREQUAL:
1484 case EXPR_BINARY_BITWISE_AND:
1485 case EXPR_BINARY_BITWISE_OR:
1486 case EXPR_BINARY_BITWISE_XOR:
1487 case EXPR_BINARY_LOGICAL_AND:
1488 case EXPR_BINARY_LOGICAL_OR:
1489 case EXPR_BINARY_SHIFTLEFT:
1490 case EXPR_BINARY_SHIFTRIGHT:
1491 case EXPR_BINARY_COMMA:
1492 case EXPR_BINARY_ISGREATER:
1493 case EXPR_BINARY_ISGREATEREQUAL:
1494 case EXPR_BINARY_ISLESS:
1495 case EXPR_BINARY_ISLESSEQUAL:
1496 case EXPR_BINARY_ISLESSGREATER:
1497 case EXPR_BINARY_ISUNORDERED:
1498 mark_vars_read(expr->binary.left, lhs_ent);
1499 mark_vars_read(expr->binary.right, lhs_ent);
1502 case EXPR_BINARY_ASSIGN:
1503 case EXPR_BINARY_MUL_ASSIGN:
1504 case EXPR_BINARY_DIV_ASSIGN:
1505 case EXPR_BINARY_MOD_ASSIGN:
1506 case EXPR_BINARY_ADD_ASSIGN:
1507 case EXPR_BINARY_SUB_ASSIGN:
1508 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1509 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1510 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1511 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1512 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1513 if (lhs_ent == ENT_ANY)
1515 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1516 mark_vars_read(expr->binary.right, lhs_ent);
1521 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1524 case EXPR_LITERAL_CASES:
1526 case EXPR_STRING_LITERAL:
1527 case EXPR_WIDE_STRING_LITERAL:
1528 case EXPR_COMPOUND_LITERAL: // TODO init?
1530 case EXPR_CLASSIFY_TYPE:
1533 case EXPR_BUILTIN_CONSTANT_P:
1534 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1536 case EXPR_STATEMENT: // TODO
1537 case EXPR_LABEL_ADDRESS:
1538 case EXPR_ENUM_CONSTANT:
1542 panic("unhandled expression");
1545 static designator_t *parse_designation(void)
1547 designator_t *result = NULL;
1548 designator_t **anchor = &result;
1551 designator_t *designator;
1552 switch (token.kind) {
1554 designator = allocate_ast_zero(sizeof(designator[0]));
1555 designator->source_position = token.base.source_position;
1557 add_anchor_token(']');
1558 designator->array_index = parse_constant_expression();
1559 rem_anchor_token(']');
1563 designator = allocate_ast_zero(sizeof(designator[0]));
1564 designator->source_position = token.base.source_position;
1566 designator->symbol = expect_identifier("while parsing designator", NULL);
1567 if (!designator->symbol)
1575 assert(designator != NULL);
1576 *anchor = designator;
1577 anchor = &designator->next;
1581 static initializer_t *initializer_from_string(array_type_t *const type,
1582 const string_t *const string)
1584 /* TODO: check len vs. size of array type */
1587 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1588 initializer->string.string = *string;
1593 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1594 const string_t *const string)
1596 /* TODO: check len vs. size of array type */
1599 initializer_t *const initializer =
1600 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1601 initializer->wide_string.string = *string;
1607 * Build an initializer from a given expression.
1609 static initializer_t *initializer_from_expression(type_t *orig_type,
1610 expression_t *expression)
1612 /* TODO check that expression is a constant expression */
1614 /* §6.7.8.14/15 char array may be initialized by string literals */
1615 type_t *type = skip_typeref(orig_type);
1616 type_t *expr_type_orig = expression->base.type;
1617 type_t *expr_type = skip_typeref(expr_type_orig);
1619 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1620 array_type_t *const array_type = &type->array;
1621 type_t *const element_type = skip_typeref(array_type->element_type);
1623 if (element_type->kind == TYPE_ATOMIC) {
1624 atomic_type_kind_t akind = element_type->atomic.akind;
1625 switch (expression->kind) {
1626 case EXPR_STRING_LITERAL:
1627 if (akind == ATOMIC_TYPE_CHAR
1628 || akind == ATOMIC_TYPE_SCHAR
1629 || akind == ATOMIC_TYPE_UCHAR) {
1630 return initializer_from_string(array_type,
1631 &expression->string_literal.value);
1635 case EXPR_WIDE_STRING_LITERAL: {
1636 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1637 if (get_unqualified_type(element_type) == bare_wchar_type) {
1638 return initializer_from_wide_string(array_type,
1639 &expression->string_literal.value);
1650 assign_error_t error = semantic_assign(type, expression);
1651 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1653 report_assign_error(error, type, expression, "initializer",
1654 &expression->base.source_position);
1656 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1657 result->value.value = create_implicit_cast(expression, type);
1663 * Parses an scalar initializer.
1665 * §6.7.8.11; eat {} without warning
1667 static initializer_t *parse_scalar_initializer(type_t *type,
1668 bool must_be_constant)
1670 /* there might be extra {} hierarchies */
1672 if (token.kind == '{') {
1673 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1677 } while (token.kind == '{');
1680 expression_t *expression = parse_assignment_expression();
1681 mark_vars_read(expression, NULL);
1682 if (must_be_constant && !is_linker_constant(expression)) {
1683 errorf(&expression->base.source_position,
1684 "initialisation expression '%E' is not constant",
1688 initializer_t *initializer = initializer_from_expression(type, expression);
1690 if (initializer == NULL) {
1691 errorf(&expression->base.source_position,
1692 "expression '%E' (type '%T') doesn't match expected type '%T'",
1693 expression, expression->base.type, type);
1698 bool additional_warning_displayed = false;
1699 while (braces > 0) {
1701 if (token.kind != '}') {
1702 if (!additional_warning_displayed) {
1703 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1704 additional_warning_displayed = true;
1715 * An entry in the type path.
1717 typedef struct type_path_entry_t type_path_entry_t;
1718 struct type_path_entry_t {
1719 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1721 size_t index; /**< For array types: the current index. */
1722 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1727 * A type path expression a position inside compound or array types.
1729 typedef struct type_path_t type_path_t;
1730 struct type_path_t {
1731 type_path_entry_t *path; /**< An flexible array containing the current path. */
1732 type_t *top_type; /**< type of the element the path points */
1733 size_t max_index; /**< largest index in outermost array */
1737 * Prints a type path for debugging.
1739 static __attribute__((unused)) void debug_print_type_path(
1740 const type_path_t *path)
1742 size_t len = ARR_LEN(path->path);
1744 for (size_t i = 0; i < len; ++i) {
1745 const type_path_entry_t *entry = & path->path[i];
1747 type_t *type = skip_typeref(entry->type);
1748 if (is_type_compound(type)) {
1749 /* in gcc mode structs can have no members */
1750 if (entry->v.compound_entry == NULL) {
1754 fprintf(stderr, ".%s",
1755 entry->v.compound_entry->base.symbol->string);
1756 } else if (is_type_array(type)) {
1757 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1759 fprintf(stderr, "-INVALID-");
1762 if (path->top_type != NULL) {
1763 fprintf(stderr, " (");
1764 print_type(path->top_type);
1765 fprintf(stderr, ")");
1770 * Return the top type path entry, ie. in a path
1771 * (type).a.b returns the b.
1773 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1775 size_t len = ARR_LEN(path->path);
1777 return &path->path[len-1];
1781 * Enlarge the type path by an (empty) element.
1783 static type_path_entry_t *append_to_type_path(type_path_t *path)
1785 size_t len = ARR_LEN(path->path);
1786 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1788 type_path_entry_t *result = & path->path[len];
1789 memset(result, 0, sizeof(result[0]));
1794 * Descending into a sub-type. Enter the scope of the current top_type.
1796 static void descend_into_subtype(type_path_t *path)
1798 type_t *orig_top_type = path->top_type;
1799 type_t *top_type = skip_typeref(orig_top_type);
1801 type_path_entry_t *top = append_to_type_path(path);
1802 top->type = top_type;
1804 if (is_type_compound(top_type)) {
1805 compound_t *const compound = top_type->compound.compound;
1806 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1808 if (entry != NULL) {
1809 top->v.compound_entry = &entry->declaration;
1810 path->top_type = entry->declaration.type;
1812 path->top_type = NULL;
1814 } else if (is_type_array(top_type)) {
1816 path->top_type = top_type->array.element_type;
1818 assert(!is_type_valid(top_type));
1823 * Pop an entry from the given type path, ie. returning from
1824 * (type).a.b to (type).a
1826 static void ascend_from_subtype(type_path_t *path)
1828 type_path_entry_t *top = get_type_path_top(path);
1830 path->top_type = top->type;
1832 size_t len = ARR_LEN(path->path);
1833 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1837 * Pop entries from the given type path until the given
1838 * path level is reached.
1840 static void ascend_to(type_path_t *path, size_t top_path_level)
1842 size_t len = ARR_LEN(path->path);
1844 while (len > top_path_level) {
1845 ascend_from_subtype(path);
1846 len = ARR_LEN(path->path);
1850 static bool walk_designator(type_path_t *path, const designator_t *designator,
1851 bool used_in_offsetof)
1853 for (; designator != NULL; designator = designator->next) {
1854 type_path_entry_t *top = get_type_path_top(path);
1855 type_t *orig_type = top->type;
1857 type_t *type = skip_typeref(orig_type);
1859 if (designator->symbol != NULL) {
1860 symbol_t *symbol = designator->symbol;
1861 if (!is_type_compound(type)) {
1862 if (is_type_valid(type)) {
1863 errorf(&designator->source_position,
1864 "'.%Y' designator used for non-compound type '%T'",
1868 top->type = type_error_type;
1869 top->v.compound_entry = NULL;
1870 orig_type = type_error_type;
1872 compound_t *compound = type->compound.compound;
1873 entity_t *iter = compound->members.entities;
1874 for (; iter != NULL; iter = iter->base.next) {
1875 if (iter->base.symbol == symbol) {
1880 errorf(&designator->source_position,
1881 "'%T' has no member named '%Y'", orig_type, symbol);
1884 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1885 if (used_in_offsetof && iter->compound_member.bitfield) {
1886 errorf(&designator->source_position,
1887 "offsetof designator '%Y' must not specify bitfield",
1892 top->type = orig_type;
1893 top->v.compound_entry = &iter->declaration;
1894 orig_type = iter->declaration.type;
1897 expression_t *array_index = designator->array_index;
1898 assert(designator->array_index != NULL);
1900 if (!is_type_array(type)) {
1901 if (is_type_valid(type)) {
1902 errorf(&designator->source_position,
1903 "[%E] designator used for non-array type '%T'",
1904 array_index, orig_type);
1909 long index = fold_constant_to_int(array_index);
1910 if (!used_in_offsetof) {
1912 errorf(&designator->source_position,
1913 "array index [%E] must be positive", array_index);
1914 } else if (type->array.size_constant) {
1915 long array_size = type->array.size;
1916 if (index >= array_size) {
1917 errorf(&designator->source_position,
1918 "designator [%E] (%d) exceeds array size %d",
1919 array_index, index, array_size);
1924 top->type = orig_type;
1925 top->v.index = (size_t) index;
1926 orig_type = type->array.element_type;
1928 path->top_type = orig_type;
1930 if (designator->next != NULL) {
1931 descend_into_subtype(path);
1937 static void advance_current_object(type_path_t *path, size_t top_path_level)
1939 type_path_entry_t *top = get_type_path_top(path);
1941 type_t *type = skip_typeref(top->type);
1942 if (is_type_union(type)) {
1943 /* in unions only the first element is initialized */
1944 top->v.compound_entry = NULL;
1945 } else if (is_type_struct(type)) {
1946 declaration_t *entry = top->v.compound_entry;
1948 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1949 if (next_entity != NULL) {
1950 assert(is_declaration(next_entity));
1951 entry = &next_entity->declaration;
1956 top->v.compound_entry = entry;
1957 if (entry != NULL) {
1958 path->top_type = entry->type;
1961 } else if (is_type_array(type)) {
1962 assert(is_type_array(type));
1966 if (!type->array.size_constant || top->v.index < type->array.size) {
1970 assert(!is_type_valid(type));
1974 /* we're past the last member of the current sub-aggregate, try if we
1975 * can ascend in the type hierarchy and continue with another subobject */
1976 size_t len = ARR_LEN(path->path);
1978 if (len > top_path_level) {
1979 ascend_from_subtype(path);
1980 advance_current_object(path, top_path_level);
1982 path->top_type = NULL;
1987 * skip any {...} blocks until a closing bracket is reached.
1989 static void skip_initializers(void)
1993 while (token.kind != '}') {
1994 if (token.kind == T_EOF)
1996 if (token.kind == '{') {
2004 static initializer_t *create_empty_initializer(void)
2006 static initializer_t empty_initializer
2007 = { .list = { { INITIALIZER_LIST }, 0 } };
2008 return &empty_initializer;
2012 * Parse a part of an initialiser for a struct or union,
2014 static initializer_t *parse_sub_initializer(type_path_t *path,
2015 type_t *outer_type, size_t top_path_level,
2016 parse_initializer_env_t *env)
2018 if (token.kind == '}') {
2019 /* empty initializer */
2020 return create_empty_initializer();
2023 type_t *orig_type = path->top_type;
2024 type_t *type = NULL;
2026 if (orig_type == NULL) {
2027 /* We are initializing an empty compound. */
2029 type = skip_typeref(orig_type);
2032 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2035 designator_t *designator = NULL;
2036 if (token.kind == '.' || token.kind == '[') {
2037 designator = parse_designation();
2038 goto finish_designator;
2039 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2040 /* GNU-style designator ("identifier: value") */
2041 designator = allocate_ast_zero(sizeof(designator[0]));
2042 designator->source_position = token.base.source_position;
2043 designator->symbol = token.identifier.symbol;
2048 /* reset path to toplevel, evaluate designator from there */
2049 ascend_to(path, top_path_level);
2050 if (!walk_designator(path, designator, false)) {
2051 /* can't continue after designation error */
2055 initializer_t *designator_initializer
2056 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2057 designator_initializer->designator.designator = designator;
2058 ARR_APP1(initializer_t*, initializers, designator_initializer);
2060 orig_type = path->top_type;
2061 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2066 if (token.kind == '{') {
2067 if (type != NULL && is_type_scalar(type)) {
2068 sub = parse_scalar_initializer(type, env->must_be_constant);
2071 if (env->entity != NULL) {
2073 "extra brace group at end of initializer for '%Y'",
2074 env->entity->base.symbol);
2076 errorf(HERE, "extra brace group at end of initializer");
2081 descend_into_subtype(path);
2084 add_anchor_token('}');
2085 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2087 rem_anchor_token('}');
2092 goto error_parse_next;
2094 ascend_from_subtype(path);
2097 /* must be an expression */
2098 expression_t *expression = parse_assignment_expression();
2099 mark_vars_read(expression, NULL);
2101 if (env->must_be_constant && !is_linker_constant(expression)) {
2102 errorf(&expression->base.source_position,
2103 "Initialisation expression '%E' is not constant",
2108 /* we are already outside, ... */
2109 if (outer_type == NULL)
2110 goto error_parse_next;
2111 type_t *const outer_type_skip = skip_typeref(outer_type);
2112 if (is_type_compound(outer_type_skip) &&
2113 !outer_type_skip->compound.compound->complete) {
2114 goto error_parse_next;
2117 source_position_t const* const pos = &expression->base.source_position;
2118 if (env->entity != NULL) {
2119 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2121 warningf(WARN_OTHER, pos, "excess elements in initializer");
2123 goto error_parse_next;
2126 /* handle { "string" } special case */
2127 if ((expression->kind == EXPR_STRING_LITERAL
2128 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2129 && outer_type != NULL) {
2130 sub = initializer_from_expression(outer_type, expression);
2133 if (token.kind != '}') {
2134 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2136 /* TODO: eat , ... */
2141 /* descend into subtypes until expression matches type */
2143 orig_type = path->top_type;
2144 type = skip_typeref(orig_type);
2146 sub = initializer_from_expression(orig_type, expression);
2150 if (!is_type_valid(type)) {
2153 if (is_type_scalar(type)) {
2154 errorf(&expression->base.source_position,
2155 "expression '%E' doesn't match expected type '%T'",
2156 expression, orig_type);
2160 descend_into_subtype(path);
2164 /* update largest index of top array */
2165 const type_path_entry_t *first = &path->path[0];
2166 type_t *first_type = first->type;
2167 first_type = skip_typeref(first_type);
2168 if (is_type_array(first_type)) {
2169 size_t index = first->v.index;
2170 if (index > path->max_index)
2171 path->max_index = index;
2174 /* append to initializers list */
2175 ARR_APP1(initializer_t*, initializers, sub);
2178 if (token.kind == '}') {
2181 add_anchor_token('}');
2183 rem_anchor_token('}');
2184 if (token.kind == '}') {
2189 /* advance to the next declaration if we are not at the end */
2190 advance_current_object(path, top_path_level);
2191 orig_type = path->top_type;
2192 if (orig_type != NULL)
2193 type = skip_typeref(orig_type);
2199 size_t len = ARR_LEN(initializers);
2200 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2201 initializer_t *result = allocate_ast_zero(size);
2202 result->kind = INITIALIZER_LIST;
2203 result->list.len = len;
2204 memcpy(&result->list.initializers, initializers,
2205 len * sizeof(initializers[0]));
2207 DEL_ARR_F(initializers);
2208 ascend_to(path, top_path_level+1);
2213 skip_initializers();
2214 DEL_ARR_F(initializers);
2215 ascend_to(path, top_path_level+1);
2219 static expression_t *make_size_literal(size_t value)
2221 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2222 literal->base.type = type_size_t;
2225 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2226 literal->literal.value = make_string(buf);
2232 * Parses an initializer. Parsers either a compound literal
2233 * (env->declaration == NULL) or an initializer of a declaration.
2235 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2237 type_t *type = skip_typeref(env->type);
2238 size_t max_index = 0;
2239 initializer_t *result;
2241 if (is_type_scalar(type)) {
2242 result = parse_scalar_initializer(type, env->must_be_constant);
2243 } else if (token.kind == '{') {
2247 memset(&path, 0, sizeof(path));
2248 path.top_type = env->type;
2249 path.path = NEW_ARR_F(type_path_entry_t, 0);
2251 descend_into_subtype(&path);
2253 add_anchor_token('}');
2254 result = parse_sub_initializer(&path, env->type, 1, env);
2255 rem_anchor_token('}');
2257 max_index = path.max_index;
2258 DEL_ARR_F(path.path);
2262 /* parse_scalar_initializer() also works in this case: we simply
2263 * have an expression without {} around it */
2264 result = parse_scalar_initializer(type, env->must_be_constant);
2267 /* §6.7.8:22 array initializers for arrays with unknown size determine
2268 * the array type size */
2269 if (is_type_array(type) && type->array.size_expression == NULL
2270 && result != NULL) {
2272 switch (result->kind) {
2273 case INITIALIZER_LIST:
2274 assert(max_index != 0xdeadbeaf);
2275 size = max_index + 1;
2278 case INITIALIZER_STRING:
2279 size = result->string.string.size;
2282 case INITIALIZER_WIDE_STRING:
2283 size = result->wide_string.string.size;
2286 case INITIALIZER_DESIGNATOR:
2287 case INITIALIZER_VALUE:
2288 /* can happen for parse errors */
2293 internal_errorf(HERE, "invalid initializer type");
2296 type_t *new_type = duplicate_type(type);
2298 new_type->array.size_expression = make_size_literal(size);
2299 new_type->array.size_constant = true;
2300 new_type->array.has_implicit_size = true;
2301 new_type->array.size = size;
2302 env->type = new_type;
2308 static void append_entity(scope_t *scope, entity_t *entity)
2310 if (scope->last_entity != NULL) {
2311 scope->last_entity->base.next = entity;
2313 scope->entities = entity;
2315 entity->base.parent_entity = current_entity;
2316 scope->last_entity = entity;
2320 static compound_t *parse_compound_type_specifier(bool is_struct)
2322 source_position_t const pos = *HERE;
2323 eat(is_struct ? T_struct : T_union);
2325 symbol_t *symbol = NULL;
2326 entity_t *entity = NULL;
2327 attribute_t *attributes = NULL;
2329 if (token.kind == T___attribute__) {
2330 attributes = parse_attributes(NULL);
2333 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2334 if (token.kind == T_IDENTIFIER) {
2335 /* the compound has a name, check if we have seen it already */
2336 symbol = token.identifier.symbol;
2337 entity = get_tag(symbol, kind);
2340 if (entity != NULL) {
2341 if (entity->base.parent_scope != current_scope &&
2342 (token.kind == '{' || token.kind == ';')) {
2343 /* we're in an inner scope and have a definition. Shadow
2344 * existing definition in outer scope */
2346 } else if (entity->compound.complete && token.kind == '{') {
2347 source_position_t const *const ppos = &entity->base.source_position;
2348 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2349 /* clear members in the hope to avoid further errors */
2350 entity->compound.members.entities = NULL;
2353 } else if (token.kind != '{') {
2354 char const *const msg =
2355 is_struct ? "while parsing struct type specifier" :
2356 "while parsing union type specifier";
2357 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2362 if (entity == NULL) {
2363 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2364 entity->compound.alignment = 1;
2365 entity->base.parent_scope = current_scope;
2366 if (symbol != NULL) {
2367 environment_push(entity);
2369 append_entity(current_scope, entity);
2372 if (token.kind == '{') {
2373 parse_compound_type_entries(&entity->compound);
2375 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2376 if (symbol == NULL) {
2377 assert(anonymous_entity == NULL);
2378 anonymous_entity = entity;
2382 if (attributes != NULL) {
2383 handle_entity_attributes(attributes, entity);
2386 return &entity->compound;
2389 static void parse_enum_entries(type_t *const enum_type)
2393 if (token.kind == '}') {
2394 errorf(HERE, "empty enum not allowed");
2399 add_anchor_token('}');
2400 add_anchor_token(',');
2402 add_anchor_token('=');
2403 source_position_t pos;
2404 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2405 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2406 entity->enum_value.enum_type = enum_type;
2407 rem_anchor_token('=');
2410 expression_t *value = parse_constant_expression();
2412 value = create_implicit_cast(value, enum_type);
2413 entity->enum_value.value = value;
2418 record_entity(entity, false);
2419 } while (next_if(',') && token.kind != '}');
2420 rem_anchor_token(',');
2421 rem_anchor_token('}');
2426 static type_t *parse_enum_specifier(void)
2428 source_position_t const pos = *HERE;
2433 switch (token.kind) {
2435 symbol = token.identifier.symbol;
2436 entity = get_tag(symbol, ENTITY_ENUM);
2439 if (entity != NULL) {
2440 if (entity->base.parent_scope != current_scope &&
2441 (token.kind == '{' || token.kind == ';')) {
2442 /* we're in an inner scope and have a definition. Shadow
2443 * existing definition in outer scope */
2445 } else if (entity->enume.complete && token.kind == '{') {
2446 source_position_t const *const ppos = &entity->base.source_position;
2447 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2458 parse_error_expected("while parsing enum type specifier",
2459 T_IDENTIFIER, '{', NULL);
2463 if (entity == NULL) {
2464 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2465 entity->base.parent_scope = current_scope;
2468 type_t *const type = allocate_type_zero(TYPE_ENUM);
2469 type->enumt.enume = &entity->enume;
2470 type->enumt.base.akind = ATOMIC_TYPE_INT;
2472 if (token.kind == '{') {
2473 if (symbol != NULL) {
2474 environment_push(entity);
2476 append_entity(current_scope, entity);
2477 entity->enume.complete = true;
2479 parse_enum_entries(type);
2480 parse_attributes(NULL);
2482 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2483 if (symbol == NULL) {
2484 assert(anonymous_entity == NULL);
2485 anonymous_entity = entity;
2487 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2488 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2495 * if a symbol is a typedef to another type, return true
2497 static bool is_typedef_symbol(symbol_t *symbol)
2499 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2500 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2503 static type_t *parse_typeof(void)
2510 add_anchor_token(')');
2512 expression_t *expression = NULL;
2514 switch (token.kind) {
2516 if (is_typedef_symbol(token.identifier.symbol)) {
2518 type = parse_typename();
2521 expression = parse_expression();
2522 type = revert_automatic_type_conversion(expression);
2527 rem_anchor_token(')');
2530 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2531 typeof_type->typeoft.expression = expression;
2532 typeof_type->typeoft.typeof_type = type;
2537 typedef enum specifiers_t {
2538 SPECIFIER_SIGNED = 1 << 0,
2539 SPECIFIER_UNSIGNED = 1 << 1,
2540 SPECIFIER_LONG = 1 << 2,
2541 SPECIFIER_INT = 1 << 3,
2542 SPECIFIER_DOUBLE = 1 << 4,
2543 SPECIFIER_CHAR = 1 << 5,
2544 SPECIFIER_WCHAR_T = 1 << 6,
2545 SPECIFIER_SHORT = 1 << 7,
2546 SPECIFIER_LONG_LONG = 1 << 8,
2547 SPECIFIER_FLOAT = 1 << 9,
2548 SPECIFIER_BOOL = 1 << 10,
2549 SPECIFIER_VOID = 1 << 11,
2550 SPECIFIER_INT8 = 1 << 12,
2551 SPECIFIER_INT16 = 1 << 13,
2552 SPECIFIER_INT32 = 1 << 14,
2553 SPECIFIER_INT64 = 1 << 15,
2554 SPECIFIER_INT128 = 1 << 16,
2555 SPECIFIER_COMPLEX = 1 << 17,
2556 SPECIFIER_IMAGINARY = 1 << 18,
2559 static type_t *get_typedef_type(symbol_t *symbol)
2561 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2562 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2565 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2566 type->typedeft.typedefe = &entity->typedefe;
2571 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2573 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2577 add_anchor_token(')');
2578 add_anchor_token(',');
2580 add_anchor_token('=');
2581 source_position_t pos;
2582 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2583 rem_anchor_token('=');
2585 symbol_t **prop = NULL;
2587 if (streq(prop_sym->string, "put")) {
2588 prop = &property->put_symbol;
2589 } else if (streq(prop_sym->string, "get")) {
2590 prop = &property->get_symbol;
2592 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2596 add_anchor_token(T_IDENTIFIER);
2598 rem_anchor_token(T_IDENTIFIER);
2600 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2602 *prop = sym ? sym : sym_anonymous;
2603 } while (next_if(','));
2604 rem_anchor_token(',');
2605 rem_anchor_token(')');
2607 attribute->a.property = property;
2613 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2615 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2616 if (next_if(T_restrict)) {
2617 kind = ATTRIBUTE_MS_RESTRICT;
2618 } else if (token.kind == T_IDENTIFIER) {
2619 const char *name = token.identifier.symbol->string;
2620 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2622 const char *attribute_name = get_attribute_name(k);
2623 if (attribute_name != NULL && streq(attribute_name, name)) {
2629 if (kind == ATTRIBUTE_UNKNOWN) {
2630 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2633 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2637 attribute_t *attribute = allocate_attribute_zero(kind);
2640 if (kind == ATTRIBUTE_MS_PROPERTY) {
2641 return parse_attribute_ms_property(attribute);
2644 /* parse arguments */
2646 attribute->a.arguments = parse_attribute_arguments();
2651 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2656 if (token.kind != ')') {
2657 add_anchor_token(')');
2659 attribute_t **anchor = &first;
2661 while (*anchor != NULL)
2662 anchor = &(*anchor)->next;
2664 attribute_t *attribute
2665 = parse_microsoft_extended_decl_modifier_single();
2666 if (attribute == NULL)
2669 *anchor = attribute;
2670 anchor = &attribute->next;
2671 } while (next_if(','));
2673 rem_anchor_token(')');
2679 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2681 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2682 if (is_declaration(entity)) {
2683 entity->declaration.type = type_error_type;
2684 entity->declaration.implicit = true;
2685 } else if (kind == ENTITY_TYPEDEF) {
2686 entity->typedefe.type = type_error_type;
2687 entity->typedefe.builtin = true;
2689 if (kind != ENTITY_COMPOUND_MEMBER)
2690 record_entity(entity, false);
2694 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2696 type_t *type = NULL;
2697 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2698 unsigned type_specifiers = 0;
2699 bool newtype = false;
2700 bool saw_error = false;
2702 memset(specifiers, 0, sizeof(*specifiers));
2703 specifiers->source_position = token.base.source_position;
2706 specifiers->attributes = parse_attributes(specifiers->attributes);
2708 switch (token.kind) {
2710 #define MATCH_STORAGE_CLASS(token, class) \
2712 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2713 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2715 specifiers->storage_class = class; \
2716 if (specifiers->thread_local) \
2717 goto check_thread_storage_class; \
2721 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2722 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2723 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2724 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2725 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2728 specifiers->attributes
2729 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2733 if (specifiers->thread_local) {
2734 errorf(HERE, "duplicate '__thread'");
2736 specifiers->thread_local = true;
2737 check_thread_storage_class:
2738 switch (specifiers->storage_class) {
2739 case STORAGE_CLASS_EXTERN:
2740 case STORAGE_CLASS_NONE:
2741 case STORAGE_CLASS_STATIC:
2745 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2746 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2747 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2748 wrong_thread_storage_class:
2749 errorf(HERE, "'__thread' used with '%s'", wrong);
2756 /* type qualifiers */
2757 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2759 qualifiers |= qualifier; \
2763 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2764 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2765 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2766 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2767 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2768 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2769 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2770 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2772 /* type specifiers */
2773 #define MATCH_SPECIFIER(token, specifier, name) \
2775 if (type_specifiers & specifier) { \
2776 errorf(HERE, "multiple " name " type specifiers given"); \
2778 type_specifiers |= specifier; \
2783 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2784 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2785 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2786 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2787 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2788 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2789 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2790 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2791 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2792 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2793 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2794 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2795 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2796 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2797 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2798 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2799 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2800 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2804 specifiers->is_inline = true;
2808 case T__forceinline:
2810 specifiers->modifiers |= DM_FORCEINLINE;
2815 if (type_specifiers & SPECIFIER_LONG_LONG) {
2816 errorf(HERE, "too many long type specifiers given");
2817 } else if (type_specifiers & SPECIFIER_LONG) {
2818 type_specifiers |= SPECIFIER_LONG_LONG;
2820 type_specifiers |= SPECIFIER_LONG;
2825 #define CHECK_DOUBLE_TYPE() \
2826 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2829 CHECK_DOUBLE_TYPE();
2830 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2832 type->compound.compound = parse_compound_type_specifier(true);
2835 CHECK_DOUBLE_TYPE();
2836 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2837 type->compound.compound = parse_compound_type_specifier(false);
2840 CHECK_DOUBLE_TYPE();
2841 type = parse_enum_specifier();
2844 CHECK_DOUBLE_TYPE();
2845 type = parse_typeof();
2847 case T___builtin_va_list:
2848 CHECK_DOUBLE_TYPE();
2849 type = duplicate_type(type_valist);
2853 case T_IDENTIFIER: {
2854 /* only parse identifier if we haven't found a type yet */
2855 if (type != NULL || type_specifiers != 0) {
2856 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2857 * declaration, so it doesn't generate errors about expecting '(' or
2859 switch (look_ahead(1)->kind) {
2866 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2870 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2875 goto finish_specifiers;
2879 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2880 if (typedef_type == NULL) {
2881 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2882 * declaration, so it doesn't generate 'implicit int' followed by more
2883 * errors later on. */
2884 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2890 errorf(HERE, "%K does not name a type", &token);
2892 symbol_t *symbol = token.identifier.symbol;
2894 = create_error_entity(symbol, ENTITY_TYPEDEF);
2896 type = allocate_type_zero(TYPE_TYPEDEF);
2897 type->typedeft.typedefe = &entity->typedefe;
2905 goto finish_specifiers;
2910 type = typedef_type;
2914 /* function specifier */
2916 goto finish_specifiers;
2921 specifiers->attributes = parse_attributes(specifiers->attributes);
2923 if (type == NULL || (saw_error && type_specifiers != 0)) {
2924 atomic_type_kind_t atomic_type;
2926 /* match valid basic types */
2927 switch (type_specifiers) {
2928 case SPECIFIER_VOID:
2929 atomic_type = ATOMIC_TYPE_VOID;
2931 case SPECIFIER_WCHAR_T:
2932 atomic_type = ATOMIC_TYPE_WCHAR_T;
2934 case SPECIFIER_CHAR:
2935 atomic_type = ATOMIC_TYPE_CHAR;
2937 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2938 atomic_type = ATOMIC_TYPE_SCHAR;
2940 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2941 atomic_type = ATOMIC_TYPE_UCHAR;
2943 case SPECIFIER_SHORT:
2944 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2945 case SPECIFIER_SHORT | SPECIFIER_INT:
2946 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2947 atomic_type = ATOMIC_TYPE_SHORT;
2949 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2950 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2951 atomic_type = ATOMIC_TYPE_USHORT;
2954 case SPECIFIER_SIGNED:
2955 case SPECIFIER_SIGNED | SPECIFIER_INT:
2956 atomic_type = ATOMIC_TYPE_INT;
2958 case SPECIFIER_UNSIGNED:
2959 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2960 atomic_type = ATOMIC_TYPE_UINT;
2962 case SPECIFIER_LONG:
2963 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2964 case SPECIFIER_LONG | SPECIFIER_INT:
2965 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2966 atomic_type = ATOMIC_TYPE_LONG;
2968 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2969 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2970 atomic_type = ATOMIC_TYPE_ULONG;
2973 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2974 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2975 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2976 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2978 atomic_type = ATOMIC_TYPE_LONGLONG;
2979 goto warn_about_long_long;
2981 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2982 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2984 atomic_type = ATOMIC_TYPE_ULONGLONG;
2985 warn_about_long_long:
2986 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2989 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2990 atomic_type = unsigned_int8_type_kind;
2993 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2994 atomic_type = unsigned_int16_type_kind;
2997 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2998 atomic_type = unsigned_int32_type_kind;
3001 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3002 atomic_type = unsigned_int64_type_kind;
3005 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3006 atomic_type = unsigned_int128_type_kind;
3009 case SPECIFIER_INT8:
3010 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3011 atomic_type = int8_type_kind;
3014 case SPECIFIER_INT16:
3015 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3016 atomic_type = int16_type_kind;
3019 case SPECIFIER_INT32:
3020 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3021 atomic_type = int32_type_kind;
3024 case SPECIFIER_INT64:
3025 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3026 atomic_type = int64_type_kind;
3029 case SPECIFIER_INT128:
3030 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3031 atomic_type = int128_type_kind;
3034 case SPECIFIER_FLOAT:
3035 atomic_type = ATOMIC_TYPE_FLOAT;
3037 case SPECIFIER_DOUBLE:
3038 atomic_type = ATOMIC_TYPE_DOUBLE;
3040 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3041 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3043 case SPECIFIER_BOOL:
3044 atomic_type = ATOMIC_TYPE_BOOL;
3046 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3047 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3048 atomic_type = ATOMIC_TYPE_FLOAT;
3050 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3051 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3052 atomic_type = ATOMIC_TYPE_DOUBLE;
3054 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3055 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3056 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3059 /* invalid specifier combination, give an error message */
3060 source_position_t const* const pos = &specifiers->source_position;
3061 if (type_specifiers == 0) {
3063 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3064 if (!(c_mode & _CXX) && !strict_mode) {
3065 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3066 atomic_type = ATOMIC_TYPE_INT;
3069 errorf(pos, "no type specifiers given in declaration");
3072 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3073 (type_specifiers & SPECIFIER_UNSIGNED)) {
3074 errorf(pos, "signed and unsigned specifiers given");
3075 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3076 errorf(pos, "only integer types can be signed or unsigned");
3078 errorf(pos, "multiple datatypes in declaration");
3084 if (type_specifiers & SPECIFIER_COMPLEX) {
3085 type = allocate_type_zero(TYPE_COMPLEX);
3086 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3087 type = allocate_type_zero(TYPE_IMAGINARY);
3089 type = allocate_type_zero(TYPE_ATOMIC);
3091 type->atomic.akind = atomic_type;
3093 } else if (type_specifiers != 0) {
3094 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3097 /* FIXME: check type qualifiers here */
3098 type->base.qualifiers = qualifiers;
3101 type = identify_new_type(type);
3103 type = typehash_insert(type);
3106 if (specifiers->attributes != NULL)
3107 type = handle_type_attributes(specifiers->attributes, type);
3108 specifiers->type = type;
3112 specifiers->type = type_error_type;
3115 static type_qualifiers_t parse_type_qualifiers(void)
3117 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3120 switch (token.kind) {
3121 /* type qualifiers */
3122 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3123 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3124 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3125 /* microsoft extended type modifiers */
3126 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3127 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3128 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3129 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3130 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3139 * Parses an K&R identifier list
3141 static void parse_identifier_list(scope_t *scope)
3143 assert(token.kind == T_IDENTIFIER);
3145 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3146 /* a K&R parameter has no type, yet */
3150 append_entity(scope, entity);
3151 } while (next_if(',') && token.kind == T_IDENTIFIER);
3154 static entity_t *parse_parameter(void)
3156 declaration_specifiers_t specifiers;
3157 parse_declaration_specifiers(&specifiers);
3159 entity_t *entity = parse_declarator(&specifiers,
3160 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3161 anonymous_entity = NULL;
3165 static void semantic_parameter_incomplete(const entity_t *entity)
3167 assert(entity->kind == ENTITY_PARAMETER);
3169 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3170 * list in a function declarator that is part of a
3171 * definition of that function shall not have
3172 * incomplete type. */
3173 type_t *type = skip_typeref(entity->declaration.type);
3174 if (is_type_incomplete(type)) {
3175 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3179 static bool has_parameters(void)
3181 /* func(void) is not a parameter */
3182 if (look_ahead(1)->kind != ')')
3184 if (token.kind == T_IDENTIFIER) {
3185 entity_t const *const entity
3186 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3189 if (entity->kind != ENTITY_TYPEDEF)
3191 type_t const *const type = skip_typeref(entity->typedefe.type);
3192 if (!is_type_void(type))
3194 if (c_mode & _CXX) {
3195 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3196 * is not allowed. */
3197 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3198 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3199 /* §6.7.5.3:10 Qualification is not allowed here. */
3200 errorf(HERE, "'void' as parameter must not have type qualifiers");
3202 } else if (token.kind != T_void) {
3210 * Parses function type parameters (and optionally creates variable_t entities
3211 * for them in a scope)
3213 static void parse_parameters(function_type_t *type, scope_t *scope)
3216 add_anchor_token(')');
3217 int saved_comma_state = save_and_reset_anchor_state(',');
3219 if (token.kind == T_IDENTIFIER
3220 && !is_typedef_symbol(token.identifier.symbol)) {
3221 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3222 if (la1_type == ',' || la1_type == ')') {
3223 type->kr_style_parameters = true;
3224 parse_identifier_list(scope);
3225 goto parameters_finished;
3229 if (token.kind == ')') {
3230 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3231 if (!(c_mode & _CXX))
3232 type->unspecified_parameters = true;
3233 } else if (has_parameters()) {
3234 function_parameter_t **anchor = &type->parameters;
3236 switch (token.kind) {
3239 type->variadic = true;
3240 goto parameters_finished;
3245 entity_t *entity = parse_parameter();
3246 if (entity->kind == ENTITY_TYPEDEF) {
3247 errorf(&entity->base.source_position,
3248 "typedef not allowed as function parameter");
3251 assert(is_declaration(entity));
3253 semantic_parameter_incomplete(entity);
3255 function_parameter_t *const parameter =
3256 allocate_parameter(entity->declaration.type);
3258 if (scope != NULL) {
3259 append_entity(scope, entity);
3262 *anchor = parameter;
3263 anchor = ¶meter->next;
3268 goto parameters_finished;
3270 } while (next_if(','));
3273 parameters_finished:
3274 rem_anchor_token(')');
3277 restore_anchor_state(',', saved_comma_state);
3280 typedef enum construct_type_kind_t {
3281 CONSTRUCT_POINTER = 1,
3282 CONSTRUCT_REFERENCE,
3285 } construct_type_kind_t;
3287 typedef union construct_type_t construct_type_t;
3289 typedef struct construct_type_base_t {
3290 construct_type_kind_t kind;
3291 source_position_t pos;
3292 construct_type_t *next;
3293 } construct_type_base_t;
3295 typedef struct parsed_pointer_t {
3296 construct_type_base_t base;
3297 type_qualifiers_t type_qualifiers;
3298 variable_t *base_variable; /**< MS __based extension. */
3301 typedef struct parsed_reference_t {
3302 construct_type_base_t base;
3303 } parsed_reference_t;
3305 typedef struct construct_function_type_t {
3306 construct_type_base_t base;
3307 type_t *function_type;
3308 } construct_function_type_t;
3310 typedef struct parsed_array_t {
3311 construct_type_base_t base;
3312 type_qualifiers_t type_qualifiers;
3318 union construct_type_t {
3319 construct_type_kind_t kind;
3320 construct_type_base_t base;
3321 parsed_pointer_t pointer;
3322 parsed_reference_t reference;
3323 construct_function_type_t function;
3324 parsed_array_t array;
3327 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3329 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3330 memset(cons, 0, size);
3332 cons->base.pos = *HERE;
3337 static construct_type_t *parse_pointer_declarator(void)
3339 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3341 cons->pointer.type_qualifiers = parse_type_qualifiers();
3342 //cons->pointer.base_variable = base_variable;
3347 /* ISO/IEC 14882:1998(E) §8.3.2 */
3348 static construct_type_t *parse_reference_declarator(void)
3350 if (!(c_mode & _CXX))
3351 errorf(HERE, "references are only available for C++");
3353 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3360 static construct_type_t *parse_array_declarator(void)
3362 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3363 parsed_array_t *const array = &cons->array;
3366 add_anchor_token(']');
3368 bool is_static = next_if(T_static);
3370 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3373 is_static = next_if(T_static);
3375 array->type_qualifiers = type_qualifiers;
3376 array->is_static = is_static;
3378 expression_t *size = NULL;
3379 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3380 array->is_variable = true;
3382 } else if (token.kind != ']') {
3383 size = parse_assignment_expression();
3385 /* §6.7.5.2:1 Array size must have integer type */
3386 type_t *const orig_type = size->base.type;
3387 type_t *const type = skip_typeref(orig_type);
3388 if (!is_type_integer(type) && is_type_valid(type)) {
3389 errorf(&size->base.source_position,
3390 "array size '%E' must have integer type but has type '%T'",
3395 mark_vars_read(size, NULL);
3398 if (is_static && size == NULL)
3399 errorf(&array->base.pos, "static array parameters require a size");
3401 rem_anchor_token(']');
3407 static construct_type_t *parse_function_declarator(scope_t *scope)
3409 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3411 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3412 function_type_t *ftype = &type->function;
3414 ftype->linkage = current_linkage;
3415 ftype->calling_convention = CC_DEFAULT;
3417 parse_parameters(ftype, scope);
3419 cons->function.function_type = type;
3424 typedef struct parse_declarator_env_t {
3425 bool may_be_abstract : 1;
3426 bool must_be_abstract : 1;
3427 decl_modifiers_t modifiers;
3429 source_position_t source_position;
3431 attribute_t *attributes;
3432 } parse_declarator_env_t;
3435 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3437 /* construct a single linked list of construct_type_t's which describe
3438 * how to construct the final declarator type */
3439 construct_type_t *first = NULL;
3440 construct_type_t **anchor = &first;
3442 env->attributes = parse_attributes(env->attributes);
3445 construct_type_t *type;
3446 //variable_t *based = NULL; /* MS __based extension */
3447 switch (token.kind) {
3449 type = parse_reference_declarator();
3453 panic("based not supported anymore");
3458 type = parse_pointer_declarator();
3462 goto ptr_operator_end;
3466 anchor = &type->base.next;
3468 /* TODO: find out if this is correct */
3469 env->attributes = parse_attributes(env->attributes);
3473 construct_type_t *inner_types = NULL;
3475 switch (token.kind) {
3477 if (env->must_be_abstract) {
3478 errorf(HERE, "no identifier expected in typename");
3480 env->symbol = token.identifier.symbol;
3481 env->source_position = token.base.source_position;
3487 /* Parenthesized declarator or function declarator? */
3488 token_t const *const la1 = look_ahead(1);
3489 switch (la1->kind) {
3491 if (is_typedef_symbol(la1->identifier.symbol)) {
3493 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3494 * interpreted as ``function with no parameter specification'', rather
3495 * than redundant parentheses around the omitted identifier. */
3497 /* Function declarator. */
3498 if (!env->may_be_abstract) {
3499 errorf(HERE, "function declarator must have a name");
3506 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3507 /* Paranthesized declarator. */
3509 add_anchor_token(')');
3510 inner_types = parse_inner_declarator(env);
3511 if (inner_types != NULL) {
3512 /* All later declarators only modify the return type */
3513 env->must_be_abstract = true;
3515 rem_anchor_token(')');
3524 if (env->may_be_abstract)
3526 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3531 construct_type_t **const p = anchor;
3534 construct_type_t *type;
3535 switch (token.kind) {
3537 scope_t *scope = NULL;
3538 if (!env->must_be_abstract) {
3539 scope = &env->parameters;
3542 type = parse_function_declarator(scope);
3546 type = parse_array_declarator();
3549 goto declarator_finished;
3552 /* insert in the middle of the list (at p) */
3553 type->base.next = *p;
3556 anchor = &type->base.next;
3559 declarator_finished:
3560 /* append inner_types at the end of the list, we don't to set anchor anymore
3561 * as it's not needed anymore */
3562 *anchor = inner_types;
3567 static type_t *construct_declarator_type(construct_type_t *construct_list,
3570 construct_type_t *iter = construct_list;
3571 for (; iter != NULL; iter = iter->base.next) {
3572 source_position_t const* const pos = &iter->base.pos;
3573 switch (iter->kind) {
3574 case CONSTRUCT_FUNCTION: {
3575 construct_function_type_t *function = &iter->function;
3576 type_t *function_type = function->function_type;
3578 function_type->function.return_type = type;
3580 type_t *skipped_return_type = skip_typeref(type);
3582 if (is_type_function(skipped_return_type)) {
3583 errorf(pos, "function returning function is not allowed");
3584 } else if (is_type_array(skipped_return_type)) {
3585 errorf(pos, "function returning array is not allowed");
3587 if (skipped_return_type->base.qualifiers != 0) {
3588 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3592 /* The function type was constructed earlier. Freeing it here will
3593 * destroy other types. */
3594 type = typehash_insert(function_type);
3598 case CONSTRUCT_POINTER: {
3599 if (is_type_reference(skip_typeref(type)))
3600 errorf(pos, "cannot declare a pointer to reference");
3602 parsed_pointer_t *pointer = &iter->pointer;
3603 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3607 case CONSTRUCT_REFERENCE:
3608 if (is_type_reference(skip_typeref(type)))
3609 errorf(pos, "cannot declare a reference to reference");
3611 type = make_reference_type(type);
3614 case CONSTRUCT_ARRAY: {
3615 if (is_type_reference(skip_typeref(type)))
3616 errorf(pos, "cannot declare an array of references");
3618 parsed_array_t *array = &iter->array;
3619 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3621 expression_t *size_expression = array->size;
3622 if (size_expression != NULL) {
3624 = create_implicit_cast(size_expression, type_size_t);
3627 array_type->base.qualifiers = array->type_qualifiers;
3628 array_type->array.element_type = type;
3629 array_type->array.is_static = array->is_static;
3630 array_type->array.is_variable = array->is_variable;
3631 array_type->array.size_expression = size_expression;
3633 if (size_expression != NULL) {
3634 switch (is_constant_expression(size_expression)) {
3635 case EXPR_CLASS_CONSTANT: {
3636 long const size = fold_constant_to_int(size_expression);
3637 array_type->array.size = size;
3638 array_type->array.size_constant = true;
3639 /* §6.7.5.2:1 If the expression is a constant expression,
3640 * it shall have a value greater than zero. */
3642 errorf(&size_expression->base.source_position,
3643 "size of array must be greater than zero");
3644 } else if (size == 0 && !GNU_MODE) {
3645 errorf(&size_expression->base.source_position,
3646 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3651 case EXPR_CLASS_VARIABLE:
3652 array_type->array.is_vla = true;
3655 case EXPR_CLASS_ERROR:
3660 type_t *skipped_type = skip_typeref(type);
3662 if (is_type_incomplete(skipped_type)) {
3663 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3664 } else if (is_type_function(skipped_type)) {
3665 errorf(pos, "array of functions is not allowed");
3667 type = identify_new_type(array_type);
3671 internal_errorf(pos, "invalid type construction found");
3677 static type_t *automatic_type_conversion(type_t *orig_type);
3679 static type_t *semantic_parameter(const source_position_t *pos,
3681 const declaration_specifiers_t *specifiers,
3682 entity_t const *const param)
3684 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3685 * shall be adjusted to ``qualified pointer to type'',
3687 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3688 * type'' shall be adjusted to ``pointer to function
3689 * returning type'', as in 6.3.2.1. */
3690 type = automatic_type_conversion(type);
3692 if (specifiers->is_inline && is_type_valid(type)) {
3693 errorf(pos, "'%N' declared 'inline'", param);
3696 /* §6.9.1:6 The declarations in the declaration list shall contain
3697 * no storage-class specifier other than register and no
3698 * initializations. */
3699 if (specifiers->thread_local || (
3700 specifiers->storage_class != STORAGE_CLASS_NONE &&
3701 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3703 errorf(pos, "invalid storage class for '%N'", param);
3706 /* delay test for incomplete type, because we might have (void)
3707 * which is legal but incomplete... */
3712 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3713 declarator_flags_t flags)
3715 parse_declarator_env_t env;
3716 memset(&env, 0, sizeof(env));
3717 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3719 construct_type_t *construct_type = parse_inner_declarator(&env);
3721 construct_declarator_type(construct_type, specifiers->type);
3722 type_t *type = skip_typeref(orig_type);
3724 if (construct_type != NULL) {
3725 obstack_free(&temp_obst, construct_type);
3728 attribute_t *attributes = parse_attributes(env.attributes);
3729 /* append (shared) specifier attribute behind attributes of this
3731 attribute_t **anchor = &attributes;
3732 while (*anchor != NULL)
3733 anchor = &(*anchor)->next;
3734 *anchor = specifiers->attributes;
3737 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3738 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3739 entity->typedefe.type = orig_type;
3741 if (anonymous_entity != NULL) {
3742 if (is_type_compound(type)) {
3743 assert(anonymous_entity->compound.alias == NULL);
3744 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3745 anonymous_entity->kind == ENTITY_UNION);
3746 anonymous_entity->compound.alias = entity;
3747 anonymous_entity = NULL;
3748 } else if (is_type_enum(type)) {
3749 assert(anonymous_entity->enume.alias == NULL);
3750 assert(anonymous_entity->kind == ENTITY_ENUM);
3751 anonymous_entity->enume.alias = entity;
3752 anonymous_entity = NULL;
3756 /* create a declaration type entity */
3757 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3758 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3759 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3761 if (env.symbol != NULL) {
3762 if (specifiers->is_inline && is_type_valid(type)) {
3763 errorf(&env.source_position,
3764 "compound member '%Y' declared 'inline'", env.symbol);
3767 if (specifiers->thread_local ||
3768 specifiers->storage_class != STORAGE_CLASS_NONE) {
3769 errorf(&env.source_position,
3770 "compound member '%Y' must have no storage class",
3774 } else if (flags & DECL_IS_PARAMETER) {
3775 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3776 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3777 } else if (is_type_function(type)) {
3778 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3779 entity->function.is_inline = specifiers->is_inline;
3780 entity->function.elf_visibility = default_visibility;
3781 entity->function.parameters = env.parameters;
3783 if (env.symbol != NULL) {
3784 /* this needs fixes for C++ */
3785 bool in_function_scope = current_function != NULL;
3787 if (specifiers->thread_local || (
3788 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3789 specifiers->storage_class != STORAGE_CLASS_NONE &&
3790 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3792 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3796 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3797 entity->variable.elf_visibility = default_visibility;
3798 entity->variable.thread_local = specifiers->thread_local;
3800 if (env.symbol != NULL) {
3801 if (specifiers->is_inline && is_type_valid(type)) {
3802 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3805 bool invalid_storage_class = false;
3806 if (current_scope == file_scope) {
3807 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3808 specifiers->storage_class != STORAGE_CLASS_NONE &&
3809 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3810 invalid_storage_class = true;
3813 if (specifiers->thread_local &&
3814 specifiers->storage_class == STORAGE_CLASS_NONE) {
3815 invalid_storage_class = true;
3818 if (invalid_storage_class) {
3819 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3824 entity->declaration.type = orig_type;
3825 entity->declaration.alignment = get_type_alignment(orig_type);
3826 entity->declaration.modifiers = env.modifiers;
3827 entity->declaration.attributes = attributes;
3829 storage_class_t storage_class = specifiers->storage_class;
3830 entity->declaration.declared_storage_class = storage_class;
3832 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3833 storage_class = STORAGE_CLASS_AUTO;
3834 entity->declaration.storage_class = storage_class;
3837 if (attributes != NULL) {
3838 handle_entity_attributes(attributes, entity);
3841 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3842 adapt_special_functions(&entity->function);
3848 static type_t *parse_abstract_declarator(type_t *base_type)
3850 parse_declarator_env_t env;
3851 memset(&env, 0, sizeof(env));
3852 env.may_be_abstract = true;
3853 env.must_be_abstract = true;
3855 construct_type_t *construct_type = parse_inner_declarator(&env);
3857 type_t *result = construct_declarator_type(construct_type, base_type);
3858 if (construct_type != NULL) {
3859 obstack_free(&temp_obst, construct_type);
3861 result = handle_type_attributes(env.attributes, result);
3867 * Check if the declaration of main is suspicious. main should be a
3868 * function with external linkage, returning int, taking either zero
3869 * arguments, two, or three arguments of appropriate types, ie.
3871 * int main([ int argc, char **argv [, char **env ] ]).
3873 * @param decl the declaration to check
3874 * @param type the function type of the declaration
3876 static void check_main(const entity_t *entity)
3878 const source_position_t *pos = &entity->base.source_position;
3879 if (entity->kind != ENTITY_FUNCTION) {
3880 warningf(WARN_MAIN, pos, "'main' is not a function");
3884 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3885 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3888 type_t *type = skip_typeref(entity->declaration.type);
3889 assert(is_type_function(type));
3891 function_type_t const *const func_type = &type->function;
3892 type_t *const ret_type = func_type->return_type;
3893 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3894 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3896 const function_parameter_t *parm = func_type->parameters;
3898 type_t *const first_type = skip_typeref(parm->type);
3899 type_t *const first_type_unqual = get_unqualified_type(first_type);
3900 if (!types_compatible(first_type_unqual, type_int)) {
3901 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3905 type_t *const second_type = skip_typeref(parm->type);
3906 type_t *const second_type_unqual
3907 = get_unqualified_type(second_type);
3908 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3909 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3913 type_t *const third_type = skip_typeref(parm->type);
3914 type_t *const third_type_unqual
3915 = get_unqualified_type(third_type);
3916 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3917 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3921 goto warn_arg_count;
3925 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3931 * Check if a symbol is the equal to "main".
3933 static bool is_sym_main(const symbol_t *const sym)
3935 return streq(sym->string, "main");
3938 static void error_redefined_as_different_kind(const source_position_t *pos,
3939 const entity_t *old, entity_kind_t new_kind)
3941 char const *const what = get_entity_kind_name(new_kind);
3942 source_position_t const *const ppos = &old->base.source_position;
3943 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3946 static bool is_entity_valid(entity_t *const ent)
3948 if (is_declaration(ent)) {
3949 return is_type_valid(skip_typeref(ent->declaration.type));
3950 } else if (ent->kind == ENTITY_TYPEDEF) {
3951 return is_type_valid(skip_typeref(ent->typedefe.type));
3956 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3958 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3959 if (attributes_equal(tattr, attr))
3966 * test wether new_list contains any attributes not included in old_list
3968 static bool has_new_attributes(const attribute_t *old_list,
3969 const attribute_t *new_list)
3971 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3972 if (!contains_attribute(old_list, attr))
3979 * Merge in attributes from an attribute list (probably from a previous
3980 * declaration with the same name). Warning: destroys the old structure
3981 * of the attribute list - don't reuse attributes after this call.
3983 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3986 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3988 if (contains_attribute(decl->attributes, attr))
3991 /* move attribute to new declarations attributes list */
3992 attr->next = decl->attributes;
3993 decl->attributes = attr;
3998 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3999 * for various problems that occur for multiple definitions
4001 entity_t *record_entity(entity_t *entity, const bool is_definition)
4003 const symbol_t *const symbol = entity->base.symbol;
4004 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4005 const source_position_t *pos = &entity->base.source_position;
4007 /* can happen in error cases */
4011 entity_t *const previous_entity = get_entity(symbol, namespc);
4012 /* pushing the same entity twice will break the stack structure */
4013 assert(previous_entity != entity);
4015 if (entity->kind == ENTITY_FUNCTION) {
4016 type_t *const orig_type = entity->declaration.type;
4017 type_t *const type = skip_typeref(orig_type);
4019 assert(is_type_function(type));
4020 if (type->function.unspecified_parameters &&
4021 previous_entity == NULL &&
4022 !entity->declaration.implicit) {
4023 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4026 if (current_scope == file_scope && is_sym_main(symbol)) {
4031 if (is_declaration(entity) &&
4032 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4033 current_scope != file_scope &&
4034 !entity->declaration.implicit) {
4035 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4038 if (previous_entity != NULL) {
4039 source_position_t const *const ppos = &previous_entity->base.source_position;
4041 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4042 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4043 assert(previous_entity->kind == ENTITY_PARAMETER);
4044 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4048 if (previous_entity->base.parent_scope == current_scope) {
4049 if (previous_entity->kind != entity->kind) {
4050 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4051 error_redefined_as_different_kind(pos, previous_entity,
4056 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4057 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4060 if (previous_entity->kind == ENTITY_TYPEDEF) {
4061 type_t *const type = skip_typeref(entity->typedefe.type);
4062 type_t *const prev_type
4063 = skip_typeref(previous_entity->typedefe.type);
4064 if (c_mode & _CXX) {
4065 /* C++ allows double typedef if they are identical
4066 * (after skipping typedefs) */
4067 if (type == prev_type)
4070 /* GCC extension: redef in system headers is allowed */
4071 if ((pos->is_system_header || ppos->is_system_header) &&
4072 types_compatible(type, prev_type))
4075 errorf(pos, "redefinition of '%N' (declared %P)",
4080 /* at this point we should have only VARIABLES or FUNCTIONS */
4081 assert(is_declaration(previous_entity) && is_declaration(entity));
4083 declaration_t *const prev_decl = &previous_entity->declaration;
4084 declaration_t *const decl = &entity->declaration;
4086 /* can happen for K&R style declarations */
4087 if (prev_decl->type == NULL &&
4088 previous_entity->kind == ENTITY_PARAMETER &&
4089 entity->kind == ENTITY_PARAMETER) {
4090 prev_decl->type = decl->type;
4091 prev_decl->storage_class = decl->storage_class;
4092 prev_decl->declared_storage_class = decl->declared_storage_class;
4093 prev_decl->modifiers = decl->modifiers;
4094 return previous_entity;
4097 type_t *const type = skip_typeref(decl->type);
4098 type_t *const prev_type = skip_typeref(prev_decl->type);
4100 if (!types_compatible(type, prev_type)) {
4101 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4103 unsigned old_storage_class = prev_decl->storage_class;
4105 if (is_definition &&
4107 !(prev_decl->modifiers & DM_USED) &&
4108 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4109 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4112 storage_class_t new_storage_class = decl->storage_class;
4114 /* pretend no storage class means extern for function
4115 * declarations (except if the previous declaration is neither
4116 * none nor extern) */
4117 if (entity->kind == ENTITY_FUNCTION) {
4118 /* the previous declaration could have unspecified parameters or
4119 * be a typedef, so use the new type */
4120 if (prev_type->function.unspecified_parameters || is_definition)
4121 prev_decl->type = type;
4123 switch (old_storage_class) {
4124 case STORAGE_CLASS_NONE:
4125 old_storage_class = STORAGE_CLASS_EXTERN;
4128 case STORAGE_CLASS_EXTERN:
4129 if (is_definition) {
4130 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4131 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4133 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4134 new_storage_class = STORAGE_CLASS_EXTERN;
4141 } else if (is_type_incomplete(prev_type)) {
4142 prev_decl->type = type;
4145 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4146 new_storage_class == STORAGE_CLASS_EXTERN) {
4148 warn_redundant_declaration: ;
4150 = has_new_attributes(prev_decl->attributes,
4152 if (has_new_attrs) {
4153 merge_in_attributes(decl, prev_decl->attributes);
4154 } else if (!is_definition &&
4155 is_type_valid(prev_type) &&
4156 !pos->is_system_header) {
4157 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4159 } else if (current_function == NULL) {
4160 if (old_storage_class != STORAGE_CLASS_STATIC &&
4161 new_storage_class == STORAGE_CLASS_STATIC) {
4162 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4163 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4164 prev_decl->storage_class = STORAGE_CLASS_NONE;
4165 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4167 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4169 goto error_redeclaration;
4170 goto warn_redundant_declaration;
4172 } else if (is_type_valid(prev_type)) {
4173 if (old_storage_class == new_storage_class) {
4174 error_redeclaration:
4175 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4177 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4182 prev_decl->modifiers |= decl->modifiers;
4183 if (entity->kind == ENTITY_FUNCTION) {
4184 previous_entity->function.is_inline |= entity->function.is_inline;
4186 return previous_entity;
4190 if (is_warn_on(why = WARN_SHADOW) ||
4191 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4192 char const *const what = get_entity_kind_name(previous_entity->kind);
4193 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4197 if (entity->kind == ENTITY_FUNCTION) {
4198 if (is_definition &&
4199 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4200 !is_sym_main(symbol)) {
4201 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4202 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4204 goto warn_missing_declaration;
4207 } else if (entity->kind == ENTITY_VARIABLE) {
4208 if (current_scope == file_scope &&
4209 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4210 !entity->declaration.implicit) {
4211 warn_missing_declaration:
4212 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4217 assert(entity->base.parent_scope == NULL);
4218 assert(current_scope != NULL);
4220 entity->base.parent_scope = current_scope;
4221 environment_push(entity);
4222 append_entity(current_scope, entity);
4227 static void parser_error_multiple_definition(entity_t *entity,
4228 const source_position_t *source_position)
4230 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4231 entity->base.symbol, &entity->base.source_position);
4234 static bool is_declaration_specifier(const token_t *token)
4236 switch (token->kind) {
4240 return is_typedef_symbol(token->identifier.symbol);
4247 static void parse_init_declarator_rest(entity_t *entity)
4249 type_t *orig_type = type_error_type;
4251 if (entity->base.kind == ENTITY_TYPEDEF) {
4252 source_position_t const *const pos = &entity->base.source_position;
4253 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4255 assert(is_declaration(entity));
4256 orig_type = entity->declaration.type;
4259 type_t *type = skip_typeref(orig_type);
4261 if (entity->kind == ENTITY_VARIABLE
4262 && entity->variable.initializer != NULL) {
4263 parser_error_multiple_definition(entity, HERE);
4267 declaration_t *const declaration = &entity->declaration;
4268 bool must_be_constant = false;
4269 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4270 entity->base.parent_scope == file_scope) {
4271 must_be_constant = true;
4274 if (is_type_function(type)) {
4275 source_position_t const *const pos = &entity->base.source_position;
4276 errorf(pos, "'%N' is initialized like a variable", entity);
4277 orig_type = type_error_type;
4280 parse_initializer_env_t env;
4281 env.type = orig_type;
4282 env.must_be_constant = must_be_constant;
4283 env.entity = entity;
4285 initializer_t *initializer = parse_initializer(&env);
4287 if (entity->kind == ENTITY_VARIABLE) {
4288 /* §6.7.5:22 array initializers for arrays with unknown size
4289 * determine the array type size */
4290 declaration->type = env.type;
4291 entity->variable.initializer = initializer;
4295 /* parse rest of a declaration without any declarator */
4296 static void parse_anonymous_declaration_rest(
4297 const declaration_specifiers_t *specifiers)
4300 anonymous_entity = NULL;
4302 source_position_t const *const pos = &specifiers->source_position;
4303 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4304 specifiers->thread_local) {
4305 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4308 type_t *type = specifiers->type;
4309 switch (type->kind) {
4310 case TYPE_COMPOUND_STRUCT:
4311 case TYPE_COMPOUND_UNION: {
4312 if (type->compound.compound->base.symbol == NULL) {
4313 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4322 warningf(WARN_OTHER, pos, "empty declaration");
4327 static void check_variable_type_complete(entity_t *ent)
4329 if (ent->kind != ENTITY_VARIABLE)
4332 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4333 * type for the object shall be complete [...] */
4334 declaration_t *decl = &ent->declaration;
4335 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4336 decl->storage_class == STORAGE_CLASS_STATIC)
4339 type_t *const type = skip_typeref(decl->type);
4340 if (!is_type_incomplete(type))
4343 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4344 * are given length one. */
4345 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4346 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4350 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4354 static void parse_declaration_rest(entity_t *ndeclaration,
4355 const declaration_specifiers_t *specifiers,
4356 parsed_declaration_func finished_declaration,
4357 declarator_flags_t flags)
4359 add_anchor_token(';');
4360 add_anchor_token(',');
4362 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4364 if (token.kind == '=') {
4365 parse_init_declarator_rest(entity);
4366 } else if (entity->kind == ENTITY_VARIABLE) {
4367 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4368 * [...] where the extern specifier is explicitly used. */
4369 declaration_t *decl = &entity->declaration;
4370 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4371 is_type_reference(skip_typeref(decl->type))) {
4372 source_position_t const *const pos = &entity->base.source_position;
4373 errorf(pos, "reference '%#N' must be initialized", entity);
4377 check_variable_type_complete(entity);
4382 add_anchor_token('=');
4383 ndeclaration = parse_declarator(specifiers, flags);
4384 rem_anchor_token('=');
4386 rem_anchor_token(',');
4387 rem_anchor_token(';');
4390 anonymous_entity = NULL;
4393 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4395 symbol_t *symbol = entity->base.symbol;
4399 assert(entity->base.namespc == NAMESPACE_NORMAL);
4400 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4401 if (previous_entity == NULL
4402 || previous_entity->base.parent_scope != current_scope) {
4403 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4408 if (is_definition) {
4409 errorf(HERE, "'%N' is initialised", entity);
4412 return record_entity(entity, false);
4415 static void parse_declaration(parsed_declaration_func finished_declaration,
4416 declarator_flags_t flags)
4418 add_anchor_token(';');
4419 declaration_specifiers_t specifiers;
4420 parse_declaration_specifiers(&specifiers);
4421 rem_anchor_token(';');
4423 if (token.kind == ';') {
4424 parse_anonymous_declaration_rest(&specifiers);
4426 entity_t *entity = parse_declarator(&specifiers, flags);
4427 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4432 static type_t *get_default_promoted_type(type_t *orig_type)
4434 type_t *result = orig_type;
4436 type_t *type = skip_typeref(orig_type);
4437 if (is_type_integer(type)) {
4438 result = promote_integer(type);
4439 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4440 result = type_double;
4446 static void parse_kr_declaration_list(entity_t *entity)
4448 if (entity->kind != ENTITY_FUNCTION)
4451 type_t *type = skip_typeref(entity->declaration.type);
4452 assert(is_type_function(type));
4453 if (!type->function.kr_style_parameters)
4456 add_anchor_token('{');
4458 PUSH_SCOPE(&entity->function.parameters);
4460 entity_t *parameter = entity->function.parameters.entities;
4461 for ( ; parameter != NULL; parameter = parameter->base.next) {
4462 assert(parameter->base.parent_scope == NULL);
4463 parameter->base.parent_scope = current_scope;
4464 environment_push(parameter);
4467 /* parse declaration list */
4469 switch (token.kind) {
4471 /* This covers symbols, which are no type, too, and results in
4472 * better error messages. The typical cases are misspelled type
4473 * names and missing includes. */
4475 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4485 /* update function type */
4486 type_t *new_type = duplicate_type(type);
4488 function_parameter_t *parameters = NULL;
4489 function_parameter_t **anchor = ¶meters;
4491 /* did we have an earlier prototype? */
4492 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4493 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4496 function_parameter_t *proto_parameter = NULL;
4497 if (proto_type != NULL) {
4498 type_t *proto_type_type = proto_type->declaration.type;
4499 proto_parameter = proto_type_type->function.parameters;
4500 /* If a K&R function definition has a variadic prototype earlier, then
4501 * make the function definition variadic, too. This should conform to
4502 * §6.7.5.3:15 and §6.9.1:8. */
4503 new_type->function.variadic = proto_type_type->function.variadic;
4505 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4507 new_type->function.unspecified_parameters = true;
4510 bool need_incompatible_warning = false;
4511 parameter = entity->function.parameters.entities;
4512 for (; parameter != NULL; parameter = parameter->base.next,
4514 proto_parameter == NULL ? NULL : proto_parameter->next) {
4515 if (parameter->kind != ENTITY_PARAMETER)
4518 type_t *parameter_type = parameter->declaration.type;
4519 if (parameter_type == NULL) {
4520 source_position_t const* const pos = ¶meter->base.source_position;
4522 errorf(pos, "no type specified for function '%N'", parameter);
4523 parameter_type = type_error_type;
4525 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4526 parameter_type = type_int;
4528 parameter->declaration.type = parameter_type;
4531 semantic_parameter_incomplete(parameter);
4533 /* we need the default promoted types for the function type */
4534 type_t *not_promoted = parameter_type;
4535 parameter_type = get_default_promoted_type(parameter_type);
4537 /* gcc special: if the type of the prototype matches the unpromoted
4538 * type don't promote */
4539 if (!strict_mode && proto_parameter != NULL) {
4540 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4541 type_t *promo_skip = skip_typeref(parameter_type);
4542 type_t *param_skip = skip_typeref(not_promoted);
4543 if (!types_compatible(proto_p_type, promo_skip)
4544 && types_compatible(proto_p_type, param_skip)) {
4546 need_incompatible_warning = true;
4547 parameter_type = not_promoted;
4550 function_parameter_t *const function_parameter
4551 = allocate_parameter(parameter_type);
4553 *anchor = function_parameter;
4554 anchor = &function_parameter->next;
4557 new_type->function.parameters = parameters;
4558 new_type = identify_new_type(new_type);
4560 if (need_incompatible_warning) {
4561 symbol_t const *const sym = entity->base.symbol;
4562 source_position_t const *const pos = &entity->base.source_position;
4563 source_position_t const *const ppos = &proto_type->base.source_position;
4564 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4566 entity->declaration.type = new_type;
4568 rem_anchor_token('{');
4571 static bool first_err = true;
4574 * When called with first_err set, prints the name of the current function,
4577 static void print_in_function(void)
4581 char const *const file = current_function->base.base.source_position.input_name;
4582 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4587 * Check if all labels are defined in the current function.
4588 * Check if all labels are used in the current function.
4590 static void check_labels(void)
4592 for (const goto_statement_t *goto_statement = goto_first;
4593 goto_statement != NULL;
4594 goto_statement = goto_statement->next) {
4595 label_t *label = goto_statement->label;
4596 if (label->base.source_position.input_name == NULL) {
4597 print_in_function();
4598 source_position_t const *const pos = &goto_statement->base.source_position;
4599 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4603 if (is_warn_on(WARN_UNUSED_LABEL)) {
4604 for (const label_statement_t *label_statement = label_first;
4605 label_statement != NULL;
4606 label_statement = label_statement->next) {
4607 label_t *label = label_statement->label;
4609 if (! label->used) {
4610 print_in_function();
4611 source_position_t const *const pos = &label_statement->base.source_position;
4612 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4618 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4620 entity_t const *const end = last != NULL ? last->base.next : NULL;
4621 for (; entity != end; entity = entity->base.next) {
4622 if (!is_declaration(entity))
4625 declaration_t *declaration = &entity->declaration;
4626 if (declaration->implicit)
4629 if (!declaration->used) {
4630 print_in_function();
4631 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4632 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4633 print_in_function();
4634 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4639 static void check_unused_variables(statement_t *const stmt, void *const env)
4643 switch (stmt->kind) {
4644 case STATEMENT_DECLARATION: {
4645 declaration_statement_t const *const decls = &stmt->declaration;
4646 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4651 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4660 * Check declarations of current_function for unused entities.
4662 static void check_declarations(void)
4664 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4665 const scope_t *scope = ¤t_function->parameters;
4667 /* do not issue unused warnings for main */
4668 if (!is_sym_main(current_function->base.base.symbol)) {
4669 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4672 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4673 walk_statements(current_function->statement, check_unused_variables,
4678 static int determine_truth(expression_t const* const cond)
4681 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4682 fold_constant_to_bool(cond) ? 1 :
4686 static void check_reachable(statement_t *);
4687 static bool reaches_end;
4689 static bool expression_returns(expression_t const *const expr)
4691 switch (expr->kind) {
4693 expression_t const *const func = expr->call.function;
4694 type_t const *const type = skip_typeref(func->base.type);
4695 if (type->kind == TYPE_POINTER) {
4696 type_t const *const points_to
4697 = skip_typeref(type->pointer.points_to);
4698 if (points_to->kind == TYPE_FUNCTION
4699 && points_to->function.modifiers & DM_NORETURN)
4703 if (!expression_returns(func))
4706 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4707 if (!expression_returns(arg->expression))
4714 case EXPR_REFERENCE:
4715 case EXPR_ENUM_CONSTANT:
4716 case EXPR_LITERAL_CASES:
4717 case EXPR_STRING_LITERAL:
4718 case EXPR_WIDE_STRING_LITERAL:
4719 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4720 case EXPR_LABEL_ADDRESS:
4721 case EXPR_CLASSIFY_TYPE:
4722 case EXPR_SIZEOF: // TODO handle obscure VLA case
4725 case EXPR_BUILTIN_CONSTANT_P:
4726 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4731 case EXPR_STATEMENT: {
4732 bool old_reaches_end = reaches_end;
4733 reaches_end = false;
4734 check_reachable(expr->statement.statement);
4735 bool returns = reaches_end;
4736 reaches_end = old_reaches_end;
4740 case EXPR_CONDITIONAL:
4741 // TODO handle constant expression
4743 if (!expression_returns(expr->conditional.condition))
4746 if (expr->conditional.true_expression != NULL
4747 && expression_returns(expr->conditional.true_expression))
4750 return expression_returns(expr->conditional.false_expression);
4753 return expression_returns(expr->select.compound);
4755 case EXPR_ARRAY_ACCESS:
4757 expression_returns(expr->array_access.array_ref) &&
4758 expression_returns(expr->array_access.index);
4761 return expression_returns(expr->va_starte.ap);
4764 return expression_returns(expr->va_arge.ap);
4767 return expression_returns(expr->va_copye.src);
4769 case EXPR_UNARY_CASES_MANDATORY:
4770 return expression_returns(expr->unary.value);
4772 case EXPR_UNARY_THROW:
4775 case EXPR_BINARY_CASES:
4776 // TODO handle constant lhs of && and ||
4778 expression_returns(expr->binary.left) &&
4779 expression_returns(expr->binary.right);
4782 panic("unhandled expression");
4785 static bool initializer_returns(initializer_t const *const init)
4787 switch (init->kind) {
4788 case INITIALIZER_VALUE:
4789 return expression_returns(init->value.value);
4791 case INITIALIZER_LIST: {
4792 initializer_t * const* i = init->list.initializers;
4793 initializer_t * const* const end = i + init->list.len;
4794 bool returns = true;
4795 for (; i != end; ++i) {
4796 if (!initializer_returns(*i))
4802 case INITIALIZER_STRING:
4803 case INITIALIZER_WIDE_STRING:
4804 case INITIALIZER_DESIGNATOR: // designators have no payload
4807 panic("unhandled initializer");
4810 static bool noreturn_candidate;
4812 static void check_reachable(statement_t *const stmt)
4814 if (stmt->base.reachable)
4816 if (stmt->kind != STATEMENT_DO_WHILE)
4817 stmt->base.reachable = true;
4819 statement_t *last = stmt;
4821 switch (stmt->kind) {
4822 case STATEMENT_ERROR:
4823 case STATEMENT_EMPTY:
4825 next = stmt->base.next;
4828 case STATEMENT_DECLARATION: {
4829 declaration_statement_t const *const decl = &stmt->declaration;
4830 entity_t const * ent = decl->declarations_begin;
4831 entity_t const *const last_decl = decl->declarations_end;
4833 for (;; ent = ent->base.next) {
4834 if (ent->kind == ENTITY_VARIABLE &&
4835 ent->variable.initializer != NULL &&
4836 !initializer_returns(ent->variable.initializer)) {
4839 if (ent == last_decl)
4843 next = stmt->base.next;
4847 case STATEMENT_COMPOUND:
4848 next = stmt->compound.statements;
4850 next = stmt->base.next;
4853 case STATEMENT_RETURN: {
4854 expression_t const *const val = stmt->returns.value;
4855 if (val == NULL || expression_returns(val))
4856 noreturn_candidate = false;
4860 case STATEMENT_IF: {
4861 if_statement_t const *const ifs = &stmt->ifs;
4862 expression_t const *const cond = ifs->condition;
4864 if (!expression_returns(cond))
4867 int const val = determine_truth(cond);
4870 check_reachable(ifs->true_statement);
4875 if (ifs->false_statement != NULL) {
4876 check_reachable(ifs->false_statement);
4880 next = stmt->base.next;
4884 case STATEMENT_SWITCH: {
4885 switch_statement_t const *const switchs = &stmt->switchs;
4886 expression_t const *const expr = switchs->expression;
4888 if (!expression_returns(expr))
4891 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4892 long const val = fold_constant_to_int(expr);
4893 case_label_statement_t * defaults = NULL;
4894 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4895 if (i->expression == NULL) {
4900 if (i->first_case <= val && val <= i->last_case) {
4901 check_reachable((statement_t*)i);
4906 if (defaults != NULL) {
4907 check_reachable((statement_t*)defaults);
4911 bool has_default = false;
4912 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4913 if (i->expression == NULL)
4916 check_reachable((statement_t*)i);
4923 next = stmt->base.next;
4927 case STATEMENT_EXPRESSION: {
4928 /* Check for noreturn function call */
4929 expression_t const *const expr = stmt->expression.expression;
4930 if (!expression_returns(expr))
4933 next = stmt->base.next;
4937 case STATEMENT_CONTINUE:
4938 for (statement_t *parent = stmt;;) {
4939 parent = parent->base.parent;
4940 if (parent == NULL) /* continue not within loop */
4944 switch (parent->kind) {
4945 case STATEMENT_WHILE: goto continue_while;
4946 case STATEMENT_DO_WHILE: goto continue_do_while;
4947 case STATEMENT_FOR: goto continue_for;
4953 case STATEMENT_BREAK:
4954 for (statement_t *parent = stmt;;) {
4955 parent = parent->base.parent;
4956 if (parent == NULL) /* break not within loop/switch */
4959 switch (parent->kind) {
4960 case STATEMENT_SWITCH:
4961 case STATEMENT_WHILE:
4962 case STATEMENT_DO_WHILE:
4965 next = parent->base.next;
4966 goto found_break_parent;
4974 case STATEMENT_COMPUTED_GOTO: {
4975 if (!expression_returns(stmt->computed_goto.expression))
4978 statement_t *parent = stmt->base.parent;
4979 if (parent == NULL) /* top level goto */
4985 case STATEMENT_GOTO:
4986 next = stmt->gotos.label->statement;
4987 if (next == NULL) /* missing label */
4991 case STATEMENT_LABEL:
4992 next = stmt->label.statement;
4995 case STATEMENT_CASE_LABEL:
4996 next = stmt->case_label.statement;
4999 case STATEMENT_WHILE: {
5000 while_statement_t const *const whiles = &stmt->whiles;
5001 expression_t const *const cond = whiles->condition;
5003 if (!expression_returns(cond))
5006 int const val = determine_truth(cond);
5009 check_reachable(whiles->body);
5014 next = stmt->base.next;
5018 case STATEMENT_DO_WHILE:
5019 next = stmt->do_while.body;
5022 case STATEMENT_FOR: {
5023 for_statement_t *const fors = &stmt->fors;
5025 if (fors->condition_reachable)
5027 fors->condition_reachable = true;
5029 expression_t const *const cond = fors->condition;
5034 } else if (expression_returns(cond)) {
5035 val = determine_truth(cond);
5041 check_reachable(fors->body);
5046 next = stmt->base.next;
5050 case STATEMENT_MS_TRY: {
5051 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5052 check_reachable(ms_try->try_statement);
5053 next = ms_try->final_statement;
5057 case STATEMENT_LEAVE: {
5058 statement_t *parent = stmt;
5060 parent = parent->base.parent;
5061 if (parent == NULL) /* __leave not within __try */
5064 if (parent->kind == STATEMENT_MS_TRY) {
5066 next = parent->ms_try.final_statement;
5074 panic("invalid statement kind");
5077 while (next == NULL) {
5078 next = last->base.parent;
5080 noreturn_candidate = false;
5082 type_t *const type = skip_typeref(current_function->base.type);
5083 assert(is_type_function(type));
5084 type_t *const ret = skip_typeref(type->function.return_type);
5085 if (!is_type_void(ret) &&
5086 is_type_valid(ret) &&
5087 !is_sym_main(current_function->base.base.symbol)) {
5088 source_position_t const *const pos = &stmt->base.source_position;
5089 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5094 switch (next->kind) {
5095 case STATEMENT_ERROR:
5096 case STATEMENT_EMPTY:
5097 case STATEMENT_DECLARATION:
5098 case STATEMENT_EXPRESSION:
5100 case STATEMENT_RETURN:
5101 case STATEMENT_CONTINUE:
5102 case STATEMENT_BREAK:
5103 case STATEMENT_COMPUTED_GOTO:
5104 case STATEMENT_GOTO:
5105 case STATEMENT_LEAVE:
5106 panic("invalid control flow in function");
5108 case STATEMENT_COMPOUND:
5109 if (next->compound.stmt_expr) {
5115 case STATEMENT_SWITCH:
5116 case STATEMENT_LABEL:
5117 case STATEMENT_CASE_LABEL:
5119 next = next->base.next;
5122 case STATEMENT_WHILE: {
5124 if (next->base.reachable)
5126 next->base.reachable = true;
5128 while_statement_t const *const whiles = &next->whiles;
5129 expression_t const *const cond = whiles->condition;
5131 if (!expression_returns(cond))
5134 int const val = determine_truth(cond);
5137 check_reachable(whiles->body);
5143 next = next->base.next;
5147 case STATEMENT_DO_WHILE: {
5149 if (next->base.reachable)
5151 next->base.reachable = true;
5153 do_while_statement_t const *const dw = &next->do_while;
5154 expression_t const *const cond = dw->condition;
5156 if (!expression_returns(cond))
5159 int const val = determine_truth(cond);
5162 check_reachable(dw->body);
5168 next = next->base.next;
5172 case STATEMENT_FOR: {
5174 for_statement_t *const fors = &next->fors;
5176 fors->step_reachable = true;
5178 if (fors->condition_reachable)
5180 fors->condition_reachable = true;
5182 expression_t const *const cond = fors->condition;
5187 } else if (expression_returns(cond)) {
5188 val = determine_truth(cond);
5194 check_reachable(fors->body);
5200 next = next->base.next;
5204 case STATEMENT_MS_TRY:
5206 next = next->ms_try.final_statement;
5211 check_reachable(next);
5214 static void check_unreachable(statement_t* const stmt, void *const env)
5218 switch (stmt->kind) {
5219 case STATEMENT_DO_WHILE:
5220 if (!stmt->base.reachable) {
5221 expression_t const *const cond = stmt->do_while.condition;
5222 if (determine_truth(cond) >= 0) {
5223 source_position_t const *const pos = &cond->base.source_position;
5224 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5229 case STATEMENT_FOR: {
5230 for_statement_t const* const fors = &stmt->fors;
5232 // if init and step are unreachable, cond is unreachable, too
5233 if (!stmt->base.reachable && !fors->step_reachable) {
5234 goto warn_unreachable;
5236 if (!stmt->base.reachable && fors->initialisation != NULL) {
5237 source_position_t const *const pos = &fors->initialisation->base.source_position;
5238 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5241 if (!fors->condition_reachable && fors->condition != NULL) {
5242 source_position_t const *const pos = &fors->condition->base.source_position;
5243 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5246 if (!fors->step_reachable && fors->step != NULL) {
5247 source_position_t const *const pos = &fors->step->base.source_position;
5248 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5254 case STATEMENT_COMPOUND:
5255 if (stmt->compound.statements != NULL)
5257 goto warn_unreachable;
5259 case STATEMENT_DECLARATION: {
5260 /* Only warn if there is at least one declarator with an initializer.
5261 * This typically occurs in switch statements. */
5262 declaration_statement_t const *const decl = &stmt->declaration;
5263 entity_t const * ent = decl->declarations_begin;
5264 entity_t const *const last = decl->declarations_end;
5266 for (;; ent = ent->base.next) {
5267 if (ent->kind == ENTITY_VARIABLE &&
5268 ent->variable.initializer != NULL) {
5269 goto warn_unreachable;
5279 if (!stmt->base.reachable) {
5280 source_position_t const *const pos = &stmt->base.source_position;
5281 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5287 static bool is_main(entity_t *entity)
5289 static symbol_t *sym_main = NULL;
5290 if (sym_main == NULL) {
5291 sym_main = symbol_table_insert("main");
5294 if (entity->base.symbol != sym_main)
5296 /* must be in outermost scope */
5297 if (entity->base.parent_scope != file_scope)
5303 static void parse_external_declaration(void)
5305 /* function-definitions and declarations both start with declaration
5307 add_anchor_token(';');
5308 declaration_specifiers_t specifiers;
5309 parse_declaration_specifiers(&specifiers);
5310 rem_anchor_token(';');
5312 /* must be a declaration */
5313 if (token.kind == ';') {
5314 parse_anonymous_declaration_rest(&specifiers);
5318 add_anchor_token(',');
5319 add_anchor_token('=');
5320 add_anchor_token(';');
5321 add_anchor_token('{');
5323 /* declarator is common to both function-definitions and declarations */
5324 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5326 rem_anchor_token('{');
5327 rem_anchor_token(';');
5328 rem_anchor_token('=');
5329 rem_anchor_token(',');
5331 /* must be a declaration */
5332 switch (token.kind) {
5336 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5341 /* must be a function definition */
5342 parse_kr_declaration_list(ndeclaration);
5344 if (token.kind != '{') {
5345 parse_error_expected("while parsing function definition", '{', NULL);
5346 eat_until_matching_token(';');
5350 assert(is_declaration(ndeclaration));
5351 type_t *const orig_type = ndeclaration->declaration.type;
5352 type_t * type = skip_typeref(orig_type);
5354 if (!is_type_function(type)) {
5355 if (is_type_valid(type)) {
5356 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5362 source_position_t const *const pos = &ndeclaration->base.source_position;
5363 if (is_typeref(orig_type)) {
5365 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5368 if (is_type_compound(skip_typeref(type->function.return_type))) {
5369 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5371 if (type->function.unspecified_parameters) {
5372 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5374 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5377 /* §6.7.5.3:14 a function definition with () means no
5378 * parameters (and not unspecified parameters) */
5379 if (type->function.unspecified_parameters &&
5380 type->function.parameters == NULL) {
5381 type_t *copy = duplicate_type(type);
5382 copy->function.unspecified_parameters = false;
5383 type = identify_new_type(copy);
5385 ndeclaration->declaration.type = type;
5388 entity_t *const entity = record_entity(ndeclaration, true);
5389 assert(entity->kind == ENTITY_FUNCTION);
5390 assert(ndeclaration->kind == ENTITY_FUNCTION);
5392 function_t *const function = &entity->function;
5393 if (ndeclaration != entity) {
5394 function->parameters = ndeclaration->function.parameters;
5396 assert(is_declaration(entity));
5397 type = skip_typeref(entity->declaration.type);
5399 PUSH_SCOPE(&function->parameters);
5401 entity_t *parameter = function->parameters.entities;
5402 for (; parameter != NULL; parameter = parameter->base.next) {
5403 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5404 parameter->base.parent_scope = current_scope;
5406 assert(parameter->base.parent_scope == NULL
5407 || parameter->base.parent_scope == current_scope);
5408 parameter->base.parent_scope = current_scope;
5409 if (parameter->base.symbol == NULL) {
5410 errorf(¶meter->base.source_position, "parameter name omitted");
5413 environment_push(parameter);
5416 if (function->statement != NULL) {
5417 parser_error_multiple_definition(entity, HERE);
5420 /* parse function body */
5421 int label_stack_top = label_top();
5422 function_t *old_current_function = current_function;
5423 entity_t *old_current_entity = current_entity;
5424 current_function = function;
5425 current_entity = entity;
5429 goto_anchor = &goto_first;
5431 label_anchor = &label_first;
5433 statement_t *const body = parse_compound_statement(false);
5434 function->statement = body;
5437 check_declarations();
5438 if (is_warn_on(WARN_RETURN_TYPE) ||
5439 is_warn_on(WARN_UNREACHABLE_CODE) ||
5440 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5441 noreturn_candidate = true;
5442 check_reachable(body);
5443 if (is_warn_on(WARN_UNREACHABLE_CODE))
5444 walk_statements(body, check_unreachable, NULL);
5445 if (noreturn_candidate &&
5446 !(function->base.modifiers & DM_NORETURN)) {
5447 source_position_t const *const pos = &body->base.source_position;
5448 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5452 if (is_main(entity) && enable_main_collect2_hack)
5453 prepare_main_collect2(entity);
5456 assert(current_function == function);
5457 assert(current_entity == entity);
5458 current_entity = old_current_entity;
5459 current_function = old_current_function;
5460 label_pop_to(label_stack_top);
5466 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5468 entity_t *iter = compound->members.entities;
5469 for (; iter != NULL; iter = iter->base.next) {
5470 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5473 if (iter->base.symbol == symbol) {
5475 } else if (iter->base.symbol == NULL) {
5476 /* search in anonymous structs and unions */
5477 type_t *type = skip_typeref(iter->declaration.type);
5478 if (is_type_compound(type)) {
5479 if (find_compound_entry(type->compound.compound, symbol)
5490 static void check_deprecated(const source_position_t *source_position,
5491 const entity_t *entity)
5493 if (!is_declaration(entity))
5495 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5498 source_position_t const *const epos = &entity->base.source_position;
5499 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5501 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5503 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5508 static expression_t *create_select(const source_position_t *pos,
5510 type_qualifiers_t qualifiers,
5513 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5515 check_deprecated(pos, entry);
5517 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5518 select->select.compound = addr;
5519 select->select.compound_entry = entry;
5521 type_t *entry_type = entry->declaration.type;
5522 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5524 /* bitfields need special treatment */
5525 if (entry->compound_member.bitfield) {
5526 unsigned bit_size = entry->compound_member.bit_size;
5527 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5528 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5529 res_type = type_int;
5533 /* we always do the auto-type conversions; the & and sizeof parser contains
5534 * code to revert this! */
5535 select->base.type = automatic_type_conversion(res_type);
5542 * Find entry with symbol in compound. Search anonymous structs and unions and
5543 * creates implicit select expressions for them.
5544 * Returns the adress for the innermost compound.
5546 static expression_t *find_create_select(const source_position_t *pos,
5548 type_qualifiers_t qualifiers,
5549 compound_t *compound, symbol_t *symbol)
5551 entity_t *iter = compound->members.entities;
5552 for (; iter != NULL; iter = iter->base.next) {
5553 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5556 symbol_t *iter_symbol = iter->base.symbol;
5557 if (iter_symbol == NULL) {
5558 type_t *type = iter->declaration.type;
5559 if (type->kind != TYPE_COMPOUND_STRUCT
5560 && type->kind != TYPE_COMPOUND_UNION)
5563 compound_t *sub_compound = type->compound.compound;
5565 if (find_compound_entry(sub_compound, symbol) == NULL)
5568 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5569 sub_addr->base.source_position = *pos;
5570 sub_addr->base.implicit = true;
5571 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5575 if (iter_symbol == symbol) {
5576 return create_select(pos, addr, qualifiers, iter);
5583 static void parse_bitfield_member(entity_t *entity)
5587 expression_t *size = parse_constant_expression();
5590 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5591 type_t *type = entity->declaration.type;
5592 if (!is_type_integer(skip_typeref(type))) {
5593 errorf(HERE, "bitfield base type '%T' is not an integer type",
5597 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5598 /* error already reported by parse_constant_expression */
5599 size_long = get_type_size(type) * 8;
5601 size_long = fold_constant_to_int(size);
5603 const symbol_t *symbol = entity->base.symbol;
5604 const symbol_t *user_symbol
5605 = symbol == NULL ? sym_anonymous : symbol;
5606 unsigned bit_size = get_type_size(type) * 8;
5607 if (size_long < 0) {
5608 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5609 } else if (size_long == 0 && symbol != NULL) {
5610 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5611 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5612 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5615 /* hope that people don't invent crazy types with more bits
5616 * than our struct can hold */
5618 (1 << sizeof(entity->compound_member.bit_size)*8));
5622 entity->compound_member.bitfield = true;
5623 entity->compound_member.bit_size = (unsigned char)size_long;
5626 static void parse_compound_declarators(compound_t *compound,
5627 const declaration_specifiers_t *specifiers)
5629 add_anchor_token(';');
5630 add_anchor_token(',');
5634 if (token.kind == ':') {
5635 /* anonymous bitfield */
5636 type_t *type = specifiers->type;
5637 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5638 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5639 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5640 entity->declaration.type = type;
5642 parse_bitfield_member(entity);
5644 attribute_t *attributes = parse_attributes(NULL);
5645 attribute_t **anchor = &attributes;
5646 while (*anchor != NULL)
5647 anchor = &(*anchor)->next;
5648 *anchor = specifiers->attributes;
5649 if (attributes != NULL) {
5650 handle_entity_attributes(attributes, entity);
5652 entity->declaration.attributes = attributes;
5654 append_entity(&compound->members, entity);
5656 entity = parse_declarator(specifiers,
5657 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5658 source_position_t const *const pos = &entity->base.source_position;
5659 if (entity->kind == ENTITY_TYPEDEF) {
5660 errorf(pos, "typedef not allowed as compound member");
5662 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5664 /* make sure we don't define a symbol multiple times */
5665 symbol_t *symbol = entity->base.symbol;
5666 if (symbol != NULL) {
5667 entity_t *prev = find_compound_entry(compound, symbol);
5669 source_position_t const *const ppos = &prev->base.source_position;
5670 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5674 if (token.kind == ':') {
5675 parse_bitfield_member(entity);
5677 attribute_t *attributes = parse_attributes(NULL);
5678 handle_entity_attributes(attributes, entity);
5680 type_t *orig_type = entity->declaration.type;
5681 type_t *type = skip_typeref(orig_type);
5682 if (is_type_function(type)) {
5683 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5684 } else if (is_type_incomplete(type)) {
5685 /* §6.7.2.1:16 flexible array member */
5686 if (!is_type_array(type) ||
5687 token.kind != ';' ||
5688 look_ahead(1)->kind != '}') {
5689 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5690 } else if (compound->members.entities == NULL) {
5691 errorf(pos, "flexible array member in otherwise empty struct");
5696 append_entity(&compound->members, entity);
5699 } while (next_if(','));
5700 rem_anchor_token(',');
5701 rem_anchor_token(';');
5704 anonymous_entity = NULL;
5707 static void parse_compound_type_entries(compound_t *compound)
5710 add_anchor_token('}');
5713 switch (token.kind) {
5715 case T___extension__:
5716 case T_IDENTIFIER: {
5718 declaration_specifiers_t specifiers;
5719 parse_declaration_specifiers(&specifiers);
5720 parse_compound_declarators(compound, &specifiers);
5726 rem_anchor_token('}');
5729 compound->complete = true;
5735 static type_t *parse_typename(void)
5737 declaration_specifiers_t specifiers;
5738 parse_declaration_specifiers(&specifiers);
5739 if (specifiers.storage_class != STORAGE_CLASS_NONE
5740 || specifiers.thread_local) {
5741 /* TODO: improve error message, user does probably not know what a
5742 * storage class is...
5744 errorf(&specifiers.source_position, "typename must not have a storage class");
5747 type_t *result = parse_abstract_declarator(specifiers.type);
5755 typedef expression_t* (*parse_expression_function)(void);
5756 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5758 typedef struct expression_parser_function_t expression_parser_function_t;
5759 struct expression_parser_function_t {
5760 parse_expression_function parser;
5761 precedence_t infix_precedence;
5762 parse_expression_infix_function infix_parser;
5765 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5768 * Prints an error message if an expression was expected but not read
5770 static expression_t *expected_expression_error(void)
5772 /* skip the error message if the error token was read */
5773 if (token.kind != T_ERROR) {
5774 errorf(HERE, "expected expression, got token %K", &token);
5778 return create_error_expression();
5781 static type_t *get_string_type(void)
5783 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5786 static type_t *get_wide_string_type(void)
5788 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5792 * Parse a string constant.
5794 static expression_t *parse_string_literal(void)
5796 source_position_t begin = token.base.source_position;
5797 string_t res = token.string.string;
5798 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5801 while (token.kind == T_STRING_LITERAL
5802 || token.kind == T_WIDE_STRING_LITERAL) {
5803 warn_string_concat(&token.base.source_position);
5804 res = concat_strings(&res, &token.string.string);
5806 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5809 expression_t *literal;
5811 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5812 literal->base.type = get_wide_string_type();
5814 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5815 literal->base.type = get_string_type();
5817 literal->base.source_position = begin;
5818 literal->literal.value = res;
5824 * Parse a boolean constant.
5826 static expression_t *parse_boolean_literal(bool value)
5828 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5829 literal->base.type = type_bool;
5830 literal->literal.value.begin = value ? "true" : "false";
5831 literal->literal.value.size = value ? 4 : 5;
5837 static void warn_traditional_suffix(void)
5839 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5840 &token.number.suffix);
5843 static void check_integer_suffix(void)
5845 const string_t *suffix = &token.number.suffix;
5846 if (suffix->size == 0)
5849 bool not_traditional = false;
5850 const char *c = suffix->begin;
5851 if (*c == 'l' || *c == 'L') {
5854 not_traditional = true;
5856 if (*c == 'u' || *c == 'U') {
5859 } else if (*c == 'u' || *c == 'U') {
5860 not_traditional = true;
5863 } else if (*c == 'u' || *c == 'U') {
5864 not_traditional = true;
5866 if (*c == 'l' || *c == 'L') {
5874 errorf(&token.base.source_position,
5875 "invalid suffix '%S' on integer constant", suffix);
5876 } else if (not_traditional) {
5877 warn_traditional_suffix();
5881 static type_t *check_floatingpoint_suffix(void)
5883 const string_t *suffix = &token.number.suffix;
5884 type_t *type = type_double;
5885 if (suffix->size == 0)
5888 bool not_traditional = false;
5889 const char *c = suffix->begin;
5890 if (*c == 'f' || *c == 'F') {
5893 } else if (*c == 'l' || *c == 'L') {
5895 type = type_long_double;
5898 errorf(&token.base.source_position,
5899 "invalid suffix '%S' on floatingpoint constant", suffix);
5900 } else if (not_traditional) {
5901 warn_traditional_suffix();
5908 * Parse an integer constant.
5910 static expression_t *parse_number_literal(void)
5912 expression_kind_t kind;
5915 switch (token.kind) {
5917 kind = EXPR_LITERAL_INTEGER;
5918 check_integer_suffix();
5921 case T_INTEGER_OCTAL:
5922 kind = EXPR_LITERAL_INTEGER_OCTAL;
5923 check_integer_suffix();
5926 case T_INTEGER_HEXADECIMAL:
5927 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5928 check_integer_suffix();
5931 case T_FLOATINGPOINT:
5932 kind = EXPR_LITERAL_FLOATINGPOINT;
5933 type = check_floatingpoint_suffix();
5935 case T_FLOATINGPOINT_HEXADECIMAL:
5936 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5937 type = check_floatingpoint_suffix();
5940 panic("unexpected token type in parse_number_literal");
5943 expression_t *literal = allocate_expression_zero(kind);
5944 literal->base.type = type;
5945 literal->literal.value = token.number.number;
5946 literal->literal.suffix = token.number.suffix;
5949 /* integer type depends on the size of the number and the size
5950 * representable by the types. The backend/codegeneration has to determine
5953 determine_literal_type(&literal->literal);
5958 * Parse a character constant.
5960 static expression_t *parse_character_constant(void)
5962 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5963 literal->base.type = c_mode & _CXX ? type_char : type_int;
5964 literal->literal.value = token.string.string;
5966 size_t len = literal->literal.value.size;
5968 if (!GNU_MODE && !(c_mode & _C99)) {
5969 errorf(HERE, "more than 1 character in character constant");
5971 literal->base.type = type_int;
5972 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5981 * Parse a wide character constant.
5983 static expression_t *parse_wide_character_constant(void)
5985 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5986 literal->base.type = type_int;
5987 literal->literal.value = token.string.string;
5989 size_t len = wstrlen(&literal->literal.value);
5991 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5998 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
6000 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6001 ntype->function.return_type = type_int;
6002 ntype->function.unspecified_parameters = true;
6003 ntype->function.linkage = LINKAGE_C;
6004 type_t *type = identify_new_type(ntype);
6006 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
6007 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6008 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6009 entity->declaration.type = type;
6010 entity->declaration.implicit = true;
6012 if (current_scope != NULL)
6013 record_entity(entity, false);
6019 * Performs automatic type cast as described in §6.3.2.1.
6021 * @param orig_type the original type
6023 static type_t *automatic_type_conversion(type_t *orig_type)
6025 type_t *type = skip_typeref(orig_type);
6026 if (is_type_array(type)) {
6027 array_type_t *array_type = &type->array;
6028 type_t *element_type = array_type->element_type;
6029 unsigned qualifiers = array_type->base.qualifiers;
6031 return make_pointer_type(element_type, qualifiers);
6034 if (is_type_function(type)) {
6035 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6042 * reverts the automatic casts of array to pointer types and function
6043 * to function-pointer types as defined §6.3.2.1
6045 type_t *revert_automatic_type_conversion(const expression_t *expression)
6047 switch (expression->kind) {
6048 case EXPR_REFERENCE: {
6049 entity_t *entity = expression->reference.entity;
6050 if (is_declaration(entity)) {
6051 return entity->declaration.type;
6052 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6053 return entity->enum_value.enum_type;
6055 panic("no declaration or enum in reference");
6060 entity_t *entity = expression->select.compound_entry;
6061 assert(is_declaration(entity));
6062 type_t *type = entity->declaration.type;
6063 return get_qualified_type(type, expression->base.type->base.qualifiers);
6066 case EXPR_UNARY_DEREFERENCE: {
6067 const expression_t *const value = expression->unary.value;
6068 type_t *const type = skip_typeref(value->base.type);
6069 if (!is_type_pointer(type))
6070 return type_error_type;
6071 return type->pointer.points_to;
6074 case EXPR_ARRAY_ACCESS: {
6075 const expression_t *array_ref = expression->array_access.array_ref;
6076 type_t *type_left = skip_typeref(array_ref->base.type);
6077 if (!is_type_pointer(type_left))
6078 return type_error_type;
6079 return type_left->pointer.points_to;
6082 case EXPR_STRING_LITERAL: {
6083 size_t size = expression->string_literal.value.size;
6084 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6087 case EXPR_WIDE_STRING_LITERAL: {
6088 size_t size = wstrlen(&expression->string_literal.value);
6089 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6092 case EXPR_COMPOUND_LITERAL:
6093 return expression->compound_literal.type;
6098 return expression->base.type;
6102 * Find an entity matching a symbol in a scope.
6103 * Uses current scope if scope is NULL
6105 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6106 namespace_tag_t namespc)
6108 if (scope == NULL) {
6109 return get_entity(symbol, namespc);
6112 /* we should optimize here, if scope grows above a certain size we should
6113 construct a hashmap here... */
6114 entity_t *entity = scope->entities;
6115 for ( ; entity != NULL; entity = entity->base.next) {
6116 if (entity->base.symbol == symbol
6117 && (namespace_tag_t)entity->base.namespc == namespc)
6124 static entity_t *parse_qualified_identifier(void)
6126 /* namespace containing the symbol */
6128 source_position_t pos;
6129 const scope_t *lookup_scope = NULL;
6131 if (next_if(T_COLONCOLON))
6132 lookup_scope = &unit->scope;
6136 symbol = expect_identifier("while parsing identifier", &pos);
6138 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6141 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6143 if (!next_if(T_COLONCOLON))
6146 switch (entity->kind) {
6147 case ENTITY_NAMESPACE:
6148 lookup_scope = &entity->namespacee.members;
6153 lookup_scope = &entity->compound.members;
6156 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6157 symbol, get_entity_kind_name(entity->kind));
6159 /* skip further qualifications */
6160 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6162 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6166 if (entity == NULL) {
6167 if (!strict_mode && token.kind == '(') {
6168 /* an implicitly declared function */
6169 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6170 "implicit declaration of function '%Y'", symbol);
6171 entity = create_implicit_function(symbol, &pos);
6173 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6174 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6181 static expression_t *parse_reference(void)
6183 source_position_t const pos = token.base.source_position;
6184 entity_t *const entity = parse_qualified_identifier();
6187 if (is_declaration(entity)) {
6188 orig_type = entity->declaration.type;
6189 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6190 orig_type = entity->enum_value.enum_type;
6192 panic("expected declaration or enum value in reference");
6195 /* we always do the auto-type conversions; the & and sizeof parser contains
6196 * code to revert this! */
6197 type_t *type = automatic_type_conversion(orig_type);
6199 expression_kind_t kind = EXPR_REFERENCE;
6200 if (entity->kind == ENTITY_ENUM_VALUE)
6201 kind = EXPR_ENUM_CONSTANT;
6203 expression_t *expression = allocate_expression_zero(kind);
6204 expression->base.source_position = pos;
6205 expression->base.type = type;
6206 expression->reference.entity = entity;
6208 /* this declaration is used */
6209 if (is_declaration(entity)) {
6210 entity->declaration.used = true;
6213 if (entity->base.parent_scope != file_scope
6214 && (current_function != NULL
6215 && entity->base.parent_scope->depth < current_function->parameters.depth)
6216 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6217 if (entity->kind == ENTITY_VARIABLE) {
6218 /* access of a variable from an outer function */
6219 entity->variable.address_taken = true;
6220 } else if (entity->kind == ENTITY_PARAMETER) {
6221 entity->parameter.address_taken = true;
6223 current_function->need_closure = true;
6226 check_deprecated(&pos, entity);
6231 static bool semantic_cast(expression_t *cast)
6233 expression_t *expression = cast->unary.value;
6234 type_t *orig_dest_type = cast->base.type;
6235 type_t *orig_type_right = expression->base.type;
6236 type_t const *dst_type = skip_typeref(orig_dest_type);
6237 type_t const *src_type = skip_typeref(orig_type_right);
6238 source_position_t const *pos = &cast->base.source_position;
6240 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6241 if (is_type_void(dst_type))
6244 /* only integer and pointer can be casted to pointer */
6245 if (is_type_pointer(dst_type) &&
6246 !is_type_pointer(src_type) &&
6247 !is_type_integer(src_type) &&
6248 is_type_valid(src_type)) {
6249 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6253 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6254 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6258 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6259 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6263 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6264 type_t *src = skip_typeref(src_type->pointer.points_to);
6265 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6266 unsigned missing_qualifiers =
6267 src->base.qualifiers & ~dst->base.qualifiers;
6268 if (missing_qualifiers != 0) {
6269 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6275 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6277 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6278 expression->base.source_position = *pos;
6280 parse_initializer_env_t env;
6283 env.must_be_constant = false;
6284 initializer_t *initializer = parse_initializer(&env);
6287 expression->compound_literal.initializer = initializer;
6288 expression->compound_literal.type = type;
6289 expression->base.type = automatic_type_conversion(type);
6295 * Parse a cast expression.
6297 static expression_t *parse_cast(void)
6299 source_position_t const pos = *HERE;
6302 add_anchor_token(')');
6304 type_t *type = parse_typename();
6306 rem_anchor_token(')');
6309 if (token.kind == '{') {
6310 return parse_compound_literal(&pos, type);
6313 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6314 cast->base.source_position = pos;
6316 expression_t *value = parse_subexpression(PREC_CAST);
6317 cast->base.type = type;
6318 cast->unary.value = value;
6320 if (! semantic_cast(cast)) {
6321 /* TODO: record the error in the AST. else it is impossible to detect it */
6328 * Parse a statement expression.
6330 static expression_t *parse_statement_expression(void)
6332 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6335 add_anchor_token(')');
6337 statement_t *statement = parse_compound_statement(true);
6338 statement->compound.stmt_expr = true;
6339 expression->statement.statement = statement;
6341 /* find last statement and use its type */
6342 type_t *type = type_void;
6343 const statement_t *stmt = statement->compound.statements;
6345 while (stmt->base.next != NULL)
6346 stmt = stmt->base.next;
6348 if (stmt->kind == STATEMENT_EXPRESSION) {
6349 type = stmt->expression.expression->base.type;
6352 source_position_t const *const pos = &expression->base.source_position;
6353 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6355 expression->base.type = type;
6357 rem_anchor_token(')');
6363 * Parse a parenthesized expression.
6365 static expression_t *parse_parenthesized_expression(void)
6367 token_t const* const la1 = look_ahead(1);
6368 switch (la1->kind) {
6370 /* gcc extension: a statement expression */
6371 return parse_statement_expression();
6374 if (is_typedef_symbol(la1->identifier.symbol)) {
6376 return parse_cast();
6381 add_anchor_token(')');
6382 expression_t *result = parse_expression();
6383 result->base.parenthesized = true;
6384 rem_anchor_token(')');
6390 static expression_t *parse_function_keyword(void)
6394 if (current_function == NULL) {
6395 errorf(HERE, "'__func__' used outside of a function");
6398 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6399 expression->base.type = type_char_ptr;
6400 expression->funcname.kind = FUNCNAME_FUNCTION;
6407 static expression_t *parse_pretty_function_keyword(void)
6409 if (current_function == NULL) {
6410 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6413 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6414 expression->base.type = type_char_ptr;
6415 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6417 eat(T___PRETTY_FUNCTION__);
6422 static expression_t *parse_funcsig_keyword(void)
6424 if (current_function == NULL) {
6425 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6428 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6429 expression->base.type = type_char_ptr;
6430 expression->funcname.kind = FUNCNAME_FUNCSIG;
6437 static expression_t *parse_funcdname_keyword(void)
6439 if (current_function == NULL) {
6440 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6443 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6444 expression->base.type = type_char_ptr;
6445 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6447 eat(T___FUNCDNAME__);
6452 static designator_t *parse_designator(void)
6454 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6455 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6456 if (!result->symbol)
6459 designator_t *last_designator = result;
6462 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6463 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6464 if (!designator->symbol)
6467 last_designator->next = designator;
6468 last_designator = designator;
6472 add_anchor_token(']');
6473 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6474 designator->source_position = *HERE;
6475 designator->array_index = parse_expression();
6476 rem_anchor_token(']');
6478 if (designator->array_index == NULL) {
6482 last_designator->next = designator;
6483 last_designator = designator;
6493 * Parse the __builtin_offsetof() expression.
6495 static expression_t *parse_offsetof(void)
6497 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6498 expression->base.type = type_size_t;
6500 eat(T___builtin_offsetof);
6503 add_anchor_token(')');
6504 add_anchor_token(',');
6505 type_t *type = parse_typename();
6506 rem_anchor_token(',');
6508 designator_t *designator = parse_designator();
6509 rem_anchor_token(')');
6512 expression->offsetofe.type = type;
6513 expression->offsetofe.designator = designator;
6516 memset(&path, 0, sizeof(path));
6517 path.top_type = type;
6518 path.path = NEW_ARR_F(type_path_entry_t, 0);
6520 descend_into_subtype(&path);
6522 if (!walk_designator(&path, designator, true)) {
6523 return create_error_expression();
6526 DEL_ARR_F(path.path);
6532 * Parses a _builtin_va_start() expression.
6534 static expression_t *parse_va_start(void)
6536 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6538 eat(T___builtin_va_start);
6541 add_anchor_token(')');
6542 add_anchor_token(',');
6543 expression->va_starte.ap = parse_assignment_expression();
6544 rem_anchor_token(',');
6546 expression_t *const expr = parse_assignment_expression();
6547 if (expr->kind == EXPR_REFERENCE) {
6548 entity_t *const entity = expr->reference.entity;
6549 if (!current_function->base.type->function.variadic) {
6550 errorf(&expr->base.source_position,
6551 "'va_start' used in non-variadic function");
6552 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6553 entity->base.next != NULL ||
6554 entity->kind != ENTITY_PARAMETER) {
6555 errorf(&expr->base.source_position,
6556 "second argument of 'va_start' must be last parameter of the current function");
6558 expression->va_starte.parameter = &entity->variable;
6561 expression = create_error_expression();
6563 rem_anchor_token(')');
6569 * Parses a __builtin_va_arg() expression.
6571 static expression_t *parse_va_arg(void)
6573 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6575 eat(T___builtin_va_arg);
6578 add_anchor_token(')');
6579 add_anchor_token(',');
6581 ap.expression = parse_assignment_expression();
6582 expression->va_arge.ap = ap.expression;
6583 check_call_argument(type_valist, &ap, 1);
6585 rem_anchor_token(',');
6587 expression->base.type = parse_typename();
6588 rem_anchor_token(')');
6595 * Parses a __builtin_va_copy() expression.
6597 static expression_t *parse_va_copy(void)
6599 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6601 eat(T___builtin_va_copy);
6604 add_anchor_token(')');
6605 add_anchor_token(',');
6606 expression_t *dst = parse_assignment_expression();
6607 assign_error_t error = semantic_assign(type_valist, dst);
6608 report_assign_error(error, type_valist, dst, "call argument 1",
6609 &dst->base.source_position);
6610 expression->va_copye.dst = dst;
6612 rem_anchor_token(',');
6615 call_argument_t src;
6616 src.expression = parse_assignment_expression();
6617 check_call_argument(type_valist, &src, 2);
6618 expression->va_copye.src = src.expression;
6619 rem_anchor_token(')');
6626 * Parses a __builtin_constant_p() expression.
6628 static expression_t *parse_builtin_constant(void)
6630 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6632 eat(T___builtin_constant_p);
6635 add_anchor_token(')');
6636 expression->builtin_constant.value = parse_assignment_expression();
6637 rem_anchor_token(')');
6639 expression->base.type = type_int;
6645 * Parses a __builtin_types_compatible_p() expression.
6647 static expression_t *parse_builtin_types_compatible(void)
6649 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6651 eat(T___builtin_types_compatible_p);
6654 add_anchor_token(')');
6655 add_anchor_token(',');
6656 expression->builtin_types_compatible.left = parse_typename();
6657 rem_anchor_token(',');
6659 expression->builtin_types_compatible.right = parse_typename();
6660 rem_anchor_token(')');
6662 expression->base.type = type_int;
6668 * Parses a __builtin_is_*() compare expression.
6670 static expression_t *parse_compare_builtin(void)
6672 expression_t *expression;
6674 switch (token.kind) {
6675 case T___builtin_isgreater:
6676 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6678 case T___builtin_isgreaterequal:
6679 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6681 case T___builtin_isless:
6682 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6684 case T___builtin_islessequal:
6685 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6687 case T___builtin_islessgreater:
6688 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6690 case T___builtin_isunordered:
6691 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6694 internal_errorf(HERE, "invalid compare builtin found");
6696 expression->base.source_position = *HERE;
6700 add_anchor_token(')');
6701 add_anchor_token(',');
6702 expression->binary.left = parse_assignment_expression();
6703 rem_anchor_token(',');
6705 expression->binary.right = parse_assignment_expression();
6706 rem_anchor_token(')');
6709 type_t *const orig_type_left = expression->binary.left->base.type;
6710 type_t *const orig_type_right = expression->binary.right->base.type;
6712 type_t *const type_left = skip_typeref(orig_type_left);
6713 type_t *const type_right = skip_typeref(orig_type_right);
6714 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6715 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6716 type_error_incompatible("invalid operands in comparison",
6717 &expression->base.source_position, orig_type_left, orig_type_right);
6720 semantic_comparison(&expression->binary);
6727 * Parses a MS assume() expression.
6729 static expression_t *parse_assume(void)
6731 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6736 add_anchor_token(')');
6737 expression->unary.value = parse_assignment_expression();
6738 rem_anchor_token(')');
6741 expression->base.type = type_void;
6746 * Return the label for the current symbol or create a new one.
6748 static label_t *get_label(void)
6750 assert(token.kind == T_IDENTIFIER);
6751 assert(current_function != NULL);
6753 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6754 /* If we find a local label, we already created the declaration. */
6755 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6756 if (label->base.parent_scope != current_scope) {
6757 assert(label->base.parent_scope->depth < current_scope->depth);
6758 current_function->goto_to_outer = true;
6760 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6761 /* There is no matching label in the same function, so create a new one. */
6762 source_position_t const nowhere = { NULL, 0, 0, false };
6763 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6768 return &label->label;
6772 * Parses a GNU && label address expression.
6774 static expression_t *parse_label_address(void)
6776 source_position_t source_position = token.base.source_position;
6778 if (token.kind != T_IDENTIFIER) {
6779 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6780 return create_error_expression();
6783 label_t *const label = get_label();
6785 label->address_taken = true;
6787 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6788 expression->base.source_position = source_position;
6790 /* label address is treated as a void pointer */
6791 expression->base.type = type_void_ptr;
6792 expression->label_address.label = label;
6797 * Parse a microsoft __noop expression.
6799 static expression_t *parse_noop_expression(void)
6801 /* the result is a (int)0 */
6802 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6803 literal->base.type = type_int;
6804 literal->literal.value.begin = "__noop";
6805 literal->literal.value.size = 6;
6809 if (token.kind == '(') {
6810 /* parse arguments */
6812 add_anchor_token(')');
6813 add_anchor_token(',');
6815 if (token.kind != ')') do {
6816 (void)parse_assignment_expression();
6817 } while (next_if(','));
6819 rem_anchor_token(',');
6820 rem_anchor_token(')');
6828 * Parses a primary expression.
6830 static expression_t *parse_primary_expression(void)
6832 switch (token.kind) {
6833 case T_false: return parse_boolean_literal(false);
6834 case T_true: return parse_boolean_literal(true);
6836 case T_INTEGER_OCTAL:
6837 case T_INTEGER_HEXADECIMAL:
6838 case T_FLOATINGPOINT:
6839 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6840 case T_CHARACTER_CONSTANT: return parse_character_constant();
6841 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6842 case T_STRING_LITERAL:
6843 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6844 case T___FUNCTION__:
6845 case T___func__: return parse_function_keyword();
6846 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6847 case T___FUNCSIG__: return parse_funcsig_keyword();
6848 case T___FUNCDNAME__: return parse_funcdname_keyword();
6849 case T___builtin_offsetof: return parse_offsetof();
6850 case T___builtin_va_start: return parse_va_start();
6851 case T___builtin_va_arg: return parse_va_arg();
6852 case T___builtin_va_copy: return parse_va_copy();
6853 case T___builtin_isgreater:
6854 case T___builtin_isgreaterequal:
6855 case T___builtin_isless:
6856 case T___builtin_islessequal:
6857 case T___builtin_islessgreater:
6858 case T___builtin_isunordered: return parse_compare_builtin();
6859 case T___builtin_constant_p: return parse_builtin_constant();
6860 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6861 case T__assume: return parse_assume();
6864 return parse_label_address();
6867 case '(': return parse_parenthesized_expression();
6868 case T___noop: return parse_noop_expression();
6870 /* Gracefully handle type names while parsing expressions. */
6872 return parse_reference();
6874 if (!is_typedef_symbol(token.identifier.symbol)) {
6875 return parse_reference();
6879 source_position_t const pos = *HERE;
6880 declaration_specifiers_t specifiers;
6881 parse_declaration_specifiers(&specifiers);
6882 type_t const *const type = parse_abstract_declarator(specifiers.type);
6883 errorf(&pos, "encountered type '%T' while parsing expression", type);
6884 return create_error_expression();
6888 errorf(HERE, "unexpected token %K, expected an expression", &token);
6890 return create_error_expression();
6893 static expression_t *parse_array_expression(expression_t *left)
6895 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6896 array_access_expression_t *const arr = &expr->array_access;
6899 add_anchor_token(']');
6901 expression_t *const inside = parse_expression();
6903 type_t *const orig_type_left = left->base.type;
6904 type_t *const orig_type_inside = inside->base.type;
6906 type_t *const type_left = skip_typeref(orig_type_left);
6907 type_t *const type_inside = skip_typeref(orig_type_inside);
6913 if (is_type_pointer(type_left)) {
6916 idx_type = type_inside;
6917 res_type = type_left->pointer.points_to;
6919 } else if (is_type_pointer(type_inside)) {
6920 arr->flipped = true;
6923 idx_type = type_left;
6924 res_type = type_inside->pointer.points_to;
6926 res_type = automatic_type_conversion(res_type);
6927 if (!is_type_integer(idx_type)) {
6928 errorf(&idx->base.source_position, "array subscript must have integer type");
6929 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6930 source_position_t const *const pos = &idx->base.source_position;
6931 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6934 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6935 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6937 res_type = type_error_type;
6942 arr->array_ref = ref;
6944 arr->base.type = res_type;
6946 rem_anchor_token(']');
6951 static bool is_bitfield(const expression_t *expression)
6953 return expression->kind == EXPR_SELECT
6954 && expression->select.compound_entry->compound_member.bitfield;
6957 static expression_t *parse_typeprop(expression_kind_t const kind)
6959 expression_t *tp_expression = allocate_expression_zero(kind);
6960 tp_expression->base.type = type_size_t;
6962 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6965 expression_t *expression;
6966 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6967 source_position_t const pos = *HERE;
6969 add_anchor_token(')');
6970 orig_type = parse_typename();
6971 rem_anchor_token(')');
6974 if (token.kind == '{') {
6975 /* It was not sizeof(type) after all. It is sizeof of an expression
6976 * starting with a compound literal */
6977 expression = parse_compound_literal(&pos, orig_type);
6978 goto typeprop_expression;
6981 expression = parse_subexpression(PREC_UNARY);
6983 typeprop_expression:
6984 if (is_bitfield(expression)) {
6985 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6986 errorf(&tp_expression->base.source_position,
6987 "operand of %s expression must not be a bitfield", what);
6990 tp_expression->typeprop.tp_expression = expression;
6992 orig_type = revert_automatic_type_conversion(expression);
6993 expression->base.type = orig_type;
6996 tp_expression->typeprop.type = orig_type;
6997 type_t const* const type = skip_typeref(orig_type);
6998 char const* wrong_type = NULL;
6999 if (is_type_incomplete(type)) {
7000 if (!is_type_void(type) || !GNU_MODE)
7001 wrong_type = "incomplete";
7002 } else if (type->kind == TYPE_FUNCTION) {
7004 /* function types are allowed (and return 1) */
7005 source_position_t const *const pos = &tp_expression->base.source_position;
7006 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7007 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7009 wrong_type = "function";
7013 if (wrong_type != NULL) {
7014 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7015 errorf(&tp_expression->base.source_position,
7016 "operand of %s expression must not be of %s type '%T'",
7017 what, wrong_type, orig_type);
7020 return tp_expression;
7023 static expression_t *parse_sizeof(void)
7025 return parse_typeprop(EXPR_SIZEOF);
7028 static expression_t *parse_alignof(void)
7030 return parse_typeprop(EXPR_ALIGNOF);
7033 static expression_t *parse_select_expression(expression_t *addr)
7035 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7036 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7037 source_position_t const pos = *HERE;
7040 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
7042 return create_error_expression();
7044 type_t *const orig_type = addr->base.type;
7045 type_t *const type = skip_typeref(orig_type);
7048 bool saw_error = false;
7049 if (is_type_pointer(type)) {
7050 if (!select_left_arrow) {
7052 "request for member '%Y' in something not a struct or union, but '%T'",
7056 type_left = skip_typeref(type->pointer.points_to);
7058 if (select_left_arrow && is_type_valid(type)) {
7059 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7065 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7066 type_left->kind != TYPE_COMPOUND_UNION) {
7068 if (is_type_valid(type_left) && !saw_error) {
7070 "request for member '%Y' in something not a struct or union, but '%T'",
7073 return create_error_expression();
7076 compound_t *compound = type_left->compound.compound;
7077 if (!compound->complete) {
7078 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7080 return create_error_expression();
7083 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7084 expression_t *result =
7085 find_create_select(&pos, addr, qualifiers, compound, symbol);
7087 if (result == NULL) {
7088 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7089 return create_error_expression();
7095 static void check_call_argument(type_t *expected_type,
7096 call_argument_t *argument, unsigned pos)
7098 type_t *expected_type_skip = skip_typeref(expected_type);
7099 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7100 expression_t *arg_expr = argument->expression;
7101 type_t *arg_type = skip_typeref(arg_expr->base.type);
7103 /* handle transparent union gnu extension */
7104 if (is_type_union(expected_type_skip)
7105 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7106 compound_t *union_decl = expected_type_skip->compound.compound;
7107 type_t *best_type = NULL;
7108 entity_t *entry = union_decl->members.entities;
7109 for ( ; entry != NULL; entry = entry->base.next) {
7110 assert(is_declaration(entry));
7111 type_t *decl_type = entry->declaration.type;
7112 error = semantic_assign(decl_type, arg_expr);
7113 if (error == ASSIGN_ERROR_INCOMPATIBLE
7114 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7117 if (error == ASSIGN_SUCCESS) {
7118 best_type = decl_type;
7119 } else if (best_type == NULL) {
7120 best_type = decl_type;
7124 if (best_type != NULL) {
7125 expected_type = best_type;
7129 error = semantic_assign(expected_type, arg_expr);
7130 argument->expression = create_implicit_cast(arg_expr, expected_type);
7132 if (error != ASSIGN_SUCCESS) {
7133 /* report exact scope in error messages (like "in argument 3") */
7135 snprintf(buf, sizeof(buf), "call argument %u", pos);
7136 report_assign_error(error, expected_type, arg_expr, buf,
7137 &arg_expr->base.source_position);
7139 type_t *const promoted_type = get_default_promoted_type(arg_type);
7140 if (!types_compatible(expected_type_skip, promoted_type) &&
7141 !types_compatible(expected_type_skip, type_void_ptr) &&
7142 !types_compatible(type_void_ptr, promoted_type)) {
7143 /* Deliberately show the skipped types in this warning */
7144 source_position_t const *const apos = &arg_expr->base.source_position;
7145 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7151 * Handle the semantic restrictions of builtin calls
7153 static void handle_builtin_argument_restrictions(call_expression_t *call)
7155 entity_t *entity = call->function->reference.entity;
7156 switch (entity->function.btk) {
7158 switch (entity->function.b.firm_builtin_kind) {
7159 case ir_bk_return_address:
7160 case ir_bk_frame_address: {
7161 /* argument must be constant */
7162 call_argument_t *argument = call->arguments;
7164 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7165 errorf(&call->base.source_position,
7166 "argument of '%Y' must be a constant expression",
7167 call->function->reference.entity->base.symbol);
7171 case ir_bk_prefetch:
7172 /* second and third argument must be constant if existent */
7173 if (call->arguments == NULL)
7175 call_argument_t *rw = call->arguments->next;
7176 call_argument_t *locality = NULL;
7179 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7180 errorf(&call->base.source_position,
7181 "second argument of '%Y' must be a constant expression",
7182 call->function->reference.entity->base.symbol);
7184 locality = rw->next;
7186 if (locality != NULL) {
7187 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7188 errorf(&call->base.source_position,
7189 "third argument of '%Y' must be a constant expression",
7190 call->function->reference.entity->base.symbol);
7192 locality = rw->next;
7199 case BUILTIN_OBJECT_SIZE:
7200 if (call->arguments == NULL)
7203 call_argument_t *arg = call->arguments->next;
7204 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7205 errorf(&call->base.source_position,
7206 "second argument of '%Y' must be a constant expression",
7207 call->function->reference.entity->base.symbol);
7216 * Parse a call expression, ie. expression '( ... )'.
7218 * @param expression the function address
7220 static expression_t *parse_call_expression(expression_t *expression)
7222 expression_t *result = allocate_expression_zero(EXPR_CALL);
7223 call_expression_t *call = &result->call;
7224 call->function = expression;
7226 type_t *const orig_type = expression->base.type;
7227 type_t *const type = skip_typeref(orig_type);
7229 function_type_t *function_type = NULL;
7230 if (is_type_pointer(type)) {
7231 type_t *const to_type = skip_typeref(type->pointer.points_to);
7233 if (is_type_function(to_type)) {
7234 function_type = &to_type->function;
7235 call->base.type = function_type->return_type;
7239 if (function_type == NULL && is_type_valid(type)) {
7241 "called object '%E' (type '%T') is not a pointer to a function",
7242 expression, orig_type);
7245 /* parse arguments */
7247 add_anchor_token(')');
7248 add_anchor_token(',');
7250 if (token.kind != ')') {
7251 call_argument_t **anchor = &call->arguments;
7253 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7254 argument->expression = parse_assignment_expression();
7257 anchor = &argument->next;
7258 } while (next_if(','));
7260 rem_anchor_token(',');
7261 rem_anchor_token(')');
7264 if (function_type == NULL)
7267 /* check type and count of call arguments */
7268 function_parameter_t *parameter = function_type->parameters;
7269 call_argument_t *argument = call->arguments;
7270 if (!function_type->unspecified_parameters) {
7271 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7272 parameter = parameter->next, argument = argument->next) {
7273 check_call_argument(parameter->type, argument, ++pos);
7276 if (parameter != NULL) {
7277 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7278 } else if (argument != NULL && !function_type->variadic) {
7279 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7283 /* do default promotion for other arguments */
7284 for (; argument != NULL; argument = argument->next) {
7285 type_t *argument_type = argument->expression->base.type;
7286 if (!is_type_object(skip_typeref(argument_type))) {
7287 errorf(&argument->expression->base.source_position,
7288 "call argument '%E' must not be void", argument->expression);
7291 argument_type = get_default_promoted_type(argument_type);
7293 argument->expression
7294 = create_implicit_cast(argument->expression, argument_type);
7299 if (is_type_compound(skip_typeref(function_type->return_type))) {
7300 source_position_t const *const pos = &expression->base.source_position;
7301 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7304 if (expression->kind == EXPR_REFERENCE) {
7305 reference_expression_t *reference = &expression->reference;
7306 if (reference->entity->kind == ENTITY_FUNCTION &&
7307 reference->entity->function.btk != BUILTIN_NONE)
7308 handle_builtin_argument_restrictions(call);
7314 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7316 static bool same_compound_type(const type_t *type1, const type_t *type2)
7319 is_type_compound(type1) &&
7320 type1->kind == type2->kind &&
7321 type1->compound.compound == type2->compound.compound;
7324 static expression_t const *get_reference_address(expression_t const *expr)
7326 bool regular_take_address = true;
7328 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7329 expr = expr->unary.value;
7331 regular_take_address = false;
7334 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7337 expr = expr->unary.value;
7340 if (expr->kind != EXPR_REFERENCE)
7343 /* special case for functions which are automatically converted to a
7344 * pointer to function without an extra TAKE_ADDRESS operation */
7345 if (!regular_take_address &&
7346 expr->reference.entity->kind != ENTITY_FUNCTION) {
7353 static void warn_reference_address_as_bool(expression_t const* expr)
7355 expr = get_reference_address(expr);
7357 source_position_t const *const pos = &expr->base.source_position;
7358 entity_t const *const ent = expr->reference.entity;
7359 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7363 static void warn_assignment_in_condition(const expression_t *const expr)
7365 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7367 if (expr->base.parenthesized)
7369 source_position_t const *const pos = &expr->base.source_position;
7370 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7373 static void semantic_condition(expression_t const *const expr,
7374 char const *const context)
7376 type_t *const type = skip_typeref(expr->base.type);
7377 if (is_type_scalar(type)) {
7378 warn_reference_address_as_bool(expr);
7379 warn_assignment_in_condition(expr);
7380 } else if (is_type_valid(type)) {
7381 errorf(&expr->base.source_position,
7382 "%s must have scalar type", context);
7387 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7389 * @param expression the conditional expression
7391 static expression_t *parse_conditional_expression(expression_t *expression)
7393 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7395 conditional_expression_t *conditional = &result->conditional;
7396 conditional->condition = expression;
7399 add_anchor_token(':');
7401 /* §6.5.15:2 The first operand shall have scalar type. */
7402 semantic_condition(expression, "condition of conditional operator");
7404 expression_t *true_expression = expression;
7405 bool gnu_cond = false;
7406 if (GNU_MODE && token.kind == ':') {
7409 true_expression = parse_expression();
7411 rem_anchor_token(':');
7413 expression_t *false_expression =
7414 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7416 type_t *const orig_true_type = true_expression->base.type;
7417 type_t *const orig_false_type = false_expression->base.type;
7418 type_t *const true_type = skip_typeref(orig_true_type);
7419 type_t *const false_type = skip_typeref(orig_false_type);
7422 source_position_t const *const pos = &conditional->base.source_position;
7423 type_t *result_type;
7424 if (is_type_void(true_type) || is_type_void(false_type)) {
7425 /* ISO/IEC 14882:1998(E) §5.16:2 */
7426 if (true_expression->kind == EXPR_UNARY_THROW) {
7427 result_type = false_type;
7428 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7429 result_type = true_type;
7431 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7432 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7434 result_type = type_void;
7436 } else if (is_type_arithmetic(true_type)
7437 && is_type_arithmetic(false_type)) {
7438 result_type = semantic_arithmetic(true_type, false_type);
7439 } else if (same_compound_type(true_type, false_type)) {
7440 /* just take 1 of the 2 types */
7441 result_type = true_type;
7442 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7443 type_t *pointer_type;
7445 expression_t *other_expression;
7446 if (is_type_pointer(true_type) &&
7447 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7448 pointer_type = true_type;
7449 other_type = false_type;
7450 other_expression = false_expression;
7452 pointer_type = false_type;
7453 other_type = true_type;
7454 other_expression = true_expression;
7457 if (is_null_pointer_constant(other_expression)) {
7458 result_type = pointer_type;
7459 } else if (is_type_pointer(other_type)) {
7460 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7461 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7464 if (is_type_void(to1) || is_type_void(to2)) {
7466 } else if (types_compatible(get_unqualified_type(to1),
7467 get_unqualified_type(to2))) {
7470 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7474 type_t *const type =
7475 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7476 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7477 } else if (is_type_integer(other_type)) {
7478 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7479 result_type = pointer_type;
7481 goto types_incompatible;
7485 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7486 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7488 result_type = type_error_type;
7491 conditional->true_expression
7492 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7493 conditional->false_expression
7494 = create_implicit_cast(false_expression, result_type);
7495 conditional->base.type = result_type;
7500 * Parse an extension expression.
7502 static expression_t *parse_extension(void)
7505 expression_t *expression = parse_subexpression(PREC_UNARY);
7511 * Parse a __builtin_classify_type() expression.
7513 static expression_t *parse_builtin_classify_type(void)
7515 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7516 result->base.type = type_int;
7518 eat(T___builtin_classify_type);
7521 add_anchor_token(')');
7522 expression_t *expression = parse_expression();
7523 rem_anchor_token(')');
7525 result->classify_type.type_expression = expression;
7531 * Parse a delete expression
7532 * ISO/IEC 14882:1998(E) §5.3.5
7534 static expression_t *parse_delete(void)
7536 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7537 result->base.type = type_void;
7542 result->kind = EXPR_UNARY_DELETE_ARRAY;
7546 expression_t *const value = parse_subexpression(PREC_CAST);
7547 result->unary.value = value;
7549 type_t *const type = skip_typeref(value->base.type);
7550 if (!is_type_pointer(type)) {
7551 if (is_type_valid(type)) {
7552 errorf(&value->base.source_position,
7553 "operand of delete must have pointer type");
7555 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7556 source_position_t const *const pos = &value->base.source_position;
7557 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7564 * Parse a throw expression
7565 * ISO/IEC 14882:1998(E) §15:1
7567 static expression_t *parse_throw(void)
7569 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7570 result->base.type = type_void;
7574 expression_t *value = NULL;
7575 switch (token.kind) {
7577 value = parse_assignment_expression();
7578 /* ISO/IEC 14882:1998(E) §15.1:3 */
7579 type_t *const orig_type = value->base.type;
7580 type_t *const type = skip_typeref(orig_type);
7581 if (is_type_incomplete(type)) {
7582 errorf(&value->base.source_position,
7583 "cannot throw object of incomplete type '%T'", orig_type);
7584 } else if (is_type_pointer(type)) {
7585 type_t *const points_to = skip_typeref(type->pointer.points_to);
7586 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7587 errorf(&value->base.source_position,
7588 "cannot throw pointer to incomplete type '%T'", orig_type);
7596 result->unary.value = value;
7601 static bool check_pointer_arithmetic(const source_position_t *source_position,
7602 type_t *pointer_type,
7603 type_t *orig_pointer_type)
7605 type_t *points_to = pointer_type->pointer.points_to;
7606 points_to = skip_typeref(points_to);
7608 if (is_type_incomplete(points_to)) {
7609 if (!GNU_MODE || !is_type_void(points_to)) {
7610 errorf(source_position,
7611 "arithmetic with pointer to incomplete type '%T' not allowed",
7615 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7617 } else if (is_type_function(points_to)) {
7619 errorf(source_position,
7620 "arithmetic with pointer to function type '%T' not allowed",
7624 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7630 static bool is_lvalue(const expression_t *expression)
7632 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7633 switch (expression->kind) {
7634 case EXPR_ARRAY_ACCESS:
7635 case EXPR_COMPOUND_LITERAL:
7636 case EXPR_REFERENCE:
7638 case EXPR_UNARY_DEREFERENCE:
7642 type_t *type = skip_typeref(expression->base.type);
7644 /* ISO/IEC 14882:1998(E) §3.10:3 */
7645 is_type_reference(type) ||
7646 /* Claim it is an lvalue, if the type is invalid. There was a parse
7647 * error before, which maybe prevented properly recognizing it as
7649 !is_type_valid(type);
7654 static void semantic_incdec(unary_expression_t *expression)
7656 type_t *const orig_type = expression->value->base.type;
7657 type_t *const type = skip_typeref(orig_type);
7658 if (is_type_pointer(type)) {
7659 if (!check_pointer_arithmetic(&expression->base.source_position,
7663 } else if (!is_type_real(type) && is_type_valid(type)) {
7664 /* TODO: improve error message */
7665 errorf(&expression->base.source_position,
7666 "operation needs an arithmetic or pointer type");
7669 if (!is_lvalue(expression->value)) {
7670 /* TODO: improve error message */
7671 errorf(&expression->base.source_position, "lvalue required as operand");
7673 expression->base.type = orig_type;
7676 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7678 type_t *const res_type = promote_integer(type);
7679 expr->base.type = res_type;
7680 expr->value = create_implicit_cast(expr->value, res_type);
7683 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7685 type_t *const orig_type = expression->value->base.type;
7686 type_t *const type = skip_typeref(orig_type);
7687 if (!is_type_arithmetic(type)) {
7688 if (is_type_valid(type)) {
7689 /* TODO: improve error message */
7690 errorf(&expression->base.source_position,
7691 "operation needs an arithmetic type");
7694 } else if (is_type_integer(type)) {
7695 promote_unary_int_expr(expression, type);
7697 expression->base.type = orig_type;
7701 static void semantic_unexpr_plus(unary_expression_t *expression)
7703 semantic_unexpr_arithmetic(expression);
7704 source_position_t const *const pos = &expression->base.source_position;
7705 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7708 static void semantic_not(unary_expression_t *expression)
7710 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7711 semantic_condition(expression->value, "operand of !");
7712 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7715 static void semantic_unexpr_integer(unary_expression_t *expression)
7717 type_t *const orig_type = expression->value->base.type;
7718 type_t *const type = skip_typeref(orig_type);
7719 if (!is_type_integer(type)) {
7720 if (is_type_valid(type)) {
7721 errorf(&expression->base.source_position,
7722 "operand of ~ must be of integer type");
7727 promote_unary_int_expr(expression, type);
7730 static void semantic_dereference(unary_expression_t *expression)
7732 type_t *const orig_type = expression->value->base.type;
7733 type_t *const type = skip_typeref(orig_type);
7734 if (!is_type_pointer(type)) {
7735 if (is_type_valid(type)) {
7736 errorf(&expression->base.source_position,
7737 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7742 type_t *result_type = type->pointer.points_to;
7743 result_type = automatic_type_conversion(result_type);
7744 expression->base.type = result_type;
7748 * Record that an address is taken (expression represents an lvalue).
7750 * @param expression the expression
7751 * @param may_be_register if true, the expression might be an register
7753 static void set_address_taken(expression_t *expression, bool may_be_register)
7755 if (expression->kind != EXPR_REFERENCE)
7758 entity_t *const entity = expression->reference.entity;
7760 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7763 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7764 && !may_be_register) {
7765 source_position_t const *const pos = &expression->base.source_position;
7766 errorf(pos, "address of register '%N' requested", entity);
7769 if (entity->kind == ENTITY_VARIABLE) {
7770 entity->variable.address_taken = true;
7772 assert(entity->kind == ENTITY_PARAMETER);
7773 entity->parameter.address_taken = true;
7778 * Check the semantic of the address taken expression.
7780 static void semantic_take_addr(unary_expression_t *expression)
7782 expression_t *value = expression->value;
7783 value->base.type = revert_automatic_type_conversion(value);
7785 type_t *orig_type = value->base.type;
7786 type_t *type = skip_typeref(orig_type);
7787 if (!is_type_valid(type))
7791 if (!is_lvalue(value)) {
7792 errorf(&expression->base.source_position, "'&' requires an lvalue");
7794 if (is_bitfield(value)) {
7795 errorf(&expression->base.source_position,
7796 "'&' not allowed on bitfield");
7799 set_address_taken(value, false);
7801 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7804 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7805 static expression_t *parse_##unexpression_type(void) \
7807 expression_t *unary_expression \
7808 = allocate_expression_zero(unexpression_type); \
7810 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7812 sfunc(&unary_expression->unary); \
7814 return unary_expression; \
7817 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7818 semantic_unexpr_arithmetic)
7819 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7820 semantic_unexpr_plus)
7821 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7823 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7824 semantic_dereference)
7825 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7827 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7828 semantic_unexpr_integer)
7829 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7831 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7834 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7836 static expression_t *parse_##unexpression_type(expression_t *left) \
7838 expression_t *unary_expression \
7839 = allocate_expression_zero(unexpression_type); \
7841 unary_expression->unary.value = left; \
7843 sfunc(&unary_expression->unary); \
7845 return unary_expression; \
7848 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7849 EXPR_UNARY_POSTFIX_INCREMENT,
7851 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7852 EXPR_UNARY_POSTFIX_DECREMENT,
7855 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7857 /* TODO: handle complex + imaginary types */
7859 type_left = get_unqualified_type(type_left);
7860 type_right = get_unqualified_type(type_right);
7862 /* §6.3.1.8 Usual arithmetic conversions */
7863 if (type_left == type_long_double || type_right == type_long_double) {
7864 return type_long_double;
7865 } else if (type_left == type_double || type_right == type_double) {
7867 } else if (type_left == type_float || type_right == type_float) {
7871 type_left = promote_integer(type_left);
7872 type_right = promote_integer(type_right);
7874 if (type_left == type_right)
7877 bool const signed_left = is_type_signed(type_left);
7878 bool const signed_right = is_type_signed(type_right);
7879 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7880 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7882 if (signed_left == signed_right)
7883 return rank_left >= rank_right ? type_left : type_right;
7887 atomic_type_kind_t s_akind;
7888 atomic_type_kind_t u_akind;
7893 u_type = type_right;
7895 s_type = type_right;
7898 s_akind = get_akind(s_type);
7899 u_akind = get_akind(u_type);
7900 s_rank = get_akind_rank(s_akind);
7901 u_rank = get_akind_rank(u_akind);
7903 if (u_rank >= s_rank)
7906 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7910 case ATOMIC_TYPE_INT: return type_unsigned_int;
7911 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7912 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7914 default: panic("invalid atomic type");
7919 * Check the semantic restrictions for a binary expression.
7921 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7923 expression_t *const left = expression->left;
7924 expression_t *const right = expression->right;
7925 type_t *const orig_type_left = left->base.type;
7926 type_t *const orig_type_right = right->base.type;
7927 type_t *const type_left = skip_typeref(orig_type_left);
7928 type_t *const type_right = skip_typeref(orig_type_right);
7930 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7931 /* TODO: improve error message */
7932 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7933 errorf(&expression->base.source_position,
7934 "operation needs arithmetic types");
7939 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7940 expression->left = create_implicit_cast(left, arithmetic_type);
7941 expression->right = create_implicit_cast(right, arithmetic_type);
7942 expression->base.type = arithmetic_type;
7945 static void semantic_binexpr_integer(binary_expression_t *const expression)
7947 expression_t *const left = expression->left;
7948 expression_t *const right = expression->right;
7949 type_t *const orig_type_left = left->base.type;
7950 type_t *const orig_type_right = right->base.type;
7951 type_t *const type_left = skip_typeref(orig_type_left);
7952 type_t *const type_right = skip_typeref(orig_type_right);
7954 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7955 /* TODO: improve error message */
7956 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7957 errorf(&expression->base.source_position,
7958 "operation needs integer types");
7963 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7964 expression->left = create_implicit_cast(left, result_type);
7965 expression->right = create_implicit_cast(right, result_type);
7966 expression->base.type = result_type;
7969 static void warn_div_by_zero(binary_expression_t const *const expression)
7971 if (!is_type_integer(expression->base.type))
7974 expression_t const *const right = expression->right;
7975 /* The type of the right operand can be different for /= */
7976 if (is_type_integer(right->base.type) &&
7977 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7978 !fold_constant_to_bool(right)) {
7979 source_position_t const *const pos = &expression->base.source_position;
7980 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7985 * Check the semantic restrictions for a div/mod expression.
7987 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7989 semantic_binexpr_arithmetic(expression);
7990 warn_div_by_zero(expression);
7993 static void warn_addsub_in_shift(const expression_t *const expr)
7995 if (expr->base.parenthesized)
7999 switch (expr->kind) {
8000 case EXPR_BINARY_ADD: op = '+'; break;
8001 case EXPR_BINARY_SUB: op = '-'; break;
8005 source_position_t const *const pos = &expr->base.source_position;
8006 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8009 static bool semantic_shift(binary_expression_t *expression)
8011 expression_t *const left = expression->left;
8012 expression_t *const right = expression->right;
8013 type_t *const orig_type_left = left->base.type;
8014 type_t *const orig_type_right = right->base.type;
8015 type_t * type_left = skip_typeref(orig_type_left);
8016 type_t * type_right = skip_typeref(orig_type_right);
8018 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8019 /* TODO: improve error message */
8020 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8021 errorf(&expression->base.source_position,
8022 "operands of shift operation must have integer types");
8027 type_left = promote_integer(type_left);
8029 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8030 source_position_t const *const pos = &right->base.source_position;
8031 long const count = fold_constant_to_int(right);
8033 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8034 } else if ((unsigned long)count >=
8035 get_atomic_type_size(type_left->atomic.akind) * 8) {
8036 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8040 type_right = promote_integer(type_right);
8041 expression->right = create_implicit_cast(right, type_right);
8046 static void semantic_shift_op(binary_expression_t *expression)
8048 expression_t *const left = expression->left;
8049 expression_t *const right = expression->right;
8051 if (!semantic_shift(expression))
8054 warn_addsub_in_shift(left);
8055 warn_addsub_in_shift(right);
8057 type_t *const orig_type_left = left->base.type;
8058 type_t * type_left = skip_typeref(orig_type_left);
8060 type_left = promote_integer(type_left);
8061 expression->left = create_implicit_cast(left, type_left);
8062 expression->base.type = type_left;
8065 static void semantic_add(binary_expression_t *expression)
8067 expression_t *const left = expression->left;
8068 expression_t *const right = expression->right;
8069 type_t *const orig_type_left = left->base.type;
8070 type_t *const orig_type_right = right->base.type;
8071 type_t *const type_left = skip_typeref(orig_type_left);
8072 type_t *const type_right = skip_typeref(orig_type_right);
8075 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8076 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8077 expression->left = create_implicit_cast(left, arithmetic_type);
8078 expression->right = create_implicit_cast(right, arithmetic_type);
8079 expression->base.type = arithmetic_type;
8080 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8081 check_pointer_arithmetic(&expression->base.source_position,
8082 type_left, orig_type_left);
8083 expression->base.type = type_left;
8084 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8085 check_pointer_arithmetic(&expression->base.source_position,
8086 type_right, orig_type_right);
8087 expression->base.type = type_right;
8088 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8089 errorf(&expression->base.source_position,
8090 "invalid operands to binary + ('%T', '%T')",
8091 orig_type_left, orig_type_right);
8095 static void semantic_sub(binary_expression_t *expression)
8097 expression_t *const left = expression->left;
8098 expression_t *const right = expression->right;
8099 type_t *const orig_type_left = left->base.type;
8100 type_t *const orig_type_right = right->base.type;
8101 type_t *const type_left = skip_typeref(orig_type_left);
8102 type_t *const type_right = skip_typeref(orig_type_right);
8103 source_position_t const *const pos = &expression->base.source_position;
8106 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8107 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8108 expression->left = create_implicit_cast(left, arithmetic_type);
8109 expression->right = create_implicit_cast(right, arithmetic_type);
8110 expression->base.type = arithmetic_type;
8111 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8112 check_pointer_arithmetic(&expression->base.source_position,
8113 type_left, orig_type_left);
8114 expression->base.type = type_left;
8115 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8116 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8117 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8118 if (!types_compatible(unqual_left, unqual_right)) {
8120 "subtracting pointers to incompatible types '%T' and '%T'",
8121 orig_type_left, orig_type_right);
8122 } else if (!is_type_object(unqual_left)) {
8123 if (!is_type_void(unqual_left)) {
8124 errorf(pos, "subtracting pointers to non-object types '%T'",
8127 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8130 expression->base.type = type_ptrdiff_t;
8131 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8132 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8133 orig_type_left, orig_type_right);
8137 static void warn_string_literal_address(expression_t const* expr)
8139 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8140 expr = expr->unary.value;
8141 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8143 expr = expr->unary.value;
8146 if (expr->kind == EXPR_STRING_LITERAL
8147 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8148 source_position_t const *const pos = &expr->base.source_position;
8149 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8153 static bool maybe_negative(expression_t const *const expr)
8155 switch (is_constant_expression(expr)) {
8156 case EXPR_CLASS_ERROR: return false;
8157 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8158 default: return true;
8162 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8164 warn_string_literal_address(expr);
8166 expression_t const* const ref = get_reference_address(expr);
8167 if (ref != NULL && is_null_pointer_constant(other)) {
8168 entity_t const *const ent = ref->reference.entity;
8169 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8172 if (!expr->base.parenthesized) {
8173 switch (expr->base.kind) {
8174 case EXPR_BINARY_LESS:
8175 case EXPR_BINARY_GREATER:
8176 case EXPR_BINARY_LESSEQUAL:
8177 case EXPR_BINARY_GREATEREQUAL:
8178 case EXPR_BINARY_NOTEQUAL:
8179 case EXPR_BINARY_EQUAL:
8180 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8189 * Check the semantics of comparison expressions.
8191 * @param expression The expression to check.
8193 static void semantic_comparison(binary_expression_t *expression)
8195 source_position_t const *const pos = &expression->base.source_position;
8196 expression_t *const left = expression->left;
8197 expression_t *const right = expression->right;
8199 warn_comparison(pos, left, right);
8200 warn_comparison(pos, right, left);
8202 type_t *orig_type_left = left->base.type;
8203 type_t *orig_type_right = right->base.type;
8204 type_t *type_left = skip_typeref(orig_type_left);
8205 type_t *type_right = skip_typeref(orig_type_right);
8207 /* TODO non-arithmetic types */
8208 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8209 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8211 /* test for signed vs unsigned compares */
8212 if (is_type_integer(arithmetic_type)) {
8213 bool const signed_left = is_type_signed(type_left);
8214 bool const signed_right = is_type_signed(type_right);
8215 if (signed_left != signed_right) {
8216 /* FIXME long long needs better const folding magic */
8217 /* TODO check whether constant value can be represented by other type */
8218 if ((signed_left && maybe_negative(left)) ||
8219 (signed_right && maybe_negative(right))) {
8220 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8225 expression->left = create_implicit_cast(left, arithmetic_type);
8226 expression->right = create_implicit_cast(right, arithmetic_type);
8227 expression->base.type = arithmetic_type;
8228 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8229 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8230 is_type_float(arithmetic_type)) {
8231 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8233 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8234 /* TODO check compatibility */
8235 } else if (is_type_pointer(type_left)) {
8236 expression->right = create_implicit_cast(right, type_left);
8237 } else if (is_type_pointer(type_right)) {
8238 expression->left = create_implicit_cast(left, type_right);
8239 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8240 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8242 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8246 * Checks if a compound type has constant fields.
8248 static bool has_const_fields(const compound_type_t *type)
8250 compound_t *compound = type->compound;
8251 entity_t *entry = compound->members.entities;
8253 for (; entry != NULL; entry = entry->base.next) {
8254 if (!is_declaration(entry))
8257 const type_t *decl_type = skip_typeref(entry->declaration.type);
8258 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8265 static bool is_valid_assignment_lhs(expression_t const* const left)
8267 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8268 type_t *const type_left = skip_typeref(orig_type_left);
8270 if (!is_lvalue(left)) {
8271 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8276 if (left->kind == EXPR_REFERENCE
8277 && left->reference.entity->kind == ENTITY_FUNCTION) {
8278 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8282 if (is_type_array(type_left)) {
8283 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8286 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8287 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8291 if (is_type_incomplete(type_left)) {
8292 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8293 left, orig_type_left);
8296 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8297 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8298 left, orig_type_left);
8305 static void semantic_arithmetic_assign(binary_expression_t *expression)
8307 expression_t *left = expression->left;
8308 expression_t *right = expression->right;
8309 type_t *orig_type_left = left->base.type;
8310 type_t *orig_type_right = right->base.type;
8312 if (!is_valid_assignment_lhs(left))
8315 type_t *type_left = skip_typeref(orig_type_left);
8316 type_t *type_right = skip_typeref(orig_type_right);
8318 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8319 /* TODO: improve error message */
8320 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8321 errorf(&expression->base.source_position,
8322 "operation needs arithmetic types");
8327 /* combined instructions are tricky. We can't create an implicit cast on
8328 * the left side, because we need the uncasted form for the store.
8329 * The ast2firm pass has to know that left_type must be right_type
8330 * for the arithmetic operation and create a cast by itself */
8331 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8332 expression->right = create_implicit_cast(right, arithmetic_type);
8333 expression->base.type = type_left;
8336 static void semantic_divmod_assign(binary_expression_t *expression)
8338 semantic_arithmetic_assign(expression);
8339 warn_div_by_zero(expression);
8342 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8344 expression_t *const left = expression->left;
8345 expression_t *const right = expression->right;
8346 type_t *const orig_type_left = left->base.type;
8347 type_t *const orig_type_right = right->base.type;
8348 type_t *const type_left = skip_typeref(orig_type_left);
8349 type_t *const type_right = skip_typeref(orig_type_right);
8351 if (!is_valid_assignment_lhs(left))
8354 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8355 /* combined instructions are tricky. We can't create an implicit cast on
8356 * the left side, because we need the uncasted form for the store.
8357 * The ast2firm pass has to know that left_type must be right_type
8358 * for the arithmetic operation and create a cast by itself */
8359 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8360 expression->right = create_implicit_cast(right, arithmetic_type);
8361 expression->base.type = type_left;
8362 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8363 check_pointer_arithmetic(&expression->base.source_position,
8364 type_left, orig_type_left);
8365 expression->base.type = type_left;
8366 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8367 errorf(&expression->base.source_position,
8368 "incompatible types '%T' and '%T' in assignment",
8369 orig_type_left, orig_type_right);
8373 static void semantic_integer_assign(binary_expression_t *expression)
8375 expression_t *left = expression->left;
8376 expression_t *right = expression->right;
8377 type_t *orig_type_left = left->base.type;
8378 type_t *orig_type_right = right->base.type;
8380 if (!is_valid_assignment_lhs(left))
8383 type_t *type_left = skip_typeref(orig_type_left);
8384 type_t *type_right = skip_typeref(orig_type_right);
8386 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8387 /* TODO: improve error message */
8388 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8389 errorf(&expression->base.source_position,
8390 "operation needs integer types");
8395 /* combined instructions are tricky. We can't create an implicit cast on
8396 * the left side, because we need the uncasted form for the store.
8397 * The ast2firm pass has to know that left_type must be right_type
8398 * for the arithmetic operation and create a cast by itself */
8399 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8400 expression->right = create_implicit_cast(right, arithmetic_type);
8401 expression->base.type = type_left;
8404 static void semantic_shift_assign(binary_expression_t *expression)
8406 expression_t *left = expression->left;
8408 if (!is_valid_assignment_lhs(left))
8411 if (!semantic_shift(expression))
8414 expression->base.type = skip_typeref(left->base.type);
8417 static void warn_logical_and_within_or(const expression_t *const expr)
8419 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8421 if (expr->base.parenthesized)
8423 source_position_t const *const pos = &expr->base.source_position;
8424 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8428 * Check the semantic restrictions of a logical expression.
8430 static void semantic_logical_op(binary_expression_t *expression)
8432 /* §6.5.13:2 Each of the operands shall have scalar type.
8433 * §6.5.14:2 Each of the operands shall have scalar type. */
8434 semantic_condition(expression->left, "left operand of logical operator");
8435 semantic_condition(expression->right, "right operand of logical operator");
8436 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8437 warn_logical_and_within_or(expression->left);
8438 warn_logical_and_within_or(expression->right);
8440 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8444 * Check the semantic restrictions of a binary assign expression.
8446 static void semantic_binexpr_assign(binary_expression_t *expression)
8448 expression_t *left = expression->left;
8449 type_t *orig_type_left = left->base.type;
8451 if (!is_valid_assignment_lhs(left))
8454 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8455 report_assign_error(error, orig_type_left, expression->right,
8456 "assignment", &left->base.source_position);
8457 expression->right = create_implicit_cast(expression->right, orig_type_left);
8458 expression->base.type = orig_type_left;
8462 * Determine if the outermost operation (or parts thereof) of the given
8463 * expression has no effect in order to generate a warning about this fact.
8464 * Therefore in some cases this only examines some of the operands of the
8465 * expression (see comments in the function and examples below).
8467 * f() + 23; // warning, because + has no effect
8468 * x || f(); // no warning, because x controls execution of f()
8469 * x ? y : f(); // warning, because y has no effect
8470 * (void)x; // no warning to be able to suppress the warning
8471 * This function can NOT be used for an "expression has definitely no effect"-
8473 static bool expression_has_effect(const expression_t *const expr)
8475 switch (expr->kind) {
8476 case EXPR_ERROR: return true; /* do NOT warn */
8477 case EXPR_REFERENCE: return false;
8478 case EXPR_ENUM_CONSTANT: return false;
8479 case EXPR_LABEL_ADDRESS: return false;
8481 /* suppress the warning for microsoft __noop operations */
8482 case EXPR_LITERAL_MS_NOOP: return true;
8483 case EXPR_LITERAL_BOOLEAN:
8484 case EXPR_LITERAL_CHARACTER:
8485 case EXPR_LITERAL_WIDE_CHARACTER:
8486 case EXPR_LITERAL_INTEGER:
8487 case EXPR_LITERAL_INTEGER_OCTAL:
8488 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8489 case EXPR_LITERAL_FLOATINGPOINT:
8490 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8491 case EXPR_STRING_LITERAL: return false;
8492 case EXPR_WIDE_STRING_LITERAL: return false;
8495 const call_expression_t *const call = &expr->call;
8496 if (call->function->kind != EXPR_REFERENCE)
8499 switch (call->function->reference.entity->function.btk) {
8500 /* FIXME: which builtins have no effect? */
8501 default: return true;
8505 /* Generate the warning if either the left or right hand side of a
8506 * conditional expression has no effect */
8507 case EXPR_CONDITIONAL: {
8508 conditional_expression_t const *const cond = &expr->conditional;
8509 expression_t const *const t = cond->true_expression;
8511 (t == NULL || expression_has_effect(t)) &&
8512 expression_has_effect(cond->false_expression);
8515 case EXPR_SELECT: return false;
8516 case EXPR_ARRAY_ACCESS: return false;
8517 case EXPR_SIZEOF: return false;
8518 case EXPR_CLASSIFY_TYPE: return false;
8519 case EXPR_ALIGNOF: return false;
8521 case EXPR_FUNCNAME: return false;
8522 case EXPR_BUILTIN_CONSTANT_P: return false;
8523 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8524 case EXPR_OFFSETOF: return false;
8525 case EXPR_VA_START: return true;
8526 case EXPR_VA_ARG: return true;
8527 case EXPR_VA_COPY: return true;
8528 case EXPR_STATEMENT: return true; // TODO
8529 case EXPR_COMPOUND_LITERAL: return false;
8531 case EXPR_UNARY_NEGATE: return false;
8532 case EXPR_UNARY_PLUS: return false;
8533 case EXPR_UNARY_BITWISE_NEGATE: return false;
8534 case EXPR_UNARY_NOT: return false;
8535 case EXPR_UNARY_DEREFERENCE: return false;
8536 case EXPR_UNARY_TAKE_ADDRESS: return false;
8537 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8538 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8539 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8540 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8542 /* Treat void casts as if they have an effect in order to being able to
8543 * suppress the warning */
8544 case EXPR_UNARY_CAST: {
8545 type_t *const type = skip_typeref(expr->base.type);
8546 return is_type_void(type);
8549 case EXPR_UNARY_ASSUME: return true;
8550 case EXPR_UNARY_DELETE: return true;
8551 case EXPR_UNARY_DELETE_ARRAY: return true;
8552 case EXPR_UNARY_THROW: return true;
8554 case EXPR_BINARY_ADD: return false;
8555 case EXPR_BINARY_SUB: return false;
8556 case EXPR_BINARY_MUL: return false;
8557 case EXPR_BINARY_DIV: return false;
8558 case EXPR_BINARY_MOD: return false;
8559 case EXPR_BINARY_EQUAL: return false;
8560 case EXPR_BINARY_NOTEQUAL: return false;
8561 case EXPR_BINARY_LESS: return false;
8562 case EXPR_BINARY_LESSEQUAL: return false;
8563 case EXPR_BINARY_GREATER: return false;
8564 case EXPR_BINARY_GREATEREQUAL: return false;
8565 case EXPR_BINARY_BITWISE_AND: return false;
8566 case EXPR_BINARY_BITWISE_OR: return false;
8567 case EXPR_BINARY_BITWISE_XOR: return false;
8568 case EXPR_BINARY_SHIFTLEFT: return false;
8569 case EXPR_BINARY_SHIFTRIGHT: return false;
8570 case EXPR_BINARY_ASSIGN: return true;
8571 case EXPR_BINARY_MUL_ASSIGN: return true;
8572 case EXPR_BINARY_DIV_ASSIGN: return true;
8573 case EXPR_BINARY_MOD_ASSIGN: return true;
8574 case EXPR_BINARY_ADD_ASSIGN: return true;
8575 case EXPR_BINARY_SUB_ASSIGN: return true;
8576 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8577 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8578 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8579 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8580 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8582 /* Only examine the right hand side of && and ||, because the left hand
8583 * side already has the effect of controlling the execution of the right
8585 case EXPR_BINARY_LOGICAL_AND:
8586 case EXPR_BINARY_LOGICAL_OR:
8587 /* Only examine the right hand side of a comma expression, because the left
8588 * hand side has a separate warning */
8589 case EXPR_BINARY_COMMA:
8590 return expression_has_effect(expr->binary.right);
8592 case EXPR_BINARY_ISGREATER: return false;
8593 case EXPR_BINARY_ISGREATEREQUAL: return false;
8594 case EXPR_BINARY_ISLESS: return false;
8595 case EXPR_BINARY_ISLESSEQUAL: return false;
8596 case EXPR_BINARY_ISLESSGREATER: return false;
8597 case EXPR_BINARY_ISUNORDERED: return false;
8600 internal_errorf(HERE, "unexpected expression");
8603 static void semantic_comma(binary_expression_t *expression)
8605 const expression_t *const left = expression->left;
8606 if (!expression_has_effect(left)) {
8607 source_position_t const *const pos = &left->base.source_position;
8608 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8610 expression->base.type = expression->right->base.type;
8614 * @param prec_r precedence of the right operand
8616 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8617 static expression_t *parse_##binexpression_type(expression_t *left) \
8619 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8620 binexpr->binary.left = left; \
8623 expression_t *right = parse_subexpression(prec_r); \
8625 binexpr->binary.right = right; \
8626 sfunc(&binexpr->binary); \
8631 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8632 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8633 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8634 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8635 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8636 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8637 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8638 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8639 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8640 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8641 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8642 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8643 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8644 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8645 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8646 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8647 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8648 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8649 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8650 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8651 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8652 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8653 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8654 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8655 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8656 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8657 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8658 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8659 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8660 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8663 static expression_t *parse_subexpression(precedence_t precedence)
8665 if (token.kind < 0) {
8666 return expected_expression_error();
8669 expression_parser_function_t *parser
8670 = &expression_parsers[token.kind];
8673 if (parser->parser != NULL) {
8674 left = parser->parser();
8676 left = parse_primary_expression();
8678 assert(left != NULL);
8681 if (token.kind < 0) {
8682 return expected_expression_error();
8685 parser = &expression_parsers[token.kind];
8686 if (parser->infix_parser == NULL)
8688 if (parser->infix_precedence < precedence)
8691 left = parser->infix_parser(left);
8693 assert(left != NULL);
8700 * Parse an expression.
8702 static expression_t *parse_expression(void)
8704 return parse_subexpression(PREC_EXPRESSION);
8708 * Register a parser for a prefix-like operator.
8710 * @param parser the parser function
8711 * @param token_kind the token type of the prefix token
8713 static void register_expression_parser(parse_expression_function parser,
8716 expression_parser_function_t *entry = &expression_parsers[token_kind];
8718 if (entry->parser != NULL) {
8719 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8720 panic("trying to register multiple expression parsers for a token");
8722 entry->parser = parser;
8726 * Register a parser for an infix operator with given precedence.
8728 * @param parser the parser function
8729 * @param token_kind the token type of the infix operator
8730 * @param precedence the precedence of the operator
8732 static void register_infix_parser(parse_expression_infix_function parser,
8733 int token_kind, precedence_t precedence)
8735 expression_parser_function_t *entry = &expression_parsers[token_kind];
8737 if (entry->infix_parser != NULL) {
8738 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8739 panic("trying to register multiple infix expression parsers for a "
8742 entry->infix_parser = parser;
8743 entry->infix_precedence = precedence;
8747 * Initialize the expression parsers.
8749 static void init_expression_parsers(void)
8751 memset(&expression_parsers, 0, sizeof(expression_parsers));
8753 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8754 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8755 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8756 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8757 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8758 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8759 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8760 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8761 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8762 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8763 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8764 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8765 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8766 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8767 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8768 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8769 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8770 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8771 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8772 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8773 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8774 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8775 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8776 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8777 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8778 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8779 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8780 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8781 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8782 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8783 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8784 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8785 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8786 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8787 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8788 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8789 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8791 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8792 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8793 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8794 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8795 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8796 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8797 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8798 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8799 register_expression_parser(parse_sizeof, T_sizeof);
8800 register_expression_parser(parse_alignof, T___alignof__);
8801 register_expression_parser(parse_extension, T___extension__);
8802 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8803 register_expression_parser(parse_delete, T_delete);
8804 register_expression_parser(parse_throw, T_throw);
8808 * Parse a asm statement arguments specification.
8810 static asm_argument_t *parse_asm_arguments(bool is_out)
8812 asm_argument_t *result = NULL;
8813 asm_argument_t **anchor = &result;
8815 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8816 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8819 add_anchor_token(']');
8820 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8821 rem_anchor_token(']');
8823 if (!argument->symbol)
8827 argument->constraints = parse_string_literals();
8829 add_anchor_token(')');
8830 expression_t *expression = parse_expression();
8831 rem_anchor_token(')');
8833 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8834 * change size or type representation (e.g. int -> long is ok, but
8835 * int -> float is not) */
8836 if (expression->kind == EXPR_UNARY_CAST) {
8837 type_t *const type = expression->base.type;
8838 type_kind_t const kind = type->kind;
8839 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8842 if (kind == TYPE_ATOMIC) {
8843 atomic_type_kind_t const akind = type->atomic.akind;
8844 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8845 size = get_atomic_type_size(akind);
8847 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8848 size = get_type_size(type_void_ptr);
8852 expression_t *const value = expression->unary.value;
8853 type_t *const value_type = value->base.type;
8854 type_kind_t const value_kind = value_type->kind;
8856 unsigned value_flags;
8857 unsigned value_size;
8858 if (value_kind == TYPE_ATOMIC) {
8859 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8860 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8861 value_size = get_atomic_type_size(value_akind);
8862 } else if (value_kind == TYPE_POINTER) {
8863 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8864 value_size = get_type_size(type_void_ptr);
8869 if (value_flags != flags || value_size != size)
8873 } while (expression->kind == EXPR_UNARY_CAST);
8877 if (!is_lvalue(expression)) {
8878 errorf(&expression->base.source_position,
8879 "asm output argument is not an lvalue");
8882 if (argument->constraints.begin[0] == '=')
8883 determine_lhs_ent(expression, NULL);
8885 mark_vars_read(expression, NULL);
8887 mark_vars_read(expression, NULL);
8889 argument->expression = expression;
8892 set_address_taken(expression, true);
8895 anchor = &argument->next;
8905 * Parse a asm statement clobber specification.
8907 static asm_clobber_t *parse_asm_clobbers(void)
8909 asm_clobber_t *result = NULL;
8910 asm_clobber_t **anchor = &result;
8912 while (token.kind == T_STRING_LITERAL) {
8913 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8914 clobber->clobber = parse_string_literals();
8917 anchor = &clobber->next;
8927 * Parse an asm statement.
8929 static statement_t *parse_asm_statement(void)
8931 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8932 asm_statement_t *asm_statement = &statement->asms;
8936 if (next_if(T_volatile))
8937 asm_statement->is_volatile = true;
8940 add_anchor_token(')');
8941 if (token.kind != T_STRING_LITERAL) {
8942 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8945 asm_statement->asm_text = parse_string_literals();
8947 add_anchor_token(':');
8948 if (!next_if(':')) {
8949 rem_anchor_token(':');
8953 asm_statement->outputs = parse_asm_arguments(true);
8954 if (!next_if(':')) {
8955 rem_anchor_token(':');
8959 asm_statement->inputs = parse_asm_arguments(false);
8960 if (!next_if(':')) {
8961 rem_anchor_token(':');
8964 rem_anchor_token(':');
8966 asm_statement->clobbers = parse_asm_clobbers();
8969 rem_anchor_token(')');
8973 if (asm_statement->outputs == NULL) {
8974 /* GCC: An 'asm' instruction without any output operands will be treated
8975 * identically to a volatile 'asm' instruction. */
8976 asm_statement->is_volatile = true;
8982 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8984 statement_t *inner_stmt;
8985 switch (token.kind) {
8987 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8988 inner_stmt = create_error_statement();
8992 if (label->kind == STATEMENT_LABEL) {
8993 /* Eat an empty statement here, to avoid the warning about an empty
8994 * statement after a label. label:; is commonly used to have a label
8995 * before a closing brace. */
8996 inner_stmt = create_empty_statement();
9003 inner_stmt = parse_statement();
9004 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9005 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9006 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9007 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9015 * Parse a case statement.
9017 static statement_t *parse_case_statement(void)
9019 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9020 source_position_t *const pos = &statement->base.source_position;
9023 add_anchor_token(':');
9025 expression_t *expression = parse_expression();
9026 type_t *expression_type = expression->base.type;
9027 type_t *skipped = skip_typeref(expression_type);
9028 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9029 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9030 expression, expression_type);
9033 type_t *type = expression_type;
9034 if (current_switch != NULL) {
9035 type_t *switch_type = current_switch->expression->base.type;
9036 if (is_type_valid(switch_type)) {
9037 expression = create_implicit_cast(expression, switch_type);
9041 statement->case_label.expression = expression;
9042 expression_classification_t const expr_class = is_constant_expression(expression);
9043 if (expr_class != EXPR_CLASS_CONSTANT) {
9044 if (expr_class != EXPR_CLASS_ERROR) {
9045 errorf(pos, "case label does not reduce to an integer constant");
9047 statement->case_label.is_bad = true;
9049 long const val = fold_constant_to_int(expression);
9050 statement->case_label.first_case = val;
9051 statement->case_label.last_case = val;
9055 if (next_if(T_DOTDOTDOT)) {
9056 expression_t *end_range = parse_expression();
9057 expression_type = expression->base.type;
9058 skipped = skip_typeref(expression_type);
9059 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9060 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9061 expression, expression_type);
9064 end_range = create_implicit_cast(end_range, type);
9065 statement->case_label.end_range = end_range;
9066 expression_classification_t const end_class = is_constant_expression(end_range);
9067 if (end_class != EXPR_CLASS_CONSTANT) {
9068 if (end_class != EXPR_CLASS_ERROR) {
9069 errorf(pos, "case range does not reduce to an integer constant");
9071 statement->case_label.is_bad = true;
9073 long const val = fold_constant_to_int(end_range);
9074 statement->case_label.last_case = val;
9076 if (val < statement->case_label.first_case) {
9077 statement->case_label.is_empty_range = true;
9078 warningf(WARN_OTHER, pos, "empty range specified");
9084 PUSH_PARENT(statement);
9086 rem_anchor_token(':');
9089 if (current_switch != NULL) {
9090 if (! statement->case_label.is_bad) {
9091 /* Check for duplicate case values */
9092 case_label_statement_t *c = &statement->case_label;
9093 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9094 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9097 if (c->last_case < l->first_case || c->first_case > l->last_case)
9100 errorf(pos, "duplicate case value (previously used %P)",
9101 &l->base.source_position);
9105 /* link all cases into the switch statement */
9106 if (current_switch->last_case == NULL) {
9107 current_switch->first_case = &statement->case_label;
9109 current_switch->last_case->next = &statement->case_label;
9111 current_switch->last_case = &statement->case_label;
9113 errorf(pos, "case label not within a switch statement");
9116 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9123 * Parse a default statement.
9125 static statement_t *parse_default_statement(void)
9127 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9131 PUSH_PARENT(statement);
9135 if (current_switch != NULL) {
9136 const case_label_statement_t *def_label = current_switch->default_label;
9137 if (def_label != NULL) {
9138 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9140 current_switch->default_label = &statement->case_label;
9142 /* link all cases into the switch statement */
9143 if (current_switch->last_case == NULL) {
9144 current_switch->first_case = &statement->case_label;
9146 current_switch->last_case->next = &statement->case_label;
9148 current_switch->last_case = &statement->case_label;
9151 errorf(&statement->base.source_position,
9152 "'default' label not within a switch statement");
9155 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9162 * Parse a label statement.
9164 static statement_t *parse_label_statement(void)
9166 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9167 label_t *const label = get_label();
9168 statement->label.label = label;
9170 PUSH_PARENT(statement);
9172 /* if statement is already set then the label is defined twice,
9173 * otherwise it was just mentioned in a goto/local label declaration so far
9175 source_position_t const* const pos = &statement->base.source_position;
9176 if (label->statement != NULL) {
9177 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9179 label->base.source_position = *pos;
9180 label->statement = statement;
9185 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9186 parse_attributes(NULL); // TODO process attributes
9189 statement->label.statement = parse_label_inner_statement(statement, "label");
9191 /* remember the labels in a list for later checking */
9192 *label_anchor = &statement->label;
9193 label_anchor = &statement->label.next;
9199 static statement_t *parse_inner_statement(void)
9201 statement_t *const stmt = parse_statement();
9202 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9203 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9204 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9205 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9211 * Parse an expression in parentheses and mark its variables as read.
9213 static expression_t *parse_condition(void)
9216 add_anchor_token(')');
9217 expression_t *const expr = parse_expression();
9218 mark_vars_read(expr, NULL);
9219 rem_anchor_token(')');
9225 * Parse an if statement.
9227 static statement_t *parse_if(void)
9229 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9233 PUSH_PARENT(statement);
9234 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9236 add_anchor_token(T_else);
9238 expression_t *const expr = parse_condition();
9239 statement->ifs.condition = expr;
9240 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9242 semantic_condition(expr, "condition of 'if'-statment");
9244 statement_t *const true_stmt = parse_inner_statement();
9245 statement->ifs.true_statement = true_stmt;
9246 rem_anchor_token(T_else);
9248 if (true_stmt->kind == STATEMENT_EMPTY) {
9249 warningf(WARN_EMPTY_BODY, HERE,
9250 "suggest braces around empty body in an ‘if’ statement");
9253 if (next_if(T_else)) {
9254 statement->ifs.false_statement = parse_inner_statement();
9256 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9257 warningf(WARN_EMPTY_BODY, HERE,
9258 "suggest braces around empty body in an ‘if’ statement");
9260 } else if (true_stmt->kind == STATEMENT_IF &&
9261 true_stmt->ifs.false_statement != NULL) {
9262 source_position_t const *const pos = &true_stmt->base.source_position;
9263 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);
9324 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9326 expression_t *const expr = parse_condition();
9327 type_t * type = skip_typeref(expr->base.type);
9328 if (is_type_integer(type)) {
9329 type = promote_integer(type);
9330 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9331 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9333 } else if (is_type_valid(type)) {
9334 errorf(&expr->base.source_position,
9335 "switch quantity is not an integer, but '%T'", type);
9336 type = type_error_type;
9338 statement->switchs.expression = create_implicit_cast(expr, type);
9340 switch_statement_t *rem = current_switch;
9341 current_switch = &statement->switchs;
9342 statement->switchs.body = parse_inner_statement();
9343 current_switch = rem;
9345 if (statement->switchs.default_label == NULL) {
9346 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9348 check_enum_cases(&statement->switchs);
9355 static statement_t *parse_loop_body(statement_t *const loop)
9357 statement_t *const rem = current_loop;
9358 current_loop = loop;
9360 statement_t *const body = parse_inner_statement();
9367 * Parse a while statement.
9369 static statement_t *parse_while(void)
9371 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9375 PUSH_PARENT(statement);
9376 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9378 expression_t *const cond = parse_condition();
9379 statement->whiles.condition = cond;
9380 /* §6.8.5:2 The controlling expression of an iteration statement shall
9381 * have scalar type. */
9382 semantic_condition(cond, "condition of 'while'-statement");
9384 statement->whiles.body = parse_loop_body(statement);
9392 * Parse a do statement.
9394 static statement_t *parse_do(void)
9396 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9400 PUSH_PARENT(statement);
9401 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9403 add_anchor_token(T_while);
9404 statement->do_while.body = parse_loop_body(statement);
9405 rem_anchor_token(T_while);
9408 expression_t *const cond = parse_condition();
9409 statement->do_while.condition = cond;
9410 /* §6.8.5:2 The controlling expression of an iteration statement shall
9411 * have scalar type. */
9412 semantic_condition(cond, "condition of 'do-while'-statement");
9421 * Parse a for statement.
9423 static statement_t *parse_for(void)
9425 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9429 PUSH_PARENT(statement);
9430 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9433 add_anchor_token(')');
9438 } else if (is_declaration_specifier(&token)) {
9439 parse_declaration(record_entity, DECL_FLAGS_NONE);
9441 add_anchor_token(';');
9442 expression_t *const init = parse_expression();
9443 statement->fors.initialisation = init;
9444 mark_vars_read(init, ENT_ANY);
9445 if (!expression_has_effect(init)) {
9446 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9448 rem_anchor_token(';');
9454 if (token.kind != ';') {
9455 add_anchor_token(';');
9456 expression_t *const cond = parse_expression();
9457 statement->fors.condition = cond;
9458 /* §6.8.5:2 The controlling expression of an iteration statement
9459 * shall have scalar type. */
9460 semantic_condition(cond, "condition of 'for'-statement");
9461 mark_vars_read(cond, NULL);
9462 rem_anchor_token(';');
9465 if (token.kind != ')') {
9466 expression_t *const step = parse_expression();
9467 statement->fors.step = step;
9468 mark_vars_read(step, ENT_ANY);
9469 if (!expression_has_effect(step)) {
9470 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9473 rem_anchor_token(')');
9475 statement->fors.body = parse_loop_body(statement);
9483 * Parse a goto statement.
9485 static statement_t *parse_goto(void)
9487 statement_t *statement;
9488 if (GNU_MODE && look_ahead(1)->kind == '*') {
9489 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9493 expression_t *expression = parse_expression();
9494 mark_vars_read(expression, NULL);
9496 /* Argh: although documentation says the expression must be of type void*,
9497 * gcc accepts anything that can be casted into void* without error */
9498 type_t *type = expression->base.type;
9500 if (type != type_error_type) {
9501 if (!is_type_pointer(type) && !is_type_integer(type)) {
9502 errorf(&expression->base.source_position,
9503 "cannot convert to a pointer type");
9504 } else if (type != type_void_ptr) {
9505 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9507 expression = create_implicit_cast(expression, type_void_ptr);
9510 statement->computed_goto.expression = expression;
9512 statement = allocate_statement_zero(STATEMENT_GOTO);
9514 if (token.kind == T_IDENTIFIER) {
9515 label_t *const label = get_label();
9517 statement->gotos.label = label;
9519 /* remember the goto's in a list for later checking */
9520 *goto_anchor = &statement->gotos;
9521 goto_anchor = &statement->gotos.next;
9524 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9526 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9528 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9537 * Parse a continue statement.
9539 static statement_t *parse_continue(void)
9541 if (current_loop == NULL) {
9542 errorf(HERE, "continue statement not within loop");
9545 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9553 * Parse a break statement.
9555 static statement_t *parse_break(void)
9557 if (current_switch == NULL && current_loop == NULL) {
9558 errorf(HERE, "break statement not within loop or switch");
9561 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9569 * Parse a __leave statement.
9571 static statement_t *parse_leave_statement(void)
9573 if (current_try == NULL) {
9574 errorf(HERE, "__leave statement not within __try");
9577 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9585 * Check if a given entity represents a local variable.
9587 static bool is_local_variable(const entity_t *entity)
9589 if (entity->kind != ENTITY_VARIABLE)
9592 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9593 case STORAGE_CLASS_AUTO:
9594 case STORAGE_CLASS_REGISTER: {
9595 const type_t *type = skip_typeref(entity->declaration.type);
9596 if (is_type_function(type)) {
9608 * Check if a given expression represents a local variable.
9610 static bool expression_is_local_variable(const expression_t *expression)
9612 if (expression->base.kind != EXPR_REFERENCE) {
9615 const entity_t *entity = expression->reference.entity;
9616 return is_local_variable(entity);
9620 * Check if a given expression represents a local variable and
9621 * return its declaration then, else return NULL.
9623 entity_t *expression_is_variable(const expression_t *expression)
9625 if (expression->base.kind != EXPR_REFERENCE) {
9628 entity_t *entity = expression->reference.entity;
9629 if (entity->kind != ENTITY_VARIABLE)
9635 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9637 if (c_mode & _CXX || strict_mode) {
9640 warningf(WARN_OTHER, pos, msg);
9645 * Parse a return statement.
9647 static statement_t *parse_return(void)
9649 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9652 expression_t *return_value = NULL;
9653 if (token.kind != ';') {
9654 return_value = parse_expression();
9655 mark_vars_read(return_value, NULL);
9658 const type_t *const func_type = skip_typeref(current_function->base.type);
9659 assert(is_type_function(func_type));
9660 type_t *const return_type = skip_typeref(func_type->function.return_type);
9662 source_position_t const *const pos = &statement->base.source_position;
9663 if (return_value != NULL) {
9664 type_t *return_value_type = skip_typeref(return_value->base.type);
9666 if (is_type_void(return_type)) {
9667 if (!is_type_void(return_value_type)) {
9668 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9669 /* Only warn in C mode, because GCC does the same */
9670 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9671 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9672 /* Only warn in C mode, because GCC does the same */
9673 err_or_warn(pos, "'return' with expression in function returning 'void'");
9676 assign_error_t error = semantic_assign(return_type, return_value);
9677 report_assign_error(error, return_type, return_value, "'return'",
9680 return_value = create_implicit_cast(return_value, return_type);
9681 /* check for returning address of a local var */
9682 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9683 const expression_t *expression = return_value->unary.value;
9684 if (expression_is_local_variable(expression)) {
9685 warningf(WARN_OTHER, pos, "function returns address of local variable");
9688 } else if (!is_type_void(return_type)) {
9689 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9690 err_or_warn(pos, "'return' without value, in function returning non-void");
9692 statement->returns.value = return_value;
9699 * Parse a declaration statement.
9701 static statement_t *parse_declaration_statement(void)
9703 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9705 entity_t *before = current_scope->last_entity;
9707 parse_external_declaration();
9709 parse_declaration(record_entity, DECL_FLAGS_NONE);
9712 declaration_statement_t *const decl = &statement->declaration;
9713 entity_t *const begin =
9714 before != NULL ? before->base.next : current_scope->entities;
9715 decl->declarations_begin = begin;
9716 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9722 * Parse an expression statement, ie. expr ';'.
9724 static statement_t *parse_expression_statement(void)
9726 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9728 expression_t *const expr = parse_expression();
9729 statement->expression.expression = expr;
9730 mark_vars_read(expr, ENT_ANY);
9737 * Parse a microsoft __try { } __finally { } or
9738 * __try{ } __except() { }
9740 static statement_t *parse_ms_try_statment(void)
9742 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9745 PUSH_PARENT(statement);
9747 ms_try_statement_t *rem = current_try;
9748 current_try = &statement->ms_try;
9749 statement->ms_try.try_statement = parse_compound_statement(false);
9754 if (next_if(T___except)) {
9755 expression_t *const expr = parse_condition();
9756 type_t * type = skip_typeref(expr->base.type);
9757 if (is_type_integer(type)) {
9758 type = promote_integer(type);
9759 } else if (is_type_valid(type)) {
9760 errorf(&expr->base.source_position,
9761 "__expect expression is not an integer, but '%T'", type);
9762 type = type_error_type;
9764 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9765 } else if (!next_if(T__finally)) {
9766 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9768 statement->ms_try.final_statement = parse_compound_statement(false);
9772 static statement_t *parse_empty_statement(void)
9774 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9775 statement_t *const statement = create_empty_statement();
9780 static statement_t *parse_local_label_declaration(void)
9782 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9786 entity_t *begin = NULL;
9787 entity_t *end = NULL;
9788 entity_t **anchor = &begin;
9790 source_position_t pos;
9791 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9795 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9796 if (entity != NULL && entity->base.parent_scope == current_scope) {
9797 source_position_t const *const ppos = &entity->base.source_position;
9798 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9800 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9801 entity->base.parent_scope = current_scope;
9804 anchor = &entity->base.next;
9807 environment_push(entity);
9809 } while (next_if(','));
9812 statement->declaration.declarations_begin = begin;
9813 statement->declaration.declarations_end = end;
9817 static void parse_namespace_definition(void)
9821 entity_t *entity = NULL;
9822 symbol_t *symbol = NULL;
9824 if (token.kind == T_IDENTIFIER) {
9825 symbol = token.identifier.symbol;
9828 entity = get_entity(symbol, NAMESPACE_NORMAL);
9830 && entity->kind != ENTITY_NAMESPACE
9831 && entity->base.parent_scope == current_scope) {
9832 if (is_entity_valid(entity)) {
9833 error_redefined_as_different_kind(&token.base.source_position,
9834 entity, ENTITY_NAMESPACE);
9840 if (entity == NULL) {
9841 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9842 entity->base.parent_scope = current_scope;
9845 if (token.kind == '=') {
9846 /* TODO: parse namespace alias */
9847 panic("namespace alias definition not supported yet");
9850 environment_push(entity);
9851 append_entity(current_scope, entity);
9853 PUSH_SCOPE(&entity->namespacee.members);
9855 entity_t *old_current_entity = current_entity;
9856 current_entity = entity;
9858 add_anchor_token('}');
9861 rem_anchor_token('}');
9864 assert(current_entity == entity);
9865 current_entity = old_current_entity;
9870 * Parse a statement.
9871 * There's also parse_statement() which additionally checks for
9872 * "statement has no effect" warnings
9874 static statement_t *intern_parse_statement(void)
9876 /* declaration or statement */
9877 statement_t *statement;
9878 switch (token.kind) {
9879 case T_IDENTIFIER: {
9880 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9881 if (la1_type == ':') {
9882 statement = parse_label_statement();
9883 } else if (is_typedef_symbol(token.identifier.symbol)) {
9884 statement = parse_declaration_statement();
9886 /* it's an identifier, the grammar says this must be an
9887 * expression statement. However it is common that users mistype
9888 * declaration types, so we guess a bit here to improve robustness
9889 * for incorrect programs */
9893 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9895 statement = parse_expression_statement();
9899 statement = parse_declaration_statement();
9907 case T___extension__: {
9908 /* This can be a prefix to a declaration or an expression statement.
9909 * We simply eat it now and parse the rest with tail recursion. */
9911 statement = intern_parse_statement();
9917 statement = parse_declaration_statement();
9921 statement = parse_local_label_declaration();
9924 case ';': statement = parse_empty_statement(); break;
9925 case '{': statement = parse_compound_statement(false); break;
9926 case T___leave: statement = parse_leave_statement(); break;
9927 case T___try: statement = parse_ms_try_statment(); break;
9928 case T_asm: statement = parse_asm_statement(); break;
9929 case T_break: statement = parse_break(); break;
9930 case T_case: statement = parse_case_statement(); break;
9931 case T_continue: statement = parse_continue(); break;
9932 case T_default: statement = parse_default_statement(); break;
9933 case T_do: statement = parse_do(); break;
9934 case T_for: statement = parse_for(); break;
9935 case T_goto: statement = parse_goto(); break;
9936 case T_if: statement = parse_if(); break;
9937 case T_return: statement = parse_return(); break;
9938 case T_switch: statement = parse_switch(); break;
9939 case T_while: statement = parse_while(); break;
9942 statement = parse_expression_statement();
9946 errorf(HERE, "unexpected token %K while parsing statement", &token);
9947 statement = create_error_statement();
9956 * parse a statement and emits "statement has no effect" warning if needed
9957 * (This is really a wrapper around intern_parse_statement with check for 1
9958 * single warning. It is needed, because for statement expressions we have
9959 * to avoid the warning on the last statement)
9961 static statement_t *parse_statement(void)
9963 statement_t *statement = intern_parse_statement();
9965 if (statement->kind == STATEMENT_EXPRESSION) {
9966 expression_t *expression = statement->expression.expression;
9967 if (!expression_has_effect(expression)) {
9968 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9976 * Parse a compound statement.
9978 static statement_t *parse_compound_statement(bool inside_expression_statement)
9980 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9982 PUSH_PARENT(statement);
9983 PUSH_SCOPE(&statement->compound.scope);
9986 add_anchor_token('}');
9987 /* tokens, which can start a statement */
9988 /* TODO MS, __builtin_FOO */
9989 add_anchor_token('!');
9990 add_anchor_token('&');
9991 add_anchor_token('(');
9992 add_anchor_token('*');
9993 add_anchor_token('+');
9994 add_anchor_token('-');
9995 add_anchor_token(';');
9996 add_anchor_token('{');
9997 add_anchor_token('~');
9998 add_anchor_token(T_CHARACTER_CONSTANT);
9999 add_anchor_token(T_COLONCOLON);
10000 add_anchor_token(T_FLOATINGPOINT);
10001 add_anchor_token(T_IDENTIFIER);
10002 add_anchor_token(T_INTEGER);
10003 add_anchor_token(T_MINUSMINUS);
10004 add_anchor_token(T_PLUSPLUS);
10005 add_anchor_token(T_STRING_LITERAL);
10006 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10007 add_anchor_token(T_WIDE_STRING_LITERAL);
10008 add_anchor_token(T__Bool);
10009 add_anchor_token(T__Complex);
10010 add_anchor_token(T__Imaginary);
10011 add_anchor_token(T___FUNCTION__);
10012 add_anchor_token(T___PRETTY_FUNCTION__);
10013 add_anchor_token(T___alignof__);
10014 add_anchor_token(T___attribute__);
10015 add_anchor_token(T___builtin_va_start);
10016 add_anchor_token(T___extension__);
10017 add_anchor_token(T___func__);
10018 add_anchor_token(T___imag__);
10019 add_anchor_token(T___label__);
10020 add_anchor_token(T___real__);
10021 add_anchor_token(T___thread);
10022 add_anchor_token(T_asm);
10023 add_anchor_token(T_auto);
10024 add_anchor_token(T_bool);
10025 add_anchor_token(T_break);
10026 add_anchor_token(T_case);
10027 add_anchor_token(T_char);
10028 add_anchor_token(T_class);
10029 add_anchor_token(T_const);
10030 add_anchor_token(T_const_cast);
10031 add_anchor_token(T_continue);
10032 add_anchor_token(T_default);
10033 add_anchor_token(T_delete);
10034 add_anchor_token(T_double);
10035 add_anchor_token(T_do);
10036 add_anchor_token(T_dynamic_cast);
10037 add_anchor_token(T_enum);
10038 add_anchor_token(T_extern);
10039 add_anchor_token(T_false);
10040 add_anchor_token(T_float);
10041 add_anchor_token(T_for);
10042 add_anchor_token(T_goto);
10043 add_anchor_token(T_if);
10044 add_anchor_token(T_inline);
10045 add_anchor_token(T_int);
10046 add_anchor_token(T_long);
10047 add_anchor_token(T_new);
10048 add_anchor_token(T_operator);
10049 add_anchor_token(T_register);
10050 add_anchor_token(T_reinterpret_cast);
10051 add_anchor_token(T_restrict);
10052 add_anchor_token(T_return);
10053 add_anchor_token(T_short);
10054 add_anchor_token(T_signed);
10055 add_anchor_token(T_sizeof);
10056 add_anchor_token(T_static);
10057 add_anchor_token(T_static_cast);
10058 add_anchor_token(T_struct);
10059 add_anchor_token(T_switch);
10060 add_anchor_token(T_template);
10061 add_anchor_token(T_this);
10062 add_anchor_token(T_throw);
10063 add_anchor_token(T_true);
10064 add_anchor_token(T_try);
10065 add_anchor_token(T_typedef);
10066 add_anchor_token(T_typeid);
10067 add_anchor_token(T_typename);
10068 add_anchor_token(T_typeof);
10069 add_anchor_token(T_union);
10070 add_anchor_token(T_unsigned);
10071 add_anchor_token(T_using);
10072 add_anchor_token(T_void);
10073 add_anchor_token(T_volatile);
10074 add_anchor_token(T_wchar_t);
10075 add_anchor_token(T_while);
10077 statement_t **anchor = &statement->compound.statements;
10078 bool only_decls_so_far = true;
10079 while (token.kind != '}' && token.kind != T_EOF) {
10080 statement_t *sub_statement = intern_parse_statement();
10081 if (sub_statement->kind == STATEMENT_ERROR) {
10085 if (sub_statement->kind != STATEMENT_DECLARATION) {
10086 only_decls_so_far = false;
10087 } else if (!only_decls_so_far) {
10088 source_position_t const *const pos = &sub_statement->base.source_position;
10089 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10092 *anchor = sub_statement;
10093 anchor = &sub_statement->base.next;
10097 /* look over all statements again to produce no effect warnings */
10098 if (is_warn_on(WARN_UNUSED_VALUE)) {
10099 statement_t *sub_statement = statement->compound.statements;
10100 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10101 if (sub_statement->kind != STATEMENT_EXPRESSION)
10103 /* don't emit a warning for the last expression in an expression
10104 * statement as it has always an effect */
10105 if (inside_expression_statement && sub_statement->base.next == NULL)
10108 expression_t *expression = sub_statement->expression.expression;
10109 if (!expression_has_effect(expression)) {
10110 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10115 rem_anchor_token(T_while);
10116 rem_anchor_token(T_wchar_t);
10117 rem_anchor_token(T_volatile);
10118 rem_anchor_token(T_void);
10119 rem_anchor_token(T_using);
10120 rem_anchor_token(T_unsigned);
10121 rem_anchor_token(T_union);
10122 rem_anchor_token(T_typeof);
10123 rem_anchor_token(T_typename);
10124 rem_anchor_token(T_typeid);
10125 rem_anchor_token(T_typedef);
10126 rem_anchor_token(T_try);
10127 rem_anchor_token(T_true);
10128 rem_anchor_token(T_throw);
10129 rem_anchor_token(T_this);
10130 rem_anchor_token(T_template);
10131 rem_anchor_token(T_switch);
10132 rem_anchor_token(T_struct);
10133 rem_anchor_token(T_static_cast);
10134 rem_anchor_token(T_static);
10135 rem_anchor_token(T_sizeof);
10136 rem_anchor_token(T_signed);
10137 rem_anchor_token(T_short);
10138 rem_anchor_token(T_return);
10139 rem_anchor_token(T_restrict);
10140 rem_anchor_token(T_reinterpret_cast);
10141 rem_anchor_token(T_register);
10142 rem_anchor_token(T_operator);
10143 rem_anchor_token(T_new);
10144 rem_anchor_token(T_long);
10145 rem_anchor_token(T_int);
10146 rem_anchor_token(T_inline);
10147 rem_anchor_token(T_if);
10148 rem_anchor_token(T_goto);
10149 rem_anchor_token(T_for);
10150 rem_anchor_token(T_float);
10151 rem_anchor_token(T_false);
10152 rem_anchor_token(T_extern);
10153 rem_anchor_token(T_enum);
10154 rem_anchor_token(T_dynamic_cast);
10155 rem_anchor_token(T_do);
10156 rem_anchor_token(T_double);
10157 rem_anchor_token(T_delete);
10158 rem_anchor_token(T_default);
10159 rem_anchor_token(T_continue);
10160 rem_anchor_token(T_const_cast);
10161 rem_anchor_token(T_const);
10162 rem_anchor_token(T_class);
10163 rem_anchor_token(T_char);
10164 rem_anchor_token(T_case);
10165 rem_anchor_token(T_break);
10166 rem_anchor_token(T_bool);
10167 rem_anchor_token(T_auto);
10168 rem_anchor_token(T_asm);
10169 rem_anchor_token(T___thread);
10170 rem_anchor_token(T___real__);
10171 rem_anchor_token(T___label__);
10172 rem_anchor_token(T___imag__);
10173 rem_anchor_token(T___func__);
10174 rem_anchor_token(T___extension__);
10175 rem_anchor_token(T___builtin_va_start);
10176 rem_anchor_token(T___attribute__);
10177 rem_anchor_token(T___alignof__);
10178 rem_anchor_token(T___PRETTY_FUNCTION__);
10179 rem_anchor_token(T___FUNCTION__);
10180 rem_anchor_token(T__Imaginary);
10181 rem_anchor_token(T__Complex);
10182 rem_anchor_token(T__Bool);
10183 rem_anchor_token(T_WIDE_STRING_LITERAL);
10184 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10185 rem_anchor_token(T_STRING_LITERAL);
10186 rem_anchor_token(T_PLUSPLUS);
10187 rem_anchor_token(T_MINUSMINUS);
10188 rem_anchor_token(T_INTEGER);
10189 rem_anchor_token(T_IDENTIFIER);
10190 rem_anchor_token(T_FLOATINGPOINT);
10191 rem_anchor_token(T_COLONCOLON);
10192 rem_anchor_token(T_CHARACTER_CONSTANT);
10193 rem_anchor_token('~');
10194 rem_anchor_token('{');
10195 rem_anchor_token(';');
10196 rem_anchor_token('-');
10197 rem_anchor_token('+');
10198 rem_anchor_token('*');
10199 rem_anchor_token('(');
10200 rem_anchor_token('&');
10201 rem_anchor_token('!');
10202 rem_anchor_token('}');
10210 * Check for unused global static functions and variables
10212 static void check_unused_globals(void)
10214 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10217 for (const entity_t *entity = file_scope->entities; entity != NULL;
10218 entity = entity->base.next) {
10219 if (!is_declaration(entity))
10222 const declaration_t *declaration = &entity->declaration;
10223 if (declaration->used ||
10224 declaration->modifiers & DM_UNUSED ||
10225 declaration->modifiers & DM_USED ||
10226 declaration->storage_class != STORAGE_CLASS_STATIC)
10231 if (entity->kind == ENTITY_FUNCTION) {
10232 /* inhibit warning for static inline functions */
10233 if (entity->function.is_inline)
10236 why = WARN_UNUSED_FUNCTION;
10237 s = entity->function.statement != NULL ? "defined" : "declared";
10239 why = WARN_UNUSED_VARIABLE;
10243 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10247 static void parse_global_asm(void)
10249 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10252 add_anchor_token(';');
10253 add_anchor_token(')');
10254 add_anchor_token(T_STRING_LITERAL);
10257 rem_anchor_token(T_STRING_LITERAL);
10258 statement->asms.asm_text = parse_string_literals();
10259 statement->base.next = unit->global_asm;
10260 unit->global_asm = statement;
10262 rem_anchor_token(')');
10264 rem_anchor_token(';');
10268 static void parse_linkage_specification(void)
10272 source_position_t const pos = *HERE;
10273 char const *const linkage = parse_string_literals().begin;
10275 linkage_kind_t old_linkage = current_linkage;
10276 linkage_kind_t new_linkage;
10277 if (streq(linkage, "C")) {
10278 new_linkage = LINKAGE_C;
10279 } else if (streq(linkage, "C++")) {
10280 new_linkage = LINKAGE_CXX;
10282 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10283 new_linkage = LINKAGE_C;
10285 current_linkage = new_linkage;
10287 if (next_if('{')) {
10294 assert(current_linkage == new_linkage);
10295 current_linkage = old_linkage;
10298 static void parse_external(void)
10300 switch (token.kind) {
10302 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10303 parse_linkage_specification();
10305 DECLARATION_START_NO_EXTERN
10307 case T___extension__:
10308 /* tokens below are for implicit int */
10309 case '&': /* & x; -> int& x; (and error later, because C++ has no
10311 case '*': /* * x; -> int* x; */
10312 case '(': /* (x); -> int (x); */
10314 parse_external_declaration();
10320 parse_global_asm();
10324 parse_namespace_definition();
10328 if (!strict_mode) {
10329 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10336 errorf(HERE, "stray %K outside of function", &token);
10337 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10338 eat_until_matching_token(token.kind);
10344 static void parse_externals(void)
10346 add_anchor_token('}');
10347 add_anchor_token(T_EOF);
10350 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10351 unsigned short token_anchor_copy[T_LAST_TOKEN];
10352 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10355 while (token.kind != T_EOF && token.kind != '}') {
10357 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10358 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10360 /* the anchor set and its copy differs */
10361 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10364 if (in_gcc_extension) {
10365 /* an gcc extension scope was not closed */
10366 internal_errorf(HERE, "Leaked __extension__");
10373 rem_anchor_token(T_EOF);
10374 rem_anchor_token('}');
10378 * Parse a translation unit.
10380 static void parse_translation_unit(void)
10382 add_anchor_token(T_EOF);
10387 if (token.kind == T_EOF)
10390 errorf(HERE, "stray %K outside of function", &token);
10391 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10392 eat_until_matching_token(token.kind);
10397 void set_default_visibility(elf_visibility_tag_t visibility)
10399 default_visibility = visibility;
10405 * @return the translation unit or NULL if errors occurred.
10407 void start_parsing(void)
10409 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10410 label_stack = NEW_ARR_F(stack_entry_t, 0);
10411 diagnostic_count = 0;
10415 print_to_file(stderr);
10417 assert(unit == NULL);
10418 unit = allocate_ast_zero(sizeof(unit[0]));
10420 assert(file_scope == NULL);
10421 file_scope = &unit->scope;
10423 assert(current_scope == NULL);
10424 scope_push(&unit->scope);
10426 create_gnu_builtins();
10428 create_microsoft_intrinsics();
10431 translation_unit_t *finish_parsing(void)
10433 assert(current_scope == &unit->scope);
10436 assert(file_scope == &unit->scope);
10437 check_unused_globals();
10440 DEL_ARR_F(environment_stack);
10441 DEL_ARR_F(label_stack);
10443 translation_unit_t *result = unit;
10448 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10449 * are given length one. */
10450 static void complete_incomplete_arrays(void)
10452 size_t n = ARR_LEN(incomplete_arrays);
10453 for (size_t i = 0; i != n; ++i) {
10454 declaration_t *const decl = incomplete_arrays[i];
10455 type_t *const type = skip_typeref(decl->type);
10457 if (!is_type_incomplete(type))
10460 source_position_t const *const pos = &decl->base.source_position;
10461 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10463 type_t *const new_type = duplicate_type(type);
10464 new_type->array.size_constant = true;
10465 new_type->array.has_implicit_size = true;
10466 new_type->array.size = 1;
10468 type_t *const result = identify_new_type(new_type);
10470 decl->type = result;
10474 void prepare_main_collect2(entity_t *entity)
10476 PUSH_SCOPE(&entity->function.statement->compound.scope);
10478 // create call to __main
10479 symbol_t *symbol = symbol_table_insert("__main");
10480 entity_t *subsubmain_ent
10481 = create_implicit_function(symbol, &builtin_source_position);
10483 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10484 type_t *ftype = subsubmain_ent->declaration.type;
10485 ref->base.source_position = builtin_source_position;
10486 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10487 ref->reference.entity = subsubmain_ent;
10489 expression_t *call = allocate_expression_zero(EXPR_CALL);
10490 call->base.source_position = builtin_source_position;
10491 call->base.type = type_void;
10492 call->call.function = ref;
10494 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10495 expr_statement->base.source_position = builtin_source_position;
10496 expr_statement->expression.expression = call;
10498 statement_t *statement = entity->function.statement;
10499 assert(statement->kind == STATEMENT_COMPOUND);
10500 compound_statement_t *compounds = &statement->compound;
10502 expr_statement->base.next = compounds->statements;
10503 compounds->statements = expr_statement;
10510 lookahead_bufpos = 0;
10511 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10514 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10515 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10516 parse_translation_unit();
10517 complete_incomplete_arrays();
10518 DEL_ARR_F(incomplete_arrays);
10519 incomplete_arrays = NULL;
10523 * Initialize the parser.
10525 void init_parser(void)
10527 sym_anonymous = symbol_table_insert("<anonymous>");
10529 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10531 init_expression_parsers();
10532 obstack_init(&temp_obst);
10536 * Terminate the parser.
10538 void exit_parser(void)
10540 obstack_free(&temp_obst, NULL);