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_CURRENT_ENTITY(entity) \
113 entity_t *const new_current_entity = (entity); \
114 entity_t *const old_current_entity = current_entity; \
115 ((void)(current_entity = new_current_entity))
116 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
118 #define PUSH_PARENT(stmt) \
119 statement_t *const new_parent = (stmt); \
120 statement_t *const old_parent = current_parent; \
121 ((void)(current_parent = new_parent))
122 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
124 #define PUSH_SCOPE(scope) \
125 size_t const top = environment_top(); \
126 scope_t *const new_scope = (scope); \
127 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
128 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
129 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
131 #define PUSH_EXTENSION() \
133 bool const old_gcc_extension = in_gcc_extension; \
134 while (next_if(T___extension__)) { \
135 in_gcc_extension = true; \
138 #define POP_EXTENSION() \
139 ((void)(in_gcc_extension = old_gcc_extension))
141 /** special symbol used for anonymous entities. */
142 static symbol_t *sym_anonymous = NULL;
144 /** The token anchor set */
145 static unsigned short token_anchor_set[T_LAST_TOKEN];
147 /** The current source position. */
148 #define HERE (&token.base.source_position)
150 /** true if we are in GCC mode. */
151 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
153 static statement_t *parse_compound_statement(bool inside_expression_statement);
154 static statement_t *parse_statement(void);
156 static expression_t *parse_subexpression(precedence_t);
157 static expression_t *parse_expression(void);
158 static type_t *parse_typename(void);
159 static void parse_externals(void);
160 static void parse_external(void);
162 static void parse_compound_type_entries(compound_t *compound_declaration);
164 static void check_call_argument(type_t *expected_type,
165 call_argument_t *argument, unsigned pos);
167 typedef enum declarator_flags_t {
169 DECL_MAY_BE_ABSTRACT = 1U << 0,
170 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
171 DECL_IS_PARAMETER = 1U << 2
172 } declarator_flags_t;
174 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
175 declarator_flags_t flags);
177 static void semantic_comparison(binary_expression_t *expression);
179 #define STORAGE_CLASSES \
180 STORAGE_CLASSES_NO_EXTERN \
183 #define STORAGE_CLASSES_NO_EXTERN \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #define COMPLEX_SPECIFIERS \
200 #define IMAGINARY_SPECIFIERS \
203 #define TYPE_SPECIFIERS \
205 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define DECLARATION_START_NO_EXTERN \
236 STORAGE_CLASSES_NO_EXTERN \
240 #define EXPRESSION_START \
249 case T_CHARACTER_CONSTANT: \
250 case T_FLOATINGPOINT: \
251 case T_FLOATINGPOINT_HEXADECIMAL: \
255 case T_STRING_LITERAL: \
256 case T_WIDE_CHARACTER_CONSTANT: \
257 case T_WIDE_STRING_LITERAL: \
258 case T___FUNCDNAME__: \
259 case T___FUNCSIG__: \
260 case T___FUNCTION__: \
261 case T___PRETTY_FUNCTION__: \
262 case T___alignof__: \
263 case T___builtin_classify_type: \
264 case T___builtin_constant_p: \
265 case T___builtin_isgreater: \
266 case T___builtin_isgreaterequal: \
267 case T___builtin_isless: \
268 case T___builtin_islessequal: \
269 case T___builtin_islessgreater: \
270 case T___builtin_isunordered: \
271 case T___builtin_offsetof: \
272 case T___builtin_va_arg: \
273 case T___builtin_va_copy: \
274 case T___builtin_va_start: \
285 * Returns the size of a statement node.
287 * @param kind the statement kind
289 static size_t get_statement_struct_size(statement_kind_t kind)
291 static const size_t sizes[] = {
292 [STATEMENT_ERROR] = sizeof(statement_base_t),
293 [STATEMENT_EMPTY] = sizeof(statement_base_t),
294 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
295 [STATEMENT_RETURN] = sizeof(return_statement_t),
296 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
297 [STATEMENT_IF] = sizeof(if_statement_t),
298 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
299 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
300 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
301 [STATEMENT_BREAK] = sizeof(statement_base_t),
302 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
303 [STATEMENT_GOTO] = sizeof(goto_statement_t),
304 [STATEMENT_LABEL] = sizeof(label_statement_t),
305 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
306 [STATEMENT_WHILE] = sizeof(while_statement_t),
307 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
308 [STATEMENT_FOR] = sizeof(for_statement_t),
309 [STATEMENT_ASM] = sizeof(asm_statement_t),
310 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
311 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
313 assert((size_t)kind < lengthof(sizes));
314 assert(sizes[kind] != 0);
319 * Returns the size of an expression node.
321 * @param kind the expression kind
323 static size_t get_expression_struct_size(expression_kind_t kind)
325 static const size_t sizes[] = {
326 [EXPR_ERROR] = sizeof(expression_base_t),
327 [EXPR_REFERENCE] = sizeof(reference_expression_t),
328 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
329 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
332 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
333 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
334 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
335 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
336 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
337 [EXPR_CALL] = sizeof(call_expression_t),
338 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
339 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
340 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
341 [EXPR_SELECT] = sizeof(select_expression_t),
342 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
343 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
344 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
345 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
346 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
347 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
348 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
349 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
350 [EXPR_VA_START] = sizeof(va_start_expression_t),
351 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
352 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
353 [EXPR_STATEMENT] = sizeof(statement_expression_t),
354 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
356 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
357 return sizes[EXPR_UNARY_FIRST];
359 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
360 return sizes[EXPR_BINARY_FIRST];
362 assert((size_t)kind < lengthof(sizes));
363 assert(sizes[kind] != 0);
368 * Allocate a statement node of given kind and initialize all
369 * fields with zero. Sets its source position to the position
370 * of the current token.
372 static statement_t *allocate_statement_zero(statement_kind_t kind)
374 size_t size = get_statement_struct_size(kind);
375 statement_t *res = allocate_ast_zero(size);
377 res->base.kind = kind;
378 res->base.parent = current_parent;
379 res->base.source_position = token.base.source_position;
384 * Allocate an expression node of given kind and initialize all
387 * @param kind the kind of the expression to allocate
389 static expression_t *allocate_expression_zero(expression_kind_t kind)
391 size_t size = get_expression_struct_size(kind);
392 expression_t *res = allocate_ast_zero(size);
394 res->base.kind = kind;
395 res->base.type = type_error_type;
396 res->base.source_position = token.base.source_position;
401 * Creates a new invalid expression at the source position
402 * of the current token.
404 static expression_t *create_error_expression(void)
406 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
407 expression->base.type = type_error_type;
412 * Creates a new invalid statement.
414 static statement_t *create_error_statement(void)
416 return allocate_statement_zero(STATEMENT_ERROR);
420 * Allocate a new empty statement.
422 static statement_t *create_empty_statement(void)
424 return allocate_statement_zero(STATEMENT_EMPTY);
428 * Returns the size of an initializer node.
430 * @param kind the initializer kind
432 static size_t get_initializer_size(initializer_kind_t kind)
434 static const size_t sizes[] = {
435 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
436 [INITIALIZER_STRING] = sizeof(initializer_string_t),
437 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
438 [INITIALIZER_LIST] = sizeof(initializer_list_t),
439 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
441 assert((size_t)kind < lengthof(sizes));
442 assert(sizes[kind] != 0);
447 * Allocate an initializer node of given kind and initialize all
450 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
452 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
459 * Returns the index of the top element of the environment stack.
461 static size_t environment_top(void)
463 return ARR_LEN(environment_stack);
467 * Returns the index of the top element of the global label stack.
469 static size_t label_top(void)
471 return ARR_LEN(label_stack);
475 * Return the next token.
477 static inline void next_token(void)
479 token = lookahead_buffer[lookahead_bufpos];
480 lookahead_buffer[lookahead_bufpos] = lexer_token;
483 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
486 print_token(stderr, &token);
487 fprintf(stderr, "\n");
491 static inline bool next_if(token_kind_t const type)
493 if (token.kind == type) {
502 * Return the next token with a given lookahead.
504 static inline const token_t *look_ahead(size_t num)
506 assert(0 < num && num <= MAX_LOOKAHEAD);
507 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
508 return &lookahead_buffer[pos];
512 * Adds a token type to the token type anchor set (a multi-set).
514 static void add_anchor_token(token_kind_t const token_kind)
516 assert(token_kind < T_LAST_TOKEN);
517 ++token_anchor_set[token_kind];
521 * Remove a token type from the token type anchor set (a multi-set).
523 static void rem_anchor_token(token_kind_t const token_kind)
525 assert(token_kind < T_LAST_TOKEN);
526 assert(token_anchor_set[token_kind] != 0);
527 --token_anchor_set[token_kind];
531 * Eat tokens until a matching token type is found.
533 static void eat_until_matching_token(token_kind_t const type)
535 token_kind_t end_token;
537 case '(': end_token = ')'; break;
538 case '{': end_token = '}'; break;
539 case '[': end_token = ']'; break;
540 default: end_token = type; break;
543 unsigned parenthesis_count = 0;
544 unsigned brace_count = 0;
545 unsigned bracket_count = 0;
546 while (token.kind != end_token ||
547 parenthesis_count != 0 ||
549 bracket_count != 0) {
550 switch (token.kind) {
552 case '(': ++parenthesis_count; break;
553 case '{': ++brace_count; break;
554 case '[': ++bracket_count; break;
557 if (parenthesis_count > 0)
567 if (bracket_count > 0)
570 if (token.kind == end_token &&
571 parenthesis_count == 0 &&
585 * Eat input tokens until an anchor is found.
587 static void eat_until_anchor(void)
589 while (token_anchor_set[token.kind] == 0) {
590 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
591 eat_until_matching_token(token.kind);
597 * Eat a whole block from input tokens.
599 static void eat_block(void)
601 eat_until_matching_token('{');
605 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
608 * Report a parse error because an expected token was not found.
611 #if defined __GNUC__ && __GNUC__ >= 4
612 __attribute__((sentinel))
614 void parse_error_expected(const char *message, ...)
616 if (message != NULL) {
617 errorf(HERE, "%s", message);
620 va_start(ap, message);
621 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
626 * Report an incompatible type.
628 static void type_error_incompatible(const char *msg,
629 const source_position_t *source_position, type_t *type1, type_t *type2)
631 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
636 * Expect the current token is the expected token.
637 * If not, generate an error and skip until the next anchor.
639 static void expect(token_kind_t const expected)
641 if (UNLIKELY(token.kind != expected)) {
642 parse_error_expected(NULL, expected, NULL);
643 add_anchor_token(expected);
645 rem_anchor_token(expected);
646 if (token.kind != expected)
652 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
654 if (token.kind != T_IDENTIFIER) {
655 parse_error_expected(context, T_IDENTIFIER, NULL);
656 add_anchor_token(T_IDENTIFIER);
658 rem_anchor_token(T_IDENTIFIER);
659 if (token.kind != T_IDENTIFIER)
662 symbol_t *const sym = token.identifier.symbol;
670 * Push a given scope on the scope stack and make it the
673 static scope_t *scope_push(scope_t *new_scope)
675 if (current_scope != NULL) {
676 new_scope->depth = current_scope->depth + 1;
679 scope_t *old_scope = current_scope;
680 current_scope = new_scope;
685 * Pop the current scope from the scope stack.
687 static void scope_pop(scope_t *old_scope)
689 current_scope = old_scope;
693 * Search an entity by its symbol in a given namespace.
695 static entity_t *get_entity(const symbol_t *const symbol,
696 namespace_tag_t namespc)
698 entity_t *entity = symbol->entity;
699 for (; entity != NULL; entity = entity->base.symbol_next) {
700 if ((namespace_tag_t)entity->base.namespc == namespc)
707 /* §6.2.3:1 24) There is only one name space for tags even though three are
709 static entity_t *get_tag(symbol_t const *const symbol,
710 entity_kind_tag_t const kind)
712 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
713 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
715 "'%Y' defined as wrong kind of tag (previous definition %P)",
716 symbol, &entity->base.source_position);
723 * pushs an entity on the environment stack and links the corresponding symbol
726 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
728 symbol_t *symbol = entity->base.symbol;
729 entity_namespace_t namespc = entity->base.namespc;
730 assert(namespc != 0);
732 /* replace/add entity into entity list of the symbol */
735 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
740 /* replace an entry? */
741 if (iter->base.namespc == namespc) {
742 entity->base.symbol_next = iter->base.symbol_next;
748 /* remember old declaration */
750 entry.symbol = symbol;
751 entry.old_entity = iter;
752 entry.namespc = namespc;
753 ARR_APP1(stack_entry_t, *stack_ptr, entry);
757 * Push an entity on the environment stack.
759 static void environment_push(entity_t *entity)
761 assert(entity->base.source_position.input_name != NULL);
762 assert(entity->base.parent_scope != NULL);
763 stack_push(&environment_stack, entity);
767 * Push a declaration on the global label stack.
769 * @param declaration the declaration
771 static void label_push(entity_t *label)
773 /* we abuse the parameters scope as parent for the labels */
774 label->base.parent_scope = ¤t_function->parameters;
775 stack_push(&label_stack, label);
779 * pops symbols from the environment stack until @p new_top is the top element
781 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
783 stack_entry_t *stack = *stack_ptr;
784 size_t top = ARR_LEN(stack);
787 assert(new_top <= top);
791 for (i = top; i > new_top; --i) {
792 stack_entry_t *entry = &stack[i - 1];
794 entity_t *old_entity = entry->old_entity;
795 symbol_t *symbol = entry->symbol;
796 entity_namespace_t namespc = entry->namespc;
798 /* replace with old_entity/remove */
801 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
803 assert(iter != NULL);
804 /* replace an entry? */
805 if (iter->base.namespc == namespc)
809 /* restore definition from outer scopes (if there was one) */
810 if (old_entity != NULL) {
811 old_entity->base.symbol_next = iter->base.symbol_next;
812 *anchor = old_entity;
814 /* remove entry from list */
815 *anchor = iter->base.symbol_next;
819 ARR_SHRINKLEN(*stack_ptr, new_top);
823 * Pop all entries from the environment stack until the new_top
826 * @param new_top the new stack top
828 static void environment_pop_to(size_t new_top)
830 stack_pop_to(&environment_stack, new_top);
834 * Pop all entries from the global label stack until the new_top
837 * @param new_top the new stack top
839 static void label_pop_to(size_t new_top)
841 stack_pop_to(&label_stack, new_top);
844 static atomic_type_kind_t get_akind(const type_t *type)
846 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
847 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
848 return type->atomic.akind;
852 * §6.3.1.1:2 Do integer promotion for a given type.
854 * @param type the type to promote
855 * @return the promoted type
857 static type_t *promote_integer(type_t *type)
859 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
866 * Check if a given expression represents a null pointer constant.
868 * @param expression the expression to check
870 static bool is_null_pointer_constant(const expression_t *expression)
872 /* skip void* cast */
873 if (expression->kind == EXPR_UNARY_CAST) {
874 type_t *const type = skip_typeref(expression->base.type);
875 if (types_compatible(type, type_void_ptr))
876 expression = expression->unary.value;
879 type_t *const type = skip_typeref(expression->base.type);
880 if (!is_type_integer(type))
882 switch (is_constant_expression(expression)) {
883 case EXPR_CLASS_ERROR: return true;
884 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
885 default: return false;
890 * Create an implicit cast expression.
892 * @param expression the expression to cast
893 * @param dest_type the destination type
895 static expression_t *create_implicit_cast(expression_t *expression,
898 type_t *const source_type = expression->base.type;
900 if (source_type == dest_type)
903 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
904 cast->unary.value = expression;
905 cast->base.type = dest_type;
906 cast->base.implicit = true;
911 typedef enum assign_error_t {
913 ASSIGN_ERROR_INCOMPATIBLE,
914 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
915 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
916 ASSIGN_WARNING_POINTER_FROM_INT,
917 ASSIGN_WARNING_INT_FROM_POINTER
920 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)
922 type_t *const orig_type_right = right->base.type;
923 type_t *const type_left = skip_typeref(orig_type_left);
924 type_t *const type_right = skip_typeref(orig_type_right);
929 case ASSIGN_ERROR_INCOMPATIBLE:
930 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
933 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
934 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
935 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
937 /* the left type has all qualifiers from the right type */
938 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
939 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);
943 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
944 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
947 case ASSIGN_WARNING_POINTER_FROM_INT:
948 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
951 case ASSIGN_WARNING_INT_FROM_POINTER:
952 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
956 panic("invalid error value");
960 /** Implements the rules from §6.5.16.1 */
961 static assign_error_t semantic_assign(type_t *orig_type_left,
962 const expression_t *const right)
964 type_t *const orig_type_right = right->base.type;
965 type_t *const type_left = skip_typeref(orig_type_left);
966 type_t *const type_right = skip_typeref(orig_type_right);
968 if (is_type_pointer(type_left)) {
969 if (is_null_pointer_constant(right)) {
970 return ASSIGN_SUCCESS;
971 } else if (is_type_pointer(type_right)) {
972 type_t *points_to_left
973 = skip_typeref(type_left->pointer.points_to);
974 type_t *points_to_right
975 = skip_typeref(type_right->pointer.points_to);
976 assign_error_t res = ASSIGN_SUCCESS;
978 /* the left type has all qualifiers from the right type */
979 unsigned missing_qualifiers
980 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
981 if (missing_qualifiers != 0) {
982 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
985 points_to_left = get_unqualified_type(points_to_left);
986 points_to_right = get_unqualified_type(points_to_right);
988 if (is_type_void(points_to_left))
991 if (is_type_void(points_to_right)) {
992 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
993 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
996 if (!types_compatible(points_to_left, points_to_right)) {
997 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1001 } else if (is_type_integer(type_right)) {
1002 return ASSIGN_WARNING_POINTER_FROM_INT;
1004 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1005 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1006 && is_type_pointer(type_right))) {
1007 return ASSIGN_SUCCESS;
1008 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1009 type_t *const unqual_type_left = get_unqualified_type(type_left);
1010 type_t *const unqual_type_right = get_unqualified_type(type_right);
1011 if (types_compatible(unqual_type_left, unqual_type_right)) {
1012 return ASSIGN_SUCCESS;
1014 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1015 return ASSIGN_WARNING_INT_FROM_POINTER;
1018 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1019 return ASSIGN_SUCCESS;
1021 return ASSIGN_ERROR_INCOMPATIBLE;
1024 static expression_t *parse_constant_expression(void)
1026 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1028 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1029 errorf(&result->base.source_position,
1030 "expression '%E' is not constant", result);
1036 static expression_t *parse_assignment_expression(void)
1038 return parse_subexpression(PREC_ASSIGNMENT);
1041 static void warn_string_concat(const source_position_t *pos)
1043 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1046 static string_t parse_string_literals(void)
1048 assert(token.kind == T_STRING_LITERAL);
1049 string_t result = token.string.string;
1053 while (token.kind == T_STRING_LITERAL) {
1054 warn_string_concat(&token.base.source_position);
1055 result = concat_strings(&result, &token.string.string);
1062 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1064 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1065 attribute->kind = kind;
1066 attribute->source_position = *HERE;
1071 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1074 * __attribute__ ( ( attribute-list ) )
1078 * attribute_list , attrib
1083 * any-word ( identifier )
1084 * any-word ( identifier , nonempty-expr-list )
1085 * any-word ( expr-list )
1087 * where the "identifier" must not be declared as a type, and
1088 * "any-word" may be any identifier (including one declared as a
1089 * type), a reserved word storage class specifier, type specifier or
1090 * type qualifier. ??? This still leaves out most reserved keywords
1091 * (following the old parser), shouldn't we include them, and why not
1092 * allow identifiers declared as types to start the arguments?
1094 * Matze: this all looks confusing and little systematic, so we're even less
1095 * strict and parse any list of things which are identifiers or
1096 * (assignment-)expressions.
1098 static attribute_argument_t *parse_attribute_arguments(void)
1100 attribute_argument_t *first = NULL;
1101 attribute_argument_t **anchor = &first;
1102 if (token.kind != ')') do {
1103 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1105 /* is it an identifier */
1106 if (token.kind == T_IDENTIFIER
1107 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1108 symbol_t *symbol = token.identifier.symbol;
1109 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1110 argument->v.symbol = symbol;
1113 /* must be an expression */
1114 expression_t *expression = parse_assignment_expression();
1116 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1117 argument->v.expression = expression;
1120 /* append argument */
1122 anchor = &argument->next;
1123 } while (next_if(','));
1128 static attribute_t *parse_attribute_asm(void)
1130 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1133 attribute->a.arguments = parse_attribute_arguments();
1137 static symbol_t *get_symbol_from_token(void)
1139 switch(token.kind) {
1140 case T_CHARACTER_CONSTANT:
1142 case T_FLOATINGPOINT:
1143 case T_FLOATINGPOINT_HEXADECIMAL:
1145 case T_STRING_LITERAL:
1146 case T_WIDE_CHARACTER_CONSTANT:
1147 case T_WIDE_STRING_LITERAL:
1151 return token.identifier.symbol;
1155 static attribute_t *parse_attribute_gnu_single(void)
1157 /* parse "any-word" */
1158 symbol_t *symbol = get_symbol_from_token();
1159 if (symbol == NULL) {
1160 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1164 attribute_kind_t kind;
1165 char const *const name = symbol->string;
1166 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1167 if (kind > ATTRIBUTE_GNU_LAST) {
1168 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1169 /* TODO: we should still save the attribute in the list... */
1170 kind = ATTRIBUTE_UNKNOWN;
1174 const char *attribute_name = get_attribute_name(kind);
1175 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1179 attribute_t *attribute = allocate_attribute_zero(kind);
1182 /* parse arguments */
1184 attribute->a.arguments = parse_attribute_arguments();
1189 static attribute_t *parse_attribute_gnu(void)
1191 attribute_t *first = NULL;
1192 attribute_t **anchor = &first;
1194 eat(T___attribute__);
1198 add_anchor_token(')');
1199 add_anchor_token(',');
1200 if (token.kind != ')') do {
1201 attribute_t *attribute = parse_attribute_gnu_single();
1203 *anchor = attribute;
1204 anchor = &attribute->next;
1206 } while (next_if(','));
1207 rem_anchor_token(',');
1208 rem_anchor_token(')');
1215 /** Parse attributes. */
1216 static attribute_t *parse_attributes(attribute_t *first)
1218 attribute_t **anchor = &first;
1220 while (*anchor != NULL)
1221 anchor = &(*anchor)->next;
1223 attribute_t *attribute;
1224 switch (token.kind) {
1225 case T___attribute__:
1226 attribute = parse_attribute_gnu();
1227 if (attribute == NULL)
1232 attribute = parse_attribute_asm();
1236 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1241 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1245 case T__forceinline:
1246 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1247 eat(T__forceinline);
1251 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1256 /* TODO record modifier */
1257 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1258 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1266 *anchor = attribute;
1267 anchor = &attribute->next;
1271 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1273 static entity_t *determine_lhs_ent(expression_t *const expr,
1276 switch (expr->kind) {
1277 case EXPR_REFERENCE: {
1278 entity_t *const entity = expr->reference.entity;
1279 /* we should only find variables as lvalues... */
1280 if (entity->base.kind != ENTITY_VARIABLE
1281 && entity->base.kind != ENTITY_PARAMETER)
1287 case EXPR_ARRAY_ACCESS: {
1288 expression_t *const ref = expr->array_access.array_ref;
1289 entity_t * ent = NULL;
1290 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1291 ent = determine_lhs_ent(ref, lhs_ent);
1294 mark_vars_read(ref, lhs_ent);
1296 mark_vars_read(expr->array_access.index, lhs_ent);
1301 mark_vars_read(expr->select.compound, lhs_ent);
1302 if (is_type_compound(skip_typeref(expr->base.type)))
1303 return determine_lhs_ent(expr->select.compound, lhs_ent);
1307 case EXPR_UNARY_DEREFERENCE: {
1308 expression_t *const val = expr->unary.value;
1309 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1311 return determine_lhs_ent(val->unary.value, lhs_ent);
1313 mark_vars_read(val, NULL);
1319 mark_vars_read(expr, NULL);
1324 #define ENT_ANY ((entity_t*)-1)
1327 * Mark declarations, which are read. This is used to detect variables, which
1331 * x is not marked as "read", because it is only read to calculate its own new
1335 * x and y are not detected as "not read", because multiple variables are
1338 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1340 switch (expr->kind) {
1341 case EXPR_REFERENCE: {
1342 entity_t *const entity = expr->reference.entity;
1343 if (entity->kind != ENTITY_VARIABLE
1344 && entity->kind != ENTITY_PARAMETER)
1347 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1348 if (entity->kind == ENTITY_VARIABLE) {
1349 entity->variable.read = true;
1351 entity->parameter.read = true;
1358 // TODO respect pure/const
1359 mark_vars_read(expr->call.function, NULL);
1360 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1361 mark_vars_read(arg->expression, NULL);
1365 case EXPR_CONDITIONAL:
1366 // TODO lhs_decl should depend on whether true/false have an effect
1367 mark_vars_read(expr->conditional.condition, NULL);
1368 if (expr->conditional.true_expression != NULL)
1369 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1370 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1374 if (lhs_ent == ENT_ANY
1375 && !is_type_compound(skip_typeref(expr->base.type)))
1377 mark_vars_read(expr->select.compound, lhs_ent);
1380 case EXPR_ARRAY_ACCESS: {
1381 mark_vars_read(expr->array_access.index, lhs_ent);
1382 expression_t *const ref = expr->array_access.array_ref;
1383 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1384 if (lhs_ent == ENT_ANY)
1387 mark_vars_read(ref, lhs_ent);
1392 mark_vars_read(expr->va_arge.ap, lhs_ent);
1396 mark_vars_read(expr->va_copye.src, lhs_ent);
1399 case EXPR_UNARY_CAST:
1400 /* Special case: Use void cast to mark a variable as "read" */
1401 if (is_type_void(skip_typeref(expr->base.type)))
1406 case EXPR_UNARY_THROW:
1407 if (expr->unary.value == NULL)
1410 case EXPR_UNARY_DEREFERENCE:
1411 case EXPR_UNARY_DELETE:
1412 case EXPR_UNARY_DELETE_ARRAY:
1413 if (lhs_ent == ENT_ANY)
1417 case EXPR_UNARY_NEGATE:
1418 case EXPR_UNARY_PLUS:
1419 case EXPR_UNARY_BITWISE_NEGATE:
1420 case EXPR_UNARY_NOT:
1421 case EXPR_UNARY_TAKE_ADDRESS:
1422 case EXPR_UNARY_POSTFIX_INCREMENT:
1423 case EXPR_UNARY_POSTFIX_DECREMENT:
1424 case EXPR_UNARY_PREFIX_INCREMENT:
1425 case EXPR_UNARY_PREFIX_DECREMENT:
1426 case EXPR_UNARY_ASSUME:
1428 mark_vars_read(expr->unary.value, lhs_ent);
1431 case EXPR_BINARY_ADD:
1432 case EXPR_BINARY_SUB:
1433 case EXPR_BINARY_MUL:
1434 case EXPR_BINARY_DIV:
1435 case EXPR_BINARY_MOD:
1436 case EXPR_BINARY_EQUAL:
1437 case EXPR_BINARY_NOTEQUAL:
1438 case EXPR_BINARY_LESS:
1439 case EXPR_BINARY_LESSEQUAL:
1440 case EXPR_BINARY_GREATER:
1441 case EXPR_BINARY_GREATEREQUAL:
1442 case EXPR_BINARY_BITWISE_AND:
1443 case EXPR_BINARY_BITWISE_OR:
1444 case EXPR_BINARY_BITWISE_XOR:
1445 case EXPR_BINARY_LOGICAL_AND:
1446 case EXPR_BINARY_LOGICAL_OR:
1447 case EXPR_BINARY_SHIFTLEFT:
1448 case EXPR_BINARY_SHIFTRIGHT:
1449 case EXPR_BINARY_COMMA:
1450 case EXPR_BINARY_ISGREATER:
1451 case EXPR_BINARY_ISGREATEREQUAL:
1452 case EXPR_BINARY_ISLESS:
1453 case EXPR_BINARY_ISLESSEQUAL:
1454 case EXPR_BINARY_ISLESSGREATER:
1455 case EXPR_BINARY_ISUNORDERED:
1456 mark_vars_read(expr->binary.left, lhs_ent);
1457 mark_vars_read(expr->binary.right, lhs_ent);
1460 case EXPR_BINARY_ASSIGN:
1461 case EXPR_BINARY_MUL_ASSIGN:
1462 case EXPR_BINARY_DIV_ASSIGN:
1463 case EXPR_BINARY_MOD_ASSIGN:
1464 case EXPR_BINARY_ADD_ASSIGN:
1465 case EXPR_BINARY_SUB_ASSIGN:
1466 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1467 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1468 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1469 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1470 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1471 if (lhs_ent == ENT_ANY)
1473 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1474 mark_vars_read(expr->binary.right, lhs_ent);
1479 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1482 case EXPR_LITERAL_CASES:
1484 case EXPR_STRING_LITERAL:
1485 case EXPR_WIDE_STRING_LITERAL:
1486 case EXPR_COMPOUND_LITERAL: // TODO init?
1488 case EXPR_CLASSIFY_TYPE:
1491 case EXPR_BUILTIN_CONSTANT_P:
1492 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1494 case EXPR_STATEMENT: // TODO
1495 case EXPR_LABEL_ADDRESS:
1496 case EXPR_ENUM_CONSTANT:
1500 panic("unhandled expression");
1503 static designator_t *parse_designation(void)
1505 designator_t *result = NULL;
1506 designator_t **anchor = &result;
1509 designator_t *designator;
1510 switch (token.kind) {
1512 designator = allocate_ast_zero(sizeof(designator[0]));
1513 designator->source_position = token.base.source_position;
1515 add_anchor_token(']');
1516 designator->array_index = parse_constant_expression();
1517 rem_anchor_token(']');
1521 designator = allocate_ast_zero(sizeof(designator[0]));
1522 designator->source_position = token.base.source_position;
1524 designator->symbol = expect_identifier("while parsing designator", NULL);
1525 if (!designator->symbol)
1533 assert(designator != NULL);
1534 *anchor = designator;
1535 anchor = &designator->next;
1539 static initializer_t *initializer_from_string(array_type_t *const type,
1540 const string_t *const string)
1542 /* TODO: check len vs. size of array type */
1545 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1546 initializer->string.string = *string;
1551 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1552 const string_t *const string)
1554 /* TODO: check len vs. size of array type */
1557 initializer_t *const initializer =
1558 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1559 initializer->wide_string.string = *string;
1565 * Build an initializer from a given expression.
1567 static initializer_t *initializer_from_expression(type_t *orig_type,
1568 expression_t *expression)
1570 /* TODO check that expression is a constant expression */
1572 /* §6.7.8.14/15 char array may be initialized by string literals */
1573 type_t *type = skip_typeref(orig_type);
1574 type_t *expr_type_orig = expression->base.type;
1575 type_t *expr_type = skip_typeref(expr_type_orig);
1577 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1578 array_type_t *const array_type = &type->array;
1579 type_t *const element_type = skip_typeref(array_type->element_type);
1581 if (element_type->kind == TYPE_ATOMIC) {
1582 atomic_type_kind_t akind = element_type->atomic.akind;
1583 switch (expression->kind) {
1584 case EXPR_STRING_LITERAL:
1585 if (akind == ATOMIC_TYPE_CHAR
1586 || akind == ATOMIC_TYPE_SCHAR
1587 || akind == ATOMIC_TYPE_UCHAR) {
1588 return initializer_from_string(array_type,
1589 &expression->string_literal.value);
1593 case EXPR_WIDE_STRING_LITERAL: {
1594 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1595 if (get_unqualified_type(element_type) == bare_wchar_type) {
1596 return initializer_from_wide_string(array_type,
1597 &expression->string_literal.value);
1608 assign_error_t error = semantic_assign(type, expression);
1609 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1611 report_assign_error(error, type, expression, "initializer",
1612 &expression->base.source_position);
1614 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1615 result->value.value = create_implicit_cast(expression, type);
1621 * Parses an scalar initializer.
1623 * §6.7.8.11; eat {} without warning
1625 static initializer_t *parse_scalar_initializer(type_t *type,
1626 bool must_be_constant)
1628 /* there might be extra {} hierarchies */
1630 if (token.kind == '{') {
1631 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1635 } while (token.kind == '{');
1638 expression_t *expression = parse_assignment_expression();
1639 mark_vars_read(expression, NULL);
1640 if (must_be_constant && !is_linker_constant(expression)) {
1641 errorf(&expression->base.source_position,
1642 "initialisation expression '%E' is not constant",
1646 initializer_t *initializer = initializer_from_expression(type, expression);
1648 if (initializer == NULL) {
1649 errorf(&expression->base.source_position,
1650 "expression '%E' (type '%T') doesn't match expected type '%T'",
1651 expression, expression->base.type, type);
1656 bool additional_warning_displayed = false;
1657 while (braces > 0) {
1659 if (token.kind != '}') {
1660 if (!additional_warning_displayed) {
1661 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1662 additional_warning_displayed = true;
1673 * An entry in the type path.
1675 typedef struct type_path_entry_t type_path_entry_t;
1676 struct type_path_entry_t {
1677 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1679 size_t index; /**< For array types: the current index. */
1680 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1685 * A type path expression a position inside compound or array types.
1687 typedef struct type_path_t type_path_t;
1688 struct type_path_t {
1689 type_path_entry_t *path; /**< An flexible array containing the current path. */
1690 type_t *top_type; /**< type of the element the path points */
1691 size_t max_index; /**< largest index in outermost array */
1695 * Prints a type path for debugging.
1697 static __attribute__((unused)) void debug_print_type_path(
1698 const type_path_t *path)
1700 size_t len = ARR_LEN(path->path);
1702 for (size_t i = 0; i < len; ++i) {
1703 const type_path_entry_t *entry = & path->path[i];
1705 type_t *type = skip_typeref(entry->type);
1706 if (is_type_compound(type)) {
1707 /* in gcc mode structs can have no members */
1708 if (entry->v.compound_entry == NULL) {
1712 fprintf(stderr, ".%s",
1713 entry->v.compound_entry->base.symbol->string);
1714 } else if (is_type_array(type)) {
1715 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1717 fprintf(stderr, "-INVALID-");
1720 if (path->top_type != NULL) {
1721 fprintf(stderr, " (");
1722 print_type(path->top_type);
1723 fprintf(stderr, ")");
1728 * Return the top type path entry, ie. in a path
1729 * (type).a.b returns the b.
1731 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1733 size_t len = ARR_LEN(path->path);
1735 return &path->path[len-1];
1739 * Enlarge the type path by an (empty) element.
1741 static type_path_entry_t *append_to_type_path(type_path_t *path)
1743 size_t len = ARR_LEN(path->path);
1744 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1746 type_path_entry_t *result = & path->path[len];
1747 memset(result, 0, sizeof(result[0]));
1752 * Descending into a sub-type. Enter the scope of the current top_type.
1754 static void descend_into_subtype(type_path_t *path)
1756 type_t *orig_top_type = path->top_type;
1757 type_t *top_type = skip_typeref(orig_top_type);
1759 type_path_entry_t *top = append_to_type_path(path);
1760 top->type = top_type;
1762 if (is_type_compound(top_type)) {
1763 compound_t *const compound = top_type->compound.compound;
1764 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1766 if (entry != NULL) {
1767 top->v.compound_entry = &entry->declaration;
1768 path->top_type = entry->declaration.type;
1770 path->top_type = NULL;
1772 } else if (is_type_array(top_type)) {
1774 path->top_type = top_type->array.element_type;
1776 assert(!is_type_valid(top_type));
1781 * Pop an entry from the given type path, ie. returning from
1782 * (type).a.b to (type).a
1784 static void ascend_from_subtype(type_path_t *path)
1786 type_path_entry_t *top = get_type_path_top(path);
1788 path->top_type = top->type;
1790 size_t len = ARR_LEN(path->path);
1791 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1795 * Pop entries from the given type path until the given
1796 * path level is reached.
1798 static void ascend_to(type_path_t *path, size_t top_path_level)
1800 size_t len = ARR_LEN(path->path);
1802 while (len > top_path_level) {
1803 ascend_from_subtype(path);
1804 len = ARR_LEN(path->path);
1808 static bool walk_designator(type_path_t *path, const designator_t *designator,
1809 bool used_in_offsetof)
1811 for (; designator != NULL; designator = designator->next) {
1812 type_path_entry_t *top = get_type_path_top(path);
1813 type_t *orig_type = top->type;
1815 type_t *type = skip_typeref(orig_type);
1817 if (designator->symbol != NULL) {
1818 symbol_t *symbol = designator->symbol;
1819 if (!is_type_compound(type)) {
1820 if (is_type_valid(type)) {
1821 errorf(&designator->source_position,
1822 "'.%Y' designator used for non-compound type '%T'",
1826 top->type = type_error_type;
1827 top->v.compound_entry = NULL;
1828 orig_type = type_error_type;
1830 compound_t *compound = type->compound.compound;
1831 entity_t *iter = compound->members.entities;
1832 for (; iter != NULL; iter = iter->base.next) {
1833 if (iter->base.symbol == symbol) {
1838 errorf(&designator->source_position,
1839 "'%T' has no member named '%Y'", orig_type, symbol);
1842 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1843 if (used_in_offsetof && iter->compound_member.bitfield) {
1844 errorf(&designator->source_position,
1845 "offsetof designator '%Y' must not specify bitfield",
1850 top->type = orig_type;
1851 top->v.compound_entry = &iter->declaration;
1852 orig_type = iter->declaration.type;
1855 expression_t *array_index = designator->array_index;
1856 assert(designator->array_index != NULL);
1858 if (!is_type_array(type)) {
1859 if (is_type_valid(type)) {
1860 errorf(&designator->source_position,
1861 "[%E] designator used for non-array type '%T'",
1862 array_index, orig_type);
1867 long index = fold_constant_to_int(array_index);
1868 if (!used_in_offsetof) {
1870 errorf(&designator->source_position,
1871 "array index [%E] must be positive", array_index);
1872 } else if (type->array.size_constant) {
1873 long array_size = type->array.size;
1874 if (index >= array_size) {
1875 errorf(&designator->source_position,
1876 "designator [%E] (%d) exceeds array size %d",
1877 array_index, index, array_size);
1882 top->type = orig_type;
1883 top->v.index = (size_t) index;
1884 orig_type = type->array.element_type;
1886 path->top_type = orig_type;
1888 if (designator->next != NULL) {
1889 descend_into_subtype(path);
1895 static void advance_current_object(type_path_t *path, size_t top_path_level)
1897 type_path_entry_t *top = get_type_path_top(path);
1899 type_t *type = skip_typeref(top->type);
1900 if (is_type_union(type)) {
1901 /* in unions only the first element is initialized */
1902 top->v.compound_entry = NULL;
1903 } else if (is_type_struct(type)) {
1904 declaration_t *entry = top->v.compound_entry;
1906 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1907 if (next_entity != NULL) {
1908 assert(is_declaration(next_entity));
1909 entry = &next_entity->declaration;
1914 top->v.compound_entry = entry;
1915 if (entry != NULL) {
1916 path->top_type = entry->type;
1919 } else if (is_type_array(type)) {
1920 assert(is_type_array(type));
1924 if (!type->array.size_constant || top->v.index < type->array.size) {
1928 assert(!is_type_valid(type));
1932 /* we're past the last member of the current sub-aggregate, try if we
1933 * can ascend in the type hierarchy and continue with another subobject */
1934 size_t len = ARR_LEN(path->path);
1936 if (len > top_path_level) {
1937 ascend_from_subtype(path);
1938 advance_current_object(path, top_path_level);
1940 path->top_type = NULL;
1945 * skip any {...} blocks until a closing bracket is reached.
1947 static void skip_initializers(void)
1951 while (token.kind != '}') {
1952 if (token.kind == T_EOF)
1954 if (token.kind == '{') {
1962 static initializer_t *create_empty_initializer(void)
1964 static initializer_t empty_initializer
1965 = { .list = { { INITIALIZER_LIST }, 0 } };
1966 return &empty_initializer;
1970 * Parse a part of an initialiser for a struct or union,
1972 static initializer_t *parse_sub_initializer(type_path_t *path,
1973 type_t *outer_type, size_t top_path_level,
1974 parse_initializer_env_t *env)
1976 if (token.kind == '}') {
1977 /* empty initializer */
1978 return create_empty_initializer();
1981 type_t *orig_type = path->top_type;
1982 type_t *type = NULL;
1984 if (orig_type == NULL) {
1985 /* We are initializing an empty compound. */
1987 type = skip_typeref(orig_type);
1990 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1993 designator_t *designator = NULL;
1994 if (token.kind == '.' || token.kind == '[') {
1995 designator = parse_designation();
1996 goto finish_designator;
1997 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1998 /* GNU-style designator ("identifier: value") */
1999 designator = allocate_ast_zero(sizeof(designator[0]));
2000 designator->source_position = token.base.source_position;
2001 designator->symbol = token.identifier.symbol;
2006 /* reset path to toplevel, evaluate designator from there */
2007 ascend_to(path, top_path_level);
2008 if (!walk_designator(path, designator, false)) {
2009 /* can't continue after designation error */
2013 initializer_t *designator_initializer
2014 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2015 designator_initializer->designator.designator = designator;
2016 ARR_APP1(initializer_t*, initializers, designator_initializer);
2018 orig_type = path->top_type;
2019 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2024 if (token.kind == '{') {
2025 if (type != NULL && is_type_scalar(type)) {
2026 sub = parse_scalar_initializer(type, env->must_be_constant);
2029 if (env->entity != NULL) {
2031 "extra brace group at end of initializer for '%Y'",
2032 env->entity->base.symbol);
2034 errorf(HERE, "extra brace group at end of initializer");
2039 descend_into_subtype(path);
2042 add_anchor_token('}');
2043 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2045 rem_anchor_token('}');
2050 goto error_parse_next;
2052 ascend_from_subtype(path);
2055 /* must be an expression */
2056 expression_t *expression = parse_assignment_expression();
2057 mark_vars_read(expression, NULL);
2059 if (env->must_be_constant && !is_linker_constant(expression)) {
2060 errorf(&expression->base.source_position,
2061 "Initialisation expression '%E' is not constant",
2066 /* we are already outside, ... */
2067 if (outer_type == NULL)
2068 goto error_parse_next;
2069 type_t *const outer_type_skip = skip_typeref(outer_type);
2070 if (is_type_compound(outer_type_skip) &&
2071 !outer_type_skip->compound.compound->complete) {
2072 goto error_parse_next;
2075 source_position_t const* const pos = &expression->base.source_position;
2076 if (env->entity != NULL) {
2077 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2079 warningf(WARN_OTHER, pos, "excess elements in initializer");
2081 goto error_parse_next;
2084 /* handle { "string" } special case */
2085 if ((expression->kind == EXPR_STRING_LITERAL
2086 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2087 && outer_type != NULL) {
2088 sub = initializer_from_expression(outer_type, expression);
2091 if (token.kind != '}') {
2092 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2094 /* TODO: eat , ... */
2099 /* descend into subtypes until expression matches type */
2101 orig_type = path->top_type;
2102 type = skip_typeref(orig_type);
2104 sub = initializer_from_expression(orig_type, expression);
2108 if (!is_type_valid(type)) {
2111 if (is_type_scalar(type)) {
2112 errorf(&expression->base.source_position,
2113 "expression '%E' doesn't match expected type '%T'",
2114 expression, orig_type);
2118 descend_into_subtype(path);
2122 /* update largest index of top array */
2123 const type_path_entry_t *first = &path->path[0];
2124 type_t *first_type = first->type;
2125 first_type = skip_typeref(first_type);
2126 if (is_type_array(first_type)) {
2127 size_t index = first->v.index;
2128 if (index > path->max_index)
2129 path->max_index = index;
2132 /* append to initializers list */
2133 ARR_APP1(initializer_t*, initializers, sub);
2136 if (token.kind == '}') {
2139 add_anchor_token('}');
2141 rem_anchor_token('}');
2142 if (token.kind == '}') {
2147 /* advance to the next declaration if we are not at the end */
2148 advance_current_object(path, top_path_level);
2149 orig_type = path->top_type;
2150 if (orig_type != NULL)
2151 type = skip_typeref(orig_type);
2157 size_t len = ARR_LEN(initializers);
2158 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2159 initializer_t *result = allocate_ast_zero(size);
2160 result->kind = INITIALIZER_LIST;
2161 result->list.len = len;
2162 memcpy(&result->list.initializers, initializers,
2163 len * sizeof(initializers[0]));
2165 DEL_ARR_F(initializers);
2166 ascend_to(path, top_path_level+1);
2171 skip_initializers();
2172 DEL_ARR_F(initializers);
2173 ascend_to(path, top_path_level+1);
2177 static expression_t *make_size_literal(size_t value)
2179 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2180 literal->base.type = type_size_t;
2183 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2184 literal->literal.value = make_string(buf);
2190 * Parses an initializer. Parsers either a compound literal
2191 * (env->declaration == NULL) or an initializer of a declaration.
2193 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2195 type_t *type = skip_typeref(env->type);
2196 size_t max_index = 0;
2197 initializer_t *result;
2199 if (is_type_scalar(type)) {
2200 result = parse_scalar_initializer(type, env->must_be_constant);
2201 } else if (token.kind == '{') {
2205 memset(&path, 0, sizeof(path));
2206 path.top_type = env->type;
2207 path.path = NEW_ARR_F(type_path_entry_t, 0);
2209 descend_into_subtype(&path);
2211 add_anchor_token('}');
2212 result = parse_sub_initializer(&path, env->type, 1, env);
2213 rem_anchor_token('}');
2215 max_index = path.max_index;
2216 DEL_ARR_F(path.path);
2220 /* parse_scalar_initializer() also works in this case: we simply
2221 * have an expression without {} around it */
2222 result = parse_scalar_initializer(type, env->must_be_constant);
2225 /* §6.7.8:22 array initializers for arrays with unknown size determine
2226 * the array type size */
2227 if (is_type_array(type) && type->array.size_expression == NULL
2228 && result != NULL) {
2230 switch (result->kind) {
2231 case INITIALIZER_LIST:
2232 assert(max_index != 0xdeadbeaf);
2233 size = max_index + 1;
2236 case INITIALIZER_STRING:
2237 size = result->string.string.size;
2240 case INITIALIZER_WIDE_STRING:
2241 size = result->wide_string.string.size;
2244 case INITIALIZER_DESIGNATOR:
2245 case INITIALIZER_VALUE:
2246 /* can happen for parse errors */
2251 internal_errorf(HERE, "invalid initializer type");
2254 type_t *new_type = duplicate_type(type);
2256 new_type->array.size_expression = make_size_literal(size);
2257 new_type->array.size_constant = true;
2258 new_type->array.has_implicit_size = true;
2259 new_type->array.size = size;
2260 env->type = new_type;
2266 static void append_entity(scope_t *scope, entity_t *entity)
2268 if (scope->last_entity != NULL) {
2269 scope->last_entity->base.next = entity;
2271 scope->entities = entity;
2273 entity->base.parent_entity = current_entity;
2274 scope->last_entity = entity;
2278 static compound_t *parse_compound_type_specifier(bool is_struct)
2280 source_position_t const pos = *HERE;
2281 eat(is_struct ? T_struct : T_union);
2283 symbol_t *symbol = NULL;
2284 entity_t *entity = NULL;
2285 attribute_t *attributes = NULL;
2287 if (token.kind == T___attribute__) {
2288 attributes = parse_attributes(NULL);
2291 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2292 if (token.kind == T_IDENTIFIER) {
2293 /* the compound has a name, check if we have seen it already */
2294 symbol = token.identifier.symbol;
2295 entity = get_tag(symbol, kind);
2298 if (entity != NULL) {
2299 if (entity->base.parent_scope != current_scope &&
2300 (token.kind == '{' || token.kind == ';')) {
2301 /* we're in an inner scope and have a definition. Shadow
2302 * existing definition in outer scope */
2304 } else if (entity->compound.complete && token.kind == '{') {
2305 source_position_t const *const ppos = &entity->base.source_position;
2306 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2307 /* clear members in the hope to avoid further errors */
2308 entity->compound.members.entities = NULL;
2311 } else if (token.kind != '{') {
2312 char const *const msg =
2313 is_struct ? "while parsing struct type specifier" :
2314 "while parsing union type specifier";
2315 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2320 if (entity == NULL) {
2321 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2322 entity->compound.alignment = 1;
2323 entity->base.parent_scope = current_scope;
2324 if (symbol != NULL) {
2325 environment_push(entity);
2327 append_entity(current_scope, entity);
2330 if (token.kind == '{') {
2331 parse_compound_type_entries(&entity->compound);
2333 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2334 if (symbol == NULL) {
2335 assert(anonymous_entity == NULL);
2336 anonymous_entity = entity;
2340 if (attributes != NULL) {
2341 handle_entity_attributes(attributes, entity);
2344 return &entity->compound;
2347 static void parse_enum_entries(type_t *const enum_type)
2351 if (token.kind == '}') {
2352 errorf(HERE, "empty enum not allowed");
2357 add_anchor_token('}');
2358 add_anchor_token(',');
2360 add_anchor_token('=');
2361 source_position_t pos;
2362 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2363 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2364 entity->enum_value.enum_type = enum_type;
2365 rem_anchor_token('=');
2368 expression_t *value = parse_constant_expression();
2370 value = create_implicit_cast(value, enum_type);
2371 entity->enum_value.value = value;
2376 record_entity(entity, false);
2377 } while (next_if(',') && token.kind != '}');
2378 rem_anchor_token(',');
2379 rem_anchor_token('}');
2384 static type_t *parse_enum_specifier(void)
2386 source_position_t const pos = *HERE;
2391 switch (token.kind) {
2393 symbol = token.identifier.symbol;
2394 entity = get_tag(symbol, ENTITY_ENUM);
2397 if (entity != NULL) {
2398 if (entity->base.parent_scope != current_scope &&
2399 (token.kind == '{' || token.kind == ';')) {
2400 /* we're in an inner scope and have a definition. Shadow
2401 * existing definition in outer scope */
2403 } else if (entity->enume.complete && token.kind == '{') {
2404 source_position_t const *const ppos = &entity->base.source_position;
2405 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2416 parse_error_expected("while parsing enum type specifier",
2417 T_IDENTIFIER, '{', NULL);
2421 if (entity == NULL) {
2422 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2423 entity->base.parent_scope = current_scope;
2426 type_t *const type = allocate_type_zero(TYPE_ENUM);
2427 type->enumt.enume = &entity->enume;
2428 type->enumt.base.akind = ATOMIC_TYPE_INT;
2430 if (token.kind == '{') {
2431 if (symbol != NULL) {
2432 environment_push(entity);
2434 append_entity(current_scope, entity);
2435 entity->enume.complete = true;
2437 parse_enum_entries(type);
2438 parse_attributes(NULL);
2440 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2441 if (symbol == NULL) {
2442 assert(anonymous_entity == NULL);
2443 anonymous_entity = entity;
2445 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2446 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2453 * if a symbol is a typedef to another type, return true
2455 static bool is_typedef_symbol(symbol_t *symbol)
2457 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2458 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2461 static type_t *parse_typeof(void)
2468 add_anchor_token(')');
2470 expression_t *expression = NULL;
2472 switch (token.kind) {
2474 if (is_typedef_symbol(token.identifier.symbol)) {
2476 type = parse_typename();
2479 expression = parse_expression();
2480 type = revert_automatic_type_conversion(expression);
2485 rem_anchor_token(')');
2488 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2489 typeof_type->typeoft.expression = expression;
2490 typeof_type->typeoft.typeof_type = type;
2495 typedef enum specifiers_t {
2496 SPECIFIER_SIGNED = 1 << 0,
2497 SPECIFIER_UNSIGNED = 1 << 1,
2498 SPECIFIER_LONG = 1 << 2,
2499 SPECIFIER_INT = 1 << 3,
2500 SPECIFIER_DOUBLE = 1 << 4,
2501 SPECIFIER_CHAR = 1 << 5,
2502 SPECIFIER_WCHAR_T = 1 << 6,
2503 SPECIFIER_SHORT = 1 << 7,
2504 SPECIFIER_LONG_LONG = 1 << 8,
2505 SPECIFIER_FLOAT = 1 << 9,
2506 SPECIFIER_BOOL = 1 << 10,
2507 SPECIFIER_VOID = 1 << 11,
2508 SPECIFIER_INT8 = 1 << 12,
2509 SPECIFIER_INT16 = 1 << 13,
2510 SPECIFIER_INT32 = 1 << 14,
2511 SPECIFIER_INT64 = 1 << 15,
2512 SPECIFIER_INT128 = 1 << 16,
2513 SPECIFIER_COMPLEX = 1 << 17,
2514 SPECIFIER_IMAGINARY = 1 << 18,
2517 static type_t *get_typedef_type(symbol_t *symbol)
2519 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2520 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2523 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2524 type->typedeft.typedefe = &entity->typedefe;
2529 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2531 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2535 add_anchor_token(')');
2536 add_anchor_token(',');
2538 add_anchor_token('=');
2539 source_position_t pos;
2540 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2541 rem_anchor_token('=');
2543 symbol_t **prop = NULL;
2545 if (streq(prop_sym->string, "put")) {
2546 prop = &property->put_symbol;
2547 } else if (streq(prop_sym->string, "get")) {
2548 prop = &property->get_symbol;
2550 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2554 add_anchor_token(T_IDENTIFIER);
2556 rem_anchor_token(T_IDENTIFIER);
2558 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2560 *prop = sym ? sym : sym_anonymous;
2561 } while (next_if(','));
2562 rem_anchor_token(',');
2563 rem_anchor_token(')');
2565 attribute->a.property = property;
2571 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2573 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2574 if (next_if(T_restrict)) {
2575 kind = ATTRIBUTE_MS_RESTRICT;
2576 } else if (token.kind == T_IDENTIFIER) {
2577 const char *name = token.identifier.symbol->string;
2578 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2580 const char *attribute_name = get_attribute_name(k);
2581 if (attribute_name != NULL && streq(attribute_name, name)) {
2587 if (kind == ATTRIBUTE_UNKNOWN) {
2588 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2591 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2595 attribute_t *attribute = allocate_attribute_zero(kind);
2598 if (kind == ATTRIBUTE_MS_PROPERTY) {
2599 return parse_attribute_ms_property(attribute);
2602 /* parse arguments */
2604 attribute->a.arguments = parse_attribute_arguments();
2609 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2614 if (token.kind != ')') {
2615 add_anchor_token(')');
2617 attribute_t **anchor = &first;
2619 while (*anchor != NULL)
2620 anchor = &(*anchor)->next;
2622 attribute_t *attribute
2623 = parse_microsoft_extended_decl_modifier_single();
2624 if (attribute == NULL)
2627 *anchor = attribute;
2628 anchor = &attribute->next;
2629 } while (next_if(','));
2631 rem_anchor_token(')');
2637 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2639 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2640 if (is_declaration(entity)) {
2641 entity->declaration.type = type_error_type;
2642 entity->declaration.implicit = true;
2643 } else if (kind == ENTITY_TYPEDEF) {
2644 entity->typedefe.type = type_error_type;
2645 entity->typedefe.builtin = true;
2647 if (kind != ENTITY_COMPOUND_MEMBER)
2648 record_entity(entity, false);
2652 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2654 type_t *type = NULL;
2655 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2656 unsigned type_specifiers = 0;
2657 bool newtype = false;
2658 bool saw_error = false;
2660 memset(specifiers, 0, sizeof(*specifiers));
2661 specifiers->source_position = token.base.source_position;
2664 specifiers->attributes = parse_attributes(specifiers->attributes);
2666 switch (token.kind) {
2668 #define MATCH_STORAGE_CLASS(token, class) \
2670 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2671 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2673 specifiers->storage_class = class; \
2674 if (specifiers->thread_local) \
2675 goto check_thread_storage_class; \
2679 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2680 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2681 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2682 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2683 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2686 specifiers->attributes
2687 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2691 if (specifiers->thread_local) {
2692 errorf(HERE, "duplicate '__thread'");
2694 specifiers->thread_local = true;
2695 check_thread_storage_class:
2696 switch (specifiers->storage_class) {
2697 case STORAGE_CLASS_EXTERN:
2698 case STORAGE_CLASS_NONE:
2699 case STORAGE_CLASS_STATIC:
2703 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2704 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2705 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2706 wrong_thread_storage_class:
2707 errorf(HERE, "'__thread' used with '%s'", wrong);
2714 /* type qualifiers */
2715 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2717 qualifiers |= qualifier; \
2721 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2722 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2723 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2724 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2725 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2726 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2727 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2728 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2730 /* type specifiers */
2731 #define MATCH_SPECIFIER(token, specifier, name) \
2733 if (type_specifiers & specifier) { \
2734 errorf(HERE, "multiple " name " type specifiers given"); \
2736 type_specifiers |= specifier; \
2741 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2742 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2743 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2744 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2745 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2746 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2747 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2748 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2749 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2750 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2751 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2752 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2753 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2754 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2755 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2756 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2757 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2758 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2762 specifiers->is_inline = true;
2766 case T__forceinline:
2768 specifiers->modifiers |= DM_FORCEINLINE;
2773 if (type_specifiers & SPECIFIER_LONG_LONG) {
2774 errorf(HERE, "too many long type specifiers given");
2775 } else if (type_specifiers & SPECIFIER_LONG) {
2776 type_specifiers |= SPECIFIER_LONG_LONG;
2778 type_specifiers |= SPECIFIER_LONG;
2783 #define CHECK_DOUBLE_TYPE() \
2784 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2787 CHECK_DOUBLE_TYPE();
2788 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2790 type->compound.compound = parse_compound_type_specifier(true);
2793 CHECK_DOUBLE_TYPE();
2794 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2795 type->compound.compound = parse_compound_type_specifier(false);
2798 CHECK_DOUBLE_TYPE();
2799 type = parse_enum_specifier();
2802 CHECK_DOUBLE_TYPE();
2803 type = parse_typeof();
2805 case T___builtin_va_list:
2806 CHECK_DOUBLE_TYPE();
2807 type = duplicate_type(type_valist);
2811 case T_IDENTIFIER: {
2812 /* only parse identifier if we haven't found a type yet */
2813 if (type != NULL || type_specifiers != 0) {
2814 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2815 * declaration, so it doesn't generate errors about expecting '(' or
2817 switch (look_ahead(1)->kind) {
2824 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2828 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2833 goto finish_specifiers;
2837 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2838 if (typedef_type == NULL) {
2839 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2840 * declaration, so it doesn't generate 'implicit int' followed by more
2841 * errors later on. */
2842 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2848 errorf(HERE, "%K does not name a type", &token);
2850 symbol_t *symbol = token.identifier.symbol;
2852 = create_error_entity(symbol, ENTITY_TYPEDEF);
2854 type = allocate_type_zero(TYPE_TYPEDEF);
2855 type->typedeft.typedefe = &entity->typedefe;
2863 goto finish_specifiers;
2868 type = typedef_type;
2872 /* function specifier */
2874 goto finish_specifiers;
2879 specifiers->attributes = parse_attributes(specifiers->attributes);
2881 if (type == NULL || (saw_error && type_specifiers != 0)) {
2882 atomic_type_kind_t atomic_type;
2884 /* match valid basic types */
2885 switch (type_specifiers) {
2886 case SPECIFIER_VOID:
2887 atomic_type = ATOMIC_TYPE_VOID;
2889 case SPECIFIER_WCHAR_T:
2890 atomic_type = ATOMIC_TYPE_WCHAR_T;
2892 case SPECIFIER_CHAR:
2893 atomic_type = ATOMIC_TYPE_CHAR;
2895 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2896 atomic_type = ATOMIC_TYPE_SCHAR;
2898 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2899 atomic_type = ATOMIC_TYPE_UCHAR;
2901 case SPECIFIER_SHORT:
2902 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2903 case SPECIFIER_SHORT | SPECIFIER_INT:
2904 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2905 atomic_type = ATOMIC_TYPE_SHORT;
2907 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2908 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2909 atomic_type = ATOMIC_TYPE_USHORT;
2912 case SPECIFIER_SIGNED:
2913 case SPECIFIER_SIGNED | SPECIFIER_INT:
2914 atomic_type = ATOMIC_TYPE_INT;
2916 case SPECIFIER_UNSIGNED:
2917 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2918 atomic_type = ATOMIC_TYPE_UINT;
2920 case SPECIFIER_LONG:
2921 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2922 case SPECIFIER_LONG | SPECIFIER_INT:
2923 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2924 atomic_type = ATOMIC_TYPE_LONG;
2926 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2927 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2928 atomic_type = ATOMIC_TYPE_ULONG;
2931 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2932 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2933 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2934 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2936 atomic_type = ATOMIC_TYPE_LONGLONG;
2937 goto warn_about_long_long;
2939 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2940 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2942 atomic_type = ATOMIC_TYPE_ULONGLONG;
2943 warn_about_long_long:
2944 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2947 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2948 atomic_type = unsigned_int8_type_kind;
2951 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2952 atomic_type = unsigned_int16_type_kind;
2955 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2956 atomic_type = unsigned_int32_type_kind;
2959 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2960 atomic_type = unsigned_int64_type_kind;
2963 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2964 atomic_type = unsigned_int128_type_kind;
2967 case SPECIFIER_INT8:
2968 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2969 atomic_type = int8_type_kind;
2972 case SPECIFIER_INT16:
2973 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2974 atomic_type = int16_type_kind;
2977 case SPECIFIER_INT32:
2978 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2979 atomic_type = int32_type_kind;
2982 case SPECIFIER_INT64:
2983 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2984 atomic_type = int64_type_kind;
2987 case SPECIFIER_INT128:
2988 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2989 atomic_type = int128_type_kind;
2992 case SPECIFIER_FLOAT:
2993 atomic_type = ATOMIC_TYPE_FLOAT;
2995 case SPECIFIER_DOUBLE:
2996 atomic_type = ATOMIC_TYPE_DOUBLE;
2998 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2999 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3001 case SPECIFIER_BOOL:
3002 atomic_type = ATOMIC_TYPE_BOOL;
3004 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3005 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3006 atomic_type = ATOMIC_TYPE_FLOAT;
3008 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3009 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3010 atomic_type = ATOMIC_TYPE_DOUBLE;
3012 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3013 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3014 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3017 /* invalid specifier combination, give an error message */
3018 source_position_t const* const pos = &specifiers->source_position;
3019 if (type_specifiers == 0) {
3021 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3022 if (!(c_mode & _CXX) && !strict_mode) {
3023 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3024 atomic_type = ATOMIC_TYPE_INT;
3027 errorf(pos, "no type specifiers given in declaration");
3030 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3031 (type_specifiers & SPECIFIER_UNSIGNED)) {
3032 errorf(pos, "signed and unsigned specifiers given");
3033 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3034 errorf(pos, "only integer types can be signed or unsigned");
3036 errorf(pos, "multiple datatypes in declaration");
3042 if (type_specifiers & SPECIFIER_COMPLEX) {
3043 type = allocate_type_zero(TYPE_COMPLEX);
3044 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3045 type = allocate_type_zero(TYPE_IMAGINARY);
3047 type = allocate_type_zero(TYPE_ATOMIC);
3049 type->atomic.akind = atomic_type;
3051 } else if (type_specifiers != 0) {
3052 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3055 /* FIXME: check type qualifiers here */
3056 type->base.qualifiers = qualifiers;
3059 type = identify_new_type(type);
3061 type = typehash_insert(type);
3064 if (specifiers->attributes != NULL)
3065 type = handle_type_attributes(specifiers->attributes, type);
3066 specifiers->type = type;
3070 specifiers->type = type_error_type;
3073 static type_qualifiers_t parse_type_qualifiers(void)
3075 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3078 switch (token.kind) {
3079 /* type qualifiers */
3080 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3081 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3082 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3083 /* microsoft extended type modifiers */
3084 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3085 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3086 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3087 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3088 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3097 * Parses an K&R identifier list
3099 static void parse_identifier_list(scope_t *scope)
3101 assert(token.kind == T_IDENTIFIER);
3103 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3104 /* a K&R parameter has no type, yet */
3108 append_entity(scope, entity);
3109 } while (next_if(',') && token.kind == T_IDENTIFIER);
3112 static entity_t *parse_parameter(void)
3114 declaration_specifiers_t specifiers;
3115 parse_declaration_specifiers(&specifiers);
3117 entity_t *entity = parse_declarator(&specifiers,
3118 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3119 anonymous_entity = NULL;
3123 static void semantic_parameter_incomplete(const entity_t *entity)
3125 assert(entity->kind == ENTITY_PARAMETER);
3127 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3128 * list in a function declarator that is part of a
3129 * definition of that function shall not have
3130 * incomplete type. */
3131 type_t *type = skip_typeref(entity->declaration.type);
3132 if (is_type_incomplete(type)) {
3133 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3137 static bool has_parameters(void)
3139 /* func(void) is not a parameter */
3140 if (look_ahead(1)->kind != ')')
3142 if (token.kind == T_IDENTIFIER) {
3143 entity_t const *const entity
3144 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3147 if (entity->kind != ENTITY_TYPEDEF)
3149 type_t const *const type = skip_typeref(entity->typedefe.type);
3150 if (!is_type_void(type))
3152 if (c_mode & _CXX) {
3153 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3154 * is not allowed. */
3155 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3156 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3157 /* §6.7.5.3:10 Qualification is not allowed here. */
3158 errorf(HERE, "'void' as parameter must not have type qualifiers");
3160 } else if (token.kind != T_void) {
3168 * Parses function type parameters (and optionally creates variable_t entities
3169 * for them in a scope)
3171 static void parse_parameters(function_type_t *type, scope_t *scope)
3174 add_anchor_token(')');
3176 if (token.kind == T_IDENTIFIER &&
3177 !is_typedef_symbol(token.identifier.symbol) &&
3178 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3179 type->kr_style_parameters = true;
3180 parse_identifier_list(scope);
3181 } else if (token.kind == ')') {
3182 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3183 if (!(c_mode & _CXX))
3184 type->unspecified_parameters = true;
3185 } else if (has_parameters()) {
3186 function_parameter_t **anchor = &type->parameters;
3187 add_anchor_token(',');
3189 switch (token.kind) {
3192 type->variadic = true;
3193 goto parameters_finished;
3198 entity_t *entity = parse_parameter();
3199 if (entity->kind == ENTITY_TYPEDEF) {
3200 errorf(&entity->base.source_position,
3201 "typedef not allowed as function parameter");
3204 assert(is_declaration(entity));
3206 semantic_parameter_incomplete(entity);
3208 function_parameter_t *const parameter =
3209 allocate_parameter(entity->declaration.type);
3211 if (scope != NULL) {
3212 append_entity(scope, entity);
3215 *anchor = parameter;
3216 anchor = ¶meter->next;
3221 goto parameters_finished;
3223 } while (next_if(','));
3224 parameters_finished:
3225 rem_anchor_token(',');
3228 rem_anchor_token(')');
3232 typedef enum construct_type_kind_t {
3233 CONSTRUCT_POINTER = 1,
3234 CONSTRUCT_REFERENCE,
3237 } construct_type_kind_t;
3239 typedef union construct_type_t construct_type_t;
3241 typedef struct construct_type_base_t {
3242 construct_type_kind_t kind;
3243 source_position_t pos;
3244 construct_type_t *next;
3245 } construct_type_base_t;
3247 typedef struct parsed_pointer_t {
3248 construct_type_base_t base;
3249 type_qualifiers_t type_qualifiers;
3250 variable_t *base_variable; /**< MS __based extension. */
3253 typedef struct parsed_reference_t {
3254 construct_type_base_t base;
3255 } parsed_reference_t;
3257 typedef struct construct_function_type_t {
3258 construct_type_base_t base;
3259 type_t *function_type;
3260 } construct_function_type_t;
3262 typedef struct parsed_array_t {
3263 construct_type_base_t base;
3264 type_qualifiers_t type_qualifiers;
3270 union construct_type_t {
3271 construct_type_kind_t kind;
3272 construct_type_base_t base;
3273 parsed_pointer_t pointer;
3274 parsed_reference_t reference;
3275 construct_function_type_t function;
3276 parsed_array_t array;
3279 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3281 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3282 memset(cons, 0, size);
3284 cons->base.pos = *HERE;
3289 static construct_type_t *parse_pointer_declarator(void)
3291 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3293 cons->pointer.type_qualifiers = parse_type_qualifiers();
3294 //cons->pointer.base_variable = base_variable;
3299 /* ISO/IEC 14882:1998(E) §8.3.2 */
3300 static construct_type_t *parse_reference_declarator(void)
3302 if (!(c_mode & _CXX))
3303 errorf(HERE, "references are only available for C++");
3305 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3312 static construct_type_t *parse_array_declarator(void)
3314 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3315 parsed_array_t *const array = &cons->array;
3318 add_anchor_token(']');
3320 bool is_static = next_if(T_static);
3322 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3325 is_static = next_if(T_static);
3327 array->type_qualifiers = type_qualifiers;
3328 array->is_static = is_static;
3330 expression_t *size = NULL;
3331 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3332 array->is_variable = true;
3334 } else if (token.kind != ']') {
3335 size = parse_assignment_expression();
3337 /* §6.7.5.2:1 Array size must have integer type */
3338 type_t *const orig_type = size->base.type;
3339 type_t *const type = skip_typeref(orig_type);
3340 if (!is_type_integer(type) && is_type_valid(type)) {
3341 errorf(&size->base.source_position,
3342 "array size '%E' must have integer type but has type '%T'",
3347 mark_vars_read(size, NULL);
3350 if (is_static && size == NULL)
3351 errorf(&array->base.pos, "static array parameters require a size");
3353 rem_anchor_token(']');
3359 static construct_type_t *parse_function_declarator(scope_t *scope)
3361 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3363 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3364 function_type_t *ftype = &type->function;
3366 ftype->linkage = current_linkage;
3367 ftype->calling_convention = CC_DEFAULT;
3369 parse_parameters(ftype, scope);
3371 cons->function.function_type = type;
3376 typedef struct parse_declarator_env_t {
3377 bool may_be_abstract : 1;
3378 bool must_be_abstract : 1;
3379 decl_modifiers_t modifiers;
3381 source_position_t source_position;
3383 attribute_t *attributes;
3384 } parse_declarator_env_t;
3387 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3389 /* construct a single linked list of construct_type_t's which describe
3390 * how to construct the final declarator type */
3391 construct_type_t *first = NULL;
3392 construct_type_t **anchor = &first;
3394 env->attributes = parse_attributes(env->attributes);
3397 construct_type_t *type;
3398 //variable_t *based = NULL; /* MS __based extension */
3399 switch (token.kind) {
3401 type = parse_reference_declarator();
3405 panic("based not supported anymore");
3410 type = parse_pointer_declarator();
3414 goto ptr_operator_end;
3418 anchor = &type->base.next;
3420 /* TODO: find out if this is correct */
3421 env->attributes = parse_attributes(env->attributes);
3425 construct_type_t *inner_types = NULL;
3427 switch (token.kind) {
3429 if (env->must_be_abstract) {
3430 errorf(HERE, "no identifier expected in typename");
3432 env->symbol = token.identifier.symbol;
3433 env->source_position = token.base.source_position;
3439 /* Parenthesized declarator or function declarator? */
3440 token_t const *const la1 = look_ahead(1);
3441 switch (la1->kind) {
3443 if (is_typedef_symbol(la1->identifier.symbol)) {
3445 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3446 * interpreted as ``function with no parameter specification'', rather
3447 * than redundant parentheses around the omitted identifier. */
3449 /* Function declarator. */
3450 if (!env->may_be_abstract) {
3451 errorf(HERE, "function declarator must have a name");
3458 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3459 /* Paranthesized declarator. */
3461 add_anchor_token(')');
3462 inner_types = parse_inner_declarator(env);
3463 if (inner_types != NULL) {
3464 /* All later declarators only modify the return type */
3465 env->must_be_abstract = true;
3467 rem_anchor_token(')');
3476 if (env->may_be_abstract)
3478 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3483 construct_type_t **const p = anchor;
3486 construct_type_t *type;
3487 switch (token.kind) {
3489 scope_t *scope = NULL;
3490 if (!env->must_be_abstract) {
3491 scope = &env->parameters;
3494 type = parse_function_declarator(scope);
3498 type = parse_array_declarator();
3501 goto declarator_finished;
3504 /* insert in the middle of the list (at p) */
3505 type->base.next = *p;
3508 anchor = &type->base.next;
3511 declarator_finished:
3512 /* append inner_types at the end of the list, we don't to set anchor anymore
3513 * as it's not needed anymore */
3514 *anchor = inner_types;
3519 static type_t *construct_declarator_type(construct_type_t *construct_list,
3522 construct_type_t *iter = construct_list;
3523 for (; iter != NULL; iter = iter->base.next) {
3524 source_position_t const* const pos = &iter->base.pos;
3525 switch (iter->kind) {
3526 case CONSTRUCT_FUNCTION: {
3527 construct_function_type_t *function = &iter->function;
3528 type_t *function_type = function->function_type;
3530 function_type->function.return_type = type;
3532 type_t *skipped_return_type = skip_typeref(type);
3534 if (is_type_function(skipped_return_type)) {
3535 errorf(pos, "function returning function is not allowed");
3536 } else if (is_type_array(skipped_return_type)) {
3537 errorf(pos, "function returning array is not allowed");
3539 if (skipped_return_type->base.qualifiers != 0) {
3540 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3544 /* The function type was constructed earlier. Freeing it here will
3545 * destroy other types. */
3546 type = typehash_insert(function_type);
3550 case CONSTRUCT_POINTER: {
3551 if (is_type_reference(skip_typeref(type)))
3552 errorf(pos, "cannot declare a pointer to reference");
3554 parsed_pointer_t *pointer = &iter->pointer;
3555 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3559 case CONSTRUCT_REFERENCE:
3560 if (is_type_reference(skip_typeref(type)))
3561 errorf(pos, "cannot declare a reference to reference");
3563 type = make_reference_type(type);
3566 case CONSTRUCT_ARRAY: {
3567 if (is_type_reference(skip_typeref(type)))
3568 errorf(pos, "cannot declare an array of references");
3570 parsed_array_t *array = &iter->array;
3571 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3573 expression_t *size_expression = array->size;
3574 if (size_expression != NULL) {
3576 = create_implicit_cast(size_expression, type_size_t);
3579 array_type->base.qualifiers = array->type_qualifiers;
3580 array_type->array.element_type = type;
3581 array_type->array.is_static = array->is_static;
3582 array_type->array.is_variable = array->is_variable;
3583 array_type->array.size_expression = size_expression;
3585 if (size_expression != NULL) {
3586 switch (is_constant_expression(size_expression)) {
3587 case EXPR_CLASS_CONSTANT: {
3588 long const size = fold_constant_to_int(size_expression);
3589 array_type->array.size = size;
3590 array_type->array.size_constant = true;
3591 /* §6.7.5.2:1 If the expression is a constant expression,
3592 * it shall have a value greater than zero. */
3594 errorf(&size_expression->base.source_position,
3595 "size of array must be greater than zero");
3596 } else if (size == 0 && !GNU_MODE) {
3597 errorf(&size_expression->base.source_position,
3598 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3603 case EXPR_CLASS_VARIABLE:
3604 array_type->array.is_vla = true;
3607 case EXPR_CLASS_ERROR:
3612 type_t *skipped_type = skip_typeref(type);
3614 if (is_type_incomplete(skipped_type)) {
3615 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3616 } else if (is_type_function(skipped_type)) {
3617 errorf(pos, "array of functions is not allowed");
3619 type = identify_new_type(array_type);
3623 internal_errorf(pos, "invalid type construction found");
3629 static type_t *automatic_type_conversion(type_t *orig_type);
3631 static type_t *semantic_parameter(const source_position_t *pos,
3633 const declaration_specifiers_t *specifiers,
3634 entity_t const *const param)
3636 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3637 * shall be adjusted to ``qualified pointer to type'',
3639 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3640 * type'' shall be adjusted to ``pointer to function
3641 * returning type'', as in 6.3.2.1. */
3642 type = automatic_type_conversion(type);
3644 if (specifiers->is_inline && is_type_valid(type)) {
3645 errorf(pos, "'%N' declared 'inline'", param);
3648 /* §6.9.1:6 The declarations in the declaration list shall contain
3649 * no storage-class specifier other than register and no
3650 * initializations. */
3651 if (specifiers->thread_local || (
3652 specifiers->storage_class != STORAGE_CLASS_NONE &&
3653 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3655 errorf(pos, "invalid storage class for '%N'", param);
3658 /* delay test for incomplete type, because we might have (void)
3659 * which is legal but incomplete... */
3664 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3665 declarator_flags_t flags)
3667 parse_declarator_env_t env;
3668 memset(&env, 0, sizeof(env));
3669 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3671 construct_type_t *construct_type = parse_inner_declarator(&env);
3673 construct_declarator_type(construct_type, specifiers->type);
3674 type_t *type = skip_typeref(orig_type);
3676 if (construct_type != NULL) {
3677 obstack_free(&temp_obst, construct_type);
3680 attribute_t *attributes = parse_attributes(env.attributes);
3681 /* append (shared) specifier attribute behind attributes of this
3683 attribute_t **anchor = &attributes;
3684 while (*anchor != NULL)
3685 anchor = &(*anchor)->next;
3686 *anchor = specifiers->attributes;
3689 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3690 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3691 entity->typedefe.type = orig_type;
3693 if (anonymous_entity != NULL) {
3694 if (is_type_compound(type)) {
3695 assert(anonymous_entity->compound.alias == NULL);
3696 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3697 anonymous_entity->kind == ENTITY_UNION);
3698 anonymous_entity->compound.alias = entity;
3699 anonymous_entity = NULL;
3700 } else if (is_type_enum(type)) {
3701 assert(anonymous_entity->enume.alias == NULL);
3702 assert(anonymous_entity->kind == ENTITY_ENUM);
3703 anonymous_entity->enume.alias = entity;
3704 anonymous_entity = NULL;
3708 /* create a declaration type entity */
3709 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3710 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3711 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3713 if (env.symbol != NULL) {
3714 if (specifiers->is_inline && is_type_valid(type)) {
3715 errorf(&env.source_position,
3716 "compound member '%Y' declared 'inline'", env.symbol);
3719 if (specifiers->thread_local ||
3720 specifiers->storage_class != STORAGE_CLASS_NONE) {
3721 errorf(&env.source_position,
3722 "compound member '%Y' must have no storage class",
3726 } else if (flags & DECL_IS_PARAMETER) {
3727 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3728 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3729 } else if (is_type_function(type)) {
3730 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3731 entity->function.is_inline = specifiers->is_inline;
3732 entity->function.elf_visibility = default_visibility;
3733 entity->function.parameters = env.parameters;
3735 if (env.symbol != NULL) {
3736 /* this needs fixes for C++ */
3737 bool in_function_scope = current_function != NULL;
3739 if (specifiers->thread_local || (
3740 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3741 specifiers->storage_class != STORAGE_CLASS_NONE &&
3742 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3744 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3748 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3749 entity->variable.elf_visibility = default_visibility;
3750 entity->variable.thread_local = specifiers->thread_local;
3752 if (env.symbol != NULL) {
3753 if (specifiers->is_inline && is_type_valid(type)) {
3754 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3757 bool invalid_storage_class = false;
3758 if (current_scope == file_scope) {
3759 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3760 specifiers->storage_class != STORAGE_CLASS_NONE &&
3761 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3762 invalid_storage_class = true;
3765 if (specifiers->thread_local &&
3766 specifiers->storage_class == STORAGE_CLASS_NONE) {
3767 invalid_storage_class = true;
3770 if (invalid_storage_class) {
3771 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3776 entity->declaration.type = orig_type;
3777 entity->declaration.alignment = get_type_alignment(orig_type);
3778 entity->declaration.modifiers = env.modifiers;
3779 entity->declaration.attributes = attributes;
3781 storage_class_t storage_class = specifiers->storage_class;
3782 entity->declaration.declared_storage_class = storage_class;
3784 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3785 storage_class = STORAGE_CLASS_AUTO;
3786 entity->declaration.storage_class = storage_class;
3789 if (attributes != NULL) {
3790 handle_entity_attributes(attributes, entity);
3793 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3794 adapt_special_functions(&entity->function);
3800 static type_t *parse_abstract_declarator(type_t *base_type)
3802 parse_declarator_env_t env;
3803 memset(&env, 0, sizeof(env));
3804 env.may_be_abstract = true;
3805 env.must_be_abstract = true;
3807 construct_type_t *construct_type = parse_inner_declarator(&env);
3809 type_t *result = construct_declarator_type(construct_type, base_type);
3810 if (construct_type != NULL) {
3811 obstack_free(&temp_obst, construct_type);
3813 result = handle_type_attributes(env.attributes, result);
3819 * Check if the declaration of main is suspicious. main should be a
3820 * function with external linkage, returning int, taking either zero
3821 * arguments, two, or three arguments of appropriate types, ie.
3823 * int main([ int argc, char **argv [, char **env ] ]).
3825 * @param decl the declaration to check
3826 * @param type the function type of the declaration
3828 static void check_main(const entity_t *entity)
3830 const source_position_t *pos = &entity->base.source_position;
3831 if (entity->kind != ENTITY_FUNCTION) {
3832 warningf(WARN_MAIN, pos, "'main' is not a function");
3836 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3837 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3840 type_t *type = skip_typeref(entity->declaration.type);
3841 assert(is_type_function(type));
3843 function_type_t const *const func_type = &type->function;
3844 type_t *const ret_type = func_type->return_type;
3845 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3846 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3848 const function_parameter_t *parm = func_type->parameters;
3850 type_t *const first_type = skip_typeref(parm->type);
3851 type_t *const first_type_unqual = get_unqualified_type(first_type);
3852 if (!types_compatible(first_type_unqual, type_int)) {
3853 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3857 type_t *const second_type = skip_typeref(parm->type);
3858 type_t *const second_type_unqual
3859 = get_unqualified_type(second_type);
3860 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3861 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3865 type_t *const third_type = skip_typeref(parm->type);
3866 type_t *const third_type_unqual
3867 = get_unqualified_type(third_type);
3868 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3869 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3873 goto warn_arg_count;
3877 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3882 static void error_redefined_as_different_kind(const source_position_t *pos,
3883 const entity_t *old, entity_kind_t new_kind)
3885 char const *const what = get_entity_kind_name(new_kind);
3886 source_position_t const *const ppos = &old->base.source_position;
3887 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3890 static bool is_entity_valid(entity_t *const ent)
3892 if (is_declaration(ent)) {
3893 return is_type_valid(skip_typeref(ent->declaration.type));
3894 } else if (ent->kind == ENTITY_TYPEDEF) {
3895 return is_type_valid(skip_typeref(ent->typedefe.type));
3900 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3902 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3903 if (attributes_equal(tattr, attr))
3910 * test wether new_list contains any attributes not included in old_list
3912 static bool has_new_attributes(const attribute_t *old_list,
3913 const attribute_t *new_list)
3915 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3916 if (!contains_attribute(old_list, attr))
3923 * Merge in attributes from an attribute list (probably from a previous
3924 * declaration with the same name). Warning: destroys the old structure
3925 * of the attribute list - don't reuse attributes after this call.
3927 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3930 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3932 if (contains_attribute(decl->attributes, attr))
3935 /* move attribute to new declarations attributes list */
3936 attr->next = decl->attributes;
3937 decl->attributes = attr;
3941 static bool is_main(entity_t*);
3944 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3945 * for various problems that occur for multiple definitions
3947 entity_t *record_entity(entity_t *entity, const bool is_definition)
3949 const symbol_t *const symbol = entity->base.symbol;
3950 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3951 const source_position_t *pos = &entity->base.source_position;
3953 /* can happen in error cases */
3957 assert(!entity->base.parent_scope);
3958 assert(current_scope);
3959 entity->base.parent_scope = current_scope;
3961 entity_t *const previous_entity = get_entity(symbol, namespc);
3962 /* pushing the same entity twice will break the stack structure */
3963 assert(previous_entity != entity);
3965 if (entity->kind == ENTITY_FUNCTION) {
3966 type_t *const orig_type = entity->declaration.type;
3967 type_t *const type = skip_typeref(orig_type);
3969 assert(is_type_function(type));
3970 if (type->function.unspecified_parameters &&
3971 previous_entity == NULL &&
3972 !entity->declaration.implicit) {
3973 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3976 if (is_main(entity)) {
3981 if (is_declaration(entity) &&
3982 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3983 current_scope != file_scope &&
3984 !entity->declaration.implicit) {
3985 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3988 if (previous_entity != NULL) {
3989 source_position_t const *const ppos = &previous_entity->base.source_position;
3991 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3992 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3993 assert(previous_entity->kind == ENTITY_PARAMETER);
3994 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3998 if (previous_entity->base.parent_scope == current_scope) {
3999 if (previous_entity->kind != entity->kind) {
4000 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4001 error_redefined_as_different_kind(pos, previous_entity,
4006 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4007 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4010 if (previous_entity->kind == ENTITY_TYPEDEF) {
4011 type_t *const type = skip_typeref(entity->typedefe.type);
4012 type_t *const prev_type
4013 = skip_typeref(previous_entity->typedefe.type);
4014 if (c_mode & _CXX) {
4015 /* C++ allows double typedef if they are identical
4016 * (after skipping typedefs) */
4017 if (type == prev_type)
4020 /* GCC extension: redef in system headers is allowed */
4021 if ((pos->is_system_header || ppos->is_system_header) &&
4022 types_compatible(type, prev_type))
4025 errorf(pos, "redefinition of '%N' (declared %P)",
4030 /* at this point we should have only VARIABLES or FUNCTIONS */
4031 assert(is_declaration(previous_entity) && is_declaration(entity));
4033 declaration_t *const prev_decl = &previous_entity->declaration;
4034 declaration_t *const decl = &entity->declaration;
4036 /* can happen for K&R style declarations */
4037 if (prev_decl->type == NULL &&
4038 previous_entity->kind == ENTITY_PARAMETER &&
4039 entity->kind == ENTITY_PARAMETER) {
4040 prev_decl->type = decl->type;
4041 prev_decl->storage_class = decl->storage_class;
4042 prev_decl->declared_storage_class = decl->declared_storage_class;
4043 prev_decl->modifiers = decl->modifiers;
4044 return previous_entity;
4047 type_t *const type = skip_typeref(decl->type);
4048 type_t *const prev_type = skip_typeref(prev_decl->type);
4050 if (!types_compatible(type, prev_type)) {
4051 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4053 unsigned old_storage_class = prev_decl->storage_class;
4055 if (is_definition &&
4057 !(prev_decl->modifiers & DM_USED) &&
4058 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4059 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4062 storage_class_t new_storage_class = decl->storage_class;
4064 /* pretend no storage class means extern for function
4065 * declarations (except if the previous declaration is neither
4066 * none nor extern) */
4067 if (entity->kind == ENTITY_FUNCTION) {
4068 /* the previous declaration could have unspecified parameters or
4069 * be a typedef, so use the new type */
4070 if (prev_type->function.unspecified_parameters || is_definition)
4071 prev_decl->type = type;
4073 switch (old_storage_class) {
4074 case STORAGE_CLASS_NONE:
4075 old_storage_class = STORAGE_CLASS_EXTERN;
4078 case STORAGE_CLASS_EXTERN:
4079 if (is_definition) {
4080 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4081 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4083 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4084 new_storage_class = STORAGE_CLASS_EXTERN;
4091 } else if (is_type_incomplete(prev_type)) {
4092 prev_decl->type = type;
4095 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4096 new_storage_class == STORAGE_CLASS_EXTERN) {
4098 warn_redundant_declaration: ;
4100 = has_new_attributes(prev_decl->attributes,
4102 if (has_new_attrs) {
4103 merge_in_attributes(decl, prev_decl->attributes);
4104 } else if (!is_definition &&
4105 is_type_valid(prev_type) &&
4106 !pos->is_system_header) {
4107 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4109 } else if (current_function == NULL) {
4110 if (old_storage_class != STORAGE_CLASS_STATIC &&
4111 new_storage_class == STORAGE_CLASS_STATIC) {
4112 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4113 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4114 prev_decl->storage_class = STORAGE_CLASS_NONE;
4115 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4117 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4119 goto error_redeclaration;
4120 goto warn_redundant_declaration;
4122 } else if (is_type_valid(prev_type)) {
4123 if (old_storage_class == new_storage_class) {
4124 error_redeclaration:
4125 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4127 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4132 prev_decl->modifiers |= decl->modifiers;
4133 if (entity->kind == ENTITY_FUNCTION) {
4134 previous_entity->function.is_inline |= entity->function.is_inline;
4136 return previous_entity;
4140 if (is_warn_on(why = WARN_SHADOW) ||
4141 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4142 char const *const what = get_entity_kind_name(previous_entity->kind);
4143 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4147 if (entity->kind == ENTITY_FUNCTION) {
4148 if (is_definition &&
4149 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4151 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4152 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4154 goto warn_missing_declaration;
4157 } else if (entity->kind == ENTITY_VARIABLE) {
4158 if (current_scope == file_scope &&
4159 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4160 !entity->declaration.implicit) {
4161 warn_missing_declaration:
4162 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4167 environment_push(entity);
4168 append_entity(current_scope, entity);
4173 static void parser_error_multiple_definition(entity_t *entity,
4174 const source_position_t *source_position)
4176 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4177 entity->base.symbol, &entity->base.source_position);
4180 static bool is_declaration_specifier(const token_t *token)
4182 switch (token->kind) {
4186 return is_typedef_symbol(token->identifier.symbol);
4193 static void parse_init_declarator_rest(entity_t *entity)
4195 type_t *orig_type = type_error_type;
4197 if (entity->base.kind == ENTITY_TYPEDEF) {
4198 source_position_t const *const pos = &entity->base.source_position;
4199 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4201 assert(is_declaration(entity));
4202 orig_type = entity->declaration.type;
4205 type_t *type = skip_typeref(orig_type);
4207 if (entity->kind == ENTITY_VARIABLE
4208 && entity->variable.initializer != NULL) {
4209 parser_error_multiple_definition(entity, HERE);
4213 declaration_t *const declaration = &entity->declaration;
4214 bool must_be_constant = false;
4215 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4216 entity->base.parent_scope == file_scope) {
4217 must_be_constant = true;
4220 if (is_type_function(type)) {
4221 source_position_t const *const pos = &entity->base.source_position;
4222 errorf(pos, "'%N' is initialized like a variable", entity);
4223 orig_type = type_error_type;
4226 parse_initializer_env_t env;
4227 env.type = orig_type;
4228 env.must_be_constant = must_be_constant;
4229 env.entity = entity;
4231 initializer_t *initializer = parse_initializer(&env);
4233 if (entity->kind == ENTITY_VARIABLE) {
4234 /* §6.7.5:22 array initializers for arrays with unknown size
4235 * determine the array type size */
4236 declaration->type = env.type;
4237 entity->variable.initializer = initializer;
4241 /* parse rest of a declaration without any declarator */
4242 static void parse_anonymous_declaration_rest(
4243 const declaration_specifiers_t *specifiers)
4246 anonymous_entity = NULL;
4248 source_position_t const *const pos = &specifiers->source_position;
4249 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4250 specifiers->thread_local) {
4251 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4254 type_t *type = specifiers->type;
4255 switch (type->kind) {
4256 case TYPE_COMPOUND_STRUCT:
4257 case TYPE_COMPOUND_UNION: {
4258 if (type->compound.compound->base.symbol == NULL) {
4259 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4268 warningf(WARN_OTHER, pos, "empty declaration");
4273 static void check_variable_type_complete(entity_t *ent)
4275 if (ent->kind != ENTITY_VARIABLE)
4278 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4279 * type for the object shall be complete [...] */
4280 declaration_t *decl = &ent->declaration;
4281 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4282 decl->storage_class == STORAGE_CLASS_STATIC)
4285 type_t *const type = skip_typeref(decl->type);
4286 if (!is_type_incomplete(type))
4289 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4290 * are given length one. */
4291 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4292 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4296 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4300 static void parse_declaration_rest(entity_t *ndeclaration,
4301 const declaration_specifiers_t *specifiers,
4302 parsed_declaration_func finished_declaration,
4303 declarator_flags_t flags)
4305 add_anchor_token(';');
4306 add_anchor_token(',');
4308 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4310 if (token.kind == '=') {
4311 parse_init_declarator_rest(entity);
4312 } else if (entity->kind == ENTITY_VARIABLE) {
4313 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4314 * [...] where the extern specifier is explicitly used. */
4315 declaration_t *decl = &entity->declaration;
4316 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4317 is_type_reference(skip_typeref(decl->type))) {
4318 source_position_t const *const pos = &entity->base.source_position;
4319 errorf(pos, "reference '%#N' must be initialized", entity);
4323 check_variable_type_complete(entity);
4328 add_anchor_token('=');
4329 ndeclaration = parse_declarator(specifiers, flags);
4330 rem_anchor_token('=');
4332 rem_anchor_token(',');
4333 rem_anchor_token(';');
4336 anonymous_entity = NULL;
4339 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4341 symbol_t *symbol = entity->base.symbol;
4345 assert(entity->base.namespc == NAMESPACE_NORMAL);
4346 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4347 if (previous_entity == NULL
4348 || previous_entity->base.parent_scope != current_scope) {
4349 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4354 if (is_definition) {
4355 errorf(HERE, "'%N' is initialised", entity);
4358 return record_entity(entity, false);
4361 static void parse_declaration(parsed_declaration_func finished_declaration,
4362 declarator_flags_t flags)
4364 add_anchor_token(';');
4365 declaration_specifiers_t specifiers;
4366 parse_declaration_specifiers(&specifiers);
4367 rem_anchor_token(';');
4369 if (token.kind == ';') {
4370 parse_anonymous_declaration_rest(&specifiers);
4372 entity_t *entity = parse_declarator(&specifiers, flags);
4373 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4378 static type_t *get_default_promoted_type(type_t *orig_type)
4380 type_t *result = orig_type;
4382 type_t *type = skip_typeref(orig_type);
4383 if (is_type_integer(type)) {
4384 result = promote_integer(type);
4385 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4386 result = type_double;
4392 static void parse_kr_declaration_list(entity_t *entity)
4394 if (entity->kind != ENTITY_FUNCTION)
4397 type_t *type = skip_typeref(entity->declaration.type);
4398 assert(is_type_function(type));
4399 if (!type->function.kr_style_parameters)
4402 add_anchor_token('{');
4404 PUSH_SCOPE(&entity->function.parameters);
4406 entity_t *parameter = entity->function.parameters.entities;
4407 for ( ; parameter != NULL; parameter = parameter->base.next) {
4408 assert(parameter->base.parent_scope == NULL);
4409 parameter->base.parent_scope = current_scope;
4410 environment_push(parameter);
4413 /* parse declaration list */
4415 switch (token.kind) {
4417 /* This covers symbols, which are no type, too, and results in
4418 * better error messages. The typical cases are misspelled type
4419 * names and missing includes. */
4421 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4431 /* update function type */
4432 type_t *new_type = duplicate_type(type);
4434 function_parameter_t *parameters = NULL;
4435 function_parameter_t **anchor = ¶meters;
4437 /* did we have an earlier prototype? */
4438 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4439 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4442 function_parameter_t *proto_parameter = NULL;
4443 if (proto_type != NULL) {
4444 type_t *proto_type_type = proto_type->declaration.type;
4445 proto_parameter = proto_type_type->function.parameters;
4446 /* If a K&R function definition has a variadic prototype earlier, then
4447 * make the function definition variadic, too. This should conform to
4448 * §6.7.5.3:15 and §6.9.1:8. */
4449 new_type->function.variadic = proto_type_type->function.variadic;
4451 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4453 new_type->function.unspecified_parameters = true;
4456 bool need_incompatible_warning = false;
4457 parameter = entity->function.parameters.entities;
4458 for (; parameter != NULL; parameter = parameter->base.next,
4460 proto_parameter == NULL ? NULL : proto_parameter->next) {
4461 if (parameter->kind != ENTITY_PARAMETER)
4464 type_t *parameter_type = parameter->declaration.type;
4465 if (parameter_type == NULL) {
4466 source_position_t const* const pos = ¶meter->base.source_position;
4468 errorf(pos, "no type specified for function '%N'", parameter);
4469 parameter_type = type_error_type;
4471 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4472 parameter_type = type_int;
4474 parameter->declaration.type = parameter_type;
4477 semantic_parameter_incomplete(parameter);
4479 /* we need the default promoted types for the function type */
4480 type_t *not_promoted = parameter_type;
4481 parameter_type = get_default_promoted_type(parameter_type);
4483 /* gcc special: if the type of the prototype matches the unpromoted
4484 * type don't promote */
4485 if (!strict_mode && proto_parameter != NULL) {
4486 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4487 type_t *promo_skip = skip_typeref(parameter_type);
4488 type_t *param_skip = skip_typeref(not_promoted);
4489 if (!types_compatible(proto_p_type, promo_skip)
4490 && types_compatible(proto_p_type, param_skip)) {
4492 need_incompatible_warning = true;
4493 parameter_type = not_promoted;
4496 function_parameter_t *const function_parameter
4497 = allocate_parameter(parameter_type);
4499 *anchor = function_parameter;
4500 anchor = &function_parameter->next;
4503 new_type->function.parameters = parameters;
4504 new_type = identify_new_type(new_type);
4506 if (need_incompatible_warning) {
4507 symbol_t const *const sym = entity->base.symbol;
4508 source_position_t const *const pos = &entity->base.source_position;
4509 source_position_t const *const ppos = &proto_type->base.source_position;
4510 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4512 entity->declaration.type = new_type;
4514 rem_anchor_token('{');
4517 static bool first_err = true;
4520 * When called with first_err set, prints the name of the current function,
4523 static void print_in_function(void)
4527 char const *const file = current_function->base.base.source_position.input_name;
4528 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4533 * Check if all labels are defined in the current function.
4534 * Check if all labels are used in the current function.
4536 static void check_labels(void)
4538 for (const goto_statement_t *goto_statement = goto_first;
4539 goto_statement != NULL;
4540 goto_statement = goto_statement->next) {
4541 label_t *label = goto_statement->label;
4542 if (label->base.source_position.input_name == NULL) {
4543 print_in_function();
4544 source_position_t const *const pos = &goto_statement->base.source_position;
4545 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4549 if (is_warn_on(WARN_UNUSED_LABEL)) {
4550 for (const label_statement_t *label_statement = label_first;
4551 label_statement != NULL;
4552 label_statement = label_statement->next) {
4553 label_t *label = label_statement->label;
4555 if (! label->used) {
4556 print_in_function();
4557 source_position_t const *const pos = &label_statement->base.source_position;
4558 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4564 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4566 entity_t const *const end = last != NULL ? last->base.next : NULL;
4567 for (; entity != end; entity = entity->base.next) {
4568 if (!is_declaration(entity))
4571 declaration_t *declaration = &entity->declaration;
4572 if (declaration->implicit)
4575 if (!declaration->used) {
4576 print_in_function();
4577 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4578 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4579 print_in_function();
4580 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4585 static void check_unused_variables(statement_t *const stmt, void *const env)
4589 switch (stmt->kind) {
4590 case STATEMENT_DECLARATION: {
4591 declaration_statement_t const *const decls = &stmt->declaration;
4592 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4597 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4606 * Check declarations of current_function for unused entities.
4608 static void check_declarations(void)
4610 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4611 const scope_t *scope = ¤t_function->parameters;
4612 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4614 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4615 walk_statements(current_function->statement, check_unused_variables,
4620 static int determine_truth(expression_t const* const cond)
4623 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4624 fold_constant_to_bool(cond) ? 1 :
4628 static void check_reachable(statement_t *);
4629 static bool reaches_end;
4631 static bool expression_returns(expression_t const *const expr)
4633 switch (expr->kind) {
4635 expression_t const *const func = expr->call.function;
4636 type_t const *const type = skip_typeref(func->base.type);
4637 if (type->kind == TYPE_POINTER) {
4638 type_t const *const points_to
4639 = skip_typeref(type->pointer.points_to);
4640 if (points_to->kind == TYPE_FUNCTION
4641 && points_to->function.modifiers & DM_NORETURN)
4645 if (!expression_returns(func))
4648 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4649 if (!expression_returns(arg->expression))
4656 case EXPR_REFERENCE:
4657 case EXPR_ENUM_CONSTANT:
4658 case EXPR_LITERAL_CASES:
4659 case EXPR_STRING_LITERAL:
4660 case EXPR_WIDE_STRING_LITERAL:
4661 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4662 case EXPR_LABEL_ADDRESS:
4663 case EXPR_CLASSIFY_TYPE:
4664 case EXPR_SIZEOF: // TODO handle obscure VLA case
4667 case EXPR_BUILTIN_CONSTANT_P:
4668 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4673 case EXPR_STATEMENT: {
4674 bool old_reaches_end = reaches_end;
4675 reaches_end = false;
4676 check_reachable(expr->statement.statement);
4677 bool returns = reaches_end;
4678 reaches_end = old_reaches_end;
4682 case EXPR_CONDITIONAL:
4683 // TODO handle constant expression
4685 if (!expression_returns(expr->conditional.condition))
4688 if (expr->conditional.true_expression != NULL
4689 && expression_returns(expr->conditional.true_expression))
4692 return expression_returns(expr->conditional.false_expression);
4695 return expression_returns(expr->select.compound);
4697 case EXPR_ARRAY_ACCESS:
4699 expression_returns(expr->array_access.array_ref) &&
4700 expression_returns(expr->array_access.index);
4703 return expression_returns(expr->va_starte.ap);
4706 return expression_returns(expr->va_arge.ap);
4709 return expression_returns(expr->va_copye.src);
4711 case EXPR_UNARY_CASES_MANDATORY:
4712 return expression_returns(expr->unary.value);
4714 case EXPR_UNARY_THROW:
4717 case EXPR_BINARY_CASES:
4718 // TODO handle constant lhs of && and ||
4720 expression_returns(expr->binary.left) &&
4721 expression_returns(expr->binary.right);
4724 panic("unhandled expression");
4727 static bool initializer_returns(initializer_t const *const init)
4729 switch (init->kind) {
4730 case INITIALIZER_VALUE:
4731 return expression_returns(init->value.value);
4733 case INITIALIZER_LIST: {
4734 initializer_t * const* i = init->list.initializers;
4735 initializer_t * const* const end = i + init->list.len;
4736 bool returns = true;
4737 for (; i != end; ++i) {
4738 if (!initializer_returns(*i))
4744 case INITIALIZER_STRING:
4745 case INITIALIZER_WIDE_STRING:
4746 case INITIALIZER_DESIGNATOR: // designators have no payload
4749 panic("unhandled initializer");
4752 static bool noreturn_candidate;
4754 static void check_reachable(statement_t *const stmt)
4756 if (stmt->base.reachable)
4758 if (stmt->kind != STATEMENT_DO_WHILE)
4759 stmt->base.reachable = true;
4761 statement_t *last = stmt;
4763 switch (stmt->kind) {
4764 case STATEMENT_ERROR:
4765 case STATEMENT_EMPTY:
4767 next = stmt->base.next;
4770 case STATEMENT_DECLARATION: {
4771 declaration_statement_t const *const decl = &stmt->declaration;
4772 entity_t const * ent = decl->declarations_begin;
4773 entity_t const *const last_decl = decl->declarations_end;
4775 for (;; ent = ent->base.next) {
4776 if (ent->kind == ENTITY_VARIABLE &&
4777 ent->variable.initializer != NULL &&
4778 !initializer_returns(ent->variable.initializer)) {
4781 if (ent == last_decl)
4785 next = stmt->base.next;
4789 case STATEMENT_COMPOUND:
4790 next = stmt->compound.statements;
4792 next = stmt->base.next;
4795 case STATEMENT_RETURN: {
4796 expression_t const *const val = stmt->returns.value;
4797 if (val == NULL || expression_returns(val))
4798 noreturn_candidate = false;
4802 case STATEMENT_IF: {
4803 if_statement_t const *const ifs = &stmt->ifs;
4804 expression_t const *const cond = ifs->condition;
4806 if (!expression_returns(cond))
4809 int const val = determine_truth(cond);
4812 check_reachable(ifs->true_statement);
4817 if (ifs->false_statement != NULL) {
4818 check_reachable(ifs->false_statement);
4822 next = stmt->base.next;
4826 case STATEMENT_SWITCH: {
4827 switch_statement_t const *const switchs = &stmt->switchs;
4828 expression_t const *const expr = switchs->expression;
4830 if (!expression_returns(expr))
4833 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4834 long const val = fold_constant_to_int(expr);
4835 case_label_statement_t * defaults = NULL;
4836 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4837 if (i->expression == NULL) {
4842 if (i->first_case <= val && val <= i->last_case) {
4843 check_reachable((statement_t*)i);
4848 if (defaults != NULL) {
4849 check_reachable((statement_t*)defaults);
4853 bool has_default = false;
4854 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4855 if (i->expression == NULL)
4858 check_reachable((statement_t*)i);
4865 next = stmt->base.next;
4869 case STATEMENT_EXPRESSION: {
4870 /* Check for noreturn function call */
4871 expression_t const *const expr = stmt->expression.expression;
4872 if (!expression_returns(expr))
4875 next = stmt->base.next;
4879 case STATEMENT_CONTINUE:
4880 for (statement_t *parent = stmt;;) {
4881 parent = parent->base.parent;
4882 if (parent == NULL) /* continue not within loop */
4886 switch (parent->kind) {
4887 case STATEMENT_WHILE: goto continue_while;
4888 case STATEMENT_DO_WHILE: goto continue_do_while;
4889 case STATEMENT_FOR: goto continue_for;
4895 case STATEMENT_BREAK:
4896 for (statement_t *parent = stmt;;) {
4897 parent = parent->base.parent;
4898 if (parent == NULL) /* break not within loop/switch */
4901 switch (parent->kind) {
4902 case STATEMENT_SWITCH:
4903 case STATEMENT_WHILE:
4904 case STATEMENT_DO_WHILE:
4907 next = parent->base.next;
4908 goto found_break_parent;
4916 case STATEMENT_COMPUTED_GOTO: {
4917 if (!expression_returns(stmt->computed_goto.expression))
4920 statement_t *parent = stmt->base.parent;
4921 if (parent == NULL) /* top level goto */
4927 case STATEMENT_GOTO:
4928 next = stmt->gotos.label->statement;
4929 if (next == NULL) /* missing label */
4933 case STATEMENT_LABEL:
4934 next = stmt->label.statement;
4937 case STATEMENT_CASE_LABEL:
4938 next = stmt->case_label.statement;
4941 case STATEMENT_WHILE: {
4942 while_statement_t const *const whiles = &stmt->whiles;
4943 expression_t const *const cond = whiles->condition;
4945 if (!expression_returns(cond))
4948 int const val = determine_truth(cond);
4951 check_reachable(whiles->body);
4956 next = stmt->base.next;
4960 case STATEMENT_DO_WHILE:
4961 next = stmt->do_while.body;
4964 case STATEMENT_FOR: {
4965 for_statement_t *const fors = &stmt->fors;
4967 if (fors->condition_reachable)
4969 fors->condition_reachable = true;
4971 expression_t const *const cond = fors->condition;
4976 } else if (expression_returns(cond)) {
4977 val = determine_truth(cond);
4983 check_reachable(fors->body);
4988 next = stmt->base.next;
4992 case STATEMENT_MS_TRY: {
4993 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4994 check_reachable(ms_try->try_statement);
4995 next = ms_try->final_statement;
4999 case STATEMENT_LEAVE: {
5000 statement_t *parent = stmt;
5002 parent = parent->base.parent;
5003 if (parent == NULL) /* __leave not within __try */
5006 if (parent->kind == STATEMENT_MS_TRY) {
5008 next = parent->ms_try.final_statement;
5016 panic("invalid statement kind");
5019 while (next == NULL) {
5020 next = last->base.parent;
5022 noreturn_candidate = false;
5024 type_t *const type = skip_typeref(current_function->base.type);
5025 assert(is_type_function(type));
5026 type_t *const ret = skip_typeref(type->function.return_type);
5027 if (!is_type_void(ret) &&
5028 is_type_valid(ret) &&
5029 !is_main(current_entity)) {
5030 source_position_t const *const pos = &stmt->base.source_position;
5031 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5036 switch (next->kind) {
5037 case STATEMENT_ERROR:
5038 case STATEMENT_EMPTY:
5039 case STATEMENT_DECLARATION:
5040 case STATEMENT_EXPRESSION:
5042 case STATEMENT_RETURN:
5043 case STATEMENT_CONTINUE:
5044 case STATEMENT_BREAK:
5045 case STATEMENT_COMPUTED_GOTO:
5046 case STATEMENT_GOTO:
5047 case STATEMENT_LEAVE:
5048 panic("invalid control flow in function");
5050 case STATEMENT_COMPOUND:
5051 if (next->compound.stmt_expr) {
5057 case STATEMENT_SWITCH:
5058 case STATEMENT_LABEL:
5059 case STATEMENT_CASE_LABEL:
5061 next = next->base.next;
5064 case STATEMENT_WHILE: {
5066 if (next->base.reachable)
5068 next->base.reachable = true;
5070 while_statement_t const *const whiles = &next->whiles;
5071 expression_t const *const cond = whiles->condition;
5073 if (!expression_returns(cond))
5076 int const val = determine_truth(cond);
5079 check_reachable(whiles->body);
5085 next = next->base.next;
5089 case STATEMENT_DO_WHILE: {
5091 if (next->base.reachable)
5093 next->base.reachable = true;
5095 do_while_statement_t const *const dw = &next->do_while;
5096 expression_t const *const cond = dw->condition;
5098 if (!expression_returns(cond))
5101 int const val = determine_truth(cond);
5104 check_reachable(dw->body);
5110 next = next->base.next;
5114 case STATEMENT_FOR: {
5116 for_statement_t *const fors = &next->fors;
5118 fors->step_reachable = true;
5120 if (fors->condition_reachable)
5122 fors->condition_reachable = true;
5124 expression_t const *const cond = fors->condition;
5129 } else if (expression_returns(cond)) {
5130 val = determine_truth(cond);
5136 check_reachable(fors->body);
5142 next = next->base.next;
5146 case STATEMENT_MS_TRY:
5148 next = next->ms_try.final_statement;
5153 check_reachable(next);
5156 static void check_unreachable(statement_t* const stmt, void *const env)
5160 switch (stmt->kind) {
5161 case STATEMENT_DO_WHILE:
5162 if (!stmt->base.reachable) {
5163 expression_t const *const cond = stmt->do_while.condition;
5164 if (determine_truth(cond) >= 0) {
5165 source_position_t const *const pos = &cond->base.source_position;
5166 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5171 case STATEMENT_FOR: {
5172 for_statement_t const* const fors = &stmt->fors;
5174 // if init and step are unreachable, cond is unreachable, too
5175 if (!stmt->base.reachable && !fors->step_reachable) {
5176 goto warn_unreachable;
5178 if (!stmt->base.reachable && fors->initialisation != NULL) {
5179 source_position_t const *const pos = &fors->initialisation->base.source_position;
5180 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5183 if (!fors->condition_reachable && fors->condition != NULL) {
5184 source_position_t const *const pos = &fors->condition->base.source_position;
5185 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5188 if (!fors->step_reachable && fors->step != NULL) {
5189 source_position_t const *const pos = &fors->step->base.source_position;
5190 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5196 case STATEMENT_COMPOUND:
5197 if (stmt->compound.statements != NULL)
5199 goto warn_unreachable;
5201 case STATEMENT_DECLARATION: {
5202 /* Only warn if there is at least one declarator with an initializer.
5203 * This typically occurs in switch statements. */
5204 declaration_statement_t const *const decl = &stmt->declaration;
5205 entity_t const * ent = decl->declarations_begin;
5206 entity_t const *const last = decl->declarations_end;
5208 for (;; ent = ent->base.next) {
5209 if (ent->kind == ENTITY_VARIABLE &&
5210 ent->variable.initializer != NULL) {
5211 goto warn_unreachable;
5221 if (!stmt->base.reachable) {
5222 source_position_t const *const pos = &stmt->base.source_position;
5223 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5229 static bool is_main(entity_t *entity)
5231 static symbol_t *sym_main = NULL;
5232 if (sym_main == NULL) {
5233 sym_main = symbol_table_insert("main");
5236 if (entity->base.symbol != sym_main)
5238 /* must be in outermost scope */
5239 if (entity->base.parent_scope != file_scope)
5245 static void prepare_main_collect2(entity_t*);
5247 static void parse_external_declaration(void)
5249 /* function-definitions and declarations both start with declaration
5251 add_anchor_token(';');
5252 declaration_specifiers_t specifiers;
5253 parse_declaration_specifiers(&specifiers);
5254 rem_anchor_token(';');
5256 /* must be a declaration */
5257 if (token.kind == ';') {
5258 parse_anonymous_declaration_rest(&specifiers);
5262 add_anchor_token(',');
5263 add_anchor_token('=');
5264 add_anchor_token(';');
5265 add_anchor_token('{');
5267 /* declarator is common to both function-definitions and declarations */
5268 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5270 rem_anchor_token('{');
5271 rem_anchor_token(';');
5272 rem_anchor_token('=');
5273 rem_anchor_token(',');
5275 /* must be a declaration */
5276 switch (token.kind) {
5280 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5285 /* must be a function definition */
5286 parse_kr_declaration_list(ndeclaration);
5288 if (token.kind != '{') {
5289 parse_error_expected("while parsing function definition", '{', NULL);
5290 eat_until_matching_token(';');
5294 assert(is_declaration(ndeclaration));
5295 type_t *const orig_type = ndeclaration->declaration.type;
5296 type_t * type = skip_typeref(orig_type);
5298 if (!is_type_function(type)) {
5299 if (is_type_valid(type)) {
5300 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5306 source_position_t const *const pos = &ndeclaration->base.source_position;
5307 if (is_typeref(orig_type)) {
5309 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5312 if (is_type_compound(skip_typeref(type->function.return_type))) {
5313 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5315 if (type->function.unspecified_parameters) {
5316 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5318 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5321 /* §6.7.5.3:14 a function definition with () means no
5322 * parameters (and not unspecified parameters) */
5323 if (type->function.unspecified_parameters &&
5324 type->function.parameters == NULL) {
5325 type_t *copy = duplicate_type(type);
5326 copy->function.unspecified_parameters = false;
5327 type = identify_new_type(copy);
5329 ndeclaration->declaration.type = type;
5332 entity_t *const entity = record_entity(ndeclaration, true);
5333 assert(entity->kind == ENTITY_FUNCTION);
5334 assert(ndeclaration->kind == ENTITY_FUNCTION);
5336 function_t *const function = &entity->function;
5337 if (ndeclaration != entity) {
5338 function->parameters = ndeclaration->function.parameters;
5341 PUSH_SCOPE(&function->parameters);
5343 entity_t *parameter = function->parameters.entities;
5344 for (; parameter != NULL; parameter = parameter->base.next) {
5345 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5346 parameter->base.parent_scope = current_scope;
5348 assert(parameter->base.parent_scope == NULL
5349 || parameter->base.parent_scope == current_scope);
5350 parameter->base.parent_scope = current_scope;
5351 if (parameter->base.symbol == NULL) {
5352 errorf(¶meter->base.source_position, "parameter name omitted");
5355 environment_push(parameter);
5358 if (function->statement != NULL) {
5359 parser_error_multiple_definition(entity, HERE);
5362 /* parse function body */
5363 int label_stack_top = label_top();
5364 function_t *old_current_function = current_function;
5365 current_function = function;
5366 PUSH_CURRENT_ENTITY(entity);
5370 goto_anchor = &goto_first;
5372 label_anchor = &label_first;
5374 statement_t *const body = parse_compound_statement(false);
5375 function->statement = body;
5378 check_declarations();
5379 if (is_warn_on(WARN_RETURN_TYPE) ||
5380 is_warn_on(WARN_UNREACHABLE_CODE) ||
5381 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5382 noreturn_candidate = true;
5383 check_reachable(body);
5384 if (is_warn_on(WARN_UNREACHABLE_CODE))
5385 walk_statements(body, check_unreachable, NULL);
5386 if (noreturn_candidate &&
5387 !(function->base.modifiers & DM_NORETURN)) {
5388 source_position_t const *const pos = &body->base.source_position;
5389 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5393 if (is_main(entity)) {
5394 /* Force main to C linkage. */
5395 type_t *const type = entity->declaration.type;
5396 assert(is_type_function(type));
5397 if (type->function.linkage != LINKAGE_C) {
5398 type_t *new_type = duplicate_type(type);
5399 new_type->function.linkage = LINKAGE_C;
5400 entity->declaration.type = identify_new_type(new_type);
5403 if (enable_main_collect2_hack)
5404 prepare_main_collect2(entity);
5407 POP_CURRENT_ENTITY();
5409 assert(current_function == function);
5410 current_function = old_current_function;
5411 label_pop_to(label_stack_top);
5417 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5419 entity_t *iter = compound->members.entities;
5420 for (; iter != NULL; iter = iter->base.next) {
5421 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5424 if (iter->base.symbol == symbol) {
5426 } else if (iter->base.symbol == NULL) {
5427 /* search in anonymous structs and unions */
5428 type_t *type = skip_typeref(iter->declaration.type);
5429 if (is_type_compound(type)) {
5430 if (find_compound_entry(type->compound.compound, symbol)
5441 static void check_deprecated(const source_position_t *source_position,
5442 const entity_t *entity)
5444 if (!is_declaration(entity))
5446 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5449 source_position_t const *const epos = &entity->base.source_position;
5450 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5452 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5454 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5459 static expression_t *create_select(const source_position_t *pos,
5461 type_qualifiers_t qualifiers,
5464 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5466 check_deprecated(pos, entry);
5468 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5469 select->select.compound = addr;
5470 select->select.compound_entry = entry;
5472 type_t *entry_type = entry->declaration.type;
5473 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5475 /* bitfields need special treatment */
5476 if (entry->compound_member.bitfield) {
5477 unsigned bit_size = entry->compound_member.bit_size;
5478 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5479 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5480 res_type = type_int;
5484 /* we always do the auto-type conversions; the & and sizeof parser contains
5485 * code to revert this! */
5486 select->base.type = automatic_type_conversion(res_type);
5493 * Find entry with symbol in compound. Search anonymous structs and unions and
5494 * creates implicit select expressions for them.
5495 * Returns the adress for the innermost compound.
5497 static expression_t *find_create_select(const source_position_t *pos,
5499 type_qualifiers_t qualifiers,
5500 compound_t *compound, symbol_t *symbol)
5502 entity_t *iter = compound->members.entities;
5503 for (; iter != NULL; iter = iter->base.next) {
5504 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5507 symbol_t *iter_symbol = iter->base.symbol;
5508 if (iter_symbol == NULL) {
5509 type_t *type = iter->declaration.type;
5510 if (type->kind != TYPE_COMPOUND_STRUCT
5511 && type->kind != TYPE_COMPOUND_UNION)
5514 compound_t *sub_compound = type->compound.compound;
5516 if (find_compound_entry(sub_compound, symbol) == NULL)
5519 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5520 sub_addr->base.source_position = *pos;
5521 sub_addr->base.implicit = true;
5522 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5526 if (iter_symbol == symbol) {
5527 return create_select(pos, addr, qualifiers, iter);
5534 static void parse_bitfield_member(entity_t *entity)
5538 expression_t *size = parse_constant_expression();
5541 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5542 type_t *type = entity->declaration.type;
5543 if (!is_type_integer(skip_typeref(type))) {
5544 errorf(HERE, "bitfield base type '%T' is not an integer type",
5548 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5549 /* error already reported by parse_constant_expression */
5550 size_long = get_type_size(type) * 8;
5552 size_long = fold_constant_to_int(size);
5554 const symbol_t *symbol = entity->base.symbol;
5555 const symbol_t *user_symbol
5556 = symbol == NULL ? sym_anonymous : symbol;
5557 unsigned bit_size = get_type_size(type) * 8;
5558 if (size_long < 0) {
5559 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5560 } else if (size_long == 0 && symbol != NULL) {
5561 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5562 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5563 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5566 /* hope that people don't invent crazy types with more bits
5567 * than our struct can hold */
5569 (1 << sizeof(entity->compound_member.bit_size)*8));
5573 entity->compound_member.bitfield = true;
5574 entity->compound_member.bit_size = (unsigned char)size_long;
5577 static void parse_compound_declarators(compound_t *compound,
5578 const declaration_specifiers_t *specifiers)
5580 add_anchor_token(';');
5581 add_anchor_token(',');
5585 if (token.kind == ':') {
5586 /* anonymous bitfield */
5587 type_t *type = specifiers->type;
5588 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5589 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5590 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5591 entity->declaration.type = type;
5593 parse_bitfield_member(entity);
5595 attribute_t *attributes = parse_attributes(NULL);
5596 attribute_t **anchor = &attributes;
5597 while (*anchor != NULL)
5598 anchor = &(*anchor)->next;
5599 *anchor = specifiers->attributes;
5600 if (attributes != NULL) {
5601 handle_entity_attributes(attributes, entity);
5603 entity->declaration.attributes = attributes;
5605 append_entity(&compound->members, entity);
5607 entity = parse_declarator(specifiers,
5608 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5609 source_position_t const *const pos = &entity->base.source_position;
5610 if (entity->kind == ENTITY_TYPEDEF) {
5611 errorf(pos, "typedef not allowed as compound member");
5613 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5615 /* make sure we don't define a symbol multiple times */
5616 symbol_t *symbol = entity->base.symbol;
5617 if (symbol != NULL) {
5618 entity_t *prev = find_compound_entry(compound, symbol);
5620 source_position_t const *const ppos = &prev->base.source_position;
5621 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5625 if (token.kind == ':') {
5626 parse_bitfield_member(entity);
5628 attribute_t *attributes = parse_attributes(NULL);
5629 handle_entity_attributes(attributes, entity);
5631 type_t *orig_type = entity->declaration.type;
5632 type_t *type = skip_typeref(orig_type);
5633 if (is_type_function(type)) {
5634 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5635 } else if (is_type_incomplete(type)) {
5636 /* §6.7.2.1:16 flexible array member */
5637 if (!is_type_array(type) ||
5638 token.kind != ';' ||
5639 look_ahead(1)->kind != '}') {
5640 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5641 } else if (compound->members.entities == NULL) {
5642 errorf(pos, "flexible array member in otherwise empty struct");
5647 append_entity(&compound->members, entity);
5650 } while (next_if(','));
5651 rem_anchor_token(',');
5652 rem_anchor_token(';');
5655 anonymous_entity = NULL;
5658 static void parse_compound_type_entries(compound_t *compound)
5661 add_anchor_token('}');
5664 switch (token.kind) {
5666 case T___extension__:
5667 case T_IDENTIFIER: {
5669 declaration_specifiers_t specifiers;
5670 parse_declaration_specifiers(&specifiers);
5671 parse_compound_declarators(compound, &specifiers);
5677 rem_anchor_token('}');
5680 compound->complete = true;
5686 static type_t *parse_typename(void)
5688 declaration_specifiers_t specifiers;
5689 parse_declaration_specifiers(&specifiers);
5690 if (specifiers.storage_class != STORAGE_CLASS_NONE
5691 || specifiers.thread_local) {
5692 /* TODO: improve error message, user does probably not know what a
5693 * storage class is...
5695 errorf(&specifiers.source_position, "typename must not have a storage class");
5698 type_t *result = parse_abstract_declarator(specifiers.type);
5706 typedef expression_t* (*parse_expression_function)(void);
5707 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5709 typedef struct expression_parser_function_t expression_parser_function_t;
5710 struct expression_parser_function_t {
5711 parse_expression_function parser;
5712 precedence_t infix_precedence;
5713 parse_expression_infix_function infix_parser;
5716 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5718 static type_t *get_string_type(void)
5720 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5723 static type_t *get_wide_string_type(void)
5725 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5729 * Parse a string constant.
5731 static expression_t *parse_string_literal(void)
5733 source_position_t begin = token.base.source_position;
5734 string_t res = token.string.string;
5735 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5738 while (token.kind == T_STRING_LITERAL
5739 || token.kind == T_WIDE_STRING_LITERAL) {
5740 warn_string_concat(&token.base.source_position);
5741 res = concat_strings(&res, &token.string.string);
5743 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5746 expression_t *literal;
5748 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5749 literal->base.type = get_wide_string_type();
5751 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5752 literal->base.type = get_string_type();
5754 literal->base.source_position = begin;
5755 literal->literal.value = res;
5761 * Parse a boolean constant.
5763 static expression_t *parse_boolean_literal(bool value)
5765 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5766 literal->base.type = type_bool;
5767 literal->literal.value.begin = value ? "true" : "false";
5768 literal->literal.value.size = value ? 4 : 5;
5774 static void warn_traditional_suffix(void)
5776 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5777 &token.number.suffix);
5780 static void check_integer_suffix(void)
5782 const string_t *suffix = &token.number.suffix;
5783 if (suffix->size == 0)
5786 bool not_traditional = false;
5787 const char *c = suffix->begin;
5788 if (*c == 'l' || *c == 'L') {
5791 not_traditional = true;
5793 if (*c == 'u' || *c == 'U') {
5796 } else if (*c == 'u' || *c == 'U') {
5797 not_traditional = true;
5800 } else if (*c == 'u' || *c == 'U') {
5801 not_traditional = true;
5803 if (*c == 'l' || *c == 'L') {
5811 errorf(&token.base.source_position,
5812 "invalid suffix '%S' on integer constant", suffix);
5813 } else if (not_traditional) {
5814 warn_traditional_suffix();
5818 static type_t *check_floatingpoint_suffix(void)
5820 const string_t *suffix = &token.number.suffix;
5821 type_t *type = type_double;
5822 if (suffix->size == 0)
5825 bool not_traditional = false;
5826 const char *c = suffix->begin;
5827 if (*c == 'f' || *c == 'F') {
5830 } else if (*c == 'l' || *c == 'L') {
5832 type = type_long_double;
5835 errorf(&token.base.source_position,
5836 "invalid suffix '%S' on floatingpoint constant", suffix);
5837 } else if (not_traditional) {
5838 warn_traditional_suffix();
5845 * Parse an integer constant.
5847 static expression_t *parse_number_literal(void)
5849 expression_kind_t kind;
5852 switch (token.kind) {
5854 kind = EXPR_LITERAL_INTEGER;
5855 check_integer_suffix();
5859 case T_FLOATINGPOINT:
5860 case T_FLOATINGPOINT_HEXADECIMAL:
5861 kind = EXPR_LITERAL_FLOATINGPOINT;
5862 type = check_floatingpoint_suffix();
5866 panic("unexpected token type in parse_number_literal");
5869 expression_t *literal = allocate_expression_zero(kind);
5870 literal->base.type = type;
5871 literal->literal.value = token.number.number;
5872 literal->literal.suffix = token.number.suffix;
5875 /* integer type depends on the size of the number and the size
5876 * representable by the types. The backend/codegeneration has to determine
5879 determine_literal_type(&literal->literal);
5884 * Parse a character constant.
5886 static expression_t *parse_character_constant(void)
5888 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5889 literal->base.type = c_mode & _CXX ? type_char : type_int;
5890 literal->literal.value = token.string.string;
5892 size_t len = literal->literal.value.size;
5894 if (!GNU_MODE && !(c_mode & _C99)) {
5895 errorf(HERE, "more than 1 character in character constant");
5897 literal->base.type = type_int;
5898 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5907 * Parse a wide character constant.
5909 static expression_t *parse_wide_character_constant(void)
5911 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5912 literal->base.type = type_int;
5913 literal->literal.value = token.string.string;
5915 size_t len = wstrlen(&literal->literal.value);
5917 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5924 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5926 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5927 ntype->function.return_type = type_int;
5928 ntype->function.unspecified_parameters = true;
5929 ntype->function.linkage = LINKAGE_C;
5930 type_t *type = identify_new_type(ntype);
5932 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5933 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5934 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5935 entity->declaration.type = type;
5936 entity->declaration.implicit = true;
5938 if (current_scope != NULL)
5939 record_entity(entity, false);
5945 * Performs automatic type cast as described in §6.3.2.1.
5947 * @param orig_type the original type
5949 static type_t *automatic_type_conversion(type_t *orig_type)
5951 type_t *type = skip_typeref(orig_type);
5952 if (is_type_array(type)) {
5953 array_type_t *array_type = &type->array;
5954 type_t *element_type = array_type->element_type;
5955 unsigned qualifiers = array_type->base.qualifiers;
5957 return make_pointer_type(element_type, qualifiers);
5960 if (is_type_function(type)) {
5961 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5968 * reverts the automatic casts of array to pointer types and function
5969 * to function-pointer types as defined §6.3.2.1
5971 type_t *revert_automatic_type_conversion(const expression_t *expression)
5973 switch (expression->kind) {
5974 case EXPR_REFERENCE: {
5975 entity_t *entity = expression->reference.entity;
5976 if (is_declaration(entity)) {
5977 return entity->declaration.type;
5978 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5979 return entity->enum_value.enum_type;
5981 panic("no declaration or enum in reference");
5986 entity_t *entity = expression->select.compound_entry;
5987 assert(is_declaration(entity));
5988 type_t *type = entity->declaration.type;
5989 return get_qualified_type(type, expression->base.type->base.qualifiers);
5992 case EXPR_UNARY_DEREFERENCE: {
5993 const expression_t *const value = expression->unary.value;
5994 type_t *const type = skip_typeref(value->base.type);
5995 if (!is_type_pointer(type))
5996 return type_error_type;
5997 return type->pointer.points_to;
6000 case EXPR_ARRAY_ACCESS: {
6001 const expression_t *array_ref = expression->array_access.array_ref;
6002 type_t *type_left = skip_typeref(array_ref->base.type);
6003 if (!is_type_pointer(type_left))
6004 return type_error_type;
6005 return type_left->pointer.points_to;
6008 case EXPR_STRING_LITERAL: {
6009 size_t size = expression->string_literal.value.size;
6010 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6013 case EXPR_WIDE_STRING_LITERAL: {
6014 size_t size = wstrlen(&expression->string_literal.value);
6015 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6018 case EXPR_COMPOUND_LITERAL:
6019 return expression->compound_literal.type;
6024 return expression->base.type;
6028 * Find an entity matching a symbol in a scope.
6029 * Uses current scope if scope is NULL
6031 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6032 namespace_tag_t namespc)
6034 if (scope == NULL) {
6035 return get_entity(symbol, namespc);
6038 /* we should optimize here, if scope grows above a certain size we should
6039 construct a hashmap here... */
6040 entity_t *entity = scope->entities;
6041 for ( ; entity != NULL; entity = entity->base.next) {
6042 if (entity->base.symbol == symbol
6043 && (namespace_tag_t)entity->base.namespc == namespc)
6050 static entity_t *parse_qualified_identifier(void)
6052 /* namespace containing the symbol */
6054 source_position_t pos;
6055 const scope_t *lookup_scope = NULL;
6057 if (next_if(T_COLONCOLON))
6058 lookup_scope = &unit->scope;
6062 symbol = expect_identifier("while parsing identifier", &pos);
6064 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6067 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6069 if (!next_if(T_COLONCOLON))
6072 switch (entity->kind) {
6073 case ENTITY_NAMESPACE:
6074 lookup_scope = &entity->namespacee.members;
6079 lookup_scope = &entity->compound.members;
6082 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6083 symbol, get_entity_kind_name(entity->kind));
6085 /* skip further qualifications */
6086 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6088 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6092 if (entity == NULL) {
6093 if (!strict_mode && token.kind == '(') {
6094 /* an implicitly declared function */
6095 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6096 "implicit declaration of function '%Y'", symbol);
6097 entity = create_implicit_function(symbol, &pos);
6099 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6100 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6107 static expression_t *parse_reference(void)
6109 source_position_t const pos = token.base.source_position;
6110 entity_t *const entity = parse_qualified_identifier();
6113 if (is_declaration(entity)) {
6114 orig_type = entity->declaration.type;
6115 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6116 orig_type = entity->enum_value.enum_type;
6118 panic("expected declaration or enum value in reference");
6121 /* we always do the auto-type conversions; the & and sizeof parser contains
6122 * code to revert this! */
6123 type_t *type = automatic_type_conversion(orig_type);
6125 expression_kind_t kind = EXPR_REFERENCE;
6126 if (entity->kind == ENTITY_ENUM_VALUE)
6127 kind = EXPR_ENUM_CONSTANT;
6129 expression_t *expression = allocate_expression_zero(kind);
6130 expression->base.source_position = pos;
6131 expression->base.type = type;
6132 expression->reference.entity = entity;
6134 /* this declaration is used */
6135 if (is_declaration(entity)) {
6136 entity->declaration.used = true;
6139 if (entity->base.parent_scope != file_scope
6140 && (current_function != NULL
6141 && entity->base.parent_scope->depth < current_function->parameters.depth)
6142 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6143 if (entity->kind == ENTITY_VARIABLE) {
6144 /* access of a variable from an outer function */
6145 entity->variable.address_taken = true;
6146 } else if (entity->kind == ENTITY_PARAMETER) {
6147 entity->parameter.address_taken = true;
6149 current_function->need_closure = true;
6152 check_deprecated(&pos, entity);
6157 static bool semantic_cast(expression_t *cast)
6159 expression_t *expression = cast->unary.value;
6160 type_t *orig_dest_type = cast->base.type;
6161 type_t *orig_type_right = expression->base.type;
6162 type_t const *dst_type = skip_typeref(orig_dest_type);
6163 type_t const *src_type = skip_typeref(orig_type_right);
6164 source_position_t const *pos = &cast->base.source_position;
6166 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6167 if (is_type_void(dst_type))
6170 /* only integer and pointer can be casted to pointer */
6171 if (is_type_pointer(dst_type) &&
6172 !is_type_pointer(src_type) &&
6173 !is_type_integer(src_type) &&
6174 is_type_valid(src_type)) {
6175 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6179 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6180 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6184 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6185 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6189 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6190 type_t *src = skip_typeref(src_type->pointer.points_to);
6191 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6192 unsigned missing_qualifiers =
6193 src->base.qualifiers & ~dst->base.qualifiers;
6194 if (missing_qualifiers != 0) {
6195 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6201 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6203 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6204 expression->base.source_position = *pos;
6206 parse_initializer_env_t env;
6209 env.must_be_constant = false;
6210 initializer_t *initializer = parse_initializer(&env);
6213 expression->compound_literal.initializer = initializer;
6214 expression->compound_literal.type = type;
6215 expression->base.type = automatic_type_conversion(type);
6221 * Parse a cast expression.
6223 static expression_t *parse_cast(void)
6225 source_position_t const pos = *HERE;
6228 add_anchor_token(')');
6230 type_t *type = parse_typename();
6232 rem_anchor_token(')');
6235 if (token.kind == '{') {
6236 return parse_compound_literal(&pos, type);
6239 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6240 cast->base.source_position = pos;
6242 expression_t *value = parse_subexpression(PREC_CAST);
6243 cast->base.type = type;
6244 cast->unary.value = value;
6246 if (! semantic_cast(cast)) {
6247 /* TODO: record the error in the AST. else it is impossible to detect it */
6254 * Parse a statement expression.
6256 static expression_t *parse_statement_expression(void)
6258 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6261 add_anchor_token(')');
6263 statement_t *statement = parse_compound_statement(true);
6264 statement->compound.stmt_expr = true;
6265 expression->statement.statement = statement;
6267 /* find last statement and use its type */
6268 type_t *type = type_void;
6269 const statement_t *stmt = statement->compound.statements;
6271 while (stmt->base.next != NULL)
6272 stmt = stmt->base.next;
6274 if (stmt->kind == STATEMENT_EXPRESSION) {
6275 type = stmt->expression.expression->base.type;
6278 source_position_t const *const pos = &expression->base.source_position;
6279 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6281 expression->base.type = type;
6283 rem_anchor_token(')');
6289 * Parse a parenthesized expression.
6291 static expression_t *parse_parenthesized_expression(void)
6293 token_t const* const la1 = look_ahead(1);
6294 switch (la1->kind) {
6296 /* gcc extension: a statement expression */
6297 return parse_statement_expression();
6300 if (is_typedef_symbol(la1->identifier.symbol)) {
6302 return parse_cast();
6307 add_anchor_token(')');
6308 expression_t *result = parse_expression();
6309 result->base.parenthesized = true;
6310 rem_anchor_token(')');
6316 static expression_t *parse_function_keyword(void)
6320 if (current_function == NULL) {
6321 errorf(HERE, "'__func__' used outside of a function");
6324 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6325 expression->base.type = type_char_ptr;
6326 expression->funcname.kind = FUNCNAME_FUNCTION;
6333 static expression_t *parse_pretty_function_keyword(void)
6335 if (current_function == NULL) {
6336 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6339 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6340 expression->base.type = type_char_ptr;
6341 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6343 eat(T___PRETTY_FUNCTION__);
6348 static expression_t *parse_funcsig_keyword(void)
6350 if (current_function == NULL) {
6351 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6354 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6355 expression->base.type = type_char_ptr;
6356 expression->funcname.kind = FUNCNAME_FUNCSIG;
6363 static expression_t *parse_funcdname_keyword(void)
6365 if (current_function == NULL) {
6366 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6369 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6370 expression->base.type = type_char_ptr;
6371 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6373 eat(T___FUNCDNAME__);
6378 static designator_t *parse_designator(void)
6380 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6381 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6382 if (!result->symbol)
6385 designator_t *last_designator = result;
6388 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6389 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6390 if (!designator->symbol)
6393 last_designator->next = designator;
6394 last_designator = designator;
6398 add_anchor_token(']');
6399 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6400 designator->source_position = *HERE;
6401 designator->array_index = parse_expression();
6402 rem_anchor_token(']');
6404 if (designator->array_index == NULL) {
6408 last_designator->next = designator;
6409 last_designator = designator;
6419 * Parse the __builtin_offsetof() expression.
6421 static expression_t *parse_offsetof(void)
6423 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6424 expression->base.type = type_size_t;
6426 eat(T___builtin_offsetof);
6429 add_anchor_token(')');
6430 add_anchor_token(',');
6431 type_t *type = parse_typename();
6432 rem_anchor_token(',');
6434 designator_t *designator = parse_designator();
6435 rem_anchor_token(')');
6438 expression->offsetofe.type = type;
6439 expression->offsetofe.designator = designator;
6442 memset(&path, 0, sizeof(path));
6443 path.top_type = type;
6444 path.path = NEW_ARR_F(type_path_entry_t, 0);
6446 descend_into_subtype(&path);
6448 if (!walk_designator(&path, designator, true)) {
6449 return create_error_expression();
6452 DEL_ARR_F(path.path);
6458 * Parses a _builtin_va_start() expression.
6460 static expression_t *parse_va_start(void)
6462 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6464 eat(T___builtin_va_start);
6467 add_anchor_token(')');
6468 add_anchor_token(',');
6469 expression->va_starte.ap = parse_assignment_expression();
6470 rem_anchor_token(',');
6472 expression_t *const expr = parse_assignment_expression();
6473 if (expr->kind == EXPR_REFERENCE) {
6474 entity_t *const entity = expr->reference.entity;
6475 if (!current_function->base.type->function.variadic) {
6476 errorf(&expr->base.source_position,
6477 "'va_start' used in non-variadic function");
6478 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6479 entity->base.next != NULL ||
6480 entity->kind != ENTITY_PARAMETER) {
6481 errorf(&expr->base.source_position,
6482 "second argument of 'va_start' must be last parameter of the current function");
6484 expression->va_starte.parameter = &entity->variable;
6487 expression = create_error_expression();
6489 rem_anchor_token(')');
6495 * Parses a __builtin_va_arg() expression.
6497 static expression_t *parse_va_arg(void)
6499 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6501 eat(T___builtin_va_arg);
6504 add_anchor_token(')');
6505 add_anchor_token(',');
6507 ap.expression = parse_assignment_expression();
6508 expression->va_arge.ap = ap.expression;
6509 check_call_argument(type_valist, &ap, 1);
6511 rem_anchor_token(',');
6513 expression->base.type = parse_typename();
6514 rem_anchor_token(')');
6521 * Parses a __builtin_va_copy() expression.
6523 static expression_t *parse_va_copy(void)
6525 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6527 eat(T___builtin_va_copy);
6530 add_anchor_token(')');
6531 add_anchor_token(',');
6532 expression_t *dst = parse_assignment_expression();
6533 assign_error_t error = semantic_assign(type_valist, dst);
6534 report_assign_error(error, type_valist, dst, "call argument 1",
6535 &dst->base.source_position);
6536 expression->va_copye.dst = dst;
6538 rem_anchor_token(',');
6541 call_argument_t src;
6542 src.expression = parse_assignment_expression();
6543 check_call_argument(type_valist, &src, 2);
6544 expression->va_copye.src = src.expression;
6545 rem_anchor_token(')');
6552 * Parses a __builtin_constant_p() expression.
6554 static expression_t *parse_builtin_constant(void)
6556 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6558 eat(T___builtin_constant_p);
6561 add_anchor_token(')');
6562 expression->builtin_constant.value = parse_assignment_expression();
6563 rem_anchor_token(')');
6565 expression->base.type = type_int;
6571 * Parses a __builtin_types_compatible_p() expression.
6573 static expression_t *parse_builtin_types_compatible(void)
6575 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6577 eat(T___builtin_types_compatible_p);
6580 add_anchor_token(')');
6581 add_anchor_token(',');
6582 expression->builtin_types_compatible.left = parse_typename();
6583 rem_anchor_token(',');
6585 expression->builtin_types_compatible.right = parse_typename();
6586 rem_anchor_token(')');
6588 expression->base.type = type_int;
6594 * Parses a __builtin_is_*() compare expression.
6596 static expression_t *parse_compare_builtin(void)
6598 expression_t *expression;
6600 switch (token.kind) {
6601 case T___builtin_isgreater:
6602 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6604 case T___builtin_isgreaterequal:
6605 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6607 case T___builtin_isless:
6608 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6610 case T___builtin_islessequal:
6611 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6613 case T___builtin_islessgreater:
6614 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6616 case T___builtin_isunordered:
6617 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6620 internal_errorf(HERE, "invalid compare builtin found");
6622 expression->base.source_position = *HERE;
6626 add_anchor_token(')');
6627 add_anchor_token(',');
6628 expression->binary.left = parse_assignment_expression();
6629 rem_anchor_token(',');
6631 expression->binary.right = parse_assignment_expression();
6632 rem_anchor_token(')');
6635 type_t *const orig_type_left = expression->binary.left->base.type;
6636 type_t *const orig_type_right = expression->binary.right->base.type;
6638 type_t *const type_left = skip_typeref(orig_type_left);
6639 type_t *const type_right = skip_typeref(orig_type_right);
6640 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6641 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6642 type_error_incompatible("invalid operands in comparison",
6643 &expression->base.source_position, orig_type_left, orig_type_right);
6646 semantic_comparison(&expression->binary);
6653 * Parses a MS assume() expression.
6655 static expression_t *parse_assume(void)
6657 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6662 add_anchor_token(')');
6663 expression->unary.value = parse_assignment_expression();
6664 rem_anchor_token(')');
6667 expression->base.type = type_void;
6672 * Return the label for the current symbol or create a new one.
6674 static label_t *get_label(void)
6676 assert(token.kind == T_IDENTIFIER);
6677 assert(current_function != NULL);
6679 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6680 /* If we find a local label, we already created the declaration. */
6681 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6682 if (label->base.parent_scope != current_scope) {
6683 assert(label->base.parent_scope->depth < current_scope->depth);
6684 current_function->goto_to_outer = true;
6686 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6687 /* There is no matching label in the same function, so create a new one. */
6688 source_position_t const nowhere = { NULL, 0, 0, false };
6689 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6694 return &label->label;
6698 * Parses a GNU && label address expression.
6700 static expression_t *parse_label_address(void)
6702 source_position_t source_position = token.base.source_position;
6704 if (token.kind != T_IDENTIFIER) {
6705 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6706 return create_error_expression();
6709 label_t *const label = get_label();
6711 label->address_taken = true;
6713 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6714 expression->base.source_position = source_position;
6716 /* label address is treated as a void pointer */
6717 expression->base.type = type_void_ptr;
6718 expression->label_address.label = label;
6723 * Parse a microsoft __noop expression.
6725 static expression_t *parse_noop_expression(void)
6727 /* the result is a (int)0 */
6728 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6729 literal->base.type = type_int;
6730 literal->literal.value.begin = "__noop";
6731 literal->literal.value.size = 6;
6735 if (token.kind == '(') {
6736 /* parse arguments */
6738 add_anchor_token(')');
6739 add_anchor_token(',');
6741 if (token.kind != ')') do {
6742 (void)parse_assignment_expression();
6743 } while (next_if(','));
6745 rem_anchor_token(',');
6746 rem_anchor_token(')');
6754 * Parses a primary expression.
6756 static expression_t *parse_primary_expression(void)
6758 switch (token.kind) {
6759 case T_false: return parse_boolean_literal(false);
6760 case T_true: return parse_boolean_literal(true);
6762 case T_FLOATINGPOINT:
6763 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6764 case T_CHARACTER_CONSTANT: return parse_character_constant();
6765 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6766 case T_STRING_LITERAL:
6767 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6768 case T___FUNCTION__:
6769 case T___func__: return parse_function_keyword();
6770 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6771 case T___FUNCSIG__: return parse_funcsig_keyword();
6772 case T___FUNCDNAME__: return parse_funcdname_keyword();
6773 case T___builtin_offsetof: return parse_offsetof();
6774 case T___builtin_va_start: return parse_va_start();
6775 case T___builtin_va_arg: return parse_va_arg();
6776 case T___builtin_va_copy: return parse_va_copy();
6777 case T___builtin_isgreater:
6778 case T___builtin_isgreaterequal:
6779 case T___builtin_isless:
6780 case T___builtin_islessequal:
6781 case T___builtin_islessgreater:
6782 case T___builtin_isunordered: return parse_compare_builtin();
6783 case T___builtin_constant_p: return parse_builtin_constant();
6784 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6785 case T__assume: return parse_assume();
6788 return parse_label_address();
6791 case '(': return parse_parenthesized_expression();
6792 case T___noop: return parse_noop_expression();
6794 /* Gracefully handle type names while parsing expressions. */
6796 return parse_reference();
6798 if (!is_typedef_symbol(token.identifier.symbol)) {
6799 return parse_reference();
6803 source_position_t const pos = *HERE;
6804 declaration_specifiers_t specifiers;
6805 parse_declaration_specifiers(&specifiers);
6806 type_t const *const type = parse_abstract_declarator(specifiers.type);
6807 errorf(&pos, "encountered type '%T' while parsing expression", type);
6808 return create_error_expression();
6812 errorf(HERE, "unexpected token %K, expected an expression", &token);
6814 return create_error_expression();
6817 static expression_t *parse_array_expression(expression_t *left)
6819 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6820 array_access_expression_t *const arr = &expr->array_access;
6823 add_anchor_token(']');
6825 expression_t *const inside = parse_expression();
6827 type_t *const orig_type_left = left->base.type;
6828 type_t *const orig_type_inside = inside->base.type;
6830 type_t *const type_left = skip_typeref(orig_type_left);
6831 type_t *const type_inside = skip_typeref(orig_type_inside);
6837 if (is_type_pointer(type_left)) {
6840 idx_type = type_inside;
6841 res_type = type_left->pointer.points_to;
6843 } else if (is_type_pointer(type_inside)) {
6844 arr->flipped = true;
6847 idx_type = type_left;
6848 res_type = type_inside->pointer.points_to;
6850 res_type = automatic_type_conversion(res_type);
6851 if (!is_type_integer(idx_type)) {
6852 errorf(&idx->base.source_position, "array subscript must have integer type");
6853 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6854 source_position_t const *const pos = &idx->base.source_position;
6855 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6858 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6859 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6861 res_type = type_error_type;
6866 arr->array_ref = ref;
6868 arr->base.type = res_type;
6870 rem_anchor_token(']');
6875 static bool is_bitfield(const expression_t *expression)
6877 return expression->kind == EXPR_SELECT
6878 && expression->select.compound_entry->compound_member.bitfield;
6881 static expression_t *parse_typeprop(expression_kind_t const kind)
6883 expression_t *tp_expression = allocate_expression_zero(kind);
6884 tp_expression->base.type = type_size_t;
6886 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6889 expression_t *expression;
6890 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6891 source_position_t const pos = *HERE;
6893 add_anchor_token(')');
6894 orig_type = parse_typename();
6895 rem_anchor_token(')');
6898 if (token.kind == '{') {
6899 /* It was not sizeof(type) after all. It is sizeof of an expression
6900 * starting with a compound literal */
6901 expression = parse_compound_literal(&pos, orig_type);
6902 goto typeprop_expression;
6905 expression = parse_subexpression(PREC_UNARY);
6907 typeprop_expression:
6908 if (is_bitfield(expression)) {
6909 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6910 errorf(&tp_expression->base.source_position,
6911 "operand of %s expression must not be a bitfield", what);
6914 tp_expression->typeprop.tp_expression = expression;
6916 orig_type = revert_automatic_type_conversion(expression);
6917 expression->base.type = orig_type;
6920 tp_expression->typeprop.type = orig_type;
6921 type_t const* const type = skip_typeref(orig_type);
6922 char const* wrong_type = NULL;
6923 if (is_type_incomplete(type)) {
6924 if (!is_type_void(type) || !GNU_MODE)
6925 wrong_type = "incomplete";
6926 } else if (type->kind == TYPE_FUNCTION) {
6928 /* function types are allowed (and return 1) */
6929 source_position_t const *const pos = &tp_expression->base.source_position;
6930 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6931 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6933 wrong_type = "function";
6937 if (wrong_type != NULL) {
6938 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6939 errorf(&tp_expression->base.source_position,
6940 "operand of %s expression must not be of %s type '%T'",
6941 what, wrong_type, orig_type);
6944 return tp_expression;
6947 static expression_t *parse_sizeof(void)
6949 return parse_typeprop(EXPR_SIZEOF);
6952 static expression_t *parse_alignof(void)
6954 return parse_typeprop(EXPR_ALIGNOF);
6957 static expression_t *parse_select_expression(expression_t *addr)
6959 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6960 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6961 source_position_t const pos = *HERE;
6964 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6966 return create_error_expression();
6968 type_t *const orig_type = addr->base.type;
6969 type_t *const type = skip_typeref(orig_type);
6972 bool saw_error = false;
6973 if (is_type_pointer(type)) {
6974 if (!select_left_arrow) {
6976 "request for member '%Y' in something not a struct or union, but '%T'",
6980 type_left = skip_typeref(type->pointer.points_to);
6982 if (select_left_arrow && is_type_valid(type)) {
6983 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6989 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6990 type_left->kind != TYPE_COMPOUND_UNION) {
6992 if (is_type_valid(type_left) && !saw_error) {
6994 "request for member '%Y' in something not a struct or union, but '%T'",
6997 return create_error_expression();
7000 compound_t *compound = type_left->compound.compound;
7001 if (!compound->complete) {
7002 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7004 return create_error_expression();
7007 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7008 expression_t *result =
7009 find_create_select(&pos, addr, qualifiers, compound, symbol);
7011 if (result == NULL) {
7012 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7013 return create_error_expression();
7019 static void check_call_argument(type_t *expected_type,
7020 call_argument_t *argument, unsigned pos)
7022 type_t *expected_type_skip = skip_typeref(expected_type);
7023 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7024 expression_t *arg_expr = argument->expression;
7025 type_t *arg_type = skip_typeref(arg_expr->base.type);
7027 /* handle transparent union gnu extension */
7028 if (is_type_union(expected_type_skip)
7029 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7030 compound_t *union_decl = expected_type_skip->compound.compound;
7031 type_t *best_type = NULL;
7032 entity_t *entry = union_decl->members.entities;
7033 for ( ; entry != NULL; entry = entry->base.next) {
7034 assert(is_declaration(entry));
7035 type_t *decl_type = entry->declaration.type;
7036 error = semantic_assign(decl_type, arg_expr);
7037 if (error == ASSIGN_ERROR_INCOMPATIBLE
7038 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7041 if (error == ASSIGN_SUCCESS) {
7042 best_type = decl_type;
7043 } else if (best_type == NULL) {
7044 best_type = decl_type;
7048 if (best_type != NULL) {
7049 expected_type = best_type;
7053 error = semantic_assign(expected_type, arg_expr);
7054 argument->expression = create_implicit_cast(arg_expr, expected_type);
7056 if (error != ASSIGN_SUCCESS) {
7057 /* report exact scope in error messages (like "in argument 3") */
7059 snprintf(buf, sizeof(buf), "call argument %u", pos);
7060 report_assign_error(error, expected_type, arg_expr, buf,
7061 &arg_expr->base.source_position);
7063 type_t *const promoted_type = get_default_promoted_type(arg_type);
7064 if (!types_compatible(expected_type_skip, promoted_type) &&
7065 !types_compatible(expected_type_skip, type_void_ptr) &&
7066 !types_compatible(type_void_ptr, promoted_type)) {
7067 /* Deliberately show the skipped types in this warning */
7068 source_position_t const *const apos = &arg_expr->base.source_position;
7069 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7075 * Handle the semantic restrictions of builtin calls
7077 static void handle_builtin_argument_restrictions(call_expression_t *call)
7079 entity_t *entity = call->function->reference.entity;
7080 switch (entity->function.btk) {
7082 switch (entity->function.b.firm_builtin_kind) {
7083 case ir_bk_return_address:
7084 case ir_bk_frame_address: {
7085 /* argument must be constant */
7086 call_argument_t *argument = call->arguments;
7088 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7089 errorf(&call->base.source_position,
7090 "argument of '%Y' must be a constant expression",
7091 call->function->reference.entity->base.symbol);
7095 case ir_bk_prefetch:
7096 /* second and third argument must be constant if existent */
7097 if (call->arguments == NULL)
7099 call_argument_t *rw = call->arguments->next;
7100 call_argument_t *locality = NULL;
7103 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7104 errorf(&call->base.source_position,
7105 "second argument of '%Y' must be a constant expression",
7106 call->function->reference.entity->base.symbol);
7108 locality = rw->next;
7110 if (locality != NULL) {
7111 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7112 errorf(&call->base.source_position,
7113 "third argument of '%Y' must be a constant expression",
7114 call->function->reference.entity->base.symbol);
7116 locality = rw->next;
7123 case BUILTIN_OBJECT_SIZE:
7124 if (call->arguments == NULL)
7127 call_argument_t *arg = call->arguments->next;
7128 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7129 errorf(&call->base.source_position,
7130 "second argument of '%Y' must be a constant expression",
7131 call->function->reference.entity->base.symbol);
7140 * Parse a call expression, ie. expression '( ... )'.
7142 * @param expression the function address
7144 static expression_t *parse_call_expression(expression_t *expression)
7146 expression_t *result = allocate_expression_zero(EXPR_CALL);
7147 call_expression_t *call = &result->call;
7148 call->function = expression;
7150 type_t *const orig_type = expression->base.type;
7151 type_t *const type = skip_typeref(orig_type);
7153 function_type_t *function_type = NULL;
7154 if (is_type_pointer(type)) {
7155 type_t *const to_type = skip_typeref(type->pointer.points_to);
7157 if (is_type_function(to_type)) {
7158 function_type = &to_type->function;
7159 call->base.type = function_type->return_type;
7163 if (function_type == NULL && is_type_valid(type)) {
7165 "called object '%E' (type '%T') is not a pointer to a function",
7166 expression, orig_type);
7169 /* parse arguments */
7171 add_anchor_token(')');
7172 add_anchor_token(',');
7174 if (token.kind != ')') {
7175 call_argument_t **anchor = &call->arguments;
7177 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7178 argument->expression = parse_assignment_expression();
7181 anchor = &argument->next;
7182 } while (next_if(','));
7184 rem_anchor_token(',');
7185 rem_anchor_token(')');
7188 if (function_type == NULL)
7191 /* check type and count of call arguments */
7192 function_parameter_t *parameter = function_type->parameters;
7193 call_argument_t *argument = call->arguments;
7194 if (!function_type->unspecified_parameters) {
7195 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7196 parameter = parameter->next, argument = argument->next) {
7197 check_call_argument(parameter->type, argument, ++pos);
7200 if (parameter != NULL) {
7201 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7202 } else if (argument != NULL && !function_type->variadic) {
7203 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7207 /* do default promotion for other arguments */
7208 for (; argument != NULL; argument = argument->next) {
7209 type_t *argument_type = argument->expression->base.type;
7210 if (!is_type_object(skip_typeref(argument_type))) {
7211 errorf(&argument->expression->base.source_position,
7212 "call argument '%E' must not be void", argument->expression);
7215 argument_type = get_default_promoted_type(argument_type);
7217 argument->expression
7218 = create_implicit_cast(argument->expression, argument_type);
7223 if (is_type_compound(skip_typeref(function_type->return_type))) {
7224 source_position_t const *const pos = &expression->base.source_position;
7225 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7228 if (expression->kind == EXPR_REFERENCE) {
7229 reference_expression_t *reference = &expression->reference;
7230 if (reference->entity->kind == ENTITY_FUNCTION &&
7231 reference->entity->function.btk != BUILTIN_NONE)
7232 handle_builtin_argument_restrictions(call);
7238 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7240 static bool same_compound_type(const type_t *type1, const type_t *type2)
7243 is_type_compound(type1) &&
7244 type1->kind == type2->kind &&
7245 type1->compound.compound == type2->compound.compound;
7248 static expression_t const *get_reference_address(expression_t const *expr)
7250 bool regular_take_address = true;
7252 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7253 expr = expr->unary.value;
7255 regular_take_address = false;
7258 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7261 expr = expr->unary.value;
7264 if (expr->kind != EXPR_REFERENCE)
7267 /* special case for functions which are automatically converted to a
7268 * pointer to function without an extra TAKE_ADDRESS operation */
7269 if (!regular_take_address &&
7270 expr->reference.entity->kind != ENTITY_FUNCTION) {
7277 static void warn_reference_address_as_bool(expression_t const* expr)
7279 expr = get_reference_address(expr);
7281 source_position_t const *const pos = &expr->base.source_position;
7282 entity_t const *const ent = expr->reference.entity;
7283 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7287 static void warn_assignment_in_condition(const expression_t *const expr)
7289 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7291 if (expr->base.parenthesized)
7293 source_position_t const *const pos = &expr->base.source_position;
7294 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7297 static void semantic_condition(expression_t const *const expr,
7298 char const *const context)
7300 type_t *const type = skip_typeref(expr->base.type);
7301 if (is_type_scalar(type)) {
7302 warn_reference_address_as_bool(expr);
7303 warn_assignment_in_condition(expr);
7304 } else if (is_type_valid(type)) {
7305 errorf(&expr->base.source_position,
7306 "%s must have scalar type", context);
7311 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7313 * @param expression the conditional expression
7315 static expression_t *parse_conditional_expression(expression_t *expression)
7317 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7319 conditional_expression_t *conditional = &result->conditional;
7320 conditional->condition = expression;
7323 add_anchor_token(':');
7325 /* §6.5.15:2 The first operand shall have scalar type. */
7326 semantic_condition(expression, "condition of conditional operator");
7328 expression_t *true_expression = expression;
7329 bool gnu_cond = false;
7330 if (GNU_MODE && token.kind == ':') {
7333 true_expression = parse_expression();
7335 rem_anchor_token(':');
7337 expression_t *false_expression =
7338 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7340 type_t *const orig_true_type = true_expression->base.type;
7341 type_t *const orig_false_type = false_expression->base.type;
7342 type_t *const true_type = skip_typeref(orig_true_type);
7343 type_t *const false_type = skip_typeref(orig_false_type);
7346 source_position_t const *const pos = &conditional->base.source_position;
7347 type_t *result_type;
7348 if (is_type_void(true_type) || is_type_void(false_type)) {
7349 /* ISO/IEC 14882:1998(E) §5.16:2 */
7350 if (true_expression->kind == EXPR_UNARY_THROW) {
7351 result_type = false_type;
7352 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7353 result_type = true_type;
7355 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7356 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7358 result_type = type_void;
7360 } else if (is_type_arithmetic(true_type)
7361 && is_type_arithmetic(false_type)) {
7362 result_type = semantic_arithmetic(true_type, false_type);
7363 } else if (same_compound_type(true_type, false_type)) {
7364 /* just take 1 of the 2 types */
7365 result_type = true_type;
7366 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7367 type_t *pointer_type;
7369 expression_t *other_expression;
7370 if (is_type_pointer(true_type) &&
7371 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7372 pointer_type = true_type;
7373 other_type = false_type;
7374 other_expression = false_expression;
7376 pointer_type = false_type;
7377 other_type = true_type;
7378 other_expression = true_expression;
7381 if (is_null_pointer_constant(other_expression)) {
7382 result_type = pointer_type;
7383 } else if (is_type_pointer(other_type)) {
7384 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7385 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7388 if (is_type_void(to1) || is_type_void(to2)) {
7390 } else if (types_compatible(get_unqualified_type(to1),
7391 get_unqualified_type(to2))) {
7394 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7398 type_t *const type =
7399 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7400 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7401 } else if (is_type_integer(other_type)) {
7402 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7403 result_type = pointer_type;
7405 goto types_incompatible;
7409 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7410 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7412 result_type = type_error_type;
7415 conditional->true_expression
7416 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7417 conditional->false_expression
7418 = create_implicit_cast(false_expression, result_type);
7419 conditional->base.type = result_type;
7424 * Parse an extension expression.
7426 static expression_t *parse_extension(void)
7429 expression_t *expression = parse_subexpression(PREC_UNARY);
7435 * Parse a __builtin_classify_type() expression.
7437 static expression_t *parse_builtin_classify_type(void)
7439 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7440 result->base.type = type_int;
7442 eat(T___builtin_classify_type);
7445 add_anchor_token(')');
7446 expression_t *expression = parse_expression();
7447 rem_anchor_token(')');
7449 result->classify_type.type_expression = expression;
7455 * Parse a delete expression
7456 * ISO/IEC 14882:1998(E) §5.3.5
7458 static expression_t *parse_delete(void)
7460 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7461 result->base.type = type_void;
7466 result->kind = EXPR_UNARY_DELETE_ARRAY;
7470 expression_t *const value = parse_subexpression(PREC_CAST);
7471 result->unary.value = value;
7473 type_t *const type = skip_typeref(value->base.type);
7474 if (!is_type_pointer(type)) {
7475 if (is_type_valid(type)) {
7476 errorf(&value->base.source_position,
7477 "operand of delete must have pointer type");
7479 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7480 source_position_t const *const pos = &value->base.source_position;
7481 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7488 * Parse a throw expression
7489 * ISO/IEC 14882:1998(E) §15:1
7491 static expression_t *parse_throw(void)
7493 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7494 result->base.type = type_void;
7498 expression_t *value = NULL;
7499 switch (token.kind) {
7501 value = parse_assignment_expression();
7502 /* ISO/IEC 14882:1998(E) §15.1:3 */
7503 type_t *const orig_type = value->base.type;
7504 type_t *const type = skip_typeref(orig_type);
7505 if (is_type_incomplete(type)) {
7506 errorf(&value->base.source_position,
7507 "cannot throw object of incomplete type '%T'", orig_type);
7508 } else if (is_type_pointer(type)) {
7509 type_t *const points_to = skip_typeref(type->pointer.points_to);
7510 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7511 errorf(&value->base.source_position,
7512 "cannot throw pointer to incomplete type '%T'", orig_type);
7520 result->unary.value = value;
7525 static bool check_pointer_arithmetic(const source_position_t *source_position,
7526 type_t *pointer_type,
7527 type_t *orig_pointer_type)
7529 type_t *points_to = pointer_type->pointer.points_to;
7530 points_to = skip_typeref(points_to);
7532 if (is_type_incomplete(points_to)) {
7533 if (!GNU_MODE || !is_type_void(points_to)) {
7534 errorf(source_position,
7535 "arithmetic with pointer to incomplete type '%T' not allowed",
7539 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7541 } else if (is_type_function(points_to)) {
7543 errorf(source_position,
7544 "arithmetic with pointer to function type '%T' not allowed",
7548 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7554 static bool is_lvalue(const expression_t *expression)
7556 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7557 switch (expression->kind) {
7558 case EXPR_ARRAY_ACCESS:
7559 case EXPR_COMPOUND_LITERAL:
7560 case EXPR_REFERENCE:
7562 case EXPR_UNARY_DEREFERENCE:
7566 type_t *type = skip_typeref(expression->base.type);
7568 /* ISO/IEC 14882:1998(E) §3.10:3 */
7569 is_type_reference(type) ||
7570 /* Claim it is an lvalue, if the type is invalid. There was a parse
7571 * error before, which maybe prevented properly recognizing it as
7573 !is_type_valid(type);
7578 static void semantic_incdec(unary_expression_t *expression)
7580 type_t *const orig_type = expression->value->base.type;
7581 type_t *const type = skip_typeref(orig_type);
7582 if (is_type_pointer(type)) {
7583 if (!check_pointer_arithmetic(&expression->base.source_position,
7587 } else if (!is_type_real(type) && is_type_valid(type)) {
7588 /* TODO: improve error message */
7589 errorf(&expression->base.source_position,
7590 "operation needs an arithmetic or pointer type");
7593 if (!is_lvalue(expression->value)) {
7594 /* TODO: improve error message */
7595 errorf(&expression->base.source_position, "lvalue required as operand");
7597 expression->base.type = orig_type;
7600 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7602 type_t *const res_type = promote_integer(type);
7603 expr->base.type = res_type;
7604 expr->value = create_implicit_cast(expr->value, res_type);
7607 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7609 type_t *const orig_type = expression->value->base.type;
7610 type_t *const type = skip_typeref(orig_type);
7611 if (!is_type_arithmetic(type)) {
7612 if (is_type_valid(type)) {
7613 /* TODO: improve error message */
7614 errorf(&expression->base.source_position,
7615 "operation needs an arithmetic type");
7618 } else if (is_type_integer(type)) {
7619 promote_unary_int_expr(expression, type);
7621 expression->base.type = orig_type;
7625 static void semantic_unexpr_plus(unary_expression_t *expression)
7627 semantic_unexpr_arithmetic(expression);
7628 source_position_t const *const pos = &expression->base.source_position;
7629 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7632 static void semantic_not(unary_expression_t *expression)
7634 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7635 semantic_condition(expression->value, "operand of !");
7636 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7639 static void semantic_unexpr_integer(unary_expression_t *expression)
7641 type_t *const orig_type = expression->value->base.type;
7642 type_t *const type = skip_typeref(orig_type);
7643 if (!is_type_integer(type)) {
7644 if (is_type_valid(type)) {
7645 errorf(&expression->base.source_position,
7646 "operand of ~ must be of integer type");
7651 promote_unary_int_expr(expression, type);
7654 static void semantic_dereference(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 (is_type_valid(type)) {
7660 errorf(&expression->base.source_position,
7661 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7666 type_t *result_type = type->pointer.points_to;
7667 result_type = automatic_type_conversion(result_type);
7668 expression->base.type = result_type;
7672 * Record that an address is taken (expression represents an lvalue).
7674 * @param expression the expression
7675 * @param may_be_register if true, the expression might be an register
7677 static void set_address_taken(expression_t *expression, bool may_be_register)
7679 if (expression->kind != EXPR_REFERENCE)
7682 entity_t *const entity = expression->reference.entity;
7684 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7687 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7688 && !may_be_register) {
7689 source_position_t const *const pos = &expression->base.source_position;
7690 errorf(pos, "address of register '%N' requested", entity);
7693 if (entity->kind == ENTITY_VARIABLE) {
7694 entity->variable.address_taken = true;
7696 assert(entity->kind == ENTITY_PARAMETER);
7697 entity->parameter.address_taken = true;
7702 * Check the semantic of the address taken expression.
7704 static void semantic_take_addr(unary_expression_t *expression)
7706 expression_t *value = expression->value;
7707 value->base.type = revert_automatic_type_conversion(value);
7709 type_t *orig_type = value->base.type;
7710 type_t *type = skip_typeref(orig_type);
7711 if (!is_type_valid(type))
7715 if (!is_lvalue(value)) {
7716 errorf(&expression->base.source_position, "'&' requires an lvalue");
7718 if (is_bitfield(value)) {
7719 errorf(&expression->base.source_position,
7720 "'&' not allowed on bitfield");
7723 set_address_taken(value, false);
7725 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7728 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7729 static expression_t *parse_##unexpression_type(void) \
7731 expression_t *unary_expression \
7732 = allocate_expression_zero(unexpression_type); \
7734 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7736 sfunc(&unary_expression->unary); \
7738 return unary_expression; \
7741 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7742 semantic_unexpr_arithmetic)
7743 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7744 semantic_unexpr_plus)
7745 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7747 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7748 semantic_dereference)
7749 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7751 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7752 semantic_unexpr_integer)
7753 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7755 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7758 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7760 static expression_t *parse_##unexpression_type(expression_t *left) \
7762 expression_t *unary_expression \
7763 = allocate_expression_zero(unexpression_type); \
7765 unary_expression->unary.value = left; \
7767 sfunc(&unary_expression->unary); \
7769 return unary_expression; \
7772 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7773 EXPR_UNARY_POSTFIX_INCREMENT,
7775 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7776 EXPR_UNARY_POSTFIX_DECREMENT,
7779 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7781 /* TODO: handle complex + imaginary types */
7783 type_left = get_unqualified_type(type_left);
7784 type_right = get_unqualified_type(type_right);
7786 /* §6.3.1.8 Usual arithmetic conversions */
7787 if (type_left == type_long_double || type_right == type_long_double) {
7788 return type_long_double;
7789 } else if (type_left == type_double || type_right == type_double) {
7791 } else if (type_left == type_float || type_right == type_float) {
7795 type_left = promote_integer(type_left);
7796 type_right = promote_integer(type_right);
7798 if (type_left == type_right)
7801 bool const signed_left = is_type_signed(type_left);
7802 bool const signed_right = is_type_signed(type_right);
7803 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7804 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7806 if (signed_left == signed_right)
7807 return rank_left >= rank_right ? type_left : type_right;
7811 atomic_type_kind_t s_akind;
7812 atomic_type_kind_t u_akind;
7817 u_type = type_right;
7819 s_type = type_right;
7822 s_akind = get_akind(s_type);
7823 u_akind = get_akind(u_type);
7824 s_rank = get_akind_rank(s_akind);
7825 u_rank = get_akind_rank(u_akind);
7827 if (u_rank >= s_rank)
7830 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7834 case ATOMIC_TYPE_INT: return type_unsigned_int;
7835 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7836 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7838 default: panic("invalid atomic type");
7843 * Check the semantic restrictions for a binary expression.
7845 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7847 expression_t *const left = expression->left;
7848 expression_t *const right = expression->right;
7849 type_t *const orig_type_left = left->base.type;
7850 type_t *const orig_type_right = right->base.type;
7851 type_t *const type_left = skip_typeref(orig_type_left);
7852 type_t *const type_right = skip_typeref(orig_type_right);
7854 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7855 /* TODO: improve error message */
7856 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7857 errorf(&expression->base.source_position,
7858 "operation needs arithmetic types");
7863 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7864 expression->left = create_implicit_cast(left, arithmetic_type);
7865 expression->right = create_implicit_cast(right, arithmetic_type);
7866 expression->base.type = arithmetic_type;
7869 static void semantic_binexpr_integer(binary_expression_t *const expression)
7871 expression_t *const left = expression->left;
7872 expression_t *const right = expression->right;
7873 type_t *const orig_type_left = left->base.type;
7874 type_t *const orig_type_right = right->base.type;
7875 type_t *const type_left = skip_typeref(orig_type_left);
7876 type_t *const type_right = skip_typeref(orig_type_right);
7878 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7879 /* TODO: improve error message */
7880 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7881 errorf(&expression->base.source_position,
7882 "operation needs integer types");
7887 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7888 expression->left = create_implicit_cast(left, result_type);
7889 expression->right = create_implicit_cast(right, result_type);
7890 expression->base.type = result_type;
7893 static void warn_div_by_zero(binary_expression_t const *const expression)
7895 if (!is_type_integer(expression->base.type))
7898 expression_t const *const right = expression->right;
7899 /* The type of the right operand can be different for /= */
7900 if (is_type_integer(right->base.type) &&
7901 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7902 !fold_constant_to_bool(right)) {
7903 source_position_t const *const pos = &expression->base.source_position;
7904 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7909 * Check the semantic restrictions for a div/mod expression.
7911 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7913 semantic_binexpr_arithmetic(expression);
7914 warn_div_by_zero(expression);
7917 static void warn_addsub_in_shift(const expression_t *const expr)
7919 if (expr->base.parenthesized)
7923 switch (expr->kind) {
7924 case EXPR_BINARY_ADD: op = '+'; break;
7925 case EXPR_BINARY_SUB: op = '-'; break;
7929 source_position_t const *const pos = &expr->base.source_position;
7930 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7933 static bool semantic_shift(binary_expression_t *expression)
7935 expression_t *const left = expression->left;
7936 expression_t *const right = expression->right;
7937 type_t *const orig_type_left = left->base.type;
7938 type_t *const orig_type_right = right->base.type;
7939 type_t * type_left = skip_typeref(orig_type_left);
7940 type_t * type_right = skip_typeref(orig_type_right);
7942 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7943 /* TODO: improve error message */
7944 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7945 errorf(&expression->base.source_position,
7946 "operands of shift operation must have integer types");
7951 type_left = promote_integer(type_left);
7953 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7954 source_position_t const *const pos = &right->base.source_position;
7955 long const count = fold_constant_to_int(right);
7957 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7958 } else if ((unsigned long)count >=
7959 get_atomic_type_size(type_left->atomic.akind) * 8) {
7960 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7964 type_right = promote_integer(type_right);
7965 expression->right = create_implicit_cast(right, type_right);
7970 static void semantic_shift_op(binary_expression_t *expression)
7972 expression_t *const left = expression->left;
7973 expression_t *const right = expression->right;
7975 if (!semantic_shift(expression))
7978 warn_addsub_in_shift(left);
7979 warn_addsub_in_shift(right);
7981 type_t *const orig_type_left = left->base.type;
7982 type_t * type_left = skip_typeref(orig_type_left);
7984 type_left = promote_integer(type_left);
7985 expression->left = create_implicit_cast(left, type_left);
7986 expression->base.type = type_left;
7989 static void semantic_add(binary_expression_t *expression)
7991 expression_t *const left = expression->left;
7992 expression_t *const right = expression->right;
7993 type_t *const orig_type_left = left->base.type;
7994 type_t *const orig_type_right = right->base.type;
7995 type_t *const type_left = skip_typeref(orig_type_left);
7996 type_t *const type_right = skip_typeref(orig_type_right);
7999 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8000 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8001 expression->left = create_implicit_cast(left, arithmetic_type);
8002 expression->right = create_implicit_cast(right, arithmetic_type);
8003 expression->base.type = arithmetic_type;
8004 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8005 check_pointer_arithmetic(&expression->base.source_position,
8006 type_left, orig_type_left);
8007 expression->base.type = type_left;
8008 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8009 check_pointer_arithmetic(&expression->base.source_position,
8010 type_right, orig_type_right);
8011 expression->base.type = type_right;
8012 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8013 errorf(&expression->base.source_position,
8014 "invalid operands to binary + ('%T', '%T')",
8015 orig_type_left, orig_type_right);
8019 static void semantic_sub(binary_expression_t *expression)
8021 expression_t *const left = expression->left;
8022 expression_t *const right = expression->right;
8023 type_t *const orig_type_left = left->base.type;
8024 type_t *const orig_type_right = right->base.type;
8025 type_t *const type_left = skip_typeref(orig_type_left);
8026 type_t *const type_right = skip_typeref(orig_type_right);
8027 source_position_t const *const pos = &expression->base.source_position;
8030 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8031 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8032 expression->left = create_implicit_cast(left, arithmetic_type);
8033 expression->right = create_implicit_cast(right, arithmetic_type);
8034 expression->base.type = arithmetic_type;
8035 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8036 check_pointer_arithmetic(&expression->base.source_position,
8037 type_left, orig_type_left);
8038 expression->base.type = type_left;
8039 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8040 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8041 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8042 if (!types_compatible(unqual_left, unqual_right)) {
8044 "subtracting pointers to incompatible types '%T' and '%T'",
8045 orig_type_left, orig_type_right);
8046 } else if (!is_type_object(unqual_left)) {
8047 if (!is_type_void(unqual_left)) {
8048 errorf(pos, "subtracting pointers to non-object types '%T'",
8051 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8054 expression->base.type = type_ptrdiff_t;
8055 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8056 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8057 orig_type_left, orig_type_right);
8061 static void warn_string_literal_address(expression_t const* expr)
8063 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8064 expr = expr->unary.value;
8065 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8067 expr = expr->unary.value;
8070 if (expr->kind == EXPR_STRING_LITERAL
8071 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8072 source_position_t const *const pos = &expr->base.source_position;
8073 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8077 static bool maybe_negative(expression_t const *const expr)
8079 switch (is_constant_expression(expr)) {
8080 case EXPR_CLASS_ERROR: return false;
8081 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8082 default: return true;
8086 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8088 warn_string_literal_address(expr);
8090 expression_t const* const ref = get_reference_address(expr);
8091 if (ref != NULL && is_null_pointer_constant(other)) {
8092 entity_t const *const ent = ref->reference.entity;
8093 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8096 if (!expr->base.parenthesized) {
8097 switch (expr->base.kind) {
8098 case EXPR_BINARY_LESS:
8099 case EXPR_BINARY_GREATER:
8100 case EXPR_BINARY_LESSEQUAL:
8101 case EXPR_BINARY_GREATEREQUAL:
8102 case EXPR_BINARY_NOTEQUAL:
8103 case EXPR_BINARY_EQUAL:
8104 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8113 * Check the semantics of comparison expressions.
8115 * @param expression The expression to check.
8117 static void semantic_comparison(binary_expression_t *expression)
8119 source_position_t const *const pos = &expression->base.source_position;
8120 expression_t *const left = expression->left;
8121 expression_t *const right = expression->right;
8123 warn_comparison(pos, left, right);
8124 warn_comparison(pos, right, left);
8126 type_t *orig_type_left = left->base.type;
8127 type_t *orig_type_right = right->base.type;
8128 type_t *type_left = skip_typeref(orig_type_left);
8129 type_t *type_right = skip_typeref(orig_type_right);
8131 /* TODO non-arithmetic types */
8132 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8133 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8135 /* test for signed vs unsigned compares */
8136 if (is_type_integer(arithmetic_type)) {
8137 bool const signed_left = is_type_signed(type_left);
8138 bool const signed_right = is_type_signed(type_right);
8139 if (signed_left != signed_right) {
8140 /* FIXME long long needs better const folding magic */
8141 /* TODO check whether constant value can be represented by other type */
8142 if ((signed_left && maybe_negative(left)) ||
8143 (signed_right && maybe_negative(right))) {
8144 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8149 expression->left = create_implicit_cast(left, arithmetic_type);
8150 expression->right = create_implicit_cast(right, arithmetic_type);
8151 expression->base.type = arithmetic_type;
8152 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8153 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8154 is_type_float(arithmetic_type)) {
8155 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8157 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8158 /* TODO check compatibility */
8159 } else if (is_type_pointer(type_left)) {
8160 expression->right = create_implicit_cast(right, type_left);
8161 } else if (is_type_pointer(type_right)) {
8162 expression->left = create_implicit_cast(left, type_right);
8163 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8164 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8166 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8170 * Checks if a compound type has constant fields.
8172 static bool has_const_fields(const compound_type_t *type)
8174 compound_t *compound = type->compound;
8175 entity_t *entry = compound->members.entities;
8177 for (; entry != NULL; entry = entry->base.next) {
8178 if (!is_declaration(entry))
8181 const type_t *decl_type = skip_typeref(entry->declaration.type);
8182 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8189 static bool is_valid_assignment_lhs(expression_t const* const left)
8191 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8192 type_t *const type_left = skip_typeref(orig_type_left);
8194 if (!is_lvalue(left)) {
8195 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8200 if (left->kind == EXPR_REFERENCE
8201 && left->reference.entity->kind == ENTITY_FUNCTION) {
8202 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8206 if (is_type_array(type_left)) {
8207 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8210 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8211 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8215 if (is_type_incomplete(type_left)) {
8216 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8217 left, orig_type_left);
8220 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8221 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8222 left, orig_type_left);
8229 static void semantic_arithmetic_assign(binary_expression_t *expression)
8231 expression_t *left = expression->left;
8232 expression_t *right = expression->right;
8233 type_t *orig_type_left = left->base.type;
8234 type_t *orig_type_right = right->base.type;
8236 if (!is_valid_assignment_lhs(left))
8239 type_t *type_left = skip_typeref(orig_type_left);
8240 type_t *type_right = skip_typeref(orig_type_right);
8242 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8243 /* TODO: improve error message */
8244 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8245 errorf(&expression->base.source_position,
8246 "operation needs arithmetic types");
8251 /* combined instructions are tricky. We can't create an implicit cast on
8252 * the left side, because we need the uncasted form for the store.
8253 * The ast2firm pass has to know that left_type must be right_type
8254 * for the arithmetic operation and create a cast by itself */
8255 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8256 expression->right = create_implicit_cast(right, arithmetic_type);
8257 expression->base.type = type_left;
8260 static void semantic_divmod_assign(binary_expression_t *expression)
8262 semantic_arithmetic_assign(expression);
8263 warn_div_by_zero(expression);
8266 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8268 expression_t *const left = expression->left;
8269 expression_t *const right = expression->right;
8270 type_t *const orig_type_left = left->base.type;
8271 type_t *const orig_type_right = right->base.type;
8272 type_t *const type_left = skip_typeref(orig_type_left);
8273 type_t *const type_right = skip_typeref(orig_type_right);
8275 if (!is_valid_assignment_lhs(left))
8278 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8279 /* combined instructions are tricky. We can't create an implicit cast on
8280 * the left side, because we need the uncasted form for the store.
8281 * The ast2firm pass has to know that left_type must be right_type
8282 * for the arithmetic operation and create a cast by itself */
8283 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8284 expression->right = create_implicit_cast(right, arithmetic_type);
8285 expression->base.type = type_left;
8286 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8287 check_pointer_arithmetic(&expression->base.source_position,
8288 type_left, orig_type_left);
8289 expression->base.type = type_left;
8290 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8291 errorf(&expression->base.source_position,
8292 "incompatible types '%T' and '%T' in assignment",
8293 orig_type_left, orig_type_right);
8297 static void semantic_integer_assign(binary_expression_t *expression)
8299 expression_t *left = expression->left;
8300 expression_t *right = expression->right;
8301 type_t *orig_type_left = left->base.type;
8302 type_t *orig_type_right = right->base.type;
8304 if (!is_valid_assignment_lhs(left))
8307 type_t *type_left = skip_typeref(orig_type_left);
8308 type_t *type_right = skip_typeref(orig_type_right);
8310 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8311 /* TODO: improve error message */
8312 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8313 errorf(&expression->base.source_position,
8314 "operation needs integer types");
8319 /* combined instructions are tricky. We can't create an implicit cast on
8320 * the left side, because we need the uncasted form for the store.
8321 * The ast2firm pass has to know that left_type must be right_type
8322 * for the arithmetic operation and create a cast by itself */
8323 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8324 expression->right = create_implicit_cast(right, arithmetic_type);
8325 expression->base.type = type_left;
8328 static void semantic_shift_assign(binary_expression_t *expression)
8330 expression_t *left = expression->left;
8332 if (!is_valid_assignment_lhs(left))
8335 if (!semantic_shift(expression))
8338 expression->base.type = skip_typeref(left->base.type);
8341 static void warn_logical_and_within_or(const expression_t *const expr)
8343 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8345 if (expr->base.parenthesized)
8347 source_position_t const *const pos = &expr->base.source_position;
8348 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8352 * Check the semantic restrictions of a logical expression.
8354 static void semantic_logical_op(binary_expression_t *expression)
8356 /* §6.5.13:2 Each of the operands shall have scalar type.
8357 * §6.5.14:2 Each of the operands shall have scalar type. */
8358 semantic_condition(expression->left, "left operand of logical operator");
8359 semantic_condition(expression->right, "right operand of logical operator");
8360 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8361 warn_logical_and_within_or(expression->left);
8362 warn_logical_and_within_or(expression->right);
8364 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8368 * Check the semantic restrictions of a binary assign expression.
8370 static void semantic_binexpr_assign(binary_expression_t *expression)
8372 expression_t *left = expression->left;
8373 type_t *orig_type_left = left->base.type;
8375 if (!is_valid_assignment_lhs(left))
8378 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8379 report_assign_error(error, orig_type_left, expression->right,
8380 "assignment", &left->base.source_position);
8381 expression->right = create_implicit_cast(expression->right, orig_type_left);
8382 expression->base.type = orig_type_left;
8386 * Determine if the outermost operation (or parts thereof) of the given
8387 * expression has no effect in order to generate a warning about this fact.
8388 * Therefore in some cases this only examines some of the operands of the
8389 * expression (see comments in the function and examples below).
8391 * f() + 23; // warning, because + has no effect
8392 * x || f(); // no warning, because x controls execution of f()
8393 * x ? y : f(); // warning, because y has no effect
8394 * (void)x; // no warning to be able to suppress the warning
8395 * This function can NOT be used for an "expression has definitely no effect"-
8397 static bool expression_has_effect(const expression_t *const expr)
8399 switch (expr->kind) {
8400 case EXPR_ERROR: return true; /* do NOT warn */
8401 case EXPR_REFERENCE: return false;
8402 case EXPR_ENUM_CONSTANT: return false;
8403 case EXPR_LABEL_ADDRESS: return false;
8405 /* suppress the warning for microsoft __noop operations */
8406 case EXPR_LITERAL_MS_NOOP: return true;
8407 case EXPR_LITERAL_BOOLEAN:
8408 case EXPR_LITERAL_CHARACTER:
8409 case EXPR_LITERAL_WIDE_CHARACTER:
8410 case EXPR_LITERAL_INTEGER:
8411 case EXPR_LITERAL_FLOATINGPOINT:
8412 case EXPR_STRING_LITERAL: return false;
8413 case EXPR_WIDE_STRING_LITERAL: return false;
8416 const call_expression_t *const call = &expr->call;
8417 if (call->function->kind != EXPR_REFERENCE)
8420 switch (call->function->reference.entity->function.btk) {
8421 /* FIXME: which builtins have no effect? */
8422 default: return true;
8426 /* Generate the warning if either the left or right hand side of a
8427 * conditional expression has no effect */
8428 case EXPR_CONDITIONAL: {
8429 conditional_expression_t const *const cond = &expr->conditional;
8430 expression_t const *const t = cond->true_expression;
8432 (t == NULL || expression_has_effect(t)) &&
8433 expression_has_effect(cond->false_expression);
8436 case EXPR_SELECT: return false;
8437 case EXPR_ARRAY_ACCESS: return false;
8438 case EXPR_SIZEOF: return false;
8439 case EXPR_CLASSIFY_TYPE: return false;
8440 case EXPR_ALIGNOF: return false;
8442 case EXPR_FUNCNAME: return false;
8443 case EXPR_BUILTIN_CONSTANT_P: return false;
8444 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8445 case EXPR_OFFSETOF: return false;
8446 case EXPR_VA_START: return true;
8447 case EXPR_VA_ARG: return true;
8448 case EXPR_VA_COPY: return true;
8449 case EXPR_STATEMENT: return true; // TODO
8450 case EXPR_COMPOUND_LITERAL: return false;
8452 case EXPR_UNARY_NEGATE: return false;
8453 case EXPR_UNARY_PLUS: return false;
8454 case EXPR_UNARY_BITWISE_NEGATE: return false;
8455 case EXPR_UNARY_NOT: return false;
8456 case EXPR_UNARY_DEREFERENCE: return false;
8457 case EXPR_UNARY_TAKE_ADDRESS: return false;
8458 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8459 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8460 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8461 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8463 /* Treat void casts as if they have an effect in order to being able to
8464 * suppress the warning */
8465 case EXPR_UNARY_CAST: {
8466 type_t *const type = skip_typeref(expr->base.type);
8467 return is_type_void(type);
8470 case EXPR_UNARY_ASSUME: return true;
8471 case EXPR_UNARY_DELETE: return true;
8472 case EXPR_UNARY_DELETE_ARRAY: return true;
8473 case EXPR_UNARY_THROW: return true;
8475 case EXPR_BINARY_ADD: return false;
8476 case EXPR_BINARY_SUB: return false;
8477 case EXPR_BINARY_MUL: return false;
8478 case EXPR_BINARY_DIV: return false;
8479 case EXPR_BINARY_MOD: return false;
8480 case EXPR_BINARY_EQUAL: return false;
8481 case EXPR_BINARY_NOTEQUAL: return false;
8482 case EXPR_BINARY_LESS: return false;
8483 case EXPR_BINARY_LESSEQUAL: return false;
8484 case EXPR_BINARY_GREATER: return false;
8485 case EXPR_BINARY_GREATEREQUAL: return false;
8486 case EXPR_BINARY_BITWISE_AND: return false;
8487 case EXPR_BINARY_BITWISE_OR: return false;
8488 case EXPR_BINARY_BITWISE_XOR: return false;
8489 case EXPR_BINARY_SHIFTLEFT: return false;
8490 case EXPR_BINARY_SHIFTRIGHT: return false;
8491 case EXPR_BINARY_ASSIGN: return true;
8492 case EXPR_BINARY_MUL_ASSIGN: return true;
8493 case EXPR_BINARY_DIV_ASSIGN: return true;
8494 case EXPR_BINARY_MOD_ASSIGN: return true;
8495 case EXPR_BINARY_ADD_ASSIGN: return true;
8496 case EXPR_BINARY_SUB_ASSIGN: return true;
8497 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8498 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8499 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8500 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8501 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8503 /* Only examine the right hand side of && and ||, because the left hand
8504 * side already has the effect of controlling the execution of the right
8506 case EXPR_BINARY_LOGICAL_AND:
8507 case EXPR_BINARY_LOGICAL_OR:
8508 /* Only examine the right hand side of a comma expression, because the left
8509 * hand side has a separate warning */
8510 case EXPR_BINARY_COMMA:
8511 return expression_has_effect(expr->binary.right);
8513 case EXPR_BINARY_ISGREATER: return false;
8514 case EXPR_BINARY_ISGREATEREQUAL: return false;
8515 case EXPR_BINARY_ISLESS: return false;
8516 case EXPR_BINARY_ISLESSEQUAL: return false;
8517 case EXPR_BINARY_ISLESSGREATER: return false;
8518 case EXPR_BINARY_ISUNORDERED: return false;
8521 internal_errorf(HERE, "unexpected expression");
8524 static void semantic_comma(binary_expression_t *expression)
8526 const expression_t *const left = expression->left;
8527 if (!expression_has_effect(left)) {
8528 source_position_t const *const pos = &left->base.source_position;
8529 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8531 expression->base.type = expression->right->base.type;
8535 * @param prec_r precedence of the right operand
8537 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8538 static expression_t *parse_##binexpression_type(expression_t *left) \
8540 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8541 binexpr->binary.left = left; \
8544 expression_t *right = parse_subexpression(prec_r); \
8546 binexpr->binary.right = right; \
8547 sfunc(&binexpr->binary); \
8552 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8553 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8554 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8555 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8556 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8557 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8558 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8559 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8560 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8561 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8562 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8563 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8564 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8565 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8566 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8567 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8568 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8569 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8570 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8571 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8572 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8573 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8574 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8575 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8576 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8577 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8578 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8579 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8580 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8581 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8584 static expression_t *parse_subexpression(precedence_t precedence)
8586 expression_parser_function_t *parser
8587 = &expression_parsers[token.kind];
8590 if (parser->parser != NULL) {
8591 left = parser->parser();
8593 left = parse_primary_expression();
8595 assert(left != NULL);
8598 parser = &expression_parsers[token.kind];
8599 if (parser->infix_parser == NULL)
8601 if (parser->infix_precedence < precedence)
8604 left = parser->infix_parser(left);
8606 assert(left != NULL);
8613 * Parse an expression.
8615 static expression_t *parse_expression(void)
8617 return parse_subexpression(PREC_EXPRESSION);
8621 * Register a parser for a prefix-like operator.
8623 * @param parser the parser function
8624 * @param token_kind the token type of the prefix token
8626 static void register_expression_parser(parse_expression_function parser,
8629 expression_parser_function_t *entry = &expression_parsers[token_kind];
8631 if (entry->parser != NULL) {
8632 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8633 panic("trying to register multiple expression parsers for a token");
8635 entry->parser = parser;
8639 * Register a parser for an infix operator with given precedence.
8641 * @param parser the parser function
8642 * @param token_kind the token type of the infix operator
8643 * @param precedence the precedence of the operator
8645 static void register_infix_parser(parse_expression_infix_function parser,
8646 int token_kind, precedence_t precedence)
8648 expression_parser_function_t *entry = &expression_parsers[token_kind];
8650 if (entry->infix_parser != NULL) {
8651 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8652 panic("trying to register multiple infix expression parsers for a "
8655 entry->infix_parser = parser;
8656 entry->infix_precedence = precedence;
8660 * Initialize the expression parsers.
8662 static void init_expression_parsers(void)
8664 memset(&expression_parsers, 0, sizeof(expression_parsers));
8666 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8667 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8668 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8669 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8670 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8671 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8672 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8673 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8674 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8675 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8676 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8677 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8678 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8679 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8680 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8681 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8682 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8683 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8684 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8685 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8686 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8687 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8688 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8689 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8690 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8691 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8692 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8693 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8694 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8695 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8696 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8697 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8698 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8699 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8700 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8701 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8702 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8704 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8705 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8706 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8707 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8708 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8709 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8710 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8711 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8712 register_expression_parser(parse_sizeof, T_sizeof);
8713 register_expression_parser(parse_alignof, T___alignof__);
8714 register_expression_parser(parse_extension, T___extension__);
8715 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8716 register_expression_parser(parse_delete, T_delete);
8717 register_expression_parser(parse_throw, T_throw);
8721 * Parse a asm statement arguments specification.
8723 static asm_argument_t *parse_asm_arguments(bool is_out)
8725 asm_argument_t *result = NULL;
8726 asm_argument_t **anchor = &result;
8728 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8729 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8732 add_anchor_token(']');
8733 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8734 rem_anchor_token(']');
8736 if (!argument->symbol)
8740 argument->constraints = parse_string_literals();
8742 add_anchor_token(')');
8743 expression_t *expression = parse_expression();
8744 rem_anchor_token(')');
8746 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8747 * change size or type representation (e.g. int -> long is ok, but
8748 * int -> float is not) */
8749 if (expression->kind == EXPR_UNARY_CAST) {
8750 type_t *const type = expression->base.type;
8751 type_kind_t const kind = type->kind;
8752 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8755 if (kind == TYPE_ATOMIC) {
8756 atomic_type_kind_t const akind = type->atomic.akind;
8757 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8758 size = get_atomic_type_size(akind);
8760 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8761 size = get_type_size(type_void_ptr);
8765 expression_t *const value = expression->unary.value;
8766 type_t *const value_type = value->base.type;
8767 type_kind_t const value_kind = value_type->kind;
8769 unsigned value_flags;
8770 unsigned value_size;
8771 if (value_kind == TYPE_ATOMIC) {
8772 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8773 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8774 value_size = get_atomic_type_size(value_akind);
8775 } else if (value_kind == TYPE_POINTER) {
8776 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8777 value_size = get_type_size(type_void_ptr);
8782 if (value_flags != flags || value_size != size)
8786 } while (expression->kind == EXPR_UNARY_CAST);
8790 if (!is_lvalue(expression)) {
8791 errorf(&expression->base.source_position,
8792 "asm output argument is not an lvalue");
8795 if (argument->constraints.begin[0] == '=')
8796 determine_lhs_ent(expression, NULL);
8798 mark_vars_read(expression, NULL);
8800 mark_vars_read(expression, NULL);
8802 argument->expression = expression;
8805 set_address_taken(expression, true);
8808 anchor = &argument->next;
8818 * Parse a asm statement clobber specification.
8820 static asm_clobber_t *parse_asm_clobbers(void)
8822 asm_clobber_t *result = NULL;
8823 asm_clobber_t **anchor = &result;
8825 while (token.kind == T_STRING_LITERAL) {
8826 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8827 clobber->clobber = parse_string_literals();
8830 anchor = &clobber->next;
8840 * Parse an asm statement.
8842 static statement_t *parse_asm_statement(void)
8844 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8845 asm_statement_t *asm_statement = &statement->asms;
8849 if (next_if(T_volatile))
8850 asm_statement->is_volatile = true;
8853 add_anchor_token(')');
8854 if (token.kind != T_STRING_LITERAL) {
8855 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8858 asm_statement->asm_text = parse_string_literals();
8860 add_anchor_token(':');
8861 if (!next_if(':')) {
8862 rem_anchor_token(':');
8866 asm_statement->outputs = parse_asm_arguments(true);
8867 if (!next_if(':')) {
8868 rem_anchor_token(':');
8872 asm_statement->inputs = parse_asm_arguments(false);
8873 if (!next_if(':')) {
8874 rem_anchor_token(':');
8877 rem_anchor_token(':');
8879 asm_statement->clobbers = parse_asm_clobbers();
8882 rem_anchor_token(')');
8886 if (asm_statement->outputs == NULL) {
8887 /* GCC: An 'asm' instruction without any output operands will be treated
8888 * identically to a volatile 'asm' instruction. */
8889 asm_statement->is_volatile = true;
8895 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8897 statement_t *inner_stmt;
8898 switch (token.kind) {
8900 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8901 inner_stmt = create_error_statement();
8905 if (label->kind == STATEMENT_LABEL) {
8906 /* Eat an empty statement here, to avoid the warning about an empty
8907 * statement after a label. label:; is commonly used to have a label
8908 * before a closing brace. */
8909 inner_stmt = create_empty_statement();
8916 inner_stmt = parse_statement();
8917 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8918 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8919 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8920 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8928 * Parse a case statement.
8930 static statement_t *parse_case_statement(void)
8932 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8933 source_position_t *const pos = &statement->base.source_position;
8936 add_anchor_token(':');
8938 expression_t *expression = parse_expression();
8939 type_t *expression_type = expression->base.type;
8940 type_t *skipped = skip_typeref(expression_type);
8941 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8942 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8943 expression, expression_type);
8946 type_t *type = expression_type;
8947 if (current_switch != NULL) {
8948 type_t *switch_type = current_switch->expression->base.type;
8949 if (is_type_valid(switch_type)) {
8950 expression = create_implicit_cast(expression, switch_type);
8954 statement->case_label.expression = expression;
8955 expression_classification_t const expr_class = is_constant_expression(expression);
8956 if (expr_class != EXPR_CLASS_CONSTANT) {
8957 if (expr_class != EXPR_CLASS_ERROR) {
8958 errorf(pos, "case label does not reduce to an integer constant");
8960 statement->case_label.is_bad = true;
8962 long const val = fold_constant_to_int(expression);
8963 statement->case_label.first_case = val;
8964 statement->case_label.last_case = val;
8968 if (next_if(T_DOTDOTDOT)) {
8969 expression_t *end_range = parse_expression();
8970 expression_type = expression->base.type;
8971 skipped = skip_typeref(expression_type);
8972 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8973 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8974 expression, expression_type);
8977 end_range = create_implicit_cast(end_range, type);
8978 statement->case_label.end_range = end_range;
8979 expression_classification_t const end_class = is_constant_expression(end_range);
8980 if (end_class != EXPR_CLASS_CONSTANT) {
8981 if (end_class != EXPR_CLASS_ERROR) {
8982 errorf(pos, "case range does not reduce to an integer constant");
8984 statement->case_label.is_bad = true;
8986 long const val = fold_constant_to_int(end_range);
8987 statement->case_label.last_case = val;
8989 if (val < statement->case_label.first_case) {
8990 statement->case_label.is_empty_range = true;
8991 warningf(WARN_OTHER, pos, "empty range specified");
8997 PUSH_PARENT(statement);
8999 rem_anchor_token(':');
9002 if (current_switch != NULL) {
9003 if (! statement->case_label.is_bad) {
9004 /* Check for duplicate case values */
9005 case_label_statement_t *c = &statement->case_label;
9006 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9007 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9010 if (c->last_case < l->first_case || c->first_case > l->last_case)
9013 errorf(pos, "duplicate case value (previously used %P)",
9014 &l->base.source_position);
9018 /* link all cases into the switch statement */
9019 if (current_switch->last_case == NULL) {
9020 current_switch->first_case = &statement->case_label;
9022 current_switch->last_case->next = &statement->case_label;
9024 current_switch->last_case = &statement->case_label;
9026 errorf(pos, "case label not within a switch statement");
9029 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9036 * Parse a default statement.
9038 static statement_t *parse_default_statement(void)
9040 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9044 PUSH_PARENT(statement);
9048 if (current_switch != NULL) {
9049 const case_label_statement_t *def_label = current_switch->default_label;
9050 if (def_label != NULL) {
9051 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9053 current_switch->default_label = &statement->case_label;
9055 /* link all cases into the switch statement */
9056 if (current_switch->last_case == NULL) {
9057 current_switch->first_case = &statement->case_label;
9059 current_switch->last_case->next = &statement->case_label;
9061 current_switch->last_case = &statement->case_label;
9064 errorf(&statement->base.source_position,
9065 "'default' label not within a switch statement");
9068 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9075 * Parse a label statement.
9077 static statement_t *parse_label_statement(void)
9079 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9080 label_t *const label = get_label();
9081 statement->label.label = label;
9083 PUSH_PARENT(statement);
9085 /* if statement is already set then the label is defined twice,
9086 * otherwise it was just mentioned in a goto/local label declaration so far
9088 source_position_t const* const pos = &statement->base.source_position;
9089 if (label->statement != NULL) {
9090 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9092 label->base.source_position = *pos;
9093 label->statement = statement;
9098 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9099 parse_attributes(NULL); // TODO process attributes
9102 statement->label.statement = parse_label_inner_statement(statement, "label");
9104 /* remember the labels in a list for later checking */
9105 *label_anchor = &statement->label;
9106 label_anchor = &statement->label.next;
9112 static statement_t *parse_inner_statement(void)
9114 statement_t *const stmt = parse_statement();
9115 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9116 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9117 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9118 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9124 * Parse an expression in parentheses and mark its variables as read.
9126 static expression_t *parse_condition(void)
9129 add_anchor_token(')');
9130 expression_t *const expr = parse_expression();
9131 mark_vars_read(expr, NULL);
9132 rem_anchor_token(')');
9138 * Parse an if statement.
9140 static statement_t *parse_if(void)
9142 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9146 PUSH_PARENT(statement);
9147 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9149 add_anchor_token(T_else);
9151 expression_t *const expr = parse_condition();
9152 statement->ifs.condition = expr;
9153 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9155 semantic_condition(expr, "condition of 'if'-statment");
9157 statement_t *const true_stmt = parse_inner_statement();
9158 statement->ifs.true_statement = true_stmt;
9159 rem_anchor_token(T_else);
9161 if (true_stmt->kind == STATEMENT_EMPTY) {
9162 warningf(WARN_EMPTY_BODY, HERE,
9163 "suggest braces around empty body in an ‘if’ statement");
9166 if (next_if(T_else)) {
9167 statement->ifs.false_statement = parse_inner_statement();
9169 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9170 warningf(WARN_EMPTY_BODY, HERE,
9171 "suggest braces around empty body in an ‘if’ statement");
9173 } else if (true_stmt->kind == STATEMENT_IF &&
9174 true_stmt->ifs.false_statement != NULL) {
9175 source_position_t const *const pos = &true_stmt->base.source_position;
9176 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9185 * Check that all enums are handled in a switch.
9187 * @param statement the switch statement to check
9189 static void check_enum_cases(const switch_statement_t *statement)
9191 if (!is_warn_on(WARN_SWITCH_ENUM))
9193 const type_t *type = skip_typeref(statement->expression->base.type);
9194 if (! is_type_enum(type))
9196 const enum_type_t *enumt = &type->enumt;
9198 /* if we have a default, no warnings */
9199 if (statement->default_label != NULL)
9202 /* FIXME: calculation of value should be done while parsing */
9203 /* TODO: quadratic algorithm here. Change to an n log n one */
9204 long last_value = -1;
9205 const entity_t *entry = enumt->enume->base.next;
9206 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9207 entry = entry->base.next) {
9208 const expression_t *expression = entry->enum_value.value;
9209 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9211 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9212 if (l->expression == NULL)
9214 if (l->first_case <= value && value <= l->last_case) {
9220 source_position_t const *const pos = &statement->base.source_position;
9221 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9228 * Parse a switch statement.
9230 static statement_t *parse_switch(void)
9232 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9236 PUSH_PARENT(statement);
9237 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9239 expression_t *const expr = parse_condition();
9240 type_t * type = skip_typeref(expr->base.type);
9241 if (is_type_integer(type)) {
9242 type = promote_integer(type);
9243 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9244 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9246 } else if (is_type_valid(type)) {
9247 errorf(&expr->base.source_position,
9248 "switch quantity is not an integer, but '%T'", type);
9249 type = type_error_type;
9251 statement->switchs.expression = create_implicit_cast(expr, type);
9253 switch_statement_t *rem = current_switch;
9254 current_switch = &statement->switchs;
9255 statement->switchs.body = parse_inner_statement();
9256 current_switch = rem;
9258 if (statement->switchs.default_label == NULL) {
9259 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9261 check_enum_cases(&statement->switchs);
9268 static statement_t *parse_loop_body(statement_t *const loop)
9270 statement_t *const rem = current_loop;
9271 current_loop = loop;
9273 statement_t *const body = parse_inner_statement();
9280 * Parse a while statement.
9282 static statement_t *parse_while(void)
9284 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9288 PUSH_PARENT(statement);
9289 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9291 expression_t *const cond = parse_condition();
9292 statement->whiles.condition = cond;
9293 /* §6.8.5:2 The controlling expression of an iteration statement shall
9294 * have scalar type. */
9295 semantic_condition(cond, "condition of 'while'-statement");
9297 statement->whiles.body = parse_loop_body(statement);
9305 * Parse a do statement.
9307 static statement_t *parse_do(void)
9309 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9313 PUSH_PARENT(statement);
9314 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9316 add_anchor_token(T_while);
9317 statement->do_while.body = parse_loop_body(statement);
9318 rem_anchor_token(T_while);
9321 expression_t *const cond = parse_condition();
9322 statement->do_while.condition = cond;
9323 /* §6.8.5:2 The controlling expression of an iteration statement shall
9324 * have scalar type. */
9325 semantic_condition(cond, "condition of 'do-while'-statement");
9334 * Parse a for statement.
9336 static statement_t *parse_for(void)
9338 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9342 PUSH_PARENT(statement);
9343 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9346 add_anchor_token(')');
9351 } else if (is_declaration_specifier(&token)) {
9352 parse_declaration(record_entity, DECL_FLAGS_NONE);
9354 add_anchor_token(';');
9355 expression_t *const init = parse_expression();
9356 statement->fors.initialisation = init;
9357 mark_vars_read(init, ENT_ANY);
9358 if (!expression_has_effect(init)) {
9359 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9361 rem_anchor_token(';');
9367 if (token.kind != ';') {
9368 add_anchor_token(';');
9369 expression_t *const cond = parse_expression();
9370 statement->fors.condition = cond;
9371 /* §6.8.5:2 The controlling expression of an iteration statement
9372 * shall have scalar type. */
9373 semantic_condition(cond, "condition of 'for'-statement");
9374 mark_vars_read(cond, NULL);
9375 rem_anchor_token(';');
9378 if (token.kind != ')') {
9379 expression_t *const step = parse_expression();
9380 statement->fors.step = step;
9381 mark_vars_read(step, ENT_ANY);
9382 if (!expression_has_effect(step)) {
9383 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9386 rem_anchor_token(')');
9388 statement->fors.body = parse_loop_body(statement);
9396 * Parse a goto statement.
9398 static statement_t *parse_goto(void)
9400 statement_t *statement;
9401 if (GNU_MODE && look_ahead(1)->kind == '*') {
9402 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9406 expression_t *expression = parse_expression();
9407 mark_vars_read(expression, NULL);
9409 /* Argh: although documentation says the expression must be of type void*,
9410 * gcc accepts anything that can be casted into void* without error */
9411 type_t *type = expression->base.type;
9413 if (type != type_error_type) {
9414 if (!is_type_pointer(type) && !is_type_integer(type)) {
9415 errorf(&expression->base.source_position,
9416 "cannot convert to a pointer type");
9417 } else if (type != type_void_ptr) {
9418 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9420 expression = create_implicit_cast(expression, type_void_ptr);
9423 statement->computed_goto.expression = expression;
9425 statement = allocate_statement_zero(STATEMENT_GOTO);
9427 if (token.kind == T_IDENTIFIER) {
9428 label_t *const label = get_label();
9430 statement->gotos.label = label;
9432 /* remember the goto's in a list for later checking */
9433 *goto_anchor = &statement->gotos;
9434 goto_anchor = &statement->gotos.next;
9437 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9439 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9441 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9450 * Parse a continue statement.
9452 static statement_t *parse_continue(void)
9454 if (current_loop == NULL) {
9455 errorf(HERE, "continue statement not within loop");
9458 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9466 * Parse a break statement.
9468 static statement_t *parse_break(void)
9470 if (current_switch == NULL && current_loop == NULL) {
9471 errorf(HERE, "break statement not within loop or switch");
9474 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9482 * Parse a __leave statement.
9484 static statement_t *parse_leave_statement(void)
9486 if (current_try == NULL) {
9487 errorf(HERE, "__leave statement not within __try");
9490 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9498 * Check if a given entity represents a local variable.
9500 static bool is_local_variable(const entity_t *entity)
9502 if (entity->kind != ENTITY_VARIABLE)
9505 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9506 case STORAGE_CLASS_AUTO:
9507 case STORAGE_CLASS_REGISTER: {
9508 const type_t *type = skip_typeref(entity->declaration.type);
9509 if (is_type_function(type)) {
9521 * Check if a given expression represents a local variable.
9523 static bool expression_is_local_variable(const expression_t *expression)
9525 if (expression->base.kind != EXPR_REFERENCE) {
9528 const entity_t *entity = expression->reference.entity;
9529 return is_local_variable(entity);
9533 * Check if a given expression represents a local variable and
9534 * return its declaration then, else return NULL.
9536 entity_t *expression_is_variable(const expression_t *expression)
9538 if (expression->base.kind != EXPR_REFERENCE) {
9541 entity_t *entity = expression->reference.entity;
9542 if (entity->kind != ENTITY_VARIABLE)
9548 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9550 if (c_mode & _CXX || strict_mode) {
9553 warningf(WARN_OTHER, pos, msg);
9558 * Parse a return statement.
9560 static statement_t *parse_return(void)
9562 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9565 expression_t *return_value = NULL;
9566 if (token.kind != ';') {
9567 return_value = parse_expression();
9568 mark_vars_read(return_value, NULL);
9571 const type_t *const func_type = skip_typeref(current_function->base.type);
9572 assert(is_type_function(func_type));
9573 type_t *const return_type = skip_typeref(func_type->function.return_type);
9575 source_position_t const *const pos = &statement->base.source_position;
9576 if (return_value != NULL) {
9577 type_t *return_value_type = skip_typeref(return_value->base.type);
9579 if (is_type_void(return_type)) {
9580 if (!is_type_void(return_value_type)) {
9581 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9582 /* Only warn in C mode, because GCC does the same */
9583 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9584 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9585 /* Only warn in C mode, because GCC does the same */
9586 err_or_warn(pos, "'return' with expression in function returning 'void'");
9589 assign_error_t error = semantic_assign(return_type, return_value);
9590 report_assign_error(error, return_type, return_value, "'return'",
9593 return_value = create_implicit_cast(return_value, return_type);
9594 /* check for returning address of a local var */
9595 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9596 const expression_t *expression = return_value->unary.value;
9597 if (expression_is_local_variable(expression)) {
9598 warningf(WARN_OTHER, pos, "function returns address of local variable");
9601 } else if (!is_type_void(return_type)) {
9602 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9603 err_or_warn(pos, "'return' without value, in function returning non-void");
9605 statement->returns.value = return_value;
9612 * Parse a declaration statement.
9614 static statement_t *parse_declaration_statement(void)
9616 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9618 entity_t *before = current_scope->last_entity;
9620 parse_external_declaration();
9622 parse_declaration(record_entity, DECL_FLAGS_NONE);
9625 declaration_statement_t *const decl = &statement->declaration;
9626 entity_t *const begin =
9627 before != NULL ? before->base.next : current_scope->entities;
9628 decl->declarations_begin = begin;
9629 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9635 * Parse an expression statement, ie. expr ';'.
9637 static statement_t *parse_expression_statement(void)
9639 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9641 expression_t *const expr = parse_expression();
9642 statement->expression.expression = expr;
9643 mark_vars_read(expr, ENT_ANY);
9650 * Parse a microsoft __try { } __finally { } or
9651 * __try{ } __except() { }
9653 static statement_t *parse_ms_try_statment(void)
9655 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9658 PUSH_PARENT(statement);
9660 ms_try_statement_t *rem = current_try;
9661 current_try = &statement->ms_try;
9662 statement->ms_try.try_statement = parse_compound_statement(false);
9667 if (next_if(T___except)) {
9668 expression_t *const expr = parse_condition();
9669 type_t * type = skip_typeref(expr->base.type);
9670 if (is_type_integer(type)) {
9671 type = promote_integer(type);
9672 } else if (is_type_valid(type)) {
9673 errorf(&expr->base.source_position,
9674 "__expect expression is not an integer, but '%T'", type);
9675 type = type_error_type;
9677 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9678 } else if (!next_if(T__finally)) {
9679 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9681 statement->ms_try.final_statement = parse_compound_statement(false);
9685 static statement_t *parse_empty_statement(void)
9687 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9688 statement_t *const statement = create_empty_statement();
9693 static statement_t *parse_local_label_declaration(void)
9695 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9699 entity_t *begin = NULL;
9700 entity_t *end = NULL;
9701 entity_t **anchor = &begin;
9703 source_position_t pos;
9704 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9708 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9709 if (entity != NULL && entity->base.parent_scope == current_scope) {
9710 source_position_t const *const ppos = &entity->base.source_position;
9711 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9713 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9714 entity->base.parent_scope = current_scope;
9717 anchor = &entity->base.next;
9720 environment_push(entity);
9722 } while (next_if(','));
9725 statement->declaration.declarations_begin = begin;
9726 statement->declaration.declarations_end = end;
9730 static void parse_namespace_definition(void)
9734 entity_t *entity = NULL;
9735 symbol_t *symbol = NULL;
9737 if (token.kind == T_IDENTIFIER) {
9738 symbol = token.identifier.symbol;
9741 entity = get_entity(symbol, NAMESPACE_NORMAL);
9743 && entity->kind != ENTITY_NAMESPACE
9744 && entity->base.parent_scope == current_scope) {
9745 if (is_entity_valid(entity)) {
9746 error_redefined_as_different_kind(&token.base.source_position,
9747 entity, ENTITY_NAMESPACE);
9753 if (entity == NULL) {
9754 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9755 entity->base.parent_scope = current_scope;
9758 if (token.kind == '=') {
9759 /* TODO: parse namespace alias */
9760 panic("namespace alias definition not supported yet");
9763 environment_push(entity);
9764 append_entity(current_scope, entity);
9766 PUSH_SCOPE(&entity->namespacee.members);
9767 PUSH_CURRENT_ENTITY(entity);
9769 add_anchor_token('}');
9772 rem_anchor_token('}');
9775 POP_CURRENT_ENTITY();
9780 * Parse a statement.
9781 * There's also parse_statement() which additionally checks for
9782 * "statement has no effect" warnings
9784 static statement_t *intern_parse_statement(void)
9786 /* declaration or statement */
9787 statement_t *statement;
9788 switch (token.kind) {
9789 case T_IDENTIFIER: {
9790 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9791 if (la1_type == ':') {
9792 statement = parse_label_statement();
9793 } else if (is_typedef_symbol(token.identifier.symbol)) {
9794 statement = parse_declaration_statement();
9796 /* it's an identifier, the grammar says this must be an
9797 * expression statement. However it is common that users mistype
9798 * declaration types, so we guess a bit here to improve robustness
9799 * for incorrect programs */
9803 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9805 statement = parse_expression_statement();
9809 statement = parse_declaration_statement();
9817 case T___extension__: {
9818 /* This can be a prefix to a declaration or an expression statement.
9819 * We simply eat it now and parse the rest with tail recursion. */
9821 statement = intern_parse_statement();
9827 statement = parse_declaration_statement();
9831 statement = parse_local_label_declaration();
9834 case ';': statement = parse_empty_statement(); break;
9835 case '{': statement = parse_compound_statement(false); break;
9836 case T___leave: statement = parse_leave_statement(); break;
9837 case T___try: statement = parse_ms_try_statment(); break;
9838 case T_asm: statement = parse_asm_statement(); break;
9839 case T_break: statement = parse_break(); break;
9840 case T_case: statement = parse_case_statement(); break;
9841 case T_continue: statement = parse_continue(); break;
9842 case T_default: statement = parse_default_statement(); break;
9843 case T_do: statement = parse_do(); break;
9844 case T_for: statement = parse_for(); break;
9845 case T_goto: statement = parse_goto(); break;
9846 case T_if: statement = parse_if(); break;
9847 case T_return: statement = parse_return(); break;
9848 case T_switch: statement = parse_switch(); break;
9849 case T_while: statement = parse_while(); break;
9852 statement = parse_expression_statement();
9856 errorf(HERE, "unexpected token %K while parsing statement", &token);
9857 statement = create_error_statement();
9866 * parse a statement and emits "statement has no effect" warning if needed
9867 * (This is really a wrapper around intern_parse_statement with check for 1
9868 * single warning. It is needed, because for statement expressions we have
9869 * to avoid the warning on the last statement)
9871 static statement_t *parse_statement(void)
9873 statement_t *statement = intern_parse_statement();
9875 if (statement->kind == STATEMENT_EXPRESSION) {
9876 expression_t *expression = statement->expression.expression;
9877 if (!expression_has_effect(expression)) {
9878 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9886 * Parse a compound statement.
9888 static statement_t *parse_compound_statement(bool inside_expression_statement)
9890 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9892 PUSH_PARENT(statement);
9893 PUSH_SCOPE(&statement->compound.scope);
9896 add_anchor_token('}');
9897 /* tokens, which can start a statement */
9898 /* TODO MS, __builtin_FOO */
9899 add_anchor_token('!');
9900 add_anchor_token('&');
9901 add_anchor_token('(');
9902 add_anchor_token('*');
9903 add_anchor_token('+');
9904 add_anchor_token('-');
9905 add_anchor_token(';');
9906 add_anchor_token('{');
9907 add_anchor_token('~');
9908 add_anchor_token(T_CHARACTER_CONSTANT);
9909 add_anchor_token(T_COLONCOLON);
9910 add_anchor_token(T_FLOATINGPOINT);
9911 add_anchor_token(T_IDENTIFIER);
9912 add_anchor_token(T_INTEGER);
9913 add_anchor_token(T_MINUSMINUS);
9914 add_anchor_token(T_PLUSPLUS);
9915 add_anchor_token(T_STRING_LITERAL);
9916 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
9917 add_anchor_token(T_WIDE_STRING_LITERAL);
9918 add_anchor_token(T__Bool);
9919 add_anchor_token(T__Complex);
9920 add_anchor_token(T__Imaginary);
9921 add_anchor_token(T___FUNCTION__);
9922 add_anchor_token(T___PRETTY_FUNCTION__);
9923 add_anchor_token(T___alignof__);
9924 add_anchor_token(T___attribute__);
9925 add_anchor_token(T___builtin_va_start);
9926 add_anchor_token(T___extension__);
9927 add_anchor_token(T___func__);
9928 add_anchor_token(T___imag__);
9929 add_anchor_token(T___label__);
9930 add_anchor_token(T___real__);
9931 add_anchor_token(T___thread);
9932 add_anchor_token(T_asm);
9933 add_anchor_token(T_auto);
9934 add_anchor_token(T_bool);
9935 add_anchor_token(T_break);
9936 add_anchor_token(T_case);
9937 add_anchor_token(T_char);
9938 add_anchor_token(T_class);
9939 add_anchor_token(T_const);
9940 add_anchor_token(T_const_cast);
9941 add_anchor_token(T_continue);
9942 add_anchor_token(T_default);
9943 add_anchor_token(T_delete);
9944 add_anchor_token(T_double);
9945 add_anchor_token(T_do);
9946 add_anchor_token(T_dynamic_cast);
9947 add_anchor_token(T_enum);
9948 add_anchor_token(T_extern);
9949 add_anchor_token(T_false);
9950 add_anchor_token(T_float);
9951 add_anchor_token(T_for);
9952 add_anchor_token(T_goto);
9953 add_anchor_token(T_if);
9954 add_anchor_token(T_inline);
9955 add_anchor_token(T_int);
9956 add_anchor_token(T_long);
9957 add_anchor_token(T_new);
9958 add_anchor_token(T_operator);
9959 add_anchor_token(T_register);
9960 add_anchor_token(T_reinterpret_cast);
9961 add_anchor_token(T_restrict);
9962 add_anchor_token(T_return);
9963 add_anchor_token(T_short);
9964 add_anchor_token(T_signed);
9965 add_anchor_token(T_sizeof);
9966 add_anchor_token(T_static);
9967 add_anchor_token(T_static_cast);
9968 add_anchor_token(T_struct);
9969 add_anchor_token(T_switch);
9970 add_anchor_token(T_template);
9971 add_anchor_token(T_this);
9972 add_anchor_token(T_throw);
9973 add_anchor_token(T_true);
9974 add_anchor_token(T_try);
9975 add_anchor_token(T_typedef);
9976 add_anchor_token(T_typeid);
9977 add_anchor_token(T_typename);
9978 add_anchor_token(T_typeof);
9979 add_anchor_token(T_union);
9980 add_anchor_token(T_unsigned);
9981 add_anchor_token(T_using);
9982 add_anchor_token(T_void);
9983 add_anchor_token(T_volatile);
9984 add_anchor_token(T_wchar_t);
9985 add_anchor_token(T_while);
9987 statement_t **anchor = &statement->compound.statements;
9988 bool only_decls_so_far = true;
9989 while (token.kind != '}' && token.kind != T_EOF) {
9990 statement_t *sub_statement = intern_parse_statement();
9991 if (sub_statement->kind == STATEMENT_ERROR) {
9995 if (sub_statement->kind != STATEMENT_DECLARATION) {
9996 only_decls_so_far = false;
9997 } else if (!only_decls_so_far) {
9998 source_position_t const *const pos = &sub_statement->base.source_position;
9999 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10002 *anchor = sub_statement;
10003 anchor = &sub_statement->base.next;
10007 /* look over all statements again to produce no effect warnings */
10008 if (is_warn_on(WARN_UNUSED_VALUE)) {
10009 statement_t *sub_statement = statement->compound.statements;
10010 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10011 if (sub_statement->kind != STATEMENT_EXPRESSION)
10013 /* don't emit a warning for the last expression in an expression
10014 * statement as it has always an effect */
10015 if (inside_expression_statement && sub_statement->base.next == NULL)
10018 expression_t *expression = sub_statement->expression.expression;
10019 if (!expression_has_effect(expression)) {
10020 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10025 rem_anchor_token(T_while);
10026 rem_anchor_token(T_wchar_t);
10027 rem_anchor_token(T_volatile);
10028 rem_anchor_token(T_void);
10029 rem_anchor_token(T_using);
10030 rem_anchor_token(T_unsigned);
10031 rem_anchor_token(T_union);
10032 rem_anchor_token(T_typeof);
10033 rem_anchor_token(T_typename);
10034 rem_anchor_token(T_typeid);
10035 rem_anchor_token(T_typedef);
10036 rem_anchor_token(T_try);
10037 rem_anchor_token(T_true);
10038 rem_anchor_token(T_throw);
10039 rem_anchor_token(T_this);
10040 rem_anchor_token(T_template);
10041 rem_anchor_token(T_switch);
10042 rem_anchor_token(T_struct);
10043 rem_anchor_token(T_static_cast);
10044 rem_anchor_token(T_static);
10045 rem_anchor_token(T_sizeof);
10046 rem_anchor_token(T_signed);
10047 rem_anchor_token(T_short);
10048 rem_anchor_token(T_return);
10049 rem_anchor_token(T_restrict);
10050 rem_anchor_token(T_reinterpret_cast);
10051 rem_anchor_token(T_register);
10052 rem_anchor_token(T_operator);
10053 rem_anchor_token(T_new);
10054 rem_anchor_token(T_long);
10055 rem_anchor_token(T_int);
10056 rem_anchor_token(T_inline);
10057 rem_anchor_token(T_if);
10058 rem_anchor_token(T_goto);
10059 rem_anchor_token(T_for);
10060 rem_anchor_token(T_float);
10061 rem_anchor_token(T_false);
10062 rem_anchor_token(T_extern);
10063 rem_anchor_token(T_enum);
10064 rem_anchor_token(T_dynamic_cast);
10065 rem_anchor_token(T_do);
10066 rem_anchor_token(T_double);
10067 rem_anchor_token(T_delete);
10068 rem_anchor_token(T_default);
10069 rem_anchor_token(T_continue);
10070 rem_anchor_token(T_const_cast);
10071 rem_anchor_token(T_const);
10072 rem_anchor_token(T_class);
10073 rem_anchor_token(T_char);
10074 rem_anchor_token(T_case);
10075 rem_anchor_token(T_break);
10076 rem_anchor_token(T_bool);
10077 rem_anchor_token(T_auto);
10078 rem_anchor_token(T_asm);
10079 rem_anchor_token(T___thread);
10080 rem_anchor_token(T___real__);
10081 rem_anchor_token(T___label__);
10082 rem_anchor_token(T___imag__);
10083 rem_anchor_token(T___func__);
10084 rem_anchor_token(T___extension__);
10085 rem_anchor_token(T___builtin_va_start);
10086 rem_anchor_token(T___attribute__);
10087 rem_anchor_token(T___alignof__);
10088 rem_anchor_token(T___PRETTY_FUNCTION__);
10089 rem_anchor_token(T___FUNCTION__);
10090 rem_anchor_token(T__Imaginary);
10091 rem_anchor_token(T__Complex);
10092 rem_anchor_token(T__Bool);
10093 rem_anchor_token(T_WIDE_STRING_LITERAL);
10094 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10095 rem_anchor_token(T_STRING_LITERAL);
10096 rem_anchor_token(T_PLUSPLUS);
10097 rem_anchor_token(T_MINUSMINUS);
10098 rem_anchor_token(T_INTEGER);
10099 rem_anchor_token(T_IDENTIFIER);
10100 rem_anchor_token(T_FLOATINGPOINT);
10101 rem_anchor_token(T_COLONCOLON);
10102 rem_anchor_token(T_CHARACTER_CONSTANT);
10103 rem_anchor_token('~');
10104 rem_anchor_token('{');
10105 rem_anchor_token(';');
10106 rem_anchor_token('-');
10107 rem_anchor_token('+');
10108 rem_anchor_token('*');
10109 rem_anchor_token('(');
10110 rem_anchor_token('&');
10111 rem_anchor_token('!');
10112 rem_anchor_token('}');
10120 * Check for unused global static functions and variables
10122 static void check_unused_globals(void)
10124 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10127 for (const entity_t *entity = file_scope->entities; entity != NULL;
10128 entity = entity->base.next) {
10129 if (!is_declaration(entity))
10132 const declaration_t *declaration = &entity->declaration;
10133 if (declaration->used ||
10134 declaration->modifiers & DM_UNUSED ||
10135 declaration->modifiers & DM_USED ||
10136 declaration->storage_class != STORAGE_CLASS_STATIC)
10141 if (entity->kind == ENTITY_FUNCTION) {
10142 /* inhibit warning for static inline functions */
10143 if (entity->function.is_inline)
10146 why = WARN_UNUSED_FUNCTION;
10147 s = entity->function.statement != NULL ? "defined" : "declared";
10149 why = WARN_UNUSED_VARIABLE;
10153 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10157 static void parse_global_asm(void)
10159 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10162 add_anchor_token(';');
10163 add_anchor_token(')');
10164 add_anchor_token(T_STRING_LITERAL);
10167 rem_anchor_token(T_STRING_LITERAL);
10168 statement->asms.asm_text = parse_string_literals();
10169 statement->base.next = unit->global_asm;
10170 unit->global_asm = statement;
10172 rem_anchor_token(')');
10174 rem_anchor_token(';');
10178 static void parse_linkage_specification(void)
10182 source_position_t const pos = *HERE;
10183 char const *const linkage = parse_string_literals().begin;
10185 linkage_kind_t old_linkage = current_linkage;
10186 linkage_kind_t new_linkage;
10187 if (streq(linkage, "C")) {
10188 new_linkage = LINKAGE_C;
10189 } else if (streq(linkage, "C++")) {
10190 new_linkage = LINKAGE_CXX;
10192 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10193 new_linkage = LINKAGE_C;
10195 current_linkage = new_linkage;
10197 if (next_if('{')) {
10204 assert(current_linkage == new_linkage);
10205 current_linkage = old_linkage;
10208 static void parse_external(void)
10210 switch (token.kind) {
10212 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10213 parse_linkage_specification();
10215 DECLARATION_START_NO_EXTERN
10217 case T___extension__:
10218 /* tokens below are for implicit int */
10219 case '&': /* & x; -> int& x; (and error later, because C++ has no
10221 case '*': /* * x; -> int* x; */
10222 case '(': /* (x); -> int (x); */
10224 parse_external_declaration();
10230 parse_global_asm();
10234 parse_namespace_definition();
10238 if (!strict_mode) {
10239 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10246 errorf(HERE, "stray %K outside of function", &token);
10247 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10248 eat_until_matching_token(token.kind);
10254 static void parse_externals(void)
10256 add_anchor_token('}');
10257 add_anchor_token(T_EOF);
10260 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10261 unsigned short token_anchor_copy[T_LAST_TOKEN];
10262 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10265 while (token.kind != T_EOF && token.kind != '}') {
10267 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10268 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10270 /* the anchor set and its copy differs */
10271 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10274 if (in_gcc_extension) {
10275 /* an gcc extension scope was not closed */
10276 internal_errorf(HERE, "Leaked __extension__");
10283 rem_anchor_token(T_EOF);
10284 rem_anchor_token('}');
10288 * Parse a translation unit.
10290 static void parse_translation_unit(void)
10292 add_anchor_token(T_EOF);
10297 if (token.kind == T_EOF)
10300 errorf(HERE, "stray %K outside of function", &token);
10301 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10302 eat_until_matching_token(token.kind);
10307 void set_default_visibility(elf_visibility_tag_t visibility)
10309 default_visibility = visibility;
10315 * @return the translation unit or NULL if errors occurred.
10317 void start_parsing(void)
10319 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10320 label_stack = NEW_ARR_F(stack_entry_t, 0);
10321 diagnostic_count = 0;
10325 print_to_file(stderr);
10327 assert(unit == NULL);
10328 unit = allocate_ast_zero(sizeof(unit[0]));
10330 assert(file_scope == NULL);
10331 file_scope = &unit->scope;
10333 assert(current_scope == NULL);
10334 scope_push(&unit->scope);
10336 create_gnu_builtins();
10338 create_microsoft_intrinsics();
10341 translation_unit_t *finish_parsing(void)
10343 assert(current_scope == &unit->scope);
10346 assert(file_scope == &unit->scope);
10347 check_unused_globals();
10350 DEL_ARR_F(environment_stack);
10351 DEL_ARR_F(label_stack);
10353 translation_unit_t *result = unit;
10358 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10359 * are given length one. */
10360 static void complete_incomplete_arrays(void)
10362 size_t n = ARR_LEN(incomplete_arrays);
10363 for (size_t i = 0; i != n; ++i) {
10364 declaration_t *const decl = incomplete_arrays[i];
10365 type_t *const type = skip_typeref(decl->type);
10367 if (!is_type_incomplete(type))
10370 source_position_t const *const pos = &decl->base.source_position;
10371 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10373 type_t *const new_type = duplicate_type(type);
10374 new_type->array.size_constant = true;
10375 new_type->array.has_implicit_size = true;
10376 new_type->array.size = 1;
10378 type_t *const result = identify_new_type(new_type);
10380 decl->type = result;
10384 static void prepare_main_collect2(entity_t *const entity)
10386 PUSH_SCOPE(&entity->function.statement->compound.scope);
10388 // create call to __main
10389 symbol_t *symbol = symbol_table_insert("__main");
10390 entity_t *subsubmain_ent
10391 = create_implicit_function(symbol, &builtin_source_position);
10393 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10394 type_t *ftype = subsubmain_ent->declaration.type;
10395 ref->base.source_position = builtin_source_position;
10396 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10397 ref->reference.entity = subsubmain_ent;
10399 expression_t *call = allocate_expression_zero(EXPR_CALL);
10400 call->base.source_position = builtin_source_position;
10401 call->base.type = type_void;
10402 call->call.function = ref;
10404 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10405 expr_statement->base.source_position = builtin_source_position;
10406 expr_statement->expression.expression = call;
10408 statement_t *statement = entity->function.statement;
10409 assert(statement->kind == STATEMENT_COMPOUND);
10410 compound_statement_t *compounds = &statement->compound;
10412 expr_statement->base.next = compounds->statements;
10413 compounds->statements = expr_statement;
10420 lookahead_bufpos = 0;
10421 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10424 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10425 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10426 parse_translation_unit();
10427 complete_incomplete_arrays();
10428 DEL_ARR_F(incomplete_arrays);
10429 incomplete_arrays = NULL;
10433 * Initialize the parser.
10435 void init_parser(void)
10437 sym_anonymous = symbol_table_insert("<anonymous>");
10439 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10441 init_expression_parsers();
10442 obstack_init(&temp_obst);
10446 * Terminate the parser.
10448 void exit_parser(void)
10450 obstack_free(&temp_obst, NULL);