2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static switch_statement_t *current_switch = NULL;
93 static statement_t *current_loop = NULL;
94 static statement_t *current_parent = NULL;
95 static ms_try_statement_t *current_try = NULL;
96 static linkage_kind_t current_linkage;
97 static goto_statement_t *goto_first = NULL;
98 static goto_statement_t **goto_anchor = NULL;
99 static label_statement_t *label_first = NULL;
100 static label_statement_t **label_anchor = NULL;
101 /** current translation unit. */
102 static translation_unit_t *unit = NULL;
103 /** true if we are in an __extension__ context. */
104 static bool in_gcc_extension = false;
105 static struct obstack temp_obst;
106 static entity_t *anonymous_entity;
107 static declaration_t **incomplete_arrays;
108 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
111 #define PUSH_PARENT(stmt) \
112 statement_t *const new_parent = (stmt); \
113 statement_t *const old_parent = current_parent; \
114 ((void)(current_parent = new_parent))
115 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
117 #define PUSH_SCOPE(scope) \
118 size_t const top = environment_top(); \
119 scope_t *const new_scope = (scope); \
120 scope_t *const old_scope = scope_push(new_scope)
121 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
123 #define PUSH_EXTENSION() \
125 bool const old_gcc_extension = in_gcc_extension; \
126 while (next_if(T___extension__)) { \
127 in_gcc_extension = true; \
130 #define POP_EXTENSION() \
131 ((void)(in_gcc_extension = old_gcc_extension))
133 /** special symbol used for anonymous entities. */
134 static symbol_t *sym_anonymous = NULL;
136 /** The token anchor set */
137 static unsigned short token_anchor_set[T_LAST_TOKEN];
139 /** The current source position. */
140 #define HERE (&token.base.source_position)
142 /** true if we are in GCC mode. */
143 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
145 static statement_t *parse_compound_statement(bool inside_expression_statement);
146 static statement_t *parse_statement(void);
148 static expression_t *parse_subexpression(precedence_t);
149 static expression_t *parse_expression(void);
150 static type_t *parse_typename(void);
151 static void parse_externals(void);
152 static void parse_external(void);
154 static void parse_compound_type_entries(compound_t *compound_declaration);
156 static void check_call_argument(type_t *expected_type,
157 call_argument_t *argument, unsigned pos);
159 typedef enum declarator_flags_t {
161 DECL_MAY_BE_ABSTRACT = 1U << 0,
162 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
163 DECL_IS_PARAMETER = 1U << 2
164 } declarator_flags_t;
166 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
167 declarator_flags_t flags);
169 static void semantic_comparison(binary_expression_t *expression);
171 #define STORAGE_CLASSES \
172 STORAGE_CLASSES_NO_EXTERN \
175 #define STORAGE_CLASSES_NO_EXTERN \
182 #define TYPE_QUALIFIERS \
187 case T__forceinline: \
188 case T___attribute__:
190 #define COMPLEX_SPECIFIERS \
192 #define IMAGINARY_SPECIFIERS \
195 #define TYPE_SPECIFIERS \
197 case T___builtin_va_list: \
222 #define DECLARATION_START \
227 #define DECLARATION_START_NO_EXTERN \
228 STORAGE_CLASSES_NO_EXTERN \
232 #define EXPRESSION_START \
241 case T_CHARACTER_CONSTANT: \
242 case T_FLOATINGPOINT: \
243 case T_FLOATINGPOINT_HEXADECIMAL: \
245 case T_INTEGER_HEXADECIMAL: \
246 case T_INTEGER_OCTAL: \
249 case T_STRING_LITERAL: \
250 case T_WIDE_CHARACTER_CONSTANT: \
251 case T_WIDE_STRING_LITERAL: \
252 case T___FUNCDNAME__: \
253 case T___FUNCSIG__: \
254 case T___FUNCTION__: \
255 case T___PRETTY_FUNCTION__: \
256 case T___alignof__: \
257 case T___builtin_classify_type: \
258 case T___builtin_constant_p: \
259 case T___builtin_isgreater: \
260 case T___builtin_isgreaterequal: \
261 case T___builtin_isless: \
262 case T___builtin_islessequal: \
263 case T___builtin_islessgreater: \
264 case T___builtin_isunordered: \
265 case T___builtin_offsetof: \
266 case T___builtin_va_arg: \
267 case T___builtin_va_copy: \
268 case T___builtin_va_start: \
279 * Returns the size of a statement node.
281 * @param kind the statement kind
283 static size_t get_statement_struct_size(statement_kind_t kind)
285 static const size_t sizes[] = {
286 [STATEMENT_ERROR] = sizeof(statement_base_t),
287 [STATEMENT_EMPTY] = sizeof(statement_base_t),
288 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
289 [STATEMENT_RETURN] = sizeof(return_statement_t),
290 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
291 [STATEMENT_IF] = sizeof(if_statement_t),
292 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
293 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
294 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
295 [STATEMENT_BREAK] = sizeof(statement_base_t),
296 [STATEMENT_GOTO] = sizeof(goto_statement_t),
297 [STATEMENT_LABEL] = sizeof(label_statement_t),
298 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
299 [STATEMENT_WHILE] = sizeof(while_statement_t),
300 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
301 [STATEMENT_FOR] = sizeof(for_statement_t),
302 [STATEMENT_ASM] = sizeof(asm_statement_t),
303 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
304 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
306 assert((size_t)kind < lengthof(sizes));
307 assert(sizes[kind] != 0);
312 * Returns the size of an expression node.
314 * @param kind the expression kind
316 static size_t get_expression_struct_size(expression_kind_t kind)
318 static const size_t sizes[] = {
319 [EXPR_ERROR] = sizeof(expression_base_t),
320 [EXPR_REFERENCE] = sizeof(reference_expression_t),
321 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
322 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
323 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
324 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
326 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
330 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
331 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
332 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
333 [EXPR_CALL] = sizeof(call_expression_t),
334 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
335 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
336 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
337 [EXPR_SELECT] = sizeof(select_expression_t),
338 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
339 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
340 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
341 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
342 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
343 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
344 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
345 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
346 [EXPR_VA_START] = sizeof(va_start_expression_t),
347 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
348 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
349 [EXPR_STATEMENT] = sizeof(statement_expression_t),
350 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
352 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
353 return sizes[EXPR_UNARY_FIRST];
355 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
356 return sizes[EXPR_BINARY_FIRST];
358 assert((size_t)kind < lengthof(sizes));
359 assert(sizes[kind] != 0);
364 * Allocate a statement node of given kind and initialize all
365 * fields with zero. Sets its source position to the position
366 * of the current token.
368 static statement_t *allocate_statement_zero(statement_kind_t kind)
370 size_t size = get_statement_struct_size(kind);
371 statement_t *res = allocate_ast_zero(size);
373 res->base.kind = kind;
374 res->base.parent = current_parent;
375 res->base.source_position = token.base.source_position;
380 * Allocate an expression node of given kind and initialize all
383 * @param kind the kind of the expression to allocate
385 static expression_t *allocate_expression_zero(expression_kind_t kind)
387 size_t size = get_expression_struct_size(kind);
388 expression_t *res = allocate_ast_zero(size);
390 res->base.kind = kind;
391 res->base.type = type_error_type;
392 res->base.source_position = token.base.source_position;
397 * Creates a new invalid expression at the source position
398 * of the current token.
400 static expression_t *create_error_expression(void)
402 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
403 expression->base.type = type_error_type;
408 * Creates a new invalid statement.
410 static statement_t *create_error_statement(void)
412 return allocate_statement_zero(STATEMENT_ERROR);
416 * Allocate a new empty statement.
418 static statement_t *create_empty_statement(void)
420 return allocate_statement_zero(STATEMENT_EMPTY);
424 * Returns the size of an initializer node.
426 * @param kind the initializer kind
428 static size_t get_initializer_size(initializer_kind_t kind)
430 static const size_t sizes[] = {
431 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
432 [INITIALIZER_STRING] = sizeof(initializer_string_t),
433 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
434 [INITIALIZER_LIST] = sizeof(initializer_list_t),
435 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
437 assert((size_t)kind < lengthof(sizes));
438 assert(sizes[kind] != 0);
443 * Allocate an initializer node of given kind and initialize all
446 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
448 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
455 * Returns the index of the top element of the environment stack.
457 static size_t environment_top(void)
459 return ARR_LEN(environment_stack);
463 * Returns the index of the top element of the global label stack.
465 static size_t label_top(void)
467 return ARR_LEN(label_stack);
471 * Return the next token.
473 static inline void next_token(void)
475 token = lookahead_buffer[lookahead_bufpos];
476 lookahead_buffer[lookahead_bufpos] = lexer_token;
479 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
482 print_token(stderr, &token);
483 fprintf(stderr, "\n");
487 static inline bool next_if(int const type)
489 if (token.kind == type) {
498 * Return the next token with a given lookahead.
500 static inline const token_t *look_ahead(size_t num)
502 assert(0 < num && num <= MAX_LOOKAHEAD);
503 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
504 return &lookahead_buffer[pos];
508 * Adds a token type to the token type anchor set (a multi-set).
510 static void add_anchor_token(int token_kind)
512 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
513 ++token_anchor_set[token_kind];
517 * Set the number of tokens types of the given type
518 * to zero and return the old count.
520 static int save_and_reset_anchor_state(int token_kind)
522 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
523 int count = token_anchor_set[token_kind];
524 token_anchor_set[token_kind] = 0;
529 * Restore the number of token types to the given count.
531 static void restore_anchor_state(int token_kind, int count)
533 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
534 token_anchor_set[token_kind] = count;
538 * Remove a token type from the token type anchor set (a multi-set).
540 static void rem_anchor_token(int token_kind)
542 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
543 assert(token_anchor_set[token_kind] != 0);
544 --token_anchor_set[token_kind];
548 * Return true if the token type of the current token is
551 static bool at_anchor(void)
555 return token_anchor_set[token.kind];
559 * Eat tokens until a matching token type is found.
561 static void eat_until_matching_token(int type)
565 case '(': end_token = ')'; break;
566 case '{': end_token = '}'; break;
567 case '[': end_token = ']'; break;
568 default: end_token = type; break;
571 unsigned parenthesis_count = 0;
572 unsigned brace_count = 0;
573 unsigned bracket_count = 0;
574 while (token.kind != end_token ||
575 parenthesis_count != 0 ||
577 bracket_count != 0) {
578 switch (token.kind) {
580 case '(': ++parenthesis_count; break;
581 case '{': ++brace_count; break;
582 case '[': ++bracket_count; break;
585 if (parenthesis_count > 0)
595 if (bracket_count > 0)
598 if (token.kind == end_token &&
599 parenthesis_count == 0 &&
613 * Eat input tokens until an anchor is found.
615 static void eat_until_anchor(void)
617 while (token_anchor_set[token.kind] == 0) {
618 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
619 eat_until_matching_token(token.kind);
625 * Eat a whole block from input tokens.
627 static void eat_block(void)
629 eat_until_matching_token('{');
633 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
636 * Report a parse error because an expected token was not found.
639 #if defined __GNUC__ && __GNUC__ >= 4
640 __attribute__((sentinel))
642 void parse_error_expected(const char *message, ...)
644 if (message != NULL) {
645 errorf(HERE, "%s", message);
648 va_start(ap, message);
649 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
654 * Report an incompatible type.
656 static void type_error_incompatible(const char *msg,
657 const source_position_t *source_position, type_t *type1, type_t *type2)
659 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
664 * Expect the current token is the expected token.
665 * If not, generate an error, eat the current statement,
666 * and goto the error_label label.
668 #define expect(expected, error_label) \
670 if (UNLIKELY(token.kind != (expected))) { \
671 parse_error_expected(NULL, (expected), NULL); \
672 add_anchor_token(expected); \
673 eat_until_anchor(); \
674 rem_anchor_token(expected); \
675 if (token.kind != (expected)) \
682 * Push a given scope on the scope stack and make it the
685 static scope_t *scope_push(scope_t *new_scope)
687 if (current_scope != NULL) {
688 new_scope->depth = current_scope->depth + 1;
691 scope_t *old_scope = current_scope;
692 current_scope = new_scope;
697 * Pop the current scope from the scope stack.
699 static void scope_pop(scope_t *old_scope)
701 current_scope = old_scope;
705 * Search an entity by its symbol in a given namespace.
707 static entity_t *get_entity(const symbol_t *const symbol,
708 namespace_tag_t namespc)
710 entity_t *entity = symbol->entity;
711 for (; entity != NULL; entity = entity->base.symbol_next) {
712 if ((namespace_tag_t)entity->base.namespc == namespc)
719 /* §6.2.3:1 24) There is only one name space for tags even though three are
721 static entity_t *get_tag(symbol_t const *const symbol,
722 entity_kind_tag_t const kind)
724 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
725 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
727 "'%Y' defined as wrong kind of tag (previous definition %P)",
728 symbol, &entity->base.source_position);
735 * pushs an entity on the environment stack and links the corresponding symbol
738 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
740 symbol_t *symbol = entity->base.symbol;
741 entity_namespace_t namespc = entity->base.namespc;
742 assert(namespc != 0);
744 /* replace/add entity into entity list of the symbol */
747 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
752 /* replace an entry? */
753 if (iter->base.namespc == namespc) {
754 entity->base.symbol_next = iter->base.symbol_next;
760 /* remember old declaration */
762 entry.symbol = symbol;
763 entry.old_entity = iter;
764 entry.namespc = namespc;
765 ARR_APP1(stack_entry_t, *stack_ptr, entry);
769 * Push an entity on the environment stack.
771 static void environment_push(entity_t *entity)
773 assert(entity->base.source_position.input_name != NULL);
774 assert(entity->base.parent_scope != NULL);
775 stack_push(&environment_stack, entity);
779 * Push a declaration on the global label stack.
781 * @param declaration the declaration
783 static void label_push(entity_t *label)
785 /* we abuse the parameters scope as parent for the labels */
786 label->base.parent_scope = ¤t_function->parameters;
787 stack_push(&label_stack, label);
791 * pops symbols from the environment stack until @p new_top is the top element
793 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
795 stack_entry_t *stack = *stack_ptr;
796 size_t top = ARR_LEN(stack);
799 assert(new_top <= top);
803 for (i = top; i > new_top; --i) {
804 stack_entry_t *entry = &stack[i - 1];
806 entity_t *old_entity = entry->old_entity;
807 symbol_t *symbol = entry->symbol;
808 entity_namespace_t namespc = entry->namespc;
810 /* replace with old_entity/remove */
813 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
815 assert(iter != NULL);
816 /* replace an entry? */
817 if (iter->base.namespc == namespc)
821 /* restore definition from outer scopes (if there was one) */
822 if (old_entity != NULL) {
823 old_entity->base.symbol_next = iter->base.symbol_next;
824 *anchor = old_entity;
826 /* remove entry from list */
827 *anchor = iter->base.symbol_next;
831 ARR_SHRINKLEN(*stack_ptr, new_top);
835 * Pop all entries from the environment stack until the new_top
838 * @param new_top the new stack top
840 static void environment_pop_to(size_t new_top)
842 stack_pop_to(&environment_stack, new_top);
846 * Pop all entries from the global label stack until the new_top
849 * @param new_top the new stack top
851 static void label_pop_to(size_t new_top)
853 stack_pop_to(&label_stack, new_top);
856 static atomic_type_kind_t get_akind(const type_t *type)
858 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
859 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
860 return type->atomic.akind;
864 * §6.3.1.1:2 Do integer promotion for a given type.
866 * @param type the type to promote
867 * @return the promoted type
869 static type_t *promote_integer(type_t *type)
871 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
878 * Check if a given expression represents a null pointer constant.
880 * @param expression the expression to check
882 static bool is_null_pointer_constant(const expression_t *expression)
884 /* skip void* cast */
885 if (expression->kind == EXPR_UNARY_CAST) {
886 type_t *const type = skip_typeref(expression->base.type);
887 if (types_compatible(type, type_void_ptr))
888 expression = expression->unary.value;
891 type_t *const type = skip_typeref(expression->base.type);
892 if (!is_type_integer(type))
894 switch (is_constant_expression(expression)) {
895 case EXPR_CLASS_ERROR: return true;
896 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
897 default: return false;
902 * Create an implicit cast expression.
904 * @param expression the expression to cast
905 * @param dest_type the destination type
907 static expression_t *create_implicit_cast(expression_t *expression,
910 type_t *const source_type = expression->base.type;
912 if (source_type == dest_type)
915 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
916 cast->unary.value = expression;
917 cast->base.type = dest_type;
918 cast->base.implicit = true;
923 typedef enum assign_error_t {
925 ASSIGN_ERROR_INCOMPATIBLE,
926 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
927 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
928 ASSIGN_WARNING_POINTER_FROM_INT,
929 ASSIGN_WARNING_INT_FROM_POINTER
932 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)
934 type_t *const orig_type_right = right->base.type;
935 type_t *const type_left = skip_typeref(orig_type_left);
936 type_t *const type_right = skip_typeref(orig_type_right);
941 case ASSIGN_ERROR_INCOMPATIBLE:
942 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
945 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
946 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
947 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
949 /* the left type has all qualifiers from the right type */
950 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
951 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);
955 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
956 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
959 case ASSIGN_WARNING_POINTER_FROM_INT:
960 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
963 case ASSIGN_WARNING_INT_FROM_POINTER:
964 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
968 panic("invalid error value");
972 /** Implements the rules from §6.5.16.1 */
973 static assign_error_t semantic_assign(type_t *orig_type_left,
974 const expression_t *const right)
976 type_t *const orig_type_right = right->base.type;
977 type_t *const type_left = skip_typeref(orig_type_left);
978 type_t *const type_right = skip_typeref(orig_type_right);
980 if (is_type_pointer(type_left)) {
981 if (is_null_pointer_constant(right)) {
982 return ASSIGN_SUCCESS;
983 } else if (is_type_pointer(type_right)) {
984 type_t *points_to_left
985 = skip_typeref(type_left->pointer.points_to);
986 type_t *points_to_right
987 = skip_typeref(type_right->pointer.points_to);
988 assign_error_t res = ASSIGN_SUCCESS;
990 /* the left type has all qualifiers from the right type */
991 unsigned missing_qualifiers
992 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
993 if (missing_qualifiers != 0) {
994 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
997 points_to_left = get_unqualified_type(points_to_left);
998 points_to_right = get_unqualified_type(points_to_right);
1000 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1003 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1004 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1005 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1008 if (!types_compatible(points_to_left, points_to_right)) {
1009 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1013 } else if (is_type_integer(type_right)) {
1014 return ASSIGN_WARNING_POINTER_FROM_INT;
1016 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1017 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1018 && is_type_pointer(type_right))) {
1019 return ASSIGN_SUCCESS;
1020 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1021 type_t *const unqual_type_left = get_unqualified_type(type_left);
1022 type_t *const unqual_type_right = get_unqualified_type(type_right);
1023 if (types_compatible(unqual_type_left, unqual_type_right)) {
1024 return ASSIGN_SUCCESS;
1026 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1027 return ASSIGN_WARNING_INT_FROM_POINTER;
1030 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1031 return ASSIGN_SUCCESS;
1033 return ASSIGN_ERROR_INCOMPATIBLE;
1036 static expression_t *parse_constant_expression(void)
1038 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1040 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1041 errorf(&result->base.source_position,
1042 "expression '%E' is not constant", result);
1048 static expression_t *parse_assignment_expression(void)
1050 return parse_subexpression(PREC_ASSIGNMENT);
1053 static void warn_string_concat(const source_position_t *pos)
1055 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1058 static string_t parse_string_literals(void)
1060 assert(token.kind == T_STRING_LITERAL);
1061 string_t result = token.string.string;
1065 while (token.kind == T_STRING_LITERAL) {
1066 warn_string_concat(&token.base.source_position);
1067 result = concat_strings(&result, &token.string.string);
1075 * compare two string, ignoring double underscores on the second.
1077 static int strcmp_underscore(const char *s1, const char *s2)
1079 if (s2[0] == '_' && s2[1] == '_') {
1080 size_t len2 = strlen(s2);
1081 size_t len1 = strlen(s1);
1082 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1083 return strncmp(s1, s2+2, len2-4);
1087 return strcmp(s1, s2);
1090 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1092 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1093 attribute->kind = kind;
1094 attribute->source_position = *HERE;
1099 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1102 * __attribute__ ( ( attribute-list ) )
1106 * attribute_list , attrib
1111 * any-word ( identifier )
1112 * any-word ( identifier , nonempty-expr-list )
1113 * any-word ( expr-list )
1115 * where the "identifier" must not be declared as a type, and
1116 * "any-word" may be any identifier (including one declared as a
1117 * type), a reserved word storage class specifier, type specifier or
1118 * type qualifier. ??? This still leaves out most reserved keywords
1119 * (following the old parser), shouldn't we include them, and why not
1120 * allow identifiers declared as types to start the arguments?
1122 * Matze: this all looks confusing and little systematic, so we're even less
1123 * strict and parse any list of things which are identifiers or
1124 * (assignment-)expressions.
1126 static attribute_argument_t *parse_attribute_arguments(void)
1128 attribute_argument_t *first = NULL;
1129 attribute_argument_t **anchor = &first;
1130 if (token.kind != ')') do {
1131 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1133 /* is it an identifier */
1134 if (token.kind == T_IDENTIFIER
1135 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1136 symbol_t *symbol = token.identifier.symbol;
1137 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1138 argument->v.symbol = symbol;
1141 /* must be an expression */
1142 expression_t *expression = parse_assignment_expression();
1144 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1145 argument->v.expression = expression;
1148 /* append argument */
1150 anchor = &argument->next;
1151 } while (next_if(','));
1152 expect(')', end_error);
1161 static attribute_t *parse_attribute_asm(void)
1163 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1166 expect('(', end_error);
1167 attribute->a.arguments = parse_attribute_arguments();
1174 static symbol_t *get_symbol_from_token(void)
1176 switch(token.kind) {
1178 return token.identifier.symbol;
1207 /* maybe we need more tokens ... add them on demand */
1208 return get_token_kind_symbol(token.kind);
1214 static attribute_t *parse_attribute_gnu_single(void)
1216 /* parse "any-word" */
1217 symbol_t *symbol = get_symbol_from_token();
1218 if (symbol == NULL) {
1219 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1223 attribute_kind_t kind;
1224 char const *const name = symbol->string;
1225 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1226 if (kind > ATTRIBUTE_GNU_LAST) {
1227 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1228 /* TODO: we should still save the attribute in the list... */
1229 kind = ATTRIBUTE_UNKNOWN;
1233 const char *attribute_name = get_attribute_name(kind);
1234 if (attribute_name != NULL
1235 && strcmp_underscore(attribute_name, name) == 0)
1239 attribute_t *attribute = allocate_attribute_zero(kind);
1242 /* parse arguments */
1244 attribute->a.arguments = parse_attribute_arguments();
1249 static attribute_t *parse_attribute_gnu(void)
1251 attribute_t *first = NULL;
1252 attribute_t **anchor = &first;
1254 eat(T___attribute__);
1255 expect('(', end_error);
1256 expect('(', end_error);
1258 if (token.kind != ')') do {
1259 attribute_t *attribute = parse_attribute_gnu_single();
1260 if (attribute == NULL)
1263 *anchor = attribute;
1264 anchor = &attribute->next;
1265 } while (next_if(','));
1266 expect(')', end_error);
1267 expect(')', end_error);
1273 /** Parse attributes. */
1274 static attribute_t *parse_attributes(attribute_t *first)
1276 attribute_t **anchor = &first;
1278 while (*anchor != NULL)
1279 anchor = &(*anchor)->next;
1281 attribute_t *attribute;
1282 switch (token.kind) {
1283 case T___attribute__:
1284 attribute = parse_attribute_gnu();
1285 if (attribute == NULL)
1290 attribute = parse_attribute_asm();
1294 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1299 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1303 case T__forceinline:
1304 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1305 eat(T__forceinline);
1309 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1314 /* TODO record modifier */
1315 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1316 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1324 *anchor = attribute;
1325 anchor = &attribute->next;
1329 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1331 static entity_t *determine_lhs_ent(expression_t *const expr,
1334 switch (expr->kind) {
1335 case EXPR_REFERENCE: {
1336 entity_t *const entity = expr->reference.entity;
1337 /* we should only find variables as lvalues... */
1338 if (entity->base.kind != ENTITY_VARIABLE
1339 && entity->base.kind != ENTITY_PARAMETER)
1345 case EXPR_ARRAY_ACCESS: {
1346 expression_t *const ref = expr->array_access.array_ref;
1347 entity_t * ent = NULL;
1348 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1349 ent = determine_lhs_ent(ref, lhs_ent);
1352 mark_vars_read(ref, lhs_ent);
1354 mark_vars_read(expr->array_access.index, lhs_ent);
1359 mark_vars_read(expr->select.compound, lhs_ent);
1360 if (is_type_compound(skip_typeref(expr->base.type)))
1361 return determine_lhs_ent(expr->select.compound, lhs_ent);
1365 case EXPR_UNARY_DEREFERENCE: {
1366 expression_t *const val = expr->unary.value;
1367 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1369 return determine_lhs_ent(val->unary.value, lhs_ent);
1371 mark_vars_read(val, NULL);
1377 mark_vars_read(expr, NULL);
1382 #define ENT_ANY ((entity_t*)-1)
1385 * Mark declarations, which are read. This is used to detect variables, which
1389 * x is not marked as "read", because it is only read to calculate its own new
1393 * x and y are not detected as "not read", because multiple variables are
1396 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1398 switch (expr->kind) {
1399 case EXPR_REFERENCE: {
1400 entity_t *const entity = expr->reference.entity;
1401 if (entity->kind != ENTITY_VARIABLE
1402 && entity->kind != ENTITY_PARAMETER)
1405 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1406 if (entity->kind == ENTITY_VARIABLE) {
1407 entity->variable.read = true;
1409 entity->parameter.read = true;
1416 // TODO respect pure/const
1417 mark_vars_read(expr->call.function, NULL);
1418 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1419 mark_vars_read(arg->expression, NULL);
1423 case EXPR_CONDITIONAL:
1424 // TODO lhs_decl should depend on whether true/false have an effect
1425 mark_vars_read(expr->conditional.condition, NULL);
1426 if (expr->conditional.true_expression != NULL)
1427 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1428 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1432 if (lhs_ent == ENT_ANY
1433 && !is_type_compound(skip_typeref(expr->base.type)))
1435 mark_vars_read(expr->select.compound, lhs_ent);
1438 case EXPR_ARRAY_ACCESS: {
1439 mark_vars_read(expr->array_access.index, lhs_ent);
1440 expression_t *const ref = expr->array_access.array_ref;
1441 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1442 if (lhs_ent == ENT_ANY)
1445 mark_vars_read(ref, lhs_ent);
1450 mark_vars_read(expr->va_arge.ap, lhs_ent);
1454 mark_vars_read(expr->va_copye.src, lhs_ent);
1457 case EXPR_UNARY_CAST:
1458 /* Special case: Use void cast to mark a variable as "read" */
1459 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1464 case EXPR_UNARY_THROW:
1465 if (expr->unary.value == NULL)
1468 case EXPR_UNARY_DEREFERENCE:
1469 case EXPR_UNARY_DELETE:
1470 case EXPR_UNARY_DELETE_ARRAY:
1471 if (lhs_ent == ENT_ANY)
1475 case EXPR_UNARY_NEGATE:
1476 case EXPR_UNARY_PLUS:
1477 case EXPR_UNARY_BITWISE_NEGATE:
1478 case EXPR_UNARY_NOT:
1479 case EXPR_UNARY_TAKE_ADDRESS:
1480 case EXPR_UNARY_POSTFIX_INCREMENT:
1481 case EXPR_UNARY_POSTFIX_DECREMENT:
1482 case EXPR_UNARY_PREFIX_INCREMENT:
1483 case EXPR_UNARY_PREFIX_DECREMENT:
1484 case EXPR_UNARY_ASSUME:
1486 mark_vars_read(expr->unary.value, lhs_ent);
1489 case EXPR_BINARY_ADD:
1490 case EXPR_BINARY_SUB:
1491 case EXPR_BINARY_MUL:
1492 case EXPR_BINARY_DIV:
1493 case EXPR_BINARY_MOD:
1494 case EXPR_BINARY_EQUAL:
1495 case EXPR_BINARY_NOTEQUAL:
1496 case EXPR_BINARY_LESS:
1497 case EXPR_BINARY_LESSEQUAL:
1498 case EXPR_BINARY_GREATER:
1499 case EXPR_BINARY_GREATEREQUAL:
1500 case EXPR_BINARY_BITWISE_AND:
1501 case EXPR_BINARY_BITWISE_OR:
1502 case EXPR_BINARY_BITWISE_XOR:
1503 case EXPR_BINARY_LOGICAL_AND:
1504 case EXPR_BINARY_LOGICAL_OR:
1505 case EXPR_BINARY_SHIFTLEFT:
1506 case EXPR_BINARY_SHIFTRIGHT:
1507 case EXPR_BINARY_COMMA:
1508 case EXPR_BINARY_ISGREATER:
1509 case EXPR_BINARY_ISGREATEREQUAL:
1510 case EXPR_BINARY_ISLESS:
1511 case EXPR_BINARY_ISLESSEQUAL:
1512 case EXPR_BINARY_ISLESSGREATER:
1513 case EXPR_BINARY_ISUNORDERED:
1514 mark_vars_read(expr->binary.left, lhs_ent);
1515 mark_vars_read(expr->binary.right, lhs_ent);
1518 case EXPR_BINARY_ASSIGN:
1519 case EXPR_BINARY_MUL_ASSIGN:
1520 case EXPR_BINARY_DIV_ASSIGN:
1521 case EXPR_BINARY_MOD_ASSIGN:
1522 case EXPR_BINARY_ADD_ASSIGN:
1523 case EXPR_BINARY_SUB_ASSIGN:
1524 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1525 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1526 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1527 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1528 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1529 if (lhs_ent == ENT_ANY)
1531 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1532 mark_vars_read(expr->binary.right, lhs_ent);
1537 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1542 case EXPR_STRING_LITERAL:
1543 case EXPR_WIDE_STRING_LITERAL:
1544 case EXPR_COMPOUND_LITERAL: // TODO init?
1546 case EXPR_CLASSIFY_TYPE:
1549 case EXPR_BUILTIN_CONSTANT_P:
1550 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1552 case EXPR_STATEMENT: // TODO
1553 case EXPR_LABEL_ADDRESS:
1554 case EXPR_REFERENCE_ENUM_VALUE:
1558 panic("unhandled expression");
1561 static designator_t *parse_designation(void)
1563 designator_t *result = NULL;
1564 designator_t **anchor = &result;
1567 designator_t *designator;
1568 switch (token.kind) {
1570 designator = allocate_ast_zero(sizeof(designator[0]));
1571 designator->source_position = token.base.source_position;
1573 add_anchor_token(']');
1574 designator->array_index = parse_constant_expression();
1575 rem_anchor_token(']');
1576 expect(']', end_error);
1579 designator = allocate_ast_zero(sizeof(designator[0]));
1580 designator->source_position = token.base.source_position;
1582 if (token.kind != T_IDENTIFIER) {
1583 parse_error_expected("while parsing designator",
1584 T_IDENTIFIER, NULL);
1587 designator->symbol = token.identifier.symbol;
1591 expect('=', end_error);
1595 assert(designator != NULL);
1596 *anchor = designator;
1597 anchor = &designator->next;
1603 static initializer_t *initializer_from_string(array_type_t *const type,
1604 const string_t *const string)
1606 /* TODO: check len vs. size of array type */
1609 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1610 initializer->string.string = *string;
1615 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1616 const string_t *const string)
1618 /* TODO: check len vs. size of array type */
1621 initializer_t *const initializer =
1622 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1623 initializer->wide_string.string = *string;
1629 * Build an initializer from a given expression.
1631 static initializer_t *initializer_from_expression(type_t *orig_type,
1632 expression_t *expression)
1634 /* TODO check that expression is a constant expression */
1636 /* §6.7.8.14/15 char array may be initialized by string literals */
1637 type_t *type = skip_typeref(orig_type);
1638 type_t *expr_type_orig = expression->base.type;
1639 type_t *expr_type = skip_typeref(expr_type_orig);
1641 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1642 array_type_t *const array_type = &type->array;
1643 type_t *const element_type = skip_typeref(array_type->element_type);
1645 if (element_type->kind == TYPE_ATOMIC) {
1646 atomic_type_kind_t akind = element_type->atomic.akind;
1647 switch (expression->kind) {
1648 case EXPR_STRING_LITERAL:
1649 if (akind == ATOMIC_TYPE_CHAR
1650 || akind == ATOMIC_TYPE_SCHAR
1651 || akind == ATOMIC_TYPE_UCHAR) {
1652 return initializer_from_string(array_type,
1653 &expression->string_literal.value);
1657 case EXPR_WIDE_STRING_LITERAL: {
1658 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1659 if (get_unqualified_type(element_type) == bare_wchar_type) {
1660 return initializer_from_wide_string(array_type,
1661 &expression->string_literal.value);
1672 assign_error_t error = semantic_assign(type, expression);
1673 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1675 report_assign_error(error, type, expression, "initializer",
1676 &expression->base.source_position);
1678 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1679 result->value.value = create_implicit_cast(expression, type);
1685 * Checks if a given expression can be used as a constant initializer.
1687 static bool is_initializer_constant(const expression_t *expression)
1689 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1690 is_linker_constant(expression) != EXPR_CLASS_VARIABLE;
1694 * Parses an scalar initializer.
1696 * §6.7.8.11; eat {} without warning
1698 static initializer_t *parse_scalar_initializer(type_t *type,
1699 bool must_be_constant)
1701 /* there might be extra {} hierarchies */
1703 if (token.kind == '{') {
1704 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1708 } while (token.kind == '{');
1711 expression_t *expression = parse_assignment_expression();
1712 mark_vars_read(expression, NULL);
1713 if (must_be_constant && !is_initializer_constant(expression)) {
1714 errorf(&expression->base.source_position,
1715 "initialisation expression '%E' is not constant",
1719 initializer_t *initializer = initializer_from_expression(type, expression);
1721 if (initializer == NULL) {
1722 errorf(&expression->base.source_position,
1723 "expression '%E' (type '%T') doesn't match expected type '%T'",
1724 expression, expression->base.type, type);
1729 bool additional_warning_displayed = false;
1730 while (braces > 0) {
1732 if (token.kind != '}') {
1733 if (!additional_warning_displayed) {
1734 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1735 additional_warning_displayed = true;
1746 * An entry in the type path.
1748 typedef struct type_path_entry_t type_path_entry_t;
1749 struct type_path_entry_t {
1750 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1752 size_t index; /**< For array types: the current index. */
1753 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1758 * A type path expression a position inside compound or array types.
1760 typedef struct type_path_t type_path_t;
1761 struct type_path_t {
1762 type_path_entry_t *path; /**< An flexible array containing the current path. */
1763 type_t *top_type; /**< type of the element the path points */
1764 size_t max_index; /**< largest index in outermost array */
1768 * Prints a type path for debugging.
1770 static __attribute__((unused)) void debug_print_type_path(
1771 const type_path_t *path)
1773 size_t len = ARR_LEN(path->path);
1775 for (size_t i = 0; i < len; ++i) {
1776 const type_path_entry_t *entry = & path->path[i];
1778 type_t *type = skip_typeref(entry->type);
1779 if (is_type_compound(type)) {
1780 /* in gcc mode structs can have no members */
1781 if (entry->v.compound_entry == NULL) {
1785 fprintf(stderr, ".%s",
1786 entry->v.compound_entry->base.symbol->string);
1787 } else if (is_type_array(type)) {
1788 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1790 fprintf(stderr, "-INVALID-");
1793 if (path->top_type != NULL) {
1794 fprintf(stderr, " (");
1795 print_type(path->top_type);
1796 fprintf(stderr, ")");
1801 * Return the top type path entry, ie. in a path
1802 * (type).a.b returns the b.
1804 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1806 size_t len = ARR_LEN(path->path);
1808 return &path->path[len-1];
1812 * Enlarge the type path by an (empty) element.
1814 static type_path_entry_t *append_to_type_path(type_path_t *path)
1816 size_t len = ARR_LEN(path->path);
1817 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1819 type_path_entry_t *result = & path->path[len];
1820 memset(result, 0, sizeof(result[0]));
1825 * Descending into a sub-type. Enter the scope of the current top_type.
1827 static void descend_into_subtype(type_path_t *path)
1829 type_t *orig_top_type = path->top_type;
1830 type_t *top_type = skip_typeref(orig_top_type);
1832 type_path_entry_t *top = append_to_type_path(path);
1833 top->type = top_type;
1835 if (is_type_compound(top_type)) {
1836 compound_t *const compound = top_type->compound.compound;
1837 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1839 if (entry != NULL) {
1840 top->v.compound_entry = &entry->declaration;
1841 path->top_type = entry->declaration.type;
1843 path->top_type = NULL;
1845 } else if (is_type_array(top_type)) {
1847 path->top_type = top_type->array.element_type;
1849 assert(!is_type_valid(top_type));
1854 * Pop an entry from the given type path, ie. returning from
1855 * (type).a.b to (type).a
1857 static void ascend_from_subtype(type_path_t *path)
1859 type_path_entry_t *top = get_type_path_top(path);
1861 path->top_type = top->type;
1863 size_t len = ARR_LEN(path->path);
1864 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1868 * Pop entries from the given type path until the given
1869 * path level is reached.
1871 static void ascend_to(type_path_t *path, size_t top_path_level)
1873 size_t len = ARR_LEN(path->path);
1875 while (len > top_path_level) {
1876 ascend_from_subtype(path);
1877 len = ARR_LEN(path->path);
1881 static bool walk_designator(type_path_t *path, const designator_t *designator,
1882 bool used_in_offsetof)
1884 for (; designator != NULL; designator = designator->next) {
1885 type_path_entry_t *top = get_type_path_top(path);
1886 type_t *orig_type = top->type;
1888 type_t *type = skip_typeref(orig_type);
1890 if (designator->symbol != NULL) {
1891 symbol_t *symbol = designator->symbol;
1892 if (!is_type_compound(type)) {
1893 if (is_type_valid(type)) {
1894 errorf(&designator->source_position,
1895 "'.%Y' designator used for non-compound type '%T'",
1899 top->type = type_error_type;
1900 top->v.compound_entry = NULL;
1901 orig_type = type_error_type;
1903 compound_t *compound = type->compound.compound;
1904 entity_t *iter = compound->members.entities;
1905 for (; iter != NULL; iter = iter->base.next) {
1906 if (iter->base.symbol == symbol) {
1911 errorf(&designator->source_position,
1912 "'%T' has no member named '%Y'", orig_type, symbol);
1915 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1916 if (used_in_offsetof && iter->compound_member.bitfield) {
1917 errorf(&designator->source_position,
1918 "offsetof designator '%Y' must not specify bitfield",
1923 top->type = orig_type;
1924 top->v.compound_entry = &iter->declaration;
1925 orig_type = iter->declaration.type;
1928 expression_t *array_index = designator->array_index;
1929 assert(designator->array_index != NULL);
1931 if (!is_type_array(type)) {
1932 if (is_type_valid(type)) {
1933 errorf(&designator->source_position,
1934 "[%E] designator used for non-array type '%T'",
1935 array_index, orig_type);
1940 long index = fold_constant_to_int(array_index);
1941 if (!used_in_offsetof) {
1943 errorf(&designator->source_position,
1944 "array index [%E] must be positive", array_index);
1945 } else if (type->array.size_constant) {
1946 long array_size = type->array.size;
1947 if (index >= array_size) {
1948 errorf(&designator->source_position,
1949 "designator [%E] (%d) exceeds array size %d",
1950 array_index, index, array_size);
1955 top->type = orig_type;
1956 top->v.index = (size_t) index;
1957 orig_type = type->array.element_type;
1959 path->top_type = orig_type;
1961 if (designator->next != NULL) {
1962 descend_into_subtype(path);
1968 static void advance_current_object(type_path_t *path, size_t top_path_level)
1970 type_path_entry_t *top = get_type_path_top(path);
1972 type_t *type = skip_typeref(top->type);
1973 if (is_type_union(type)) {
1974 /* in unions only the first element is initialized */
1975 top->v.compound_entry = NULL;
1976 } else if (is_type_struct(type)) {
1977 declaration_t *entry = top->v.compound_entry;
1979 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1980 if (next_entity != NULL) {
1981 assert(is_declaration(next_entity));
1982 entry = &next_entity->declaration;
1987 top->v.compound_entry = entry;
1988 if (entry != NULL) {
1989 path->top_type = entry->type;
1992 } else if (is_type_array(type)) {
1993 assert(is_type_array(type));
1997 if (!type->array.size_constant || top->v.index < type->array.size) {
2001 assert(!is_type_valid(type));
2005 /* we're past the last member of the current sub-aggregate, try if we
2006 * can ascend in the type hierarchy and continue with another subobject */
2007 size_t len = ARR_LEN(path->path);
2009 if (len > top_path_level) {
2010 ascend_from_subtype(path);
2011 advance_current_object(path, top_path_level);
2013 path->top_type = NULL;
2018 * skip any {...} blocks until a closing bracket is reached.
2020 static void skip_initializers(void)
2024 while (token.kind != '}') {
2025 if (token.kind == T_EOF)
2027 if (token.kind == '{') {
2035 static initializer_t *create_empty_initializer(void)
2037 static initializer_t empty_initializer
2038 = { .list = { { INITIALIZER_LIST }, 0 } };
2039 return &empty_initializer;
2043 * Parse a part of an initialiser for a struct or union,
2045 static initializer_t *parse_sub_initializer(type_path_t *path,
2046 type_t *outer_type, size_t top_path_level,
2047 parse_initializer_env_t *env)
2049 if (token.kind == '}') {
2050 /* empty initializer */
2051 return create_empty_initializer();
2054 type_t *orig_type = path->top_type;
2055 type_t *type = NULL;
2057 if (orig_type == NULL) {
2058 /* We are initializing an empty compound. */
2060 type = skip_typeref(orig_type);
2063 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2066 designator_t *designator = NULL;
2067 if (token.kind == '.' || token.kind == '[') {
2068 designator = parse_designation();
2069 goto finish_designator;
2070 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2071 /* GNU-style designator ("identifier: value") */
2072 designator = allocate_ast_zero(sizeof(designator[0]));
2073 designator->source_position = token.base.source_position;
2074 designator->symbol = token.identifier.symbol;
2079 /* reset path to toplevel, evaluate designator from there */
2080 ascend_to(path, top_path_level);
2081 if (!walk_designator(path, designator, false)) {
2082 /* can't continue after designation error */
2086 initializer_t *designator_initializer
2087 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2088 designator_initializer->designator.designator = designator;
2089 ARR_APP1(initializer_t*, initializers, designator_initializer);
2091 orig_type = path->top_type;
2092 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2097 if (token.kind == '{') {
2098 if (type != NULL && is_type_scalar(type)) {
2099 sub = parse_scalar_initializer(type, env->must_be_constant);
2102 if (env->entity != NULL) {
2104 "extra brace group at end of initializer for '%Y'",
2105 env->entity->base.symbol);
2107 errorf(HERE, "extra brace group at end of initializer");
2112 descend_into_subtype(path);
2115 add_anchor_token('}');
2116 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2118 rem_anchor_token('}');
2121 ascend_from_subtype(path);
2122 expect('}', end_error);
2124 expect('}', end_error);
2125 goto error_parse_next;
2129 /* must be an expression */
2130 expression_t *expression = parse_assignment_expression();
2131 mark_vars_read(expression, NULL);
2133 if (env->must_be_constant && !is_initializer_constant(expression)) {
2134 errorf(&expression->base.source_position,
2135 "Initialisation expression '%E' is not constant",
2140 /* we are already outside, ... */
2141 if (outer_type == NULL)
2142 goto error_parse_next;
2143 type_t *const outer_type_skip = skip_typeref(outer_type);
2144 if (is_type_compound(outer_type_skip) &&
2145 !outer_type_skip->compound.compound->complete) {
2146 goto error_parse_next;
2149 source_position_t const* const pos = &expression->base.source_position;
2150 if (env->entity != NULL) {
2151 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2153 warningf(WARN_OTHER, pos, "excess elements in initializer");
2155 goto error_parse_next;
2158 /* handle { "string" } special case */
2159 if ((expression->kind == EXPR_STRING_LITERAL
2160 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2161 && outer_type != NULL) {
2162 sub = initializer_from_expression(outer_type, expression);
2165 if (token.kind != '}') {
2166 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2168 /* TODO: eat , ... */
2173 /* descend into subtypes until expression matches type */
2175 orig_type = path->top_type;
2176 type = skip_typeref(orig_type);
2178 sub = initializer_from_expression(orig_type, expression);
2182 if (!is_type_valid(type)) {
2185 if (is_type_scalar(type)) {
2186 errorf(&expression->base.source_position,
2187 "expression '%E' doesn't match expected type '%T'",
2188 expression, orig_type);
2192 descend_into_subtype(path);
2196 /* update largest index of top array */
2197 const type_path_entry_t *first = &path->path[0];
2198 type_t *first_type = first->type;
2199 first_type = skip_typeref(first_type);
2200 if (is_type_array(first_type)) {
2201 size_t index = first->v.index;
2202 if (index > path->max_index)
2203 path->max_index = index;
2206 /* append to initializers list */
2207 ARR_APP1(initializer_t*, initializers, sub);
2210 if (token.kind == '}') {
2213 expect(',', end_error);
2214 if (token.kind == '}') {
2219 /* advance to the next declaration if we are not at the end */
2220 advance_current_object(path, top_path_level);
2221 orig_type = path->top_type;
2222 if (orig_type != NULL)
2223 type = skip_typeref(orig_type);
2229 size_t len = ARR_LEN(initializers);
2230 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2231 initializer_t *result = allocate_ast_zero(size);
2232 result->kind = INITIALIZER_LIST;
2233 result->list.len = len;
2234 memcpy(&result->list.initializers, initializers,
2235 len * sizeof(initializers[0]));
2237 DEL_ARR_F(initializers);
2238 ascend_to(path, top_path_level+1);
2243 skip_initializers();
2244 DEL_ARR_F(initializers);
2245 ascend_to(path, top_path_level+1);
2249 static expression_t *make_size_literal(size_t value)
2251 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2252 literal->base.type = type_size_t;
2255 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2256 literal->literal.value = make_string(buf);
2262 * Parses an initializer. Parsers either a compound literal
2263 * (env->declaration == NULL) or an initializer of a declaration.
2265 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2267 type_t *type = skip_typeref(env->type);
2268 size_t max_index = 0;
2269 initializer_t *result;
2271 if (is_type_scalar(type)) {
2272 result = parse_scalar_initializer(type, env->must_be_constant);
2273 } else if (token.kind == '{') {
2277 memset(&path, 0, sizeof(path));
2278 path.top_type = env->type;
2279 path.path = NEW_ARR_F(type_path_entry_t, 0);
2281 descend_into_subtype(&path);
2283 add_anchor_token('}');
2284 result = parse_sub_initializer(&path, env->type, 1, env);
2285 rem_anchor_token('}');
2287 max_index = path.max_index;
2288 DEL_ARR_F(path.path);
2290 expect('}', end_error);
2293 /* parse_scalar_initializer() also works in this case: we simply
2294 * have an expression without {} around it */
2295 result = parse_scalar_initializer(type, env->must_be_constant);
2298 /* §6.7.8:22 array initializers for arrays with unknown size determine
2299 * the array type size */
2300 if (is_type_array(type) && type->array.size_expression == NULL
2301 && result != NULL) {
2303 switch (result->kind) {
2304 case INITIALIZER_LIST:
2305 assert(max_index != 0xdeadbeaf);
2306 size = max_index + 1;
2309 case INITIALIZER_STRING:
2310 size = result->string.string.size;
2313 case INITIALIZER_WIDE_STRING:
2314 size = result->wide_string.string.size;
2317 case INITIALIZER_DESIGNATOR:
2318 case INITIALIZER_VALUE:
2319 /* can happen for parse errors */
2324 internal_errorf(HERE, "invalid initializer type");
2327 type_t *new_type = duplicate_type(type);
2329 new_type->array.size_expression = make_size_literal(size);
2330 new_type->array.size_constant = true;
2331 new_type->array.has_implicit_size = true;
2332 new_type->array.size = size;
2333 env->type = new_type;
2339 static void append_entity(scope_t *scope, entity_t *entity)
2341 if (scope->last_entity != NULL) {
2342 scope->last_entity->base.next = entity;
2344 scope->entities = entity;
2346 entity->base.parent_entity = current_entity;
2347 scope->last_entity = entity;
2351 static compound_t *parse_compound_type_specifier(bool is_struct)
2353 source_position_t const pos = *HERE;
2354 eat(is_struct ? T_struct : T_union);
2356 symbol_t *symbol = NULL;
2357 entity_t *entity = NULL;
2358 attribute_t *attributes = NULL;
2360 if (token.kind == T___attribute__) {
2361 attributes = parse_attributes(NULL);
2364 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2365 if (token.kind == T_IDENTIFIER) {
2366 /* the compound has a name, check if we have seen it already */
2367 symbol = token.identifier.symbol;
2368 entity = get_tag(symbol, kind);
2371 if (entity != NULL) {
2372 if (entity->base.parent_scope != current_scope &&
2373 (token.kind == '{' || token.kind == ';')) {
2374 /* we're in an inner scope and have a definition. Shadow
2375 * existing definition in outer scope */
2377 } else if (entity->compound.complete && token.kind == '{') {
2378 source_position_t const *const ppos = &entity->base.source_position;
2379 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2380 /* clear members in the hope to avoid further errors */
2381 entity->compound.members.entities = NULL;
2384 } else if (token.kind != '{') {
2385 char const *const msg =
2386 is_struct ? "while parsing struct type specifier" :
2387 "while parsing union type specifier";
2388 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2393 if (entity == NULL) {
2394 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2395 entity->compound.alignment = 1;
2396 entity->base.source_position = pos;
2397 entity->base.parent_scope = current_scope;
2398 if (symbol != NULL) {
2399 environment_push(entity);
2401 append_entity(current_scope, entity);
2404 if (token.kind == '{') {
2405 parse_compound_type_entries(&entity->compound);
2407 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2408 if (symbol == NULL) {
2409 assert(anonymous_entity == NULL);
2410 anonymous_entity = entity;
2414 if (attributes != NULL) {
2415 handle_entity_attributes(attributes, entity);
2418 return &entity->compound;
2421 static void parse_enum_entries(type_t *const enum_type)
2425 if (token.kind == '}') {
2426 errorf(HERE, "empty enum not allowed");
2431 add_anchor_token('}');
2433 if (token.kind != T_IDENTIFIER) {
2434 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2436 rem_anchor_token('}');
2440 symbol_t *symbol = token.identifier.symbol;
2441 entity_t *const entity
2442 = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol);
2443 entity->enum_value.enum_type = enum_type;
2444 entity->base.source_position = token.base.source_position;
2448 expression_t *value = parse_constant_expression();
2450 value = create_implicit_cast(value, enum_type);
2451 entity->enum_value.value = value;
2456 record_entity(entity, false);
2457 } while (next_if(',') && token.kind != '}');
2458 rem_anchor_token('}');
2460 expect('}', end_error);
2466 static type_t *parse_enum_specifier(void)
2468 source_position_t const pos = *HERE;
2473 switch (token.kind) {
2475 symbol = token.identifier.symbol;
2476 entity = get_tag(symbol, ENTITY_ENUM);
2479 if (entity != NULL) {
2480 if (entity->base.parent_scope != current_scope &&
2481 (token.kind == '{' || token.kind == ';')) {
2482 /* we're in an inner scope and have a definition. Shadow
2483 * existing definition in outer scope */
2485 } else if (entity->enume.complete && token.kind == '{') {
2486 source_position_t const *const ppos = &entity->base.source_position;
2487 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2498 parse_error_expected("while parsing enum type specifier",
2499 T_IDENTIFIER, '{', NULL);
2503 if (entity == NULL) {
2504 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2505 entity->base.source_position = pos;
2506 entity->base.parent_scope = current_scope;
2509 type_t *const type = allocate_type_zero(TYPE_ENUM);
2510 type->enumt.enume = &entity->enume;
2511 type->enumt.base.akind = ATOMIC_TYPE_INT;
2513 if (token.kind == '{') {
2514 if (symbol != NULL) {
2515 environment_push(entity);
2517 append_entity(current_scope, entity);
2518 entity->enume.complete = true;
2520 parse_enum_entries(type);
2521 parse_attributes(NULL);
2523 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2524 if (symbol == NULL) {
2525 assert(anonymous_entity == NULL);
2526 anonymous_entity = entity;
2528 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2529 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2536 * if a symbol is a typedef to another type, return true
2538 static bool is_typedef_symbol(symbol_t *symbol)
2540 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2541 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2544 static type_t *parse_typeof(void)
2550 expect('(', end_error);
2551 add_anchor_token(')');
2553 expression_t *expression = NULL;
2555 switch (token.kind) {
2557 if (is_typedef_symbol(token.identifier.symbol)) {
2559 type = parse_typename();
2562 expression = parse_expression();
2563 type = revert_automatic_type_conversion(expression);
2568 rem_anchor_token(')');
2569 expect(')', end_error);
2571 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2572 typeof_type->typeoft.expression = expression;
2573 typeof_type->typeoft.typeof_type = type;
2580 typedef enum specifiers_t {
2581 SPECIFIER_SIGNED = 1 << 0,
2582 SPECIFIER_UNSIGNED = 1 << 1,
2583 SPECIFIER_LONG = 1 << 2,
2584 SPECIFIER_INT = 1 << 3,
2585 SPECIFIER_DOUBLE = 1 << 4,
2586 SPECIFIER_CHAR = 1 << 5,
2587 SPECIFIER_WCHAR_T = 1 << 6,
2588 SPECIFIER_SHORT = 1 << 7,
2589 SPECIFIER_LONG_LONG = 1 << 8,
2590 SPECIFIER_FLOAT = 1 << 9,
2591 SPECIFIER_BOOL = 1 << 10,
2592 SPECIFIER_VOID = 1 << 11,
2593 SPECIFIER_INT8 = 1 << 12,
2594 SPECIFIER_INT16 = 1 << 13,
2595 SPECIFIER_INT32 = 1 << 14,
2596 SPECIFIER_INT64 = 1 << 15,
2597 SPECIFIER_INT128 = 1 << 16,
2598 SPECIFIER_COMPLEX = 1 << 17,
2599 SPECIFIER_IMAGINARY = 1 << 18,
2602 static type_t *get_typedef_type(symbol_t *symbol)
2604 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2605 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2608 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2609 type->typedeft.typedefe = &entity->typedefe;
2614 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2616 expect('(', end_error);
2618 attribute_property_argument_t *property
2619 = allocate_ast_zero(sizeof(*property));
2622 if (token.kind != T_IDENTIFIER) {
2623 parse_error_expected("while parsing property declspec",
2624 T_IDENTIFIER, NULL);
2629 symbol_t *symbol = token.identifier.symbol;
2630 if (strcmp(symbol->string, "put") == 0) {
2631 prop = &property->put_symbol;
2632 } else if (strcmp(symbol->string, "get") == 0) {
2633 prop = &property->get_symbol;
2635 errorf(HERE, "expected put or get in property declspec");
2639 expect('=', end_error);
2640 if (token.kind != T_IDENTIFIER) {
2641 parse_error_expected("while parsing property declspec",
2642 T_IDENTIFIER, NULL);
2646 *prop = token.identifier.symbol;
2648 } while (next_if(','));
2650 attribute->a.property = property;
2652 expect(')', end_error);
2658 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2660 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2661 if (next_if(T_restrict)) {
2662 kind = ATTRIBUTE_MS_RESTRICT;
2663 } else if (token.kind == T_IDENTIFIER) {
2664 const char *name = token.identifier.symbol->string;
2665 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2667 const char *attribute_name = get_attribute_name(k);
2668 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2674 if (kind == ATTRIBUTE_UNKNOWN) {
2675 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2678 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2682 attribute_t *attribute = allocate_attribute_zero(kind);
2685 if (kind == ATTRIBUTE_MS_PROPERTY) {
2686 return parse_attribute_ms_property(attribute);
2689 /* parse arguments */
2691 attribute->a.arguments = parse_attribute_arguments();
2696 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2700 expect('(', end_error);
2705 add_anchor_token(')');
2707 attribute_t **anchor = &first;
2709 while (*anchor != NULL)
2710 anchor = &(*anchor)->next;
2712 attribute_t *attribute
2713 = parse_microsoft_extended_decl_modifier_single();
2714 if (attribute == NULL)
2717 *anchor = attribute;
2718 anchor = &attribute->next;
2719 } while (next_if(','));
2721 rem_anchor_token(')');
2722 expect(')', end_error);
2726 rem_anchor_token(')');
2730 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2732 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2733 entity->base.source_position = *HERE;
2734 if (is_declaration(entity)) {
2735 entity->declaration.type = type_error_type;
2736 entity->declaration.implicit = true;
2737 } else if (kind == ENTITY_TYPEDEF) {
2738 entity->typedefe.type = type_error_type;
2739 entity->typedefe.builtin = true;
2741 if (kind != ENTITY_COMPOUND_MEMBER)
2742 record_entity(entity, false);
2746 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2748 type_t *type = NULL;
2749 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2750 unsigned type_specifiers = 0;
2751 bool newtype = false;
2752 bool saw_error = false;
2754 memset(specifiers, 0, sizeof(*specifiers));
2755 specifiers->source_position = token.base.source_position;
2758 specifiers->attributes = parse_attributes(specifiers->attributes);
2760 switch (token.kind) {
2762 #define MATCH_STORAGE_CLASS(token, class) \
2764 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2765 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2767 specifiers->storage_class = class; \
2768 if (specifiers->thread_local) \
2769 goto check_thread_storage_class; \
2773 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2774 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2775 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2776 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2777 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2780 specifiers->attributes
2781 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2785 if (specifiers->thread_local) {
2786 errorf(HERE, "duplicate '__thread'");
2788 specifiers->thread_local = true;
2789 check_thread_storage_class:
2790 switch (specifiers->storage_class) {
2791 case STORAGE_CLASS_EXTERN:
2792 case STORAGE_CLASS_NONE:
2793 case STORAGE_CLASS_STATIC:
2797 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2798 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2799 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2800 wrong_thread_storage_class:
2801 errorf(HERE, "'__thread' used with '%s'", wrong);
2808 /* type qualifiers */
2809 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2811 qualifiers |= qualifier; \
2815 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2816 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2817 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2818 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2819 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2820 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2821 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2822 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2824 /* type specifiers */
2825 #define MATCH_SPECIFIER(token, specifier, name) \
2827 if (type_specifiers & specifier) { \
2828 errorf(HERE, "multiple " name " type specifiers given"); \
2830 type_specifiers |= specifier; \
2835 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2836 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2837 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2838 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2839 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2840 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2841 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2842 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2843 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2844 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2845 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2846 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2847 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2848 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2849 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2850 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2851 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2852 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2856 specifiers->is_inline = true;
2860 case T__forceinline:
2862 specifiers->modifiers |= DM_FORCEINLINE;
2867 if (type_specifiers & SPECIFIER_LONG_LONG) {
2868 errorf(HERE, "too many long type specifiers given");
2869 } else if (type_specifiers & SPECIFIER_LONG) {
2870 type_specifiers |= SPECIFIER_LONG_LONG;
2872 type_specifiers |= SPECIFIER_LONG;
2877 #define CHECK_DOUBLE_TYPE() \
2878 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2881 CHECK_DOUBLE_TYPE();
2882 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2884 type->compound.compound = parse_compound_type_specifier(true);
2887 CHECK_DOUBLE_TYPE();
2888 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2889 type->compound.compound = parse_compound_type_specifier(false);
2892 CHECK_DOUBLE_TYPE();
2893 type = parse_enum_specifier();
2896 CHECK_DOUBLE_TYPE();
2897 type = parse_typeof();
2899 case T___builtin_va_list:
2900 CHECK_DOUBLE_TYPE();
2901 type = duplicate_type(type_valist);
2905 case T_IDENTIFIER: {
2906 /* only parse identifier if we haven't found a type yet */
2907 if (type != NULL || type_specifiers != 0) {
2908 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2909 * declaration, so it doesn't generate errors about expecting '(' or
2911 switch (look_ahead(1)->kind) {
2918 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2922 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2927 goto finish_specifiers;
2931 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2932 if (typedef_type == NULL) {
2933 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2934 * declaration, so it doesn't generate 'implicit int' followed by more
2935 * errors later on. */
2936 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2942 errorf(HERE, "%K does not name a type", &token);
2944 symbol_t *symbol = token.identifier.symbol;
2946 = create_error_entity(symbol, ENTITY_TYPEDEF);
2948 type = allocate_type_zero(TYPE_TYPEDEF);
2949 type->typedeft.typedefe = &entity->typedefe;
2957 goto finish_specifiers;
2962 type = typedef_type;
2966 /* function specifier */
2968 goto finish_specifiers;
2973 specifiers->attributes = parse_attributes(specifiers->attributes);
2975 if (type == NULL || (saw_error && type_specifiers != 0)) {
2976 atomic_type_kind_t atomic_type;
2978 /* match valid basic types */
2979 switch (type_specifiers) {
2980 case SPECIFIER_VOID:
2981 atomic_type = ATOMIC_TYPE_VOID;
2983 case SPECIFIER_WCHAR_T:
2984 atomic_type = ATOMIC_TYPE_WCHAR_T;
2986 case SPECIFIER_CHAR:
2987 atomic_type = ATOMIC_TYPE_CHAR;
2989 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2990 atomic_type = ATOMIC_TYPE_SCHAR;
2992 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2993 atomic_type = ATOMIC_TYPE_UCHAR;
2995 case SPECIFIER_SHORT:
2996 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2997 case SPECIFIER_SHORT | SPECIFIER_INT:
2998 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2999 atomic_type = ATOMIC_TYPE_SHORT;
3001 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3002 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3003 atomic_type = ATOMIC_TYPE_USHORT;
3006 case SPECIFIER_SIGNED:
3007 case SPECIFIER_SIGNED | SPECIFIER_INT:
3008 atomic_type = ATOMIC_TYPE_INT;
3010 case SPECIFIER_UNSIGNED:
3011 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3012 atomic_type = ATOMIC_TYPE_UINT;
3014 case SPECIFIER_LONG:
3015 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3016 case SPECIFIER_LONG | SPECIFIER_INT:
3017 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3018 atomic_type = ATOMIC_TYPE_LONG;
3020 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3021 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3022 atomic_type = ATOMIC_TYPE_ULONG;
3025 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3026 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3027 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3028 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3030 atomic_type = ATOMIC_TYPE_LONGLONG;
3031 goto warn_about_long_long;
3033 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3034 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3036 atomic_type = ATOMIC_TYPE_ULONGLONG;
3037 warn_about_long_long:
3038 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3041 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3042 atomic_type = unsigned_int8_type_kind;
3045 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3046 atomic_type = unsigned_int16_type_kind;
3049 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3050 atomic_type = unsigned_int32_type_kind;
3053 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3054 atomic_type = unsigned_int64_type_kind;
3057 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3058 atomic_type = unsigned_int128_type_kind;
3061 case SPECIFIER_INT8:
3062 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3063 atomic_type = int8_type_kind;
3066 case SPECIFIER_INT16:
3067 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3068 atomic_type = int16_type_kind;
3071 case SPECIFIER_INT32:
3072 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3073 atomic_type = int32_type_kind;
3076 case SPECIFIER_INT64:
3077 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3078 atomic_type = int64_type_kind;
3081 case SPECIFIER_INT128:
3082 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3083 atomic_type = int128_type_kind;
3086 case SPECIFIER_FLOAT:
3087 atomic_type = ATOMIC_TYPE_FLOAT;
3089 case SPECIFIER_DOUBLE:
3090 atomic_type = ATOMIC_TYPE_DOUBLE;
3092 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3093 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3095 case SPECIFIER_BOOL:
3096 atomic_type = ATOMIC_TYPE_BOOL;
3098 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3099 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3100 atomic_type = ATOMIC_TYPE_FLOAT;
3102 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3103 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3104 atomic_type = ATOMIC_TYPE_DOUBLE;
3106 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3107 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3108 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3111 /* invalid specifier combination, give an error message */
3112 source_position_t const* const pos = &specifiers->source_position;
3113 if (type_specifiers == 0) {
3115 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3116 if (!(c_mode & _CXX) && !strict_mode) {
3117 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3118 atomic_type = ATOMIC_TYPE_INT;
3121 errorf(pos, "no type specifiers given in declaration");
3124 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3125 (type_specifiers & SPECIFIER_UNSIGNED)) {
3126 errorf(pos, "signed and unsigned specifiers given");
3127 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3128 errorf(pos, "only integer types can be signed or unsigned");
3130 errorf(pos, "multiple datatypes in declaration");
3136 if (type_specifiers & SPECIFIER_COMPLEX) {
3137 type = allocate_type_zero(TYPE_COMPLEX);
3138 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3139 type = allocate_type_zero(TYPE_IMAGINARY);
3141 type = allocate_type_zero(TYPE_ATOMIC);
3143 type->atomic.akind = atomic_type;
3145 } else if (type_specifiers != 0) {
3146 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3149 /* FIXME: check type qualifiers here */
3150 type->base.qualifiers = qualifiers;
3153 type = identify_new_type(type);
3155 type = typehash_insert(type);
3158 if (specifiers->attributes != NULL)
3159 type = handle_type_attributes(specifiers->attributes, type);
3160 specifiers->type = type;
3164 specifiers->type = type_error_type;
3167 static type_qualifiers_t parse_type_qualifiers(void)
3169 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3172 switch (token.kind) {
3173 /* type qualifiers */
3174 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3175 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3176 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3177 /* microsoft extended type modifiers */
3178 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3179 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3180 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3181 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3182 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3191 * Parses an K&R identifier list
3193 static void parse_identifier_list(scope_t *scope)
3195 assert(token.kind == T_IDENTIFIER);
3197 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol);
3198 entity->base.source_position = token.base.source_position;
3199 /* a K&R parameter has no type, yet */
3203 append_entity(scope, entity);
3204 } while (next_if(',') && token.kind == T_IDENTIFIER);
3207 static entity_t *parse_parameter(void)
3209 declaration_specifiers_t specifiers;
3210 parse_declaration_specifiers(&specifiers);
3212 entity_t *entity = parse_declarator(&specifiers,
3213 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3214 anonymous_entity = NULL;
3218 static void semantic_parameter_incomplete(const entity_t *entity)
3220 assert(entity->kind == ENTITY_PARAMETER);
3222 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3223 * list in a function declarator that is part of a
3224 * definition of that function shall not have
3225 * incomplete type. */
3226 type_t *type = skip_typeref(entity->declaration.type);
3227 if (is_type_incomplete(type)) {
3228 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3232 static bool has_parameters(void)
3234 /* func(void) is not a parameter */
3235 if (token.kind == T_IDENTIFIER) {
3236 entity_t const *const entity
3237 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3240 if (entity->kind != ENTITY_TYPEDEF)
3242 if (skip_typeref(entity->typedefe.type) != type_void)
3244 } else if (token.kind != T_void) {
3247 if (look_ahead(1)->kind != ')')
3254 * Parses function type parameters (and optionally creates variable_t entities
3255 * for them in a scope)
3257 static void parse_parameters(function_type_t *type, scope_t *scope)
3260 add_anchor_token(')');
3261 int saved_comma_state = save_and_reset_anchor_state(',');
3263 if (token.kind == T_IDENTIFIER
3264 && !is_typedef_symbol(token.identifier.symbol)) {
3265 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3266 if (la1_type == ',' || la1_type == ')') {
3267 type->kr_style_parameters = true;
3268 parse_identifier_list(scope);
3269 goto parameters_finished;
3273 if (token.kind == ')') {
3274 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3275 if (!(c_mode & _CXX))
3276 type->unspecified_parameters = true;
3277 } else if (has_parameters()) {
3278 function_parameter_t **anchor = &type->parameters;
3280 switch (token.kind) {
3283 type->variadic = true;
3284 goto parameters_finished;
3289 entity_t *entity = parse_parameter();
3290 if (entity->kind == ENTITY_TYPEDEF) {
3291 errorf(&entity->base.source_position,
3292 "typedef not allowed as function parameter");
3295 assert(is_declaration(entity));
3297 semantic_parameter_incomplete(entity);
3299 function_parameter_t *const parameter =
3300 allocate_parameter(entity->declaration.type);
3302 if (scope != NULL) {
3303 append_entity(scope, entity);
3306 *anchor = parameter;
3307 anchor = ¶meter->next;
3312 goto parameters_finished;
3314 } while (next_if(','));
3317 parameters_finished:
3318 rem_anchor_token(')');
3319 expect(')', end_error);
3322 restore_anchor_state(',', saved_comma_state);
3325 typedef enum construct_type_kind_t {
3326 CONSTRUCT_POINTER = 1,
3327 CONSTRUCT_REFERENCE,
3330 } construct_type_kind_t;
3332 typedef union construct_type_t construct_type_t;
3334 typedef struct construct_type_base_t {
3335 construct_type_kind_t kind;
3336 source_position_t pos;
3337 construct_type_t *next;
3338 } construct_type_base_t;
3340 typedef struct parsed_pointer_t {
3341 construct_type_base_t base;
3342 type_qualifiers_t type_qualifiers;
3343 variable_t *base_variable; /**< MS __based extension. */
3346 typedef struct parsed_reference_t {
3347 construct_type_base_t base;
3348 } parsed_reference_t;
3350 typedef struct construct_function_type_t {
3351 construct_type_base_t base;
3352 type_t *function_type;
3353 } construct_function_type_t;
3355 typedef struct parsed_array_t {
3356 construct_type_base_t base;
3357 type_qualifiers_t type_qualifiers;
3363 union construct_type_t {
3364 construct_type_kind_t kind;
3365 construct_type_base_t base;
3366 parsed_pointer_t pointer;
3367 parsed_reference_t reference;
3368 construct_function_type_t function;
3369 parsed_array_t array;
3372 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3374 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3375 memset(cons, 0, size);
3377 cons->base.pos = *HERE;
3382 static construct_type_t *parse_pointer_declarator(void)
3384 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3386 cons->pointer.type_qualifiers = parse_type_qualifiers();
3387 //cons->pointer.base_variable = base_variable;
3392 /* ISO/IEC 14882:1998(E) §8.3.2 */
3393 static construct_type_t *parse_reference_declarator(void)
3395 if (!(c_mode & _CXX))
3396 errorf(HERE, "references are only available for C++");
3398 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3405 static construct_type_t *parse_array_declarator(void)
3407 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3408 parsed_array_t *const array = &cons->array;
3411 add_anchor_token(']');
3413 bool is_static = next_if(T_static);
3415 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3418 is_static = next_if(T_static);
3420 array->type_qualifiers = type_qualifiers;
3421 array->is_static = is_static;
3423 expression_t *size = NULL;
3424 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3425 array->is_variable = true;
3427 } else if (token.kind != ']') {
3428 size = parse_assignment_expression();
3430 /* §6.7.5.2:1 Array size must have integer type */
3431 type_t *const orig_type = size->base.type;
3432 type_t *const type = skip_typeref(orig_type);
3433 if (!is_type_integer(type) && is_type_valid(type)) {
3434 errorf(&size->base.source_position,
3435 "array size '%E' must have integer type but has type '%T'",
3440 mark_vars_read(size, NULL);
3443 if (is_static && size == NULL)
3444 errorf(&array->base.pos, "static array parameters require a size");
3446 rem_anchor_token(']');
3447 expect(']', end_error);
3454 static construct_type_t *parse_function_declarator(scope_t *scope)
3456 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3458 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3459 function_type_t *ftype = &type->function;
3461 ftype->linkage = current_linkage;
3462 ftype->calling_convention = CC_DEFAULT;
3464 parse_parameters(ftype, scope);
3466 cons->function.function_type = type;
3471 typedef struct parse_declarator_env_t {
3472 bool may_be_abstract : 1;
3473 bool must_be_abstract : 1;
3474 decl_modifiers_t modifiers;
3476 source_position_t source_position;
3478 attribute_t *attributes;
3479 } parse_declarator_env_t;
3482 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3484 /* construct a single linked list of construct_type_t's which describe
3485 * how to construct the final declarator type */
3486 construct_type_t *first = NULL;
3487 construct_type_t **anchor = &first;
3489 env->attributes = parse_attributes(env->attributes);
3492 construct_type_t *type;
3493 //variable_t *based = NULL; /* MS __based extension */
3494 switch (token.kind) {
3496 type = parse_reference_declarator();
3500 panic("based not supported anymore");
3505 type = parse_pointer_declarator();
3509 goto ptr_operator_end;
3513 anchor = &type->base.next;
3515 /* TODO: find out if this is correct */
3516 env->attributes = parse_attributes(env->attributes);
3520 construct_type_t *inner_types = NULL;
3522 switch (token.kind) {
3524 if (env->must_be_abstract) {
3525 errorf(HERE, "no identifier expected in typename");
3527 env->symbol = token.identifier.symbol;
3528 env->source_position = token.base.source_position;
3534 /* Parenthesized declarator or function declarator? */
3535 token_t const *const la1 = look_ahead(1);
3536 switch (la1->kind) {
3538 if (is_typedef_symbol(la1->identifier.symbol)) {
3540 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3541 * interpreted as ``function with no parameter specification'', rather
3542 * than redundant parentheses around the omitted identifier. */
3544 /* Function declarator. */
3545 if (!env->may_be_abstract) {
3546 errorf(HERE, "function declarator must have a name");
3553 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3554 /* Paranthesized declarator. */
3556 add_anchor_token(')');
3557 inner_types = parse_inner_declarator(env);
3558 if (inner_types != NULL) {
3559 /* All later declarators only modify the return type */
3560 env->must_be_abstract = true;
3562 rem_anchor_token(')');
3563 expect(')', end_error);
3571 if (env->may_be_abstract)
3573 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3578 construct_type_t **const p = anchor;
3581 construct_type_t *type;
3582 switch (token.kind) {
3584 scope_t *scope = NULL;
3585 if (!env->must_be_abstract) {
3586 scope = &env->parameters;
3589 type = parse_function_declarator(scope);
3593 type = parse_array_declarator();
3596 goto declarator_finished;
3599 /* insert in the middle of the list (at p) */
3600 type->base.next = *p;
3603 anchor = &type->base.next;
3606 declarator_finished:
3607 /* append inner_types at the end of the list, we don't to set anchor anymore
3608 * as it's not needed anymore */
3609 *anchor = inner_types;
3616 static type_t *construct_declarator_type(construct_type_t *construct_list,
3619 construct_type_t *iter = construct_list;
3620 for (; iter != NULL; iter = iter->base.next) {
3621 source_position_t const* const pos = &iter->base.pos;
3622 switch (iter->kind) {
3623 case CONSTRUCT_FUNCTION: {
3624 construct_function_type_t *function = &iter->function;
3625 type_t *function_type = function->function_type;
3627 function_type->function.return_type = type;
3629 type_t *skipped_return_type = skip_typeref(type);
3631 if (is_type_function(skipped_return_type)) {
3632 errorf(pos, "function returning function is not allowed");
3633 } else if (is_type_array(skipped_return_type)) {
3634 errorf(pos, "function returning array is not allowed");
3636 if (skipped_return_type->base.qualifiers != 0) {
3637 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3641 /* The function type was constructed earlier. Freeing it here will
3642 * destroy other types. */
3643 type = typehash_insert(function_type);
3647 case CONSTRUCT_POINTER: {
3648 if (is_type_reference(skip_typeref(type)))
3649 errorf(pos, "cannot declare a pointer to reference");
3651 parsed_pointer_t *pointer = &iter->pointer;
3652 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3656 case CONSTRUCT_REFERENCE:
3657 if (is_type_reference(skip_typeref(type)))
3658 errorf(pos, "cannot declare a reference to reference");
3660 type = make_reference_type(type);
3663 case CONSTRUCT_ARRAY: {
3664 if (is_type_reference(skip_typeref(type)))
3665 errorf(pos, "cannot declare an array of references");
3667 parsed_array_t *array = &iter->array;
3668 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3670 expression_t *size_expression = array->size;
3671 if (size_expression != NULL) {
3673 = create_implicit_cast(size_expression, type_size_t);
3676 array_type->base.qualifiers = array->type_qualifiers;
3677 array_type->array.element_type = type;
3678 array_type->array.is_static = array->is_static;
3679 array_type->array.is_variable = array->is_variable;
3680 array_type->array.size_expression = size_expression;
3682 if (size_expression != NULL) {
3683 switch (is_constant_expression(size_expression)) {
3684 case EXPR_CLASS_CONSTANT: {
3685 long const size = fold_constant_to_int(size_expression);
3686 array_type->array.size = size;
3687 array_type->array.size_constant = true;
3688 /* §6.7.5.2:1 If the expression is a constant expression,
3689 * it shall have a value greater than zero. */
3691 errorf(&size_expression->base.source_position,
3692 "size of array must be greater than zero");
3693 } else if (size == 0 && !GNU_MODE) {
3694 errorf(&size_expression->base.source_position,
3695 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3700 case EXPR_CLASS_VARIABLE:
3701 array_type->array.is_vla = true;
3704 case EXPR_CLASS_ERROR:
3709 type_t *skipped_type = skip_typeref(type);
3711 if (is_type_incomplete(skipped_type)) {
3712 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3713 } else if (is_type_function(skipped_type)) {
3714 errorf(pos, "array of functions is not allowed");
3716 type = identify_new_type(array_type);
3720 internal_errorf(pos, "invalid type construction found");
3726 static type_t *automatic_type_conversion(type_t *orig_type);
3728 static type_t *semantic_parameter(const source_position_t *pos,
3730 const declaration_specifiers_t *specifiers,
3731 entity_t const *const param)
3733 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3734 * shall be adjusted to ``qualified pointer to type'',
3736 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3737 * type'' shall be adjusted to ``pointer to function
3738 * returning type'', as in 6.3.2.1. */
3739 type = automatic_type_conversion(type);
3741 if (specifiers->is_inline && is_type_valid(type)) {
3742 errorf(pos, "'%N' declared 'inline'", param);
3745 /* §6.9.1:6 The declarations in the declaration list shall contain
3746 * no storage-class specifier other than register and no
3747 * initializations. */
3748 if (specifiers->thread_local || (
3749 specifiers->storage_class != STORAGE_CLASS_NONE &&
3750 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3752 errorf(pos, "invalid storage class for '%N'", param);
3755 /* delay test for incomplete type, because we might have (void)
3756 * which is legal but incomplete... */
3761 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3762 declarator_flags_t flags)
3764 parse_declarator_env_t env;
3765 memset(&env, 0, sizeof(env));
3766 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3768 construct_type_t *construct_type = parse_inner_declarator(&env);
3770 construct_declarator_type(construct_type, specifiers->type);
3771 type_t *type = skip_typeref(orig_type);
3773 if (construct_type != NULL) {
3774 obstack_free(&temp_obst, construct_type);
3777 attribute_t *attributes = parse_attributes(env.attributes);
3778 /* append (shared) specifier attribute behind attributes of this
3780 attribute_t **anchor = &attributes;
3781 while (*anchor != NULL)
3782 anchor = &(*anchor)->next;
3783 *anchor = specifiers->attributes;
3786 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3787 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3788 entity->base.source_position = env.source_position;
3789 entity->typedefe.type = orig_type;
3791 if (anonymous_entity != NULL) {
3792 if (is_type_compound(type)) {
3793 assert(anonymous_entity->compound.alias == NULL);
3794 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3795 anonymous_entity->kind == ENTITY_UNION);
3796 anonymous_entity->compound.alias = entity;
3797 anonymous_entity = NULL;
3798 } else if (is_type_enum(type)) {
3799 assert(anonymous_entity->enume.alias == NULL);
3800 assert(anonymous_entity->kind == ENTITY_ENUM);
3801 anonymous_entity->enume.alias = entity;
3802 anonymous_entity = NULL;
3806 /* create a declaration type entity */
3807 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3808 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3810 if (env.symbol != NULL) {
3811 if (specifiers->is_inline && is_type_valid(type)) {
3812 errorf(&env.source_position,
3813 "compound member '%Y' declared 'inline'", env.symbol);
3816 if (specifiers->thread_local ||
3817 specifiers->storage_class != STORAGE_CLASS_NONE) {
3818 errorf(&env.source_position,
3819 "compound member '%Y' must have no storage class",
3823 } else if (flags & DECL_IS_PARAMETER) {
3824 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3825 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3826 } else if (is_type_function(type)) {
3827 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3828 entity->function.is_inline = specifiers->is_inline;
3829 entity->function.elf_visibility = default_visibility;
3830 entity->function.parameters = env.parameters;
3832 if (env.symbol != NULL) {
3833 /* this needs fixes for C++ */
3834 bool in_function_scope = current_function != NULL;
3836 if (specifiers->thread_local || (
3837 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3838 specifiers->storage_class != STORAGE_CLASS_NONE &&
3839 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3841 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3845 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3846 entity->variable.elf_visibility = default_visibility;
3847 entity->variable.thread_local = specifiers->thread_local;
3849 if (env.symbol != NULL) {
3850 if (specifiers->is_inline && is_type_valid(type)) {
3851 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3854 bool invalid_storage_class = false;
3855 if (current_scope == file_scope) {
3856 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3857 specifiers->storage_class != STORAGE_CLASS_NONE &&
3858 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3859 invalid_storage_class = true;
3862 if (specifiers->thread_local &&
3863 specifiers->storage_class == STORAGE_CLASS_NONE) {
3864 invalid_storage_class = true;
3867 if (invalid_storage_class) {
3868 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3873 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3874 entity->declaration.type = orig_type;
3875 entity->declaration.alignment = get_type_alignment(orig_type);
3876 entity->declaration.modifiers = env.modifiers;
3877 entity->declaration.attributes = attributes;
3879 storage_class_t storage_class = specifiers->storage_class;
3880 entity->declaration.declared_storage_class = storage_class;
3882 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3883 storage_class = STORAGE_CLASS_AUTO;
3884 entity->declaration.storage_class = storage_class;
3887 if (attributes != NULL) {
3888 handle_entity_attributes(attributes, entity);
3891 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3892 adapt_special_functions(&entity->function);
3898 static type_t *parse_abstract_declarator(type_t *base_type)
3900 parse_declarator_env_t env;
3901 memset(&env, 0, sizeof(env));
3902 env.may_be_abstract = true;
3903 env.must_be_abstract = true;
3905 construct_type_t *construct_type = parse_inner_declarator(&env);
3907 type_t *result = construct_declarator_type(construct_type, base_type);
3908 if (construct_type != NULL) {
3909 obstack_free(&temp_obst, construct_type);
3911 result = handle_type_attributes(env.attributes, result);
3917 * Check if the declaration of main is suspicious. main should be a
3918 * function with external linkage, returning int, taking either zero
3919 * arguments, two, or three arguments of appropriate types, ie.
3921 * int main([ int argc, char **argv [, char **env ] ]).
3923 * @param decl the declaration to check
3924 * @param type the function type of the declaration
3926 static void check_main(const entity_t *entity)
3928 const source_position_t *pos = &entity->base.source_position;
3929 if (entity->kind != ENTITY_FUNCTION) {
3930 warningf(WARN_MAIN, pos, "'main' is not a function");
3934 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3935 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3938 type_t *type = skip_typeref(entity->declaration.type);
3939 assert(is_type_function(type));
3941 function_type_t const *const func_type = &type->function;
3942 type_t *const ret_type = func_type->return_type;
3943 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3944 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3946 const function_parameter_t *parm = func_type->parameters;
3948 type_t *const first_type = skip_typeref(parm->type);
3949 type_t *const first_type_unqual = get_unqualified_type(first_type);
3950 if (!types_compatible(first_type_unqual, type_int)) {
3951 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3955 type_t *const second_type = skip_typeref(parm->type);
3956 type_t *const second_type_unqual
3957 = get_unqualified_type(second_type);
3958 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3959 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3963 type_t *const third_type = skip_typeref(parm->type);
3964 type_t *const third_type_unqual
3965 = get_unqualified_type(third_type);
3966 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3967 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3971 goto warn_arg_count;
3975 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3981 * Check if a symbol is the equal to "main".
3983 static bool is_sym_main(const symbol_t *const sym)
3985 return strcmp(sym->string, "main") == 0;
3988 static void error_redefined_as_different_kind(const source_position_t *pos,
3989 const entity_t *old, entity_kind_t new_kind)
3991 char const *const what = get_entity_kind_name(new_kind);
3992 source_position_t const *const ppos = &old->base.source_position;
3993 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3996 static bool is_entity_valid(entity_t *const ent)
3998 if (is_declaration(ent)) {
3999 return is_type_valid(skip_typeref(ent->declaration.type));
4000 } else if (ent->kind == ENTITY_TYPEDEF) {
4001 return is_type_valid(skip_typeref(ent->typedefe.type));
4006 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4008 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4009 if (attributes_equal(tattr, attr))
4016 * test wether new_list contains any attributes not included in old_list
4018 static bool has_new_attributes(const attribute_t *old_list,
4019 const attribute_t *new_list)
4021 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4022 if (!contains_attribute(old_list, attr))
4029 * Merge in attributes from an attribute list (probably from a previous
4030 * declaration with the same name). Warning: destroys the old structure
4031 * of the attribute list - don't reuse attributes after this call.
4033 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4036 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4038 if (contains_attribute(decl->attributes, attr))
4041 /* move attribute to new declarations attributes list */
4042 attr->next = decl->attributes;
4043 decl->attributes = attr;
4048 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4049 * for various problems that occur for multiple definitions
4051 entity_t *record_entity(entity_t *entity, const bool is_definition)
4053 const symbol_t *const symbol = entity->base.symbol;
4054 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4055 const source_position_t *pos = &entity->base.source_position;
4057 /* can happen in error cases */
4061 entity_t *const previous_entity = get_entity(symbol, namespc);
4062 /* pushing the same entity twice will break the stack structure */
4063 assert(previous_entity != entity);
4065 if (entity->kind == ENTITY_FUNCTION) {
4066 type_t *const orig_type = entity->declaration.type;
4067 type_t *const type = skip_typeref(orig_type);
4069 assert(is_type_function(type));
4070 if (type->function.unspecified_parameters &&
4071 previous_entity == NULL &&
4072 !entity->declaration.implicit) {
4073 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4076 if (current_scope == file_scope && is_sym_main(symbol)) {
4081 if (is_declaration(entity) &&
4082 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4083 current_scope != file_scope &&
4084 !entity->declaration.implicit) {
4085 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4088 if (previous_entity != NULL) {
4089 source_position_t const *const ppos = &previous_entity->base.source_position;
4091 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4092 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4093 assert(previous_entity->kind == ENTITY_PARAMETER);
4094 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4098 if (previous_entity->base.parent_scope == current_scope) {
4099 if (previous_entity->kind != entity->kind) {
4100 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4101 error_redefined_as_different_kind(pos, previous_entity,
4106 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4107 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4110 if (previous_entity->kind == ENTITY_TYPEDEF) {
4111 type_t *const type = skip_typeref(entity->typedefe.type);
4112 type_t *const prev_type
4113 = skip_typeref(previous_entity->typedefe.type);
4114 if (c_mode & _CXX) {
4115 /* C++ allows double typedef if they are identical
4116 * (after skipping typedefs) */
4117 if (type == prev_type)
4120 /* GCC extension: redef in system headers is allowed */
4121 if ((pos->is_system_header || ppos->is_system_header) &&
4122 types_compatible(type, prev_type))
4125 errorf(pos, "redefinition of '%N' (declared %P)",
4130 /* at this point we should have only VARIABLES or FUNCTIONS */
4131 assert(is_declaration(previous_entity) && is_declaration(entity));
4133 declaration_t *const prev_decl = &previous_entity->declaration;
4134 declaration_t *const decl = &entity->declaration;
4136 /* can happen for K&R style declarations */
4137 if (prev_decl->type == NULL &&
4138 previous_entity->kind == ENTITY_PARAMETER &&
4139 entity->kind == ENTITY_PARAMETER) {
4140 prev_decl->type = decl->type;
4141 prev_decl->storage_class = decl->storage_class;
4142 prev_decl->declared_storage_class = decl->declared_storage_class;
4143 prev_decl->modifiers = decl->modifiers;
4144 return previous_entity;
4147 type_t *const type = skip_typeref(decl->type);
4148 type_t *const prev_type = skip_typeref(prev_decl->type);
4150 if (!types_compatible(type, prev_type)) {
4151 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4153 unsigned old_storage_class = prev_decl->storage_class;
4155 if (is_definition &&
4157 !(prev_decl->modifiers & DM_USED) &&
4158 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4159 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4162 storage_class_t new_storage_class = decl->storage_class;
4164 /* pretend no storage class means extern for function
4165 * declarations (except if the previous declaration is neither
4166 * none nor extern) */
4167 if (entity->kind == ENTITY_FUNCTION) {
4168 /* the previous declaration could have unspecified parameters or
4169 * be a typedef, so use the new type */
4170 if (prev_type->function.unspecified_parameters || is_definition)
4171 prev_decl->type = type;
4173 switch (old_storage_class) {
4174 case STORAGE_CLASS_NONE:
4175 old_storage_class = STORAGE_CLASS_EXTERN;
4178 case STORAGE_CLASS_EXTERN:
4179 if (is_definition) {
4180 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4181 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4183 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4184 new_storage_class = STORAGE_CLASS_EXTERN;
4191 } else if (is_type_incomplete(prev_type)) {
4192 prev_decl->type = type;
4195 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4196 new_storage_class == STORAGE_CLASS_EXTERN) {
4198 warn_redundant_declaration: ;
4200 = has_new_attributes(prev_decl->attributes,
4202 if (has_new_attrs) {
4203 merge_in_attributes(decl, prev_decl->attributes);
4204 } else if (!is_definition &&
4205 is_type_valid(prev_type) &&
4206 !pos->is_system_header) {
4207 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4209 } else if (current_function == NULL) {
4210 if (old_storage_class != STORAGE_CLASS_STATIC &&
4211 new_storage_class == STORAGE_CLASS_STATIC) {
4212 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4213 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4214 prev_decl->storage_class = STORAGE_CLASS_NONE;
4215 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4217 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4219 goto error_redeclaration;
4220 goto warn_redundant_declaration;
4222 } else if (is_type_valid(prev_type)) {
4223 if (old_storage_class == new_storage_class) {
4224 error_redeclaration:
4225 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4227 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4232 prev_decl->modifiers |= decl->modifiers;
4233 if (entity->kind == ENTITY_FUNCTION) {
4234 previous_entity->function.is_inline |= entity->function.is_inline;
4236 return previous_entity;
4240 if (is_warn_on(why = WARN_SHADOW) ||
4241 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4242 char const *const what = get_entity_kind_name(previous_entity->kind);
4243 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4247 if (entity->kind == ENTITY_FUNCTION) {
4248 if (is_definition &&
4249 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4250 !is_sym_main(symbol)) {
4251 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4252 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4254 goto warn_missing_declaration;
4257 } else if (entity->kind == ENTITY_VARIABLE) {
4258 if (current_scope == file_scope &&
4259 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4260 !entity->declaration.implicit) {
4261 warn_missing_declaration:
4262 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4267 assert(entity->base.parent_scope == NULL);
4268 assert(current_scope != NULL);
4270 entity->base.parent_scope = current_scope;
4271 environment_push(entity);
4272 append_entity(current_scope, entity);
4277 static void parser_error_multiple_definition(entity_t *entity,
4278 const source_position_t *source_position)
4280 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4281 entity->base.symbol, &entity->base.source_position);
4284 static bool is_declaration_specifier(const token_t *token)
4286 switch (token->kind) {
4290 return is_typedef_symbol(token->identifier.symbol);
4297 static void parse_init_declarator_rest(entity_t *entity)
4299 type_t *orig_type = type_error_type;
4301 if (entity->base.kind == ENTITY_TYPEDEF) {
4302 source_position_t const *const pos = &entity->base.source_position;
4303 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4305 assert(is_declaration(entity));
4306 orig_type = entity->declaration.type;
4309 type_t *type = skip_typeref(orig_type);
4311 if (entity->kind == ENTITY_VARIABLE
4312 && entity->variable.initializer != NULL) {
4313 parser_error_multiple_definition(entity, HERE);
4317 declaration_t *const declaration = &entity->declaration;
4318 bool must_be_constant = false;
4319 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4320 entity->base.parent_scope == file_scope) {
4321 must_be_constant = true;
4324 if (is_type_function(type)) {
4325 source_position_t const *const pos = &entity->base.source_position;
4326 errorf(pos, "'%N' is initialized like a variable", entity);
4327 orig_type = type_error_type;
4330 parse_initializer_env_t env;
4331 env.type = orig_type;
4332 env.must_be_constant = must_be_constant;
4333 env.entity = entity;
4335 initializer_t *initializer = parse_initializer(&env);
4337 if (entity->kind == ENTITY_VARIABLE) {
4338 /* §6.7.5:22 array initializers for arrays with unknown size
4339 * determine the array type size */
4340 declaration->type = env.type;
4341 entity->variable.initializer = initializer;
4345 /* parse rest of a declaration without any declarator */
4346 static void parse_anonymous_declaration_rest(
4347 const declaration_specifiers_t *specifiers)
4350 anonymous_entity = NULL;
4352 source_position_t const *const pos = &specifiers->source_position;
4353 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4354 specifiers->thread_local) {
4355 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4358 type_t *type = specifiers->type;
4359 switch (type->kind) {
4360 case TYPE_COMPOUND_STRUCT:
4361 case TYPE_COMPOUND_UNION: {
4362 if (type->compound.compound->base.symbol == NULL) {
4363 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4372 warningf(WARN_OTHER, pos, "empty declaration");
4377 static void check_variable_type_complete(entity_t *ent)
4379 if (ent->kind != ENTITY_VARIABLE)
4382 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4383 * type for the object shall be complete [...] */
4384 declaration_t *decl = &ent->declaration;
4385 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4386 decl->storage_class == STORAGE_CLASS_STATIC)
4389 type_t *const type = skip_typeref(decl->type);
4390 if (!is_type_incomplete(type))
4393 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4394 * are given length one. */
4395 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4396 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4400 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4404 static void parse_declaration_rest(entity_t *ndeclaration,
4405 const declaration_specifiers_t *specifiers,
4406 parsed_declaration_func finished_declaration,
4407 declarator_flags_t flags)
4409 add_anchor_token(';');
4410 add_anchor_token(',');
4412 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4414 if (token.kind == '=') {
4415 parse_init_declarator_rest(entity);
4416 } else if (entity->kind == ENTITY_VARIABLE) {
4417 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4418 * [...] where the extern specifier is explicitly used. */
4419 declaration_t *decl = &entity->declaration;
4420 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4421 type_t *type = decl->type;
4422 if (is_type_reference(skip_typeref(type))) {
4423 source_position_t const *const pos = &entity->base.source_position;
4424 errorf(pos, "reference '%#N' must be initialized", entity);
4429 check_variable_type_complete(entity);
4434 add_anchor_token('=');
4435 ndeclaration = parse_declarator(specifiers, flags);
4436 rem_anchor_token('=');
4438 expect(';', end_error);
4441 anonymous_entity = NULL;
4442 rem_anchor_token(';');
4443 rem_anchor_token(',');
4446 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4448 symbol_t *symbol = entity->base.symbol;
4452 assert(entity->base.namespc == NAMESPACE_NORMAL);
4453 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4454 if (previous_entity == NULL
4455 || previous_entity->base.parent_scope != current_scope) {
4456 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4461 if (is_definition) {
4462 errorf(HERE, "'%N' is initialised", entity);
4465 return record_entity(entity, false);
4468 static void parse_declaration(parsed_declaration_func finished_declaration,
4469 declarator_flags_t flags)
4471 add_anchor_token(';');
4472 declaration_specifiers_t specifiers;
4473 parse_declaration_specifiers(&specifiers);
4474 rem_anchor_token(';');
4476 if (token.kind == ';') {
4477 parse_anonymous_declaration_rest(&specifiers);
4479 entity_t *entity = parse_declarator(&specifiers, flags);
4480 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4485 static type_t *get_default_promoted_type(type_t *orig_type)
4487 type_t *result = orig_type;
4489 type_t *type = skip_typeref(orig_type);
4490 if (is_type_integer(type)) {
4491 result = promote_integer(type);
4492 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4493 result = type_double;
4499 static void parse_kr_declaration_list(entity_t *entity)
4501 if (entity->kind != ENTITY_FUNCTION)
4504 type_t *type = skip_typeref(entity->declaration.type);
4505 assert(is_type_function(type));
4506 if (!type->function.kr_style_parameters)
4509 add_anchor_token('{');
4511 PUSH_SCOPE(&entity->function.parameters);
4513 entity_t *parameter = entity->function.parameters.entities;
4514 for ( ; parameter != NULL; parameter = parameter->base.next) {
4515 assert(parameter->base.parent_scope == NULL);
4516 parameter->base.parent_scope = current_scope;
4517 environment_push(parameter);
4520 /* parse declaration list */
4522 switch (token.kind) {
4524 /* This covers symbols, which are no type, too, and results in
4525 * better error messages. The typical cases are misspelled type
4526 * names and missing includes. */
4528 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4538 /* update function type */
4539 type_t *new_type = duplicate_type(type);
4541 function_parameter_t *parameters = NULL;
4542 function_parameter_t **anchor = ¶meters;
4544 /* did we have an earlier prototype? */
4545 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4546 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4549 function_parameter_t *proto_parameter = NULL;
4550 if (proto_type != NULL) {
4551 type_t *proto_type_type = proto_type->declaration.type;
4552 proto_parameter = proto_type_type->function.parameters;
4553 /* If a K&R function definition has a variadic prototype earlier, then
4554 * make the function definition variadic, too. This should conform to
4555 * §6.7.5.3:15 and §6.9.1:8. */
4556 new_type->function.variadic = proto_type_type->function.variadic;
4558 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4560 new_type->function.unspecified_parameters = true;
4563 bool need_incompatible_warning = false;
4564 parameter = entity->function.parameters.entities;
4565 for (; parameter != NULL; parameter = parameter->base.next,
4567 proto_parameter == NULL ? NULL : proto_parameter->next) {
4568 if (parameter->kind != ENTITY_PARAMETER)
4571 type_t *parameter_type = parameter->declaration.type;
4572 if (parameter_type == NULL) {
4573 source_position_t const* const pos = ¶meter->base.source_position;
4575 errorf(pos, "no type specified for function '%N'", parameter);
4576 parameter_type = type_error_type;
4578 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4579 parameter_type = type_int;
4581 parameter->declaration.type = parameter_type;
4584 semantic_parameter_incomplete(parameter);
4586 /* we need the default promoted types for the function type */
4587 type_t *not_promoted = parameter_type;
4588 parameter_type = get_default_promoted_type(parameter_type);
4590 /* gcc special: if the type of the prototype matches the unpromoted
4591 * type don't promote */
4592 if (!strict_mode && proto_parameter != NULL) {
4593 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4594 type_t *promo_skip = skip_typeref(parameter_type);
4595 type_t *param_skip = skip_typeref(not_promoted);
4596 if (!types_compatible(proto_p_type, promo_skip)
4597 && types_compatible(proto_p_type, param_skip)) {
4599 need_incompatible_warning = true;
4600 parameter_type = not_promoted;
4603 function_parameter_t *const function_parameter
4604 = allocate_parameter(parameter_type);
4606 *anchor = function_parameter;
4607 anchor = &function_parameter->next;
4610 new_type->function.parameters = parameters;
4611 new_type = identify_new_type(new_type);
4613 if (need_incompatible_warning) {
4614 symbol_t const *const sym = entity->base.symbol;
4615 source_position_t const *const pos = &entity->base.source_position;
4616 source_position_t const *const ppos = &proto_type->base.source_position;
4617 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4619 entity->declaration.type = new_type;
4621 rem_anchor_token('{');
4624 static bool first_err = true;
4627 * When called with first_err set, prints the name of the current function,
4630 static void print_in_function(void)
4634 char const *const file = current_function->base.base.source_position.input_name;
4635 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4640 * Check if all labels are defined in the current function.
4641 * Check if all labels are used in the current function.
4643 static void check_labels(void)
4645 for (const goto_statement_t *goto_statement = goto_first;
4646 goto_statement != NULL;
4647 goto_statement = goto_statement->next) {
4648 /* skip computed gotos */
4649 if (goto_statement->expression != NULL)
4652 label_t *label = goto_statement->label;
4653 if (label->base.source_position.input_name == NULL) {
4654 print_in_function();
4655 source_position_t const *const pos = &goto_statement->base.source_position;
4656 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4660 if (is_warn_on(WARN_UNUSED_LABEL)) {
4661 for (const label_statement_t *label_statement = label_first;
4662 label_statement != NULL;
4663 label_statement = label_statement->next) {
4664 label_t *label = label_statement->label;
4666 if (! label->used) {
4667 print_in_function();
4668 source_position_t const *const pos = &label_statement->base.source_position;
4669 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4675 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4677 entity_t const *const end = last != NULL ? last->base.next : NULL;
4678 for (; entity != end; entity = entity->base.next) {
4679 if (!is_declaration(entity))
4682 declaration_t *declaration = &entity->declaration;
4683 if (declaration->implicit)
4686 if (!declaration->used) {
4687 print_in_function();
4688 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4689 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4690 print_in_function();
4691 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4696 static void check_unused_variables(statement_t *const stmt, void *const env)
4700 switch (stmt->kind) {
4701 case STATEMENT_DECLARATION: {
4702 declaration_statement_t const *const decls = &stmt->declaration;
4703 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4708 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4717 * Check declarations of current_function for unused entities.
4719 static void check_declarations(void)
4721 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4722 const scope_t *scope = ¤t_function->parameters;
4724 /* do not issue unused warnings for main */
4725 if (!is_sym_main(current_function->base.base.symbol)) {
4726 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4729 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4730 walk_statements(current_function->statement, check_unused_variables,
4735 static int determine_truth(expression_t const* const cond)
4738 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4739 fold_constant_to_bool(cond) ? 1 :
4743 static void check_reachable(statement_t *);
4744 static bool reaches_end;
4746 static bool expression_returns(expression_t const *const expr)
4748 switch (expr->kind) {
4750 expression_t const *const func = expr->call.function;
4751 if (func->kind == EXPR_REFERENCE) {
4752 entity_t *entity = func->reference.entity;
4753 if (entity->kind == ENTITY_FUNCTION
4754 && entity->declaration.modifiers & DM_NORETURN)
4758 if (!expression_returns(func))
4761 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4762 if (!expression_returns(arg->expression))
4769 case EXPR_REFERENCE:
4770 case EXPR_REFERENCE_ENUM_VALUE:
4772 case EXPR_STRING_LITERAL:
4773 case EXPR_WIDE_STRING_LITERAL:
4774 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4775 case EXPR_LABEL_ADDRESS:
4776 case EXPR_CLASSIFY_TYPE:
4777 case EXPR_SIZEOF: // TODO handle obscure VLA case
4780 case EXPR_BUILTIN_CONSTANT_P:
4781 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4786 case EXPR_STATEMENT: {
4787 bool old_reaches_end = reaches_end;
4788 reaches_end = false;
4789 check_reachable(expr->statement.statement);
4790 bool returns = reaches_end;
4791 reaches_end = old_reaches_end;
4795 case EXPR_CONDITIONAL:
4796 // TODO handle constant expression
4798 if (!expression_returns(expr->conditional.condition))
4801 if (expr->conditional.true_expression != NULL
4802 && expression_returns(expr->conditional.true_expression))
4805 return expression_returns(expr->conditional.false_expression);
4808 return expression_returns(expr->select.compound);
4810 case EXPR_ARRAY_ACCESS:
4812 expression_returns(expr->array_access.array_ref) &&
4813 expression_returns(expr->array_access.index);
4816 return expression_returns(expr->va_starte.ap);
4819 return expression_returns(expr->va_arge.ap);
4822 return expression_returns(expr->va_copye.src);
4824 EXPR_UNARY_CASES_MANDATORY
4825 return expression_returns(expr->unary.value);
4827 case EXPR_UNARY_THROW:
4831 // TODO handle constant lhs of && and ||
4833 expression_returns(expr->binary.left) &&
4834 expression_returns(expr->binary.right);
4837 panic("unhandled expression");
4840 static bool initializer_returns(initializer_t const *const init)
4842 switch (init->kind) {
4843 case INITIALIZER_VALUE:
4844 return expression_returns(init->value.value);
4846 case INITIALIZER_LIST: {
4847 initializer_t * const* i = init->list.initializers;
4848 initializer_t * const* const end = i + init->list.len;
4849 bool returns = true;
4850 for (; i != end; ++i) {
4851 if (!initializer_returns(*i))
4857 case INITIALIZER_STRING:
4858 case INITIALIZER_WIDE_STRING:
4859 case INITIALIZER_DESIGNATOR: // designators have no payload
4862 panic("unhandled initializer");
4865 static bool noreturn_candidate;
4867 static void check_reachable(statement_t *const stmt)
4869 if (stmt->base.reachable)
4871 if (stmt->kind != STATEMENT_DO_WHILE)
4872 stmt->base.reachable = true;
4874 statement_t *last = stmt;
4876 switch (stmt->kind) {
4877 case STATEMENT_ERROR:
4878 case STATEMENT_EMPTY:
4880 next = stmt->base.next;
4883 case STATEMENT_DECLARATION: {
4884 declaration_statement_t const *const decl = &stmt->declaration;
4885 entity_t const * ent = decl->declarations_begin;
4886 entity_t const *const last_decl = decl->declarations_end;
4888 for (;; ent = ent->base.next) {
4889 if (ent->kind == ENTITY_VARIABLE &&
4890 ent->variable.initializer != NULL &&
4891 !initializer_returns(ent->variable.initializer)) {
4894 if (ent == last_decl)
4898 next = stmt->base.next;
4902 case STATEMENT_COMPOUND:
4903 next = stmt->compound.statements;
4905 next = stmt->base.next;
4908 case STATEMENT_RETURN: {
4909 expression_t const *const val = stmt->returns.value;
4910 if (val == NULL || expression_returns(val))
4911 noreturn_candidate = false;
4915 case STATEMENT_IF: {
4916 if_statement_t const *const ifs = &stmt->ifs;
4917 expression_t const *const cond = ifs->condition;
4919 if (!expression_returns(cond))
4922 int const val = determine_truth(cond);
4925 check_reachable(ifs->true_statement);
4930 if (ifs->false_statement != NULL) {
4931 check_reachable(ifs->false_statement);
4935 next = stmt->base.next;
4939 case STATEMENT_SWITCH: {
4940 switch_statement_t const *const switchs = &stmt->switchs;
4941 expression_t const *const expr = switchs->expression;
4943 if (!expression_returns(expr))
4946 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4947 long const val = fold_constant_to_int(expr);
4948 case_label_statement_t * defaults = NULL;
4949 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4950 if (i->expression == NULL) {
4955 if (i->first_case <= val && val <= i->last_case) {
4956 check_reachable((statement_t*)i);
4961 if (defaults != NULL) {
4962 check_reachable((statement_t*)defaults);
4966 bool has_default = false;
4967 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4968 if (i->expression == NULL)
4971 check_reachable((statement_t*)i);
4978 next = stmt->base.next;
4982 case STATEMENT_EXPRESSION: {
4983 /* Check for noreturn function call */
4984 expression_t const *const expr = stmt->expression.expression;
4985 if (!expression_returns(expr))
4988 next = stmt->base.next;
4992 case STATEMENT_CONTINUE:
4993 for (statement_t *parent = stmt;;) {
4994 parent = parent->base.parent;
4995 if (parent == NULL) /* continue not within loop */
4999 switch (parent->kind) {
5000 case STATEMENT_WHILE: goto continue_while;
5001 case STATEMENT_DO_WHILE: goto continue_do_while;
5002 case STATEMENT_FOR: goto continue_for;
5008 case STATEMENT_BREAK:
5009 for (statement_t *parent = stmt;;) {
5010 parent = parent->base.parent;
5011 if (parent == NULL) /* break not within loop/switch */
5014 switch (parent->kind) {
5015 case STATEMENT_SWITCH:
5016 case STATEMENT_WHILE:
5017 case STATEMENT_DO_WHILE:
5020 next = parent->base.next;
5021 goto found_break_parent;
5029 case STATEMENT_GOTO:
5030 if (stmt->gotos.expression) {
5031 if (!expression_returns(stmt->gotos.expression))
5034 statement_t *parent = stmt->base.parent;
5035 if (parent == NULL) /* top level goto */
5039 next = stmt->gotos.label->statement;
5040 if (next == NULL) /* missing label */
5045 case STATEMENT_LABEL:
5046 next = stmt->label.statement;
5049 case STATEMENT_CASE_LABEL:
5050 next = stmt->case_label.statement;
5053 case STATEMENT_WHILE: {
5054 while_statement_t const *const whiles = &stmt->whiles;
5055 expression_t const *const cond = whiles->condition;
5057 if (!expression_returns(cond))
5060 int const val = determine_truth(cond);
5063 check_reachable(whiles->body);
5068 next = stmt->base.next;
5072 case STATEMENT_DO_WHILE:
5073 next = stmt->do_while.body;
5076 case STATEMENT_FOR: {
5077 for_statement_t *const fors = &stmt->fors;
5079 if (fors->condition_reachable)
5081 fors->condition_reachable = true;
5083 expression_t const *const cond = fors->condition;
5088 } else if (expression_returns(cond)) {
5089 val = determine_truth(cond);
5095 check_reachable(fors->body);
5100 next = stmt->base.next;
5104 case STATEMENT_MS_TRY: {
5105 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5106 check_reachable(ms_try->try_statement);
5107 next = ms_try->final_statement;
5111 case STATEMENT_LEAVE: {
5112 statement_t *parent = stmt;
5114 parent = parent->base.parent;
5115 if (parent == NULL) /* __leave not within __try */
5118 if (parent->kind == STATEMENT_MS_TRY) {
5120 next = parent->ms_try.final_statement;
5128 panic("invalid statement kind");
5131 while (next == NULL) {
5132 next = last->base.parent;
5134 noreturn_candidate = false;
5136 type_t *const type = skip_typeref(current_function->base.type);
5137 assert(is_type_function(type));
5138 type_t *const ret = skip_typeref(type->function.return_type);
5139 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5140 is_type_valid(ret) &&
5141 !is_sym_main(current_function->base.base.symbol)) {
5142 source_position_t const *const pos = &stmt->base.source_position;
5143 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5148 switch (next->kind) {
5149 case STATEMENT_ERROR:
5150 case STATEMENT_EMPTY:
5151 case STATEMENT_DECLARATION:
5152 case STATEMENT_EXPRESSION:
5154 case STATEMENT_RETURN:
5155 case STATEMENT_CONTINUE:
5156 case STATEMENT_BREAK:
5157 case STATEMENT_GOTO:
5158 case STATEMENT_LEAVE:
5159 panic("invalid control flow in function");
5161 case STATEMENT_COMPOUND:
5162 if (next->compound.stmt_expr) {
5168 case STATEMENT_SWITCH:
5169 case STATEMENT_LABEL:
5170 case STATEMENT_CASE_LABEL:
5172 next = next->base.next;
5175 case STATEMENT_WHILE: {
5177 if (next->base.reachable)
5179 next->base.reachable = true;
5181 while_statement_t const *const whiles = &next->whiles;
5182 expression_t const *const cond = whiles->condition;
5184 if (!expression_returns(cond))
5187 int const val = determine_truth(cond);
5190 check_reachable(whiles->body);
5196 next = next->base.next;
5200 case STATEMENT_DO_WHILE: {
5202 if (next->base.reachable)
5204 next->base.reachable = true;
5206 do_while_statement_t const *const dw = &next->do_while;
5207 expression_t const *const cond = dw->condition;
5209 if (!expression_returns(cond))
5212 int const val = determine_truth(cond);
5215 check_reachable(dw->body);
5221 next = next->base.next;
5225 case STATEMENT_FOR: {
5227 for_statement_t *const fors = &next->fors;
5229 fors->step_reachable = true;
5231 if (fors->condition_reachable)
5233 fors->condition_reachable = true;
5235 expression_t const *const cond = fors->condition;
5240 } else if (expression_returns(cond)) {
5241 val = determine_truth(cond);
5247 check_reachable(fors->body);
5253 next = next->base.next;
5257 case STATEMENT_MS_TRY:
5259 next = next->ms_try.final_statement;
5264 check_reachable(next);
5267 static void check_unreachable(statement_t* const stmt, void *const env)
5271 switch (stmt->kind) {
5272 case STATEMENT_DO_WHILE:
5273 if (!stmt->base.reachable) {
5274 expression_t const *const cond = stmt->do_while.condition;
5275 if (determine_truth(cond) >= 0) {
5276 source_position_t const *const pos = &cond->base.source_position;
5277 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5282 case STATEMENT_FOR: {
5283 for_statement_t const* const fors = &stmt->fors;
5285 // if init and step are unreachable, cond is unreachable, too
5286 if (!stmt->base.reachable && !fors->step_reachable) {
5287 goto warn_unreachable;
5289 if (!stmt->base.reachable && fors->initialisation != NULL) {
5290 source_position_t const *const pos = &fors->initialisation->base.source_position;
5291 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5294 if (!fors->condition_reachable && fors->condition != NULL) {
5295 source_position_t const *const pos = &fors->condition->base.source_position;
5296 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5299 if (!fors->step_reachable && fors->step != NULL) {
5300 source_position_t const *const pos = &fors->step->base.source_position;
5301 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5307 case STATEMENT_COMPOUND:
5308 if (stmt->compound.statements != NULL)
5310 goto warn_unreachable;
5312 case STATEMENT_DECLARATION: {
5313 /* Only warn if there is at least one declarator with an initializer.
5314 * This typically occurs in switch statements. */
5315 declaration_statement_t const *const decl = &stmt->declaration;
5316 entity_t const * ent = decl->declarations_begin;
5317 entity_t const *const last = decl->declarations_end;
5319 for (;; ent = ent->base.next) {
5320 if (ent->kind == ENTITY_VARIABLE &&
5321 ent->variable.initializer != NULL) {
5322 goto warn_unreachable;
5332 if (!stmt->base.reachable) {
5333 source_position_t const *const pos = &stmt->base.source_position;
5334 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5340 static void parse_external_declaration(void)
5342 /* function-definitions and declarations both start with declaration
5344 add_anchor_token(';');
5345 declaration_specifiers_t specifiers;
5346 parse_declaration_specifiers(&specifiers);
5347 rem_anchor_token(';');
5349 /* must be a declaration */
5350 if (token.kind == ';') {
5351 parse_anonymous_declaration_rest(&specifiers);
5355 add_anchor_token(',');
5356 add_anchor_token('=');
5357 add_anchor_token(';');
5358 add_anchor_token('{');
5360 /* declarator is common to both function-definitions and declarations */
5361 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5363 rem_anchor_token('{');
5364 rem_anchor_token(';');
5365 rem_anchor_token('=');
5366 rem_anchor_token(',');
5368 /* must be a declaration */
5369 switch (token.kind) {
5373 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5378 /* must be a function definition */
5379 parse_kr_declaration_list(ndeclaration);
5381 if (token.kind != '{') {
5382 parse_error_expected("while parsing function definition", '{', NULL);
5383 eat_until_matching_token(';');
5387 assert(is_declaration(ndeclaration));
5388 type_t *const orig_type = ndeclaration->declaration.type;
5389 type_t * type = skip_typeref(orig_type);
5391 if (!is_type_function(type)) {
5392 if (is_type_valid(type)) {
5393 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5399 source_position_t const *const pos = &ndeclaration->base.source_position;
5400 if (is_typeref(orig_type)) {
5402 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5405 if (is_type_compound(skip_typeref(type->function.return_type))) {
5406 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5408 if (type->function.unspecified_parameters) {
5409 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5411 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5414 /* §6.7.5.3:14 a function definition with () means no
5415 * parameters (and not unspecified parameters) */
5416 if (type->function.unspecified_parameters &&
5417 type->function.parameters == NULL) {
5418 type_t *copy = duplicate_type(type);
5419 copy->function.unspecified_parameters = false;
5420 type = identify_new_type(copy);
5422 ndeclaration->declaration.type = type;
5425 entity_t *const entity = record_entity(ndeclaration, true);
5426 assert(entity->kind == ENTITY_FUNCTION);
5427 assert(ndeclaration->kind == ENTITY_FUNCTION);
5429 function_t *const function = &entity->function;
5430 if (ndeclaration != entity) {
5431 function->parameters = ndeclaration->function.parameters;
5433 assert(is_declaration(entity));
5434 type = skip_typeref(entity->declaration.type);
5436 PUSH_SCOPE(&function->parameters);
5438 entity_t *parameter = function->parameters.entities;
5439 for (; parameter != NULL; parameter = parameter->base.next) {
5440 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5441 parameter->base.parent_scope = current_scope;
5443 assert(parameter->base.parent_scope == NULL
5444 || parameter->base.parent_scope == current_scope);
5445 parameter->base.parent_scope = current_scope;
5446 if (parameter->base.symbol == NULL) {
5447 errorf(¶meter->base.source_position, "parameter name omitted");
5450 environment_push(parameter);
5453 if (function->statement != NULL) {
5454 parser_error_multiple_definition(entity, HERE);
5457 /* parse function body */
5458 int label_stack_top = label_top();
5459 function_t *old_current_function = current_function;
5460 entity_t *old_current_entity = current_entity;
5461 current_function = function;
5462 current_entity = entity;
5466 goto_anchor = &goto_first;
5468 label_anchor = &label_first;
5470 statement_t *const body = parse_compound_statement(false);
5471 function->statement = body;
5474 check_declarations();
5475 if (is_warn_on(WARN_RETURN_TYPE) ||
5476 is_warn_on(WARN_UNREACHABLE_CODE) ||
5477 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5478 noreturn_candidate = true;
5479 check_reachable(body);
5480 if (is_warn_on(WARN_UNREACHABLE_CODE))
5481 walk_statements(body, check_unreachable, NULL);
5482 if (noreturn_candidate &&
5483 !(function->base.modifiers & DM_NORETURN)) {
5484 source_position_t const *const pos = &body->base.source_position;
5485 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5490 assert(current_function == function);
5491 assert(current_entity == entity);
5492 current_entity = old_current_entity;
5493 current_function = old_current_function;
5494 label_pop_to(label_stack_top);
5500 static entity_t *find_compound_entry(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 if (iter->base.symbol == symbol) {
5509 } else if (iter->base.symbol == NULL) {
5510 /* search in anonymous structs and unions */
5511 type_t *type = skip_typeref(iter->declaration.type);
5512 if (is_type_compound(type)) {
5513 if (find_compound_entry(type->compound.compound, symbol)
5524 static void check_deprecated(const source_position_t *source_position,
5525 const entity_t *entity)
5527 if (!is_declaration(entity))
5529 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5532 source_position_t const *const epos = &entity->base.source_position;
5533 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5535 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5537 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5542 static expression_t *create_select(const source_position_t *pos,
5544 type_qualifiers_t qualifiers,
5547 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5549 check_deprecated(pos, entry);
5551 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5552 select->select.compound = addr;
5553 select->select.compound_entry = entry;
5555 type_t *entry_type = entry->declaration.type;
5556 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5558 /* bitfields need special treatment */
5559 if (entry->compound_member.bitfield) {
5560 unsigned bit_size = entry->compound_member.bit_size;
5561 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5562 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5563 res_type = type_int;
5567 /* we always do the auto-type conversions; the & and sizeof parser contains
5568 * code to revert this! */
5569 select->base.type = automatic_type_conversion(res_type);
5576 * Find entry with symbol in compound. Search anonymous structs and unions and
5577 * creates implicit select expressions for them.
5578 * Returns the adress for the innermost compound.
5580 static expression_t *find_create_select(const source_position_t *pos,
5582 type_qualifiers_t qualifiers,
5583 compound_t *compound, symbol_t *symbol)
5585 entity_t *iter = compound->members.entities;
5586 for (; iter != NULL; iter = iter->base.next) {
5587 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5590 symbol_t *iter_symbol = iter->base.symbol;
5591 if (iter_symbol == NULL) {
5592 type_t *type = iter->declaration.type;
5593 if (type->kind != TYPE_COMPOUND_STRUCT
5594 && type->kind != TYPE_COMPOUND_UNION)
5597 compound_t *sub_compound = type->compound.compound;
5599 if (find_compound_entry(sub_compound, symbol) == NULL)
5602 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5603 sub_addr->base.source_position = *pos;
5604 sub_addr->base.implicit = true;
5605 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5609 if (iter_symbol == symbol) {
5610 return create_select(pos, addr, qualifiers, iter);
5617 static void parse_bitfield_member(entity_t *entity)
5621 expression_t *size = parse_constant_expression();
5624 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5625 type_t *type = entity->declaration.type;
5626 if (!is_type_integer(skip_typeref(type))) {
5627 errorf(HERE, "bitfield base type '%T' is not an integer type",
5631 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5632 /* error already reported by parse_constant_expression */
5633 size_long = get_type_size(type) * 8;
5635 size_long = fold_constant_to_int(size);
5637 const symbol_t *symbol = entity->base.symbol;
5638 const symbol_t *user_symbol
5639 = symbol == NULL ? sym_anonymous : symbol;
5640 unsigned bit_size = get_type_size(type) * 8;
5641 if (size_long < 0) {
5642 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5643 } else if (size_long == 0 && symbol != NULL) {
5644 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5645 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5646 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5649 /* hope that people don't invent crazy types with more bits
5650 * than our struct can hold */
5652 (1 << sizeof(entity->compound_member.bit_size)*8));
5656 entity->compound_member.bitfield = true;
5657 entity->compound_member.bit_size = (unsigned char)size_long;
5660 static void parse_compound_declarators(compound_t *compound,
5661 const declaration_specifiers_t *specifiers)
5666 if (token.kind == ':') {
5667 /* anonymous bitfield */
5668 type_t *type = specifiers->type;
5669 entity_t *entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER,
5670 NAMESPACE_NORMAL, NULL);
5671 entity->base.source_position = *HERE;
5672 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5673 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5674 entity->declaration.type = type;
5676 parse_bitfield_member(entity);
5678 attribute_t *attributes = parse_attributes(NULL);
5679 attribute_t **anchor = &attributes;
5680 while (*anchor != NULL)
5681 anchor = &(*anchor)->next;
5682 *anchor = specifiers->attributes;
5683 if (attributes != NULL) {
5684 handle_entity_attributes(attributes, entity);
5686 entity->declaration.attributes = attributes;
5688 append_entity(&compound->members, entity);
5690 entity = parse_declarator(specifiers,
5691 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5692 source_position_t const *const pos = &entity->base.source_position;
5693 if (entity->kind == ENTITY_TYPEDEF) {
5694 errorf(pos, "typedef not allowed as compound member");
5696 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5698 /* make sure we don't define a symbol multiple times */
5699 symbol_t *symbol = entity->base.symbol;
5700 if (symbol != NULL) {
5701 entity_t *prev = find_compound_entry(compound, symbol);
5703 source_position_t const *const ppos = &prev->base.source_position;
5704 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5708 if (token.kind == ':') {
5709 parse_bitfield_member(entity);
5711 attribute_t *attributes = parse_attributes(NULL);
5712 handle_entity_attributes(attributes, entity);
5714 type_t *orig_type = entity->declaration.type;
5715 type_t *type = skip_typeref(orig_type);
5716 if (is_type_function(type)) {
5717 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5718 } else if (is_type_incomplete(type)) {
5719 /* §6.7.2.1:16 flexible array member */
5720 if (!is_type_array(type) ||
5721 token.kind != ';' ||
5722 look_ahead(1)->kind != '}') {
5723 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5728 append_entity(&compound->members, entity);
5731 } while (next_if(','));
5732 expect(';', end_error);
5735 anonymous_entity = NULL;
5738 static void parse_compound_type_entries(compound_t *compound)
5741 add_anchor_token('}');
5744 switch (token.kind) {
5746 case T___extension__:
5747 case T_IDENTIFIER: {
5749 declaration_specifiers_t specifiers;
5750 parse_declaration_specifiers(&specifiers);
5751 parse_compound_declarators(compound, &specifiers);
5757 rem_anchor_token('}');
5758 expect('}', end_error);
5761 compound->complete = true;
5767 static type_t *parse_typename(void)
5769 declaration_specifiers_t specifiers;
5770 parse_declaration_specifiers(&specifiers);
5771 if (specifiers.storage_class != STORAGE_CLASS_NONE
5772 || specifiers.thread_local) {
5773 /* TODO: improve error message, user does probably not know what a
5774 * storage class is...
5776 errorf(&specifiers.source_position, "typename must not have a storage class");
5779 type_t *result = parse_abstract_declarator(specifiers.type);
5787 typedef expression_t* (*parse_expression_function)(void);
5788 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5790 typedef struct expression_parser_function_t expression_parser_function_t;
5791 struct expression_parser_function_t {
5792 parse_expression_function parser;
5793 precedence_t infix_precedence;
5794 parse_expression_infix_function infix_parser;
5797 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5800 * Prints an error message if an expression was expected but not read
5802 static expression_t *expected_expression_error(void)
5804 /* skip the error message if the error token was read */
5805 if (token.kind != T_ERROR) {
5806 errorf(HERE, "expected expression, got token %K", &token);
5810 return create_error_expression();
5813 static type_t *get_string_type(void)
5815 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5818 static type_t *get_wide_string_type(void)
5820 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5824 * Parse a string constant.
5826 static expression_t *parse_string_literal(void)
5828 source_position_t begin = token.base.source_position;
5829 string_t res = token.string.string;
5830 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5833 while (token.kind == T_STRING_LITERAL
5834 || token.kind == T_WIDE_STRING_LITERAL) {
5835 warn_string_concat(&token.base.source_position);
5836 res = concat_strings(&res, &token.string.string);
5838 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5841 expression_t *literal;
5843 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5844 literal->base.type = get_wide_string_type();
5846 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5847 literal->base.type = get_string_type();
5849 literal->base.source_position = begin;
5850 literal->literal.value = res;
5856 * Parse a boolean constant.
5858 static expression_t *parse_boolean_literal(bool value)
5860 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5861 literal->base.type = type_bool;
5862 literal->literal.value.begin = value ? "true" : "false";
5863 literal->literal.value.size = value ? 4 : 5;
5869 static void warn_traditional_suffix(void)
5871 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5872 &token.number.suffix);
5875 static void check_integer_suffix(void)
5877 const string_t *suffix = &token.number.suffix;
5878 if (suffix->size == 0)
5881 bool not_traditional = false;
5882 const char *c = suffix->begin;
5883 if (*c == 'l' || *c == 'L') {
5886 not_traditional = true;
5888 if (*c == 'u' || *c == 'U') {
5891 } else if (*c == 'u' || *c == 'U') {
5892 not_traditional = true;
5895 } else if (*c == 'u' || *c == 'U') {
5896 not_traditional = true;
5898 if (*c == 'l' || *c == 'L') {
5906 errorf(&token.base.source_position,
5907 "invalid suffix '%S' on integer constant", suffix);
5908 } else if (not_traditional) {
5909 warn_traditional_suffix();
5913 static type_t *check_floatingpoint_suffix(void)
5915 const string_t *suffix = &token.number.suffix;
5916 type_t *type = type_double;
5917 if (suffix->size == 0)
5920 bool not_traditional = false;
5921 const char *c = suffix->begin;
5922 if (*c == 'f' || *c == 'F') {
5925 } else if (*c == 'l' || *c == 'L') {
5927 type = type_long_double;
5930 errorf(&token.base.source_position,
5931 "invalid suffix '%S' on floatingpoint constant", suffix);
5932 } else if (not_traditional) {
5933 warn_traditional_suffix();
5940 * Parse an integer constant.
5942 static expression_t *parse_number_literal(void)
5944 expression_kind_t kind;
5947 switch (token.kind) {
5949 kind = EXPR_LITERAL_INTEGER;
5950 check_integer_suffix();
5953 case T_INTEGER_OCTAL:
5954 kind = EXPR_LITERAL_INTEGER_OCTAL;
5955 check_integer_suffix();
5958 case T_INTEGER_HEXADECIMAL:
5959 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5960 check_integer_suffix();
5963 case T_FLOATINGPOINT:
5964 kind = EXPR_LITERAL_FLOATINGPOINT;
5965 type = check_floatingpoint_suffix();
5967 case T_FLOATINGPOINT_HEXADECIMAL:
5968 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5969 type = check_floatingpoint_suffix();
5972 panic("unexpected token type in parse_number_literal");
5975 expression_t *literal = allocate_expression_zero(kind);
5976 literal->base.type = type;
5977 literal->literal.value = token.number.number;
5978 literal->literal.suffix = token.number.suffix;
5981 /* integer type depends on the size of the number and the size
5982 * representable by the types. The backend/codegeneration has to determine
5985 determine_literal_type(&literal->literal);
5990 * Parse a character constant.
5992 static expression_t *parse_character_constant(void)
5994 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5995 literal->base.type = c_mode & _CXX ? type_char : type_int;
5996 literal->literal.value = token.string.string;
5998 size_t len = literal->literal.value.size;
6000 if (!GNU_MODE && !(c_mode & _C99)) {
6001 errorf(HERE, "more than 1 character in character constant");
6003 literal->base.type = type_int;
6004 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6013 * Parse a wide character constant.
6015 static expression_t *parse_wide_character_constant(void)
6017 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6018 literal->base.type = type_int;
6019 literal->literal.value = token.string.string;
6021 size_t len = wstrlen(&literal->literal.value);
6023 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6030 static entity_t *create_implicit_function(symbol_t *symbol,
6031 const source_position_t *source_position)
6033 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6034 ntype->function.return_type = type_int;
6035 ntype->function.unspecified_parameters = true;
6036 ntype->function.linkage = LINKAGE_C;
6037 type_t *type = identify_new_type(ntype);
6039 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6040 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6041 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6042 entity->declaration.type = type;
6043 entity->declaration.implicit = true;
6044 entity->base.source_position = *source_position;
6046 if (current_scope != NULL)
6047 record_entity(entity, false);
6053 * Performs automatic type cast as described in §6.3.2.1.
6055 * @param orig_type the original type
6057 static type_t *automatic_type_conversion(type_t *orig_type)
6059 type_t *type = skip_typeref(orig_type);
6060 if (is_type_array(type)) {
6061 array_type_t *array_type = &type->array;
6062 type_t *element_type = array_type->element_type;
6063 unsigned qualifiers = array_type->base.qualifiers;
6065 return make_pointer_type(element_type, qualifiers);
6068 if (is_type_function(type)) {
6069 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6076 * reverts the automatic casts of array to pointer types and function
6077 * to function-pointer types as defined §6.3.2.1
6079 type_t *revert_automatic_type_conversion(const expression_t *expression)
6081 switch (expression->kind) {
6082 case EXPR_REFERENCE: {
6083 entity_t *entity = expression->reference.entity;
6084 if (is_declaration(entity)) {
6085 return entity->declaration.type;
6086 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6087 return entity->enum_value.enum_type;
6089 panic("no declaration or enum in reference");
6094 entity_t *entity = expression->select.compound_entry;
6095 assert(is_declaration(entity));
6096 type_t *type = entity->declaration.type;
6097 return get_qualified_type(type, expression->base.type->base.qualifiers);
6100 case EXPR_UNARY_DEREFERENCE: {
6101 const expression_t *const value = expression->unary.value;
6102 type_t *const type = skip_typeref(value->base.type);
6103 if (!is_type_pointer(type))
6104 return type_error_type;
6105 return type->pointer.points_to;
6108 case EXPR_ARRAY_ACCESS: {
6109 const expression_t *array_ref = expression->array_access.array_ref;
6110 type_t *type_left = skip_typeref(array_ref->base.type);
6111 if (!is_type_pointer(type_left))
6112 return type_error_type;
6113 return type_left->pointer.points_to;
6116 case EXPR_STRING_LITERAL: {
6117 size_t size = expression->string_literal.value.size;
6118 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6121 case EXPR_WIDE_STRING_LITERAL: {
6122 size_t size = wstrlen(&expression->string_literal.value);
6123 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6126 case EXPR_COMPOUND_LITERAL:
6127 return expression->compound_literal.type;
6132 return expression->base.type;
6136 * Find an entity matching a symbol in a scope.
6137 * Uses current scope if scope is NULL
6139 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6140 namespace_tag_t namespc)
6142 if (scope == NULL) {
6143 return get_entity(symbol, namespc);
6146 /* we should optimize here, if scope grows above a certain size we should
6147 construct a hashmap here... */
6148 entity_t *entity = scope->entities;
6149 for ( ; entity != NULL; entity = entity->base.next) {
6150 if (entity->base.symbol == symbol
6151 && (namespace_tag_t)entity->base.namespc == namespc)
6158 static entity_t *parse_qualified_identifier(void)
6160 /* namespace containing the symbol */
6162 source_position_t pos;
6163 const scope_t *lookup_scope = NULL;
6165 if (next_if(T_COLONCOLON))
6166 lookup_scope = &unit->scope;
6170 if (token.kind != T_IDENTIFIER) {
6171 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6172 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6174 symbol = token.identifier.symbol;
6179 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6181 if (!next_if(T_COLONCOLON))
6184 switch (entity->kind) {
6185 case ENTITY_NAMESPACE:
6186 lookup_scope = &entity->namespacee.members;
6191 lookup_scope = &entity->compound.members;
6194 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6195 symbol, get_entity_kind_name(entity->kind));
6197 /* skip further qualifications */
6198 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6200 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6204 if (entity == NULL) {
6205 if (!strict_mode && token.kind == '(') {
6206 /* an implicitly declared function */
6207 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6208 "implicit declaration of function '%Y'", symbol);
6209 entity = create_implicit_function(symbol, &pos);
6211 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6212 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6219 static expression_t *parse_reference(void)
6221 source_position_t const pos = token.base.source_position;
6222 entity_t *const entity = parse_qualified_identifier();
6225 if (is_declaration(entity)) {
6226 orig_type = entity->declaration.type;
6227 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6228 orig_type = entity->enum_value.enum_type;
6230 panic("expected declaration or enum value in reference");
6233 /* we always do the auto-type conversions; the & and sizeof parser contains
6234 * code to revert this! */
6235 type_t *type = automatic_type_conversion(orig_type);
6237 expression_kind_t kind = EXPR_REFERENCE;
6238 if (entity->kind == ENTITY_ENUM_VALUE)
6239 kind = EXPR_REFERENCE_ENUM_VALUE;
6241 expression_t *expression = allocate_expression_zero(kind);
6242 expression->base.source_position = pos;
6243 expression->base.type = type;
6244 expression->reference.entity = entity;
6246 /* this declaration is used */
6247 if (is_declaration(entity)) {
6248 entity->declaration.used = true;
6251 if (entity->base.parent_scope != file_scope
6252 && (current_function != NULL
6253 && entity->base.parent_scope->depth < current_function->parameters.depth)
6254 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6255 if (entity->kind == ENTITY_VARIABLE) {
6256 /* access of a variable from an outer function */
6257 entity->variable.address_taken = true;
6258 } else if (entity->kind == ENTITY_PARAMETER) {
6259 entity->parameter.address_taken = true;
6261 current_function->need_closure = true;
6264 check_deprecated(&pos, entity);
6269 static bool semantic_cast(expression_t *cast)
6271 expression_t *expression = cast->unary.value;
6272 type_t *orig_dest_type = cast->base.type;
6273 type_t *orig_type_right = expression->base.type;
6274 type_t const *dst_type = skip_typeref(orig_dest_type);
6275 type_t const *src_type = skip_typeref(orig_type_right);
6276 source_position_t const *pos = &cast->base.source_position;
6278 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6279 if (dst_type == type_void)
6282 /* only integer and pointer can be casted to pointer */
6283 if (is_type_pointer(dst_type) &&
6284 !is_type_pointer(src_type) &&
6285 !is_type_integer(src_type) &&
6286 is_type_valid(src_type)) {
6287 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6291 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6292 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6296 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6297 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6301 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6302 type_t *src = skip_typeref(src_type->pointer.points_to);
6303 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6304 unsigned missing_qualifiers =
6305 src->base.qualifiers & ~dst->base.qualifiers;
6306 if (missing_qualifiers != 0) {
6307 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6313 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6315 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6316 expression->base.source_position = *pos;
6318 parse_initializer_env_t env;
6321 env.must_be_constant = false;
6322 initializer_t *initializer = parse_initializer(&env);
6325 expression->compound_literal.initializer = initializer;
6326 expression->compound_literal.type = type;
6327 expression->base.type = automatic_type_conversion(type);
6333 * Parse a cast expression.
6335 static expression_t *parse_cast(void)
6337 source_position_t const pos = *HERE;
6340 add_anchor_token(')');
6342 type_t *type = parse_typename();
6344 rem_anchor_token(')');
6345 expect(')', end_error);
6347 if (token.kind == '{') {
6348 return parse_compound_literal(&pos, type);
6351 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6352 cast->base.source_position = pos;
6354 expression_t *value = parse_subexpression(PREC_CAST);
6355 cast->base.type = type;
6356 cast->unary.value = value;
6358 if (! semantic_cast(cast)) {
6359 /* TODO: record the error in the AST. else it is impossible to detect it */
6364 return create_error_expression();
6368 * Parse a statement expression.
6370 static expression_t *parse_statement_expression(void)
6372 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6375 add_anchor_token(')');
6377 statement_t *statement = parse_compound_statement(true);
6378 statement->compound.stmt_expr = true;
6379 expression->statement.statement = statement;
6381 /* find last statement and use its type */
6382 type_t *type = type_void;
6383 const statement_t *stmt = statement->compound.statements;
6385 while (stmt->base.next != NULL)
6386 stmt = stmt->base.next;
6388 if (stmt->kind == STATEMENT_EXPRESSION) {
6389 type = stmt->expression.expression->base.type;
6392 source_position_t const *const pos = &expression->base.source_position;
6393 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6395 expression->base.type = type;
6397 rem_anchor_token(')');
6398 expect(')', end_error);
6405 * Parse a parenthesized expression.
6407 static expression_t *parse_parenthesized_expression(void)
6409 token_t const* const la1 = look_ahead(1);
6410 switch (la1->kind) {
6412 /* gcc extension: a statement expression */
6413 return parse_statement_expression();
6416 if (is_typedef_symbol(la1->identifier.symbol)) {
6418 return parse_cast();
6423 add_anchor_token(')');
6424 expression_t *result = parse_expression();
6425 result->base.parenthesized = true;
6426 rem_anchor_token(')');
6427 expect(')', end_error);
6433 static expression_t *parse_function_keyword(void)
6437 if (current_function == NULL) {
6438 errorf(HERE, "'__func__' used outside of a function");
6441 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6442 expression->base.type = type_char_ptr;
6443 expression->funcname.kind = FUNCNAME_FUNCTION;
6450 static expression_t *parse_pretty_function_keyword(void)
6452 if (current_function == NULL) {
6453 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6456 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6457 expression->base.type = type_char_ptr;
6458 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6460 eat(T___PRETTY_FUNCTION__);
6465 static expression_t *parse_funcsig_keyword(void)
6467 if (current_function == NULL) {
6468 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6471 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6472 expression->base.type = type_char_ptr;
6473 expression->funcname.kind = FUNCNAME_FUNCSIG;
6480 static expression_t *parse_funcdname_keyword(void)
6482 if (current_function == NULL) {
6483 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6486 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6487 expression->base.type = type_char_ptr;
6488 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6490 eat(T___FUNCDNAME__);
6495 static designator_t *parse_designator(void)
6497 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6498 result->source_position = *HERE;
6500 if (token.kind != T_IDENTIFIER) {
6501 parse_error_expected("while parsing member designator",
6502 T_IDENTIFIER, NULL);
6505 result->symbol = token.identifier.symbol;
6508 designator_t *last_designator = result;
6511 if (token.kind != T_IDENTIFIER) {
6512 parse_error_expected("while parsing member designator",
6513 T_IDENTIFIER, NULL);
6516 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6517 designator->source_position = *HERE;
6518 designator->symbol = token.identifier.symbol;
6521 last_designator->next = designator;
6522 last_designator = designator;
6526 add_anchor_token(']');
6527 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6528 designator->source_position = *HERE;
6529 designator->array_index = parse_expression();
6530 rem_anchor_token(']');
6531 expect(']', end_error);
6532 if (designator->array_index == NULL) {
6536 last_designator->next = designator;
6537 last_designator = designator;
6549 * Parse the __builtin_offsetof() expression.
6551 static expression_t *parse_offsetof(void)
6553 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6554 expression->base.type = type_size_t;
6556 eat(T___builtin_offsetof);
6558 expect('(', end_error);
6559 add_anchor_token(',');
6560 type_t *type = parse_typename();
6561 rem_anchor_token(',');
6562 expect(',', end_error);
6563 add_anchor_token(')');
6564 designator_t *designator = parse_designator();
6565 rem_anchor_token(')');
6566 expect(')', end_error);
6568 expression->offsetofe.type = type;
6569 expression->offsetofe.designator = designator;
6572 memset(&path, 0, sizeof(path));
6573 path.top_type = type;
6574 path.path = NEW_ARR_F(type_path_entry_t, 0);
6576 descend_into_subtype(&path);
6578 if (!walk_designator(&path, designator, true)) {
6579 return create_error_expression();
6582 DEL_ARR_F(path.path);
6586 return create_error_expression();
6590 * Parses a _builtin_va_start() expression.
6592 static expression_t *parse_va_start(void)
6594 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6596 eat(T___builtin_va_start);
6598 expect('(', end_error);
6599 add_anchor_token(',');
6600 expression->va_starte.ap = parse_assignment_expression();
6601 rem_anchor_token(',');
6602 expect(',', end_error);
6603 expression_t *const expr = parse_assignment_expression();
6604 if (expr->kind == EXPR_REFERENCE) {
6605 entity_t *const entity = expr->reference.entity;
6606 if (!current_function->base.type->function.variadic) {
6607 errorf(&expr->base.source_position,
6608 "'va_start' used in non-variadic function");
6609 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6610 entity->base.next != NULL ||
6611 entity->kind != ENTITY_PARAMETER) {
6612 errorf(&expr->base.source_position,
6613 "second argument of 'va_start' must be last parameter of the current function");
6615 expression->va_starte.parameter = &entity->variable;
6617 expect(')', end_error);
6620 expect(')', end_error);
6622 return create_error_expression();
6626 * Parses a __builtin_va_arg() expression.
6628 static expression_t *parse_va_arg(void)
6630 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6632 eat(T___builtin_va_arg);
6634 expect('(', end_error);
6636 ap.expression = parse_assignment_expression();
6637 expression->va_arge.ap = ap.expression;
6638 check_call_argument(type_valist, &ap, 1);
6640 expect(',', end_error);
6641 expression->base.type = parse_typename();
6642 expect(')', end_error);
6646 return create_error_expression();
6650 * Parses a __builtin_va_copy() expression.
6652 static expression_t *parse_va_copy(void)
6654 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6656 eat(T___builtin_va_copy);
6658 expect('(', end_error);
6659 expression_t *dst = parse_assignment_expression();
6660 assign_error_t error = semantic_assign(type_valist, dst);
6661 report_assign_error(error, type_valist, dst, "call argument 1",
6662 &dst->base.source_position);
6663 expression->va_copye.dst = dst;
6665 expect(',', end_error);
6667 call_argument_t src;
6668 src.expression = parse_assignment_expression();
6669 check_call_argument(type_valist, &src, 2);
6670 expression->va_copye.src = src.expression;
6671 expect(')', end_error);
6675 return create_error_expression();
6679 * Parses a __builtin_constant_p() expression.
6681 static expression_t *parse_builtin_constant(void)
6683 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6685 eat(T___builtin_constant_p);
6687 expect('(', end_error);
6688 add_anchor_token(')');
6689 expression->builtin_constant.value = parse_assignment_expression();
6690 rem_anchor_token(')');
6691 expect(')', end_error);
6692 expression->base.type = type_int;
6696 return create_error_expression();
6700 * Parses a __builtin_types_compatible_p() expression.
6702 static expression_t *parse_builtin_types_compatible(void)
6704 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6706 eat(T___builtin_types_compatible_p);
6708 expect('(', end_error);
6709 add_anchor_token(')');
6710 add_anchor_token(',');
6711 expression->builtin_types_compatible.left = parse_typename();
6712 rem_anchor_token(',');
6713 expect(',', end_error);
6714 expression->builtin_types_compatible.right = parse_typename();
6715 rem_anchor_token(')');
6716 expect(')', end_error);
6717 expression->base.type = type_int;
6721 return create_error_expression();
6725 * Parses a __builtin_is_*() compare expression.
6727 static expression_t *parse_compare_builtin(void)
6729 expression_t *expression;
6731 switch (token.kind) {
6732 case T___builtin_isgreater:
6733 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6735 case T___builtin_isgreaterequal:
6736 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6738 case T___builtin_isless:
6739 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6741 case T___builtin_islessequal:
6742 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6744 case T___builtin_islessgreater:
6745 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6747 case T___builtin_isunordered:
6748 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6751 internal_errorf(HERE, "invalid compare builtin found");
6753 expression->base.source_position = *HERE;
6756 expect('(', end_error);
6757 expression->binary.left = parse_assignment_expression();
6758 expect(',', end_error);
6759 expression->binary.right = parse_assignment_expression();
6760 expect(')', end_error);
6762 type_t *const orig_type_left = expression->binary.left->base.type;
6763 type_t *const orig_type_right = expression->binary.right->base.type;
6765 type_t *const type_left = skip_typeref(orig_type_left);
6766 type_t *const type_right = skip_typeref(orig_type_right);
6767 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6768 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6769 type_error_incompatible("invalid operands in comparison",
6770 &expression->base.source_position, orig_type_left, orig_type_right);
6773 semantic_comparison(&expression->binary);
6778 return create_error_expression();
6782 * Parses a MS assume() expression.
6784 static expression_t *parse_assume(void)
6786 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6790 expect('(', end_error);
6791 add_anchor_token(')');
6792 expression->unary.value = parse_assignment_expression();
6793 rem_anchor_token(')');
6794 expect(')', end_error);
6796 expression->base.type = type_void;
6799 return create_error_expression();
6803 * Return the label for the current symbol or create a new one.
6805 static label_t *get_label(void)
6807 assert(token.kind == T_IDENTIFIER);
6808 assert(current_function != NULL);
6810 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6811 /* If we find a local label, we already created the declaration. */
6812 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6813 if (label->base.parent_scope != current_scope) {
6814 assert(label->base.parent_scope->depth < current_scope->depth);
6815 current_function->goto_to_outer = true;
6817 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6818 /* There is no matching label in the same function, so create a new one. */
6819 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol);
6824 return &label->label;
6828 * Parses a GNU && label address expression.
6830 static expression_t *parse_label_address(void)
6832 source_position_t source_position = token.base.source_position;
6834 if (token.kind != T_IDENTIFIER) {
6835 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6836 return create_error_expression();
6839 label_t *const label = get_label();
6841 label->address_taken = true;
6843 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6844 expression->base.source_position = source_position;
6846 /* label address is treated as a void pointer */
6847 expression->base.type = type_void_ptr;
6848 expression->label_address.label = label;
6853 * Parse a microsoft __noop expression.
6855 static expression_t *parse_noop_expression(void)
6857 /* the result is a (int)0 */
6858 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6859 literal->base.type = type_int;
6860 literal->literal.value.begin = "__noop";
6861 literal->literal.value.size = 6;
6865 if (token.kind == '(') {
6866 /* parse arguments */
6868 add_anchor_token(')');
6869 add_anchor_token(',');
6871 if (token.kind != ')') do {
6872 (void)parse_assignment_expression();
6873 } while (next_if(','));
6875 rem_anchor_token(',');
6876 rem_anchor_token(')');
6877 expect(')', end_error);
6884 * Parses a primary expression.
6886 static expression_t *parse_primary_expression(void)
6888 switch (token.kind) {
6889 case T_false: return parse_boolean_literal(false);
6890 case T_true: return parse_boolean_literal(true);
6892 case T_INTEGER_OCTAL:
6893 case T_INTEGER_HEXADECIMAL:
6894 case T_FLOATINGPOINT:
6895 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6896 case T_CHARACTER_CONSTANT: return parse_character_constant();
6897 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6898 case T_STRING_LITERAL:
6899 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6900 case T___FUNCTION__:
6901 case T___func__: return parse_function_keyword();
6902 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6903 case T___FUNCSIG__: return parse_funcsig_keyword();
6904 case T___FUNCDNAME__: return parse_funcdname_keyword();
6905 case T___builtin_offsetof: return parse_offsetof();
6906 case T___builtin_va_start: return parse_va_start();
6907 case T___builtin_va_arg: return parse_va_arg();
6908 case T___builtin_va_copy: return parse_va_copy();
6909 case T___builtin_isgreater:
6910 case T___builtin_isgreaterequal:
6911 case T___builtin_isless:
6912 case T___builtin_islessequal:
6913 case T___builtin_islessgreater:
6914 case T___builtin_isunordered: return parse_compare_builtin();
6915 case T___builtin_constant_p: return parse_builtin_constant();
6916 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6917 case T__assume: return parse_assume();
6920 return parse_label_address();
6923 case '(': return parse_parenthesized_expression();
6924 case T___noop: return parse_noop_expression();
6926 /* Gracefully handle type names while parsing expressions. */
6928 return parse_reference();
6930 if (!is_typedef_symbol(token.identifier.symbol)) {
6931 return parse_reference();
6935 source_position_t const pos = *HERE;
6936 declaration_specifiers_t specifiers;
6937 parse_declaration_specifiers(&specifiers);
6938 type_t const *const type = parse_abstract_declarator(specifiers.type);
6939 errorf(&pos, "encountered type '%T' while parsing expression", type);
6940 return create_error_expression();
6944 errorf(HERE, "unexpected token %K, expected an expression", &token);
6946 return create_error_expression();
6949 static expression_t *parse_array_expression(expression_t *left)
6951 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6952 array_access_expression_t *const arr = &expr->array_access;
6955 add_anchor_token(']');
6957 expression_t *const inside = parse_expression();
6959 type_t *const orig_type_left = left->base.type;
6960 type_t *const orig_type_inside = inside->base.type;
6962 type_t *const type_left = skip_typeref(orig_type_left);
6963 type_t *const type_inside = skip_typeref(orig_type_inside);
6969 if (is_type_pointer(type_left)) {
6972 idx_type = type_inside;
6973 res_type = type_left->pointer.points_to;
6975 } else if (is_type_pointer(type_inside)) {
6976 arr->flipped = true;
6979 idx_type = type_left;
6980 res_type = type_inside->pointer.points_to;
6982 res_type = automatic_type_conversion(res_type);
6983 if (!is_type_integer(idx_type)) {
6984 errorf(&idx->base.source_position, "array subscript must have integer type");
6985 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6986 source_position_t const *const pos = &idx->base.source_position;
6987 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6990 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6991 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6993 res_type = type_error_type;
6998 arr->array_ref = ref;
7000 arr->base.type = res_type;
7002 rem_anchor_token(']');
7003 expect(']', end_error);
7008 static bool is_bitfield(const expression_t *expression)
7010 return expression->kind == EXPR_SELECT
7011 && expression->select.compound_entry->compound_member.bitfield;
7014 static expression_t *parse_typeprop(expression_kind_t const kind)
7016 expression_t *tp_expression = allocate_expression_zero(kind);
7017 tp_expression->base.type = type_size_t;
7019 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7022 expression_t *expression;
7023 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
7024 source_position_t const pos = *HERE;
7026 add_anchor_token(')');
7027 orig_type = parse_typename();
7028 rem_anchor_token(')');
7029 expect(')', end_error);
7031 if (token.kind == '{') {
7032 /* It was not sizeof(type) after all. It is sizeof of an expression
7033 * starting with a compound literal */
7034 expression = parse_compound_literal(&pos, orig_type);
7035 goto typeprop_expression;
7038 expression = parse_subexpression(PREC_UNARY);
7040 typeprop_expression:
7041 if (is_bitfield(expression)) {
7042 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7043 errorf(&tp_expression->base.source_position,
7044 "operand of %s expression must not be a bitfield", what);
7047 tp_expression->typeprop.tp_expression = expression;
7049 orig_type = revert_automatic_type_conversion(expression);
7050 expression->base.type = orig_type;
7053 tp_expression->typeprop.type = orig_type;
7054 type_t const* const type = skip_typeref(orig_type);
7055 char const* wrong_type = NULL;
7056 if (is_type_incomplete(type)) {
7057 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7058 wrong_type = "incomplete";
7059 } else if (type->kind == TYPE_FUNCTION) {
7061 /* function types are allowed (and return 1) */
7062 source_position_t const *const pos = &tp_expression->base.source_position;
7063 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7064 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7066 wrong_type = "function";
7070 if (wrong_type != NULL) {
7071 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7072 errorf(&tp_expression->base.source_position,
7073 "operand of %s expression must not be of %s type '%T'",
7074 what, wrong_type, orig_type);
7078 return tp_expression;
7081 static expression_t *parse_sizeof(void)
7083 return parse_typeprop(EXPR_SIZEOF);
7086 static expression_t *parse_alignof(void)
7088 return parse_typeprop(EXPR_ALIGNOF);
7091 static expression_t *parse_select_expression(expression_t *addr)
7093 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7094 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7095 source_position_t const pos = *HERE;
7098 if (token.kind != T_IDENTIFIER) {
7099 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7100 return create_error_expression();
7102 symbol_t *symbol = token.identifier.symbol;
7105 type_t *const orig_type = addr->base.type;
7106 type_t *const type = skip_typeref(orig_type);
7109 bool saw_error = false;
7110 if (is_type_pointer(type)) {
7111 if (!select_left_arrow) {
7113 "request for member '%Y' in something not a struct or union, but '%T'",
7117 type_left = skip_typeref(type->pointer.points_to);
7119 if (select_left_arrow && is_type_valid(type)) {
7120 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7126 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7127 type_left->kind != TYPE_COMPOUND_UNION) {
7129 if (is_type_valid(type_left) && !saw_error) {
7131 "request for member '%Y' in something not a struct or union, but '%T'",
7134 return create_error_expression();
7137 compound_t *compound = type_left->compound.compound;
7138 if (!compound->complete) {
7139 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7141 return create_error_expression();
7144 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7145 expression_t *result =
7146 find_create_select(&pos, addr, qualifiers, compound, symbol);
7148 if (result == NULL) {
7149 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7150 return create_error_expression();
7156 static void check_call_argument(type_t *expected_type,
7157 call_argument_t *argument, unsigned pos)
7159 type_t *expected_type_skip = skip_typeref(expected_type);
7160 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7161 expression_t *arg_expr = argument->expression;
7162 type_t *arg_type = skip_typeref(arg_expr->base.type);
7164 /* handle transparent union gnu extension */
7165 if (is_type_union(expected_type_skip)
7166 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7167 compound_t *union_decl = expected_type_skip->compound.compound;
7168 type_t *best_type = NULL;
7169 entity_t *entry = union_decl->members.entities;
7170 for ( ; entry != NULL; entry = entry->base.next) {
7171 assert(is_declaration(entry));
7172 type_t *decl_type = entry->declaration.type;
7173 error = semantic_assign(decl_type, arg_expr);
7174 if (error == ASSIGN_ERROR_INCOMPATIBLE
7175 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7178 if (error == ASSIGN_SUCCESS) {
7179 best_type = decl_type;
7180 } else if (best_type == NULL) {
7181 best_type = decl_type;
7185 if (best_type != NULL) {
7186 expected_type = best_type;
7190 error = semantic_assign(expected_type, arg_expr);
7191 argument->expression = create_implicit_cast(arg_expr, expected_type);
7193 if (error != ASSIGN_SUCCESS) {
7194 /* report exact scope in error messages (like "in argument 3") */
7196 snprintf(buf, sizeof(buf), "call argument %u", pos);
7197 report_assign_error(error, expected_type, arg_expr, buf,
7198 &arg_expr->base.source_position);
7200 type_t *const promoted_type = get_default_promoted_type(arg_type);
7201 if (!types_compatible(expected_type_skip, promoted_type) &&
7202 !types_compatible(expected_type_skip, type_void_ptr) &&
7203 !types_compatible(type_void_ptr, promoted_type)) {
7204 /* Deliberately show the skipped types in this warning */
7205 source_position_t const *const apos = &arg_expr->base.source_position;
7206 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7212 * Handle the semantic restrictions of builtin calls
7214 static void handle_builtin_argument_restrictions(call_expression_t *call)
7216 entity_t *entity = call->function->reference.entity;
7217 switch (entity->function.btk) {
7219 switch (entity->function.b.firm_builtin_kind) {
7220 case ir_bk_return_address:
7221 case ir_bk_frame_address: {
7222 /* argument must be constant */
7223 call_argument_t *argument = call->arguments;
7225 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7226 errorf(&call->base.source_position,
7227 "argument of '%Y' must be a constant expression",
7228 call->function->reference.entity->base.symbol);
7232 case ir_bk_prefetch:
7233 /* second and third argument must be constant if existent */
7234 if (call->arguments == NULL)
7236 call_argument_t *rw = call->arguments->next;
7237 call_argument_t *locality = NULL;
7240 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7241 errorf(&call->base.source_position,
7242 "second argument of '%Y' must be a constant expression",
7243 call->function->reference.entity->base.symbol);
7245 locality = rw->next;
7247 if (locality != NULL) {
7248 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7249 errorf(&call->base.source_position,
7250 "third argument of '%Y' must be a constant expression",
7251 call->function->reference.entity->base.symbol);
7253 locality = rw->next;
7260 case BUILTIN_OBJECT_SIZE:
7261 if (call->arguments == NULL)
7264 call_argument_t *arg = call->arguments->next;
7265 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7266 errorf(&call->base.source_position,
7267 "second argument of '%Y' must be a constant expression",
7268 call->function->reference.entity->base.symbol);
7277 * Parse a call expression, ie. expression '( ... )'.
7279 * @param expression the function address
7281 static expression_t *parse_call_expression(expression_t *expression)
7283 expression_t *result = allocate_expression_zero(EXPR_CALL);
7284 call_expression_t *call = &result->call;
7285 call->function = expression;
7287 type_t *const orig_type = expression->base.type;
7288 type_t *const type = skip_typeref(orig_type);
7290 function_type_t *function_type = NULL;
7291 if (is_type_pointer(type)) {
7292 type_t *const to_type = skip_typeref(type->pointer.points_to);
7294 if (is_type_function(to_type)) {
7295 function_type = &to_type->function;
7296 call->base.type = function_type->return_type;
7300 if (function_type == NULL && is_type_valid(type)) {
7302 "called object '%E' (type '%T') is not a pointer to a function",
7303 expression, orig_type);
7306 /* parse arguments */
7308 add_anchor_token(')');
7309 add_anchor_token(',');
7311 if (token.kind != ')') {
7312 call_argument_t **anchor = &call->arguments;
7314 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7315 argument->expression = parse_assignment_expression();
7318 anchor = &argument->next;
7319 } while (next_if(','));
7321 rem_anchor_token(',');
7322 rem_anchor_token(')');
7323 expect(')', end_error);
7325 if (function_type == NULL)
7328 /* check type and count of call arguments */
7329 function_parameter_t *parameter = function_type->parameters;
7330 call_argument_t *argument = call->arguments;
7331 if (!function_type->unspecified_parameters) {
7332 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7333 parameter = parameter->next, argument = argument->next) {
7334 check_call_argument(parameter->type, argument, ++pos);
7337 if (parameter != NULL) {
7338 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7339 } else if (argument != NULL && !function_type->variadic) {
7340 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7344 /* do default promotion for other arguments */
7345 for (; argument != NULL; argument = argument->next) {
7346 type_t *argument_type = argument->expression->base.type;
7347 if (!is_type_object(skip_typeref(argument_type))) {
7348 errorf(&argument->expression->base.source_position,
7349 "call argument '%E' must not be void", argument->expression);
7352 argument_type = get_default_promoted_type(argument_type);
7354 argument->expression
7355 = create_implicit_cast(argument->expression, argument_type);
7360 if (is_type_compound(skip_typeref(function_type->return_type))) {
7361 source_position_t const *const pos = &expression->base.source_position;
7362 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7365 if (expression->kind == EXPR_REFERENCE) {
7366 reference_expression_t *reference = &expression->reference;
7367 if (reference->entity->kind == ENTITY_FUNCTION &&
7368 reference->entity->function.btk != BUILTIN_NONE)
7369 handle_builtin_argument_restrictions(call);
7376 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7378 static bool same_compound_type(const type_t *type1, const type_t *type2)
7381 is_type_compound(type1) &&
7382 type1->kind == type2->kind &&
7383 type1->compound.compound == type2->compound.compound;
7386 static expression_t const *get_reference_address(expression_t const *expr)
7388 bool regular_take_address = true;
7390 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7391 expr = expr->unary.value;
7393 regular_take_address = false;
7396 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7399 expr = expr->unary.value;
7402 if (expr->kind != EXPR_REFERENCE)
7405 /* special case for functions which are automatically converted to a
7406 * pointer to function without an extra TAKE_ADDRESS operation */
7407 if (!regular_take_address &&
7408 expr->reference.entity->kind != ENTITY_FUNCTION) {
7415 static void warn_reference_address_as_bool(expression_t const* expr)
7417 expr = get_reference_address(expr);
7419 source_position_t const *const pos = &expr->base.source_position;
7420 entity_t const *const ent = expr->reference.entity;
7421 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7425 static void warn_assignment_in_condition(const expression_t *const expr)
7427 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7429 if (expr->base.parenthesized)
7431 source_position_t const *const pos = &expr->base.source_position;
7432 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7435 static void semantic_condition(expression_t const *const expr,
7436 char const *const context)
7438 type_t *const type = skip_typeref(expr->base.type);
7439 if (is_type_scalar(type)) {
7440 warn_reference_address_as_bool(expr);
7441 warn_assignment_in_condition(expr);
7442 } else if (is_type_valid(type)) {
7443 errorf(&expr->base.source_position,
7444 "%s must have scalar type", context);
7449 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7451 * @param expression the conditional expression
7453 static expression_t *parse_conditional_expression(expression_t *expression)
7455 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7457 conditional_expression_t *conditional = &result->conditional;
7458 conditional->condition = expression;
7461 add_anchor_token(':');
7463 /* §6.5.15:2 The first operand shall have scalar type. */
7464 semantic_condition(expression, "condition of conditional operator");
7466 expression_t *true_expression = expression;
7467 bool gnu_cond = false;
7468 if (GNU_MODE && token.kind == ':') {
7471 true_expression = parse_expression();
7473 rem_anchor_token(':');
7474 expect(':', end_error);
7476 expression_t *false_expression =
7477 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7479 type_t *const orig_true_type = true_expression->base.type;
7480 type_t *const orig_false_type = false_expression->base.type;
7481 type_t *const true_type = skip_typeref(orig_true_type);
7482 type_t *const false_type = skip_typeref(orig_false_type);
7485 source_position_t const *const pos = &conditional->base.source_position;
7486 type_t *result_type;
7487 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7488 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7489 /* ISO/IEC 14882:1998(E) §5.16:2 */
7490 if (true_expression->kind == EXPR_UNARY_THROW) {
7491 result_type = false_type;
7492 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7493 result_type = true_type;
7495 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7496 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7497 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7499 result_type = type_void;
7501 } else if (is_type_arithmetic(true_type)
7502 && is_type_arithmetic(false_type)) {
7503 result_type = semantic_arithmetic(true_type, false_type);
7504 } else if (same_compound_type(true_type, false_type)) {
7505 /* just take 1 of the 2 types */
7506 result_type = true_type;
7507 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7508 type_t *pointer_type;
7510 expression_t *other_expression;
7511 if (is_type_pointer(true_type) &&
7512 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7513 pointer_type = true_type;
7514 other_type = false_type;
7515 other_expression = false_expression;
7517 pointer_type = false_type;
7518 other_type = true_type;
7519 other_expression = true_expression;
7522 if (is_null_pointer_constant(other_expression)) {
7523 result_type = pointer_type;
7524 } else if (is_type_pointer(other_type)) {
7525 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7526 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7529 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7530 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7532 } else if (types_compatible(get_unqualified_type(to1),
7533 get_unqualified_type(to2))) {
7536 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7540 type_t *const type =
7541 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7542 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7543 } else if (is_type_integer(other_type)) {
7544 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7545 result_type = pointer_type;
7547 goto types_incompatible;
7551 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7552 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7554 result_type = type_error_type;
7557 conditional->true_expression
7558 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7559 conditional->false_expression
7560 = create_implicit_cast(false_expression, result_type);
7561 conditional->base.type = result_type;
7566 * Parse an extension expression.
7568 static expression_t *parse_extension(void)
7571 expression_t *expression = parse_subexpression(PREC_UNARY);
7577 * Parse a __builtin_classify_type() expression.
7579 static expression_t *parse_builtin_classify_type(void)
7581 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7582 result->base.type = type_int;
7584 eat(T___builtin_classify_type);
7586 expect('(', end_error);
7587 add_anchor_token(')');
7588 expression_t *expression = parse_expression();
7589 rem_anchor_token(')');
7590 expect(')', end_error);
7591 result->classify_type.type_expression = expression;
7595 return create_error_expression();
7599 * Parse a delete expression
7600 * ISO/IEC 14882:1998(E) §5.3.5
7602 static expression_t *parse_delete(void)
7604 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7605 result->base.type = type_void;
7610 result->kind = EXPR_UNARY_DELETE_ARRAY;
7611 expect(']', end_error);
7615 expression_t *const value = parse_subexpression(PREC_CAST);
7616 result->unary.value = value;
7618 type_t *const type = skip_typeref(value->base.type);
7619 if (!is_type_pointer(type)) {
7620 if (is_type_valid(type)) {
7621 errorf(&value->base.source_position,
7622 "operand of delete must have pointer type");
7624 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7625 source_position_t const *const pos = &value->base.source_position;
7626 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7633 * Parse a throw expression
7634 * ISO/IEC 14882:1998(E) §15:1
7636 static expression_t *parse_throw(void)
7638 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7639 result->base.type = type_void;
7643 expression_t *value = NULL;
7644 switch (token.kind) {
7646 value = parse_assignment_expression();
7647 /* ISO/IEC 14882:1998(E) §15.1:3 */
7648 type_t *const orig_type = value->base.type;
7649 type_t *const type = skip_typeref(orig_type);
7650 if (is_type_incomplete(type)) {
7651 errorf(&value->base.source_position,
7652 "cannot throw object of incomplete type '%T'", orig_type);
7653 } else if (is_type_pointer(type)) {
7654 type_t *const points_to = skip_typeref(type->pointer.points_to);
7655 if (is_type_incomplete(points_to) &&
7656 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7657 errorf(&value->base.source_position,
7658 "cannot throw pointer to incomplete type '%T'", orig_type);
7666 result->unary.value = value;
7671 static bool check_pointer_arithmetic(const source_position_t *source_position,
7672 type_t *pointer_type,
7673 type_t *orig_pointer_type)
7675 type_t *points_to = pointer_type->pointer.points_to;
7676 points_to = skip_typeref(points_to);
7678 if (is_type_incomplete(points_to)) {
7679 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7680 errorf(source_position,
7681 "arithmetic with pointer to incomplete type '%T' not allowed",
7685 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7687 } else if (is_type_function(points_to)) {
7689 errorf(source_position,
7690 "arithmetic with pointer to function type '%T' not allowed",
7694 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7700 static bool is_lvalue(const expression_t *expression)
7702 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7703 switch (expression->kind) {
7704 case EXPR_ARRAY_ACCESS:
7705 case EXPR_COMPOUND_LITERAL:
7706 case EXPR_REFERENCE:
7708 case EXPR_UNARY_DEREFERENCE:
7712 type_t *type = skip_typeref(expression->base.type);
7714 /* ISO/IEC 14882:1998(E) §3.10:3 */
7715 is_type_reference(type) ||
7716 /* Claim it is an lvalue, if the type is invalid. There was a parse
7717 * error before, which maybe prevented properly recognizing it as
7719 !is_type_valid(type);
7724 static void semantic_incdec(unary_expression_t *expression)
7726 type_t *const orig_type = expression->value->base.type;
7727 type_t *const type = skip_typeref(orig_type);
7728 if (is_type_pointer(type)) {
7729 if (!check_pointer_arithmetic(&expression->base.source_position,
7733 } else if (!is_type_real(type) && is_type_valid(type)) {
7734 /* TODO: improve error message */
7735 errorf(&expression->base.source_position,
7736 "operation needs an arithmetic or pointer type");
7739 if (!is_lvalue(expression->value)) {
7740 /* TODO: improve error message */
7741 errorf(&expression->base.source_position, "lvalue required as operand");
7743 expression->base.type = orig_type;
7746 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7748 type_t *const res_type = promote_integer(type);
7749 expr->base.type = res_type;
7750 expr->value = create_implicit_cast(expr->value, res_type);
7753 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7755 type_t *const orig_type = expression->value->base.type;
7756 type_t *const type = skip_typeref(orig_type);
7757 if (!is_type_arithmetic(type)) {
7758 if (is_type_valid(type)) {
7759 /* TODO: improve error message */
7760 errorf(&expression->base.source_position,
7761 "operation needs an arithmetic type");
7764 } else if (is_type_integer(type)) {
7765 promote_unary_int_expr(expression, type);
7767 expression->base.type = orig_type;
7771 static void semantic_unexpr_plus(unary_expression_t *expression)
7773 semantic_unexpr_arithmetic(expression);
7774 source_position_t const *const pos = &expression->base.source_position;
7775 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7778 static void semantic_not(unary_expression_t *expression)
7780 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7781 semantic_condition(expression->value, "operand of !");
7782 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7785 static void semantic_unexpr_integer(unary_expression_t *expression)
7787 type_t *const orig_type = expression->value->base.type;
7788 type_t *const type = skip_typeref(orig_type);
7789 if (!is_type_integer(type)) {
7790 if (is_type_valid(type)) {
7791 errorf(&expression->base.source_position,
7792 "operand of ~ must be of integer type");
7797 promote_unary_int_expr(expression, type);
7800 static void semantic_dereference(unary_expression_t *expression)
7802 type_t *const orig_type = expression->value->base.type;
7803 type_t *const type = skip_typeref(orig_type);
7804 if (!is_type_pointer(type)) {
7805 if (is_type_valid(type)) {
7806 errorf(&expression->base.source_position,
7807 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7812 type_t *result_type = type->pointer.points_to;
7813 result_type = automatic_type_conversion(result_type);
7814 expression->base.type = result_type;
7818 * Record that an address is taken (expression represents an lvalue).
7820 * @param expression the expression
7821 * @param may_be_register if true, the expression might be an register
7823 static void set_address_taken(expression_t *expression, bool may_be_register)
7825 if (expression->kind != EXPR_REFERENCE)
7828 entity_t *const entity = expression->reference.entity;
7830 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7833 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7834 && !may_be_register) {
7835 source_position_t const *const pos = &expression->base.source_position;
7836 errorf(pos, "address of register '%N' requested", entity);
7839 if (entity->kind == ENTITY_VARIABLE) {
7840 entity->variable.address_taken = true;
7842 assert(entity->kind == ENTITY_PARAMETER);
7843 entity->parameter.address_taken = true;
7848 * Check the semantic of the address taken expression.
7850 static void semantic_take_addr(unary_expression_t *expression)
7852 expression_t *value = expression->value;
7853 value->base.type = revert_automatic_type_conversion(value);
7855 type_t *orig_type = value->base.type;
7856 type_t *type = skip_typeref(orig_type);
7857 if (!is_type_valid(type))
7861 if (!is_lvalue(value)) {
7862 errorf(&expression->base.source_position, "'&' requires an lvalue");
7864 if (is_bitfield(value)) {
7865 errorf(&expression->base.source_position,
7866 "'&' not allowed on bitfield");
7869 set_address_taken(value, false);
7871 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7874 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7875 static expression_t *parse_##unexpression_type(void) \
7877 expression_t *unary_expression \
7878 = allocate_expression_zero(unexpression_type); \
7880 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7882 sfunc(&unary_expression->unary); \
7884 return unary_expression; \
7887 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7888 semantic_unexpr_arithmetic)
7889 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7890 semantic_unexpr_plus)
7891 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7893 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7894 semantic_dereference)
7895 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7897 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7898 semantic_unexpr_integer)
7899 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7901 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7904 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7906 static expression_t *parse_##unexpression_type(expression_t *left) \
7908 expression_t *unary_expression \
7909 = allocate_expression_zero(unexpression_type); \
7911 unary_expression->unary.value = left; \
7913 sfunc(&unary_expression->unary); \
7915 return unary_expression; \
7918 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7919 EXPR_UNARY_POSTFIX_INCREMENT,
7921 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7922 EXPR_UNARY_POSTFIX_DECREMENT,
7925 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7927 /* TODO: handle complex + imaginary types */
7929 type_left = get_unqualified_type(type_left);
7930 type_right = get_unqualified_type(type_right);
7932 /* §6.3.1.8 Usual arithmetic conversions */
7933 if (type_left == type_long_double || type_right == type_long_double) {
7934 return type_long_double;
7935 } else if (type_left == type_double || type_right == type_double) {
7937 } else if (type_left == type_float || type_right == type_float) {
7941 type_left = promote_integer(type_left);
7942 type_right = promote_integer(type_right);
7944 if (type_left == type_right)
7947 bool const signed_left = is_type_signed(type_left);
7948 bool const signed_right = is_type_signed(type_right);
7949 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7950 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7952 if (signed_left == signed_right)
7953 return rank_left >= rank_right ? type_left : type_right;
7957 atomic_type_kind_t s_akind;
7958 atomic_type_kind_t u_akind;
7963 u_type = type_right;
7965 s_type = type_right;
7968 s_akind = get_akind(s_type);
7969 u_akind = get_akind(u_type);
7970 s_rank = get_akind_rank(s_akind);
7971 u_rank = get_akind_rank(u_akind);
7973 if (u_rank >= s_rank)
7976 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7980 case ATOMIC_TYPE_INT: return type_unsigned_int;
7981 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7982 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7984 default: panic("invalid atomic type");
7989 * Check the semantic restrictions for a binary expression.
7991 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7993 expression_t *const left = expression->left;
7994 expression_t *const right = expression->right;
7995 type_t *const orig_type_left = left->base.type;
7996 type_t *const orig_type_right = right->base.type;
7997 type_t *const type_left = skip_typeref(orig_type_left);
7998 type_t *const type_right = skip_typeref(orig_type_right);
8000 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8001 /* TODO: improve error message */
8002 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8003 errorf(&expression->base.source_position,
8004 "operation needs arithmetic types");
8009 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8010 expression->left = create_implicit_cast(left, arithmetic_type);
8011 expression->right = create_implicit_cast(right, arithmetic_type);
8012 expression->base.type = arithmetic_type;
8015 static void semantic_binexpr_integer(binary_expression_t *const expression)
8017 expression_t *const left = expression->left;
8018 expression_t *const right = expression->right;
8019 type_t *const orig_type_left = left->base.type;
8020 type_t *const orig_type_right = right->base.type;
8021 type_t *const type_left = skip_typeref(orig_type_left);
8022 type_t *const type_right = skip_typeref(orig_type_right);
8024 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8025 /* TODO: improve error message */
8026 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8027 errorf(&expression->base.source_position,
8028 "operation needs integer types");
8033 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8034 expression->left = create_implicit_cast(left, result_type);
8035 expression->right = create_implicit_cast(right, result_type);
8036 expression->base.type = result_type;
8039 static void warn_div_by_zero(binary_expression_t const *const expression)
8041 if (!is_type_integer(expression->base.type))
8044 expression_t const *const right = expression->right;
8045 /* The type of the right operand can be different for /= */
8046 if (is_type_integer(right->base.type) &&
8047 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8048 !fold_constant_to_bool(right)) {
8049 source_position_t const *const pos = &expression->base.source_position;
8050 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8055 * Check the semantic restrictions for a div/mod expression.
8057 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8059 semantic_binexpr_arithmetic(expression);
8060 warn_div_by_zero(expression);
8063 static void warn_addsub_in_shift(const expression_t *const expr)
8065 if (expr->base.parenthesized)
8069 switch (expr->kind) {
8070 case EXPR_BINARY_ADD: op = '+'; break;
8071 case EXPR_BINARY_SUB: op = '-'; break;
8075 source_position_t const *const pos = &expr->base.source_position;
8076 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8079 static bool semantic_shift(binary_expression_t *expression)
8081 expression_t *const left = expression->left;
8082 expression_t *const right = expression->right;
8083 type_t *const orig_type_left = left->base.type;
8084 type_t *const orig_type_right = right->base.type;
8085 type_t * type_left = skip_typeref(orig_type_left);
8086 type_t * type_right = skip_typeref(orig_type_right);
8088 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8089 /* TODO: improve error message */
8090 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8091 errorf(&expression->base.source_position,
8092 "operands of shift operation must have integer types");
8097 type_left = promote_integer(type_left);
8099 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8100 source_position_t const *const pos = &right->base.source_position;
8101 long const count = fold_constant_to_int(right);
8103 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8104 } else if ((unsigned long)count >=
8105 get_atomic_type_size(type_left->atomic.akind) * 8) {
8106 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8110 type_right = promote_integer(type_right);
8111 expression->right = create_implicit_cast(right, type_right);
8116 static void semantic_shift_op(binary_expression_t *expression)
8118 expression_t *const left = expression->left;
8119 expression_t *const right = expression->right;
8121 if (!semantic_shift(expression))
8124 warn_addsub_in_shift(left);
8125 warn_addsub_in_shift(right);
8127 type_t *const orig_type_left = left->base.type;
8128 type_t * type_left = skip_typeref(orig_type_left);
8130 type_left = promote_integer(type_left);
8131 expression->left = create_implicit_cast(left, type_left);
8132 expression->base.type = type_left;
8135 static void semantic_add(binary_expression_t *expression)
8137 expression_t *const left = expression->left;
8138 expression_t *const right = expression->right;
8139 type_t *const orig_type_left = left->base.type;
8140 type_t *const orig_type_right = right->base.type;
8141 type_t *const type_left = skip_typeref(orig_type_left);
8142 type_t *const type_right = skip_typeref(orig_type_right);
8145 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8146 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8147 expression->left = create_implicit_cast(left, arithmetic_type);
8148 expression->right = create_implicit_cast(right, arithmetic_type);
8149 expression->base.type = arithmetic_type;
8150 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8151 check_pointer_arithmetic(&expression->base.source_position,
8152 type_left, orig_type_left);
8153 expression->base.type = type_left;
8154 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8155 check_pointer_arithmetic(&expression->base.source_position,
8156 type_right, orig_type_right);
8157 expression->base.type = type_right;
8158 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8159 errorf(&expression->base.source_position,
8160 "invalid operands to binary + ('%T', '%T')",
8161 orig_type_left, orig_type_right);
8165 static void semantic_sub(binary_expression_t *expression)
8167 expression_t *const left = expression->left;
8168 expression_t *const right = expression->right;
8169 type_t *const orig_type_left = left->base.type;
8170 type_t *const orig_type_right = right->base.type;
8171 type_t *const type_left = skip_typeref(orig_type_left);
8172 type_t *const type_right = skip_typeref(orig_type_right);
8173 source_position_t const *const pos = &expression->base.source_position;
8176 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8177 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8178 expression->left = create_implicit_cast(left, arithmetic_type);
8179 expression->right = create_implicit_cast(right, arithmetic_type);
8180 expression->base.type = arithmetic_type;
8181 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8182 check_pointer_arithmetic(&expression->base.source_position,
8183 type_left, orig_type_left);
8184 expression->base.type = type_left;
8185 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8186 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8187 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8188 if (!types_compatible(unqual_left, unqual_right)) {
8190 "subtracting pointers to incompatible types '%T' and '%T'",
8191 orig_type_left, orig_type_right);
8192 } else if (!is_type_object(unqual_left)) {
8193 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8194 errorf(pos, "subtracting pointers to non-object types '%T'",
8197 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8200 expression->base.type = type_ptrdiff_t;
8201 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8202 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8203 orig_type_left, orig_type_right);
8207 static void warn_string_literal_address(expression_t const* expr)
8209 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8210 expr = expr->unary.value;
8211 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8213 expr = expr->unary.value;
8216 if (expr->kind == EXPR_STRING_LITERAL
8217 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8218 source_position_t const *const pos = &expr->base.source_position;
8219 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8223 static bool maybe_negative(expression_t const *const expr)
8225 switch (is_constant_expression(expr)) {
8226 case EXPR_CLASS_ERROR: return false;
8227 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8228 default: return true;
8232 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8234 warn_string_literal_address(expr);
8236 expression_t const* const ref = get_reference_address(expr);
8237 if (ref != NULL && is_null_pointer_constant(other)) {
8238 entity_t const *const ent = ref->reference.entity;
8239 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8242 if (!expr->base.parenthesized) {
8243 switch (expr->base.kind) {
8244 case EXPR_BINARY_LESS:
8245 case EXPR_BINARY_GREATER:
8246 case EXPR_BINARY_LESSEQUAL:
8247 case EXPR_BINARY_GREATEREQUAL:
8248 case EXPR_BINARY_NOTEQUAL:
8249 case EXPR_BINARY_EQUAL:
8250 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8259 * Check the semantics of comparison expressions.
8261 * @param expression The expression to check.
8263 static void semantic_comparison(binary_expression_t *expression)
8265 source_position_t const *const pos = &expression->base.source_position;
8266 expression_t *const left = expression->left;
8267 expression_t *const right = expression->right;
8269 warn_comparison(pos, left, right);
8270 warn_comparison(pos, right, left);
8272 type_t *orig_type_left = left->base.type;
8273 type_t *orig_type_right = right->base.type;
8274 type_t *type_left = skip_typeref(orig_type_left);
8275 type_t *type_right = skip_typeref(orig_type_right);
8277 /* TODO non-arithmetic types */
8278 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8279 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8281 /* test for signed vs unsigned compares */
8282 if (is_type_integer(arithmetic_type)) {
8283 bool const signed_left = is_type_signed(type_left);
8284 bool const signed_right = is_type_signed(type_right);
8285 if (signed_left != signed_right) {
8286 /* FIXME long long needs better const folding magic */
8287 /* TODO check whether constant value can be represented by other type */
8288 if ((signed_left && maybe_negative(left)) ||
8289 (signed_right && maybe_negative(right))) {
8290 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8295 expression->left = create_implicit_cast(left, arithmetic_type);
8296 expression->right = create_implicit_cast(right, arithmetic_type);
8297 expression->base.type = arithmetic_type;
8298 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8299 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8300 is_type_float(arithmetic_type)) {
8301 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8303 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8304 /* TODO check compatibility */
8305 } else if (is_type_pointer(type_left)) {
8306 expression->right = create_implicit_cast(right, type_left);
8307 } else if (is_type_pointer(type_right)) {
8308 expression->left = create_implicit_cast(left, type_right);
8309 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8310 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8312 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8316 * Checks if a compound type has constant fields.
8318 static bool has_const_fields(const compound_type_t *type)
8320 compound_t *compound = type->compound;
8321 entity_t *entry = compound->members.entities;
8323 for (; entry != NULL; entry = entry->base.next) {
8324 if (!is_declaration(entry))
8327 const type_t *decl_type = skip_typeref(entry->declaration.type);
8328 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8335 static bool is_valid_assignment_lhs(expression_t const* const left)
8337 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8338 type_t *const type_left = skip_typeref(orig_type_left);
8340 if (!is_lvalue(left)) {
8341 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8346 if (left->kind == EXPR_REFERENCE
8347 && left->reference.entity->kind == ENTITY_FUNCTION) {
8348 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8352 if (is_type_array(type_left)) {
8353 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8356 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8357 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8361 if (is_type_incomplete(type_left)) {
8362 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8363 left, orig_type_left);
8366 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8367 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8368 left, orig_type_left);
8375 static void semantic_arithmetic_assign(binary_expression_t *expression)
8377 expression_t *left = expression->left;
8378 expression_t *right = expression->right;
8379 type_t *orig_type_left = left->base.type;
8380 type_t *orig_type_right = right->base.type;
8382 if (!is_valid_assignment_lhs(left))
8385 type_t *type_left = skip_typeref(orig_type_left);
8386 type_t *type_right = skip_typeref(orig_type_right);
8388 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8389 /* TODO: improve error message */
8390 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8391 errorf(&expression->base.source_position,
8392 "operation needs arithmetic types");
8397 /* combined instructions are tricky. We can't create an implicit cast on
8398 * the left side, because we need the uncasted form for the store.
8399 * The ast2firm pass has to know that left_type must be right_type
8400 * for the arithmetic operation and create a cast by itself */
8401 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8402 expression->right = create_implicit_cast(right, arithmetic_type);
8403 expression->base.type = type_left;
8406 static void semantic_divmod_assign(binary_expression_t *expression)
8408 semantic_arithmetic_assign(expression);
8409 warn_div_by_zero(expression);
8412 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8414 expression_t *const left = expression->left;
8415 expression_t *const right = expression->right;
8416 type_t *const orig_type_left = left->base.type;
8417 type_t *const orig_type_right = right->base.type;
8418 type_t *const type_left = skip_typeref(orig_type_left);
8419 type_t *const type_right = skip_typeref(orig_type_right);
8421 if (!is_valid_assignment_lhs(left))
8424 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8425 /* combined instructions are tricky. We can't create an implicit cast on
8426 * the left side, because we need the uncasted form for the store.
8427 * The ast2firm pass has to know that left_type must be right_type
8428 * for the arithmetic operation and create a cast by itself */
8429 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8430 expression->right = create_implicit_cast(right, arithmetic_type);
8431 expression->base.type = type_left;
8432 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8433 check_pointer_arithmetic(&expression->base.source_position,
8434 type_left, orig_type_left);
8435 expression->base.type = type_left;
8436 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8437 errorf(&expression->base.source_position,
8438 "incompatible types '%T' and '%T' in assignment",
8439 orig_type_left, orig_type_right);
8443 static void semantic_integer_assign(binary_expression_t *expression)
8445 expression_t *left = expression->left;
8446 expression_t *right = expression->right;
8447 type_t *orig_type_left = left->base.type;
8448 type_t *orig_type_right = right->base.type;
8450 if (!is_valid_assignment_lhs(left))
8453 type_t *type_left = skip_typeref(orig_type_left);
8454 type_t *type_right = skip_typeref(orig_type_right);
8456 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8457 /* TODO: improve error message */
8458 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8459 errorf(&expression->base.source_position,
8460 "operation needs integer types");
8465 /* combined instructions are tricky. We can't create an implicit cast on
8466 * the left side, because we need the uncasted form for the store.
8467 * The ast2firm pass has to know that left_type must be right_type
8468 * for the arithmetic operation and create a cast by itself */
8469 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8470 expression->right = create_implicit_cast(right, arithmetic_type);
8471 expression->base.type = type_left;
8474 static void semantic_shift_assign(binary_expression_t *expression)
8476 expression_t *left = expression->left;
8478 if (!is_valid_assignment_lhs(left))
8481 if (!semantic_shift(expression))
8484 expression->base.type = skip_typeref(left->base.type);
8487 static void warn_logical_and_within_or(const expression_t *const expr)
8489 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8491 if (expr->base.parenthesized)
8493 source_position_t const *const pos = &expr->base.source_position;
8494 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8498 * Check the semantic restrictions of a logical expression.
8500 static void semantic_logical_op(binary_expression_t *expression)
8502 /* §6.5.13:2 Each of the operands shall have scalar type.
8503 * §6.5.14:2 Each of the operands shall have scalar type. */
8504 semantic_condition(expression->left, "left operand of logical operator");
8505 semantic_condition(expression->right, "right operand of logical operator");
8506 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8507 warn_logical_and_within_or(expression->left);
8508 warn_logical_and_within_or(expression->right);
8510 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8514 * Check the semantic restrictions of a binary assign expression.
8516 static void semantic_binexpr_assign(binary_expression_t *expression)
8518 expression_t *left = expression->left;
8519 type_t *orig_type_left = left->base.type;
8521 if (!is_valid_assignment_lhs(left))
8524 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8525 report_assign_error(error, orig_type_left, expression->right,
8526 "assignment", &left->base.source_position);
8527 expression->right = create_implicit_cast(expression->right, orig_type_left);
8528 expression->base.type = orig_type_left;
8532 * Determine if the outermost operation (or parts thereof) of the given
8533 * expression has no effect in order to generate a warning about this fact.
8534 * Therefore in some cases this only examines some of the operands of the
8535 * expression (see comments in the function and examples below).
8537 * f() + 23; // warning, because + has no effect
8538 * x || f(); // no warning, because x controls execution of f()
8539 * x ? y : f(); // warning, because y has no effect
8540 * (void)x; // no warning to be able to suppress the warning
8541 * This function can NOT be used for an "expression has definitely no effect"-
8543 static bool expression_has_effect(const expression_t *const expr)
8545 switch (expr->kind) {
8546 case EXPR_ERROR: return true; /* do NOT warn */
8547 case EXPR_REFERENCE: return false;
8548 case EXPR_REFERENCE_ENUM_VALUE: return false;
8549 case EXPR_LABEL_ADDRESS: return false;
8551 /* suppress the warning for microsoft __noop operations */
8552 case EXPR_LITERAL_MS_NOOP: return true;
8553 case EXPR_LITERAL_BOOLEAN:
8554 case EXPR_LITERAL_CHARACTER:
8555 case EXPR_LITERAL_WIDE_CHARACTER:
8556 case EXPR_LITERAL_INTEGER:
8557 case EXPR_LITERAL_INTEGER_OCTAL:
8558 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8559 case EXPR_LITERAL_FLOATINGPOINT:
8560 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8561 case EXPR_STRING_LITERAL: return false;
8562 case EXPR_WIDE_STRING_LITERAL: return false;
8565 const call_expression_t *const call = &expr->call;
8566 if (call->function->kind != EXPR_REFERENCE)
8569 switch (call->function->reference.entity->function.btk) {
8570 /* FIXME: which builtins have no effect? */
8571 default: return true;
8575 /* Generate the warning if either the left or right hand side of a
8576 * conditional expression has no effect */
8577 case EXPR_CONDITIONAL: {
8578 conditional_expression_t const *const cond = &expr->conditional;
8579 expression_t const *const t = cond->true_expression;
8581 (t == NULL || expression_has_effect(t)) &&
8582 expression_has_effect(cond->false_expression);
8585 case EXPR_SELECT: return false;
8586 case EXPR_ARRAY_ACCESS: return false;
8587 case EXPR_SIZEOF: return false;
8588 case EXPR_CLASSIFY_TYPE: return false;
8589 case EXPR_ALIGNOF: return false;
8591 case EXPR_FUNCNAME: return false;
8592 case EXPR_BUILTIN_CONSTANT_P: return false;
8593 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8594 case EXPR_OFFSETOF: return false;
8595 case EXPR_VA_START: return true;
8596 case EXPR_VA_ARG: return true;
8597 case EXPR_VA_COPY: return true;
8598 case EXPR_STATEMENT: return true; // TODO
8599 case EXPR_COMPOUND_LITERAL: return false;
8601 case EXPR_UNARY_NEGATE: return false;
8602 case EXPR_UNARY_PLUS: return false;
8603 case EXPR_UNARY_BITWISE_NEGATE: return false;
8604 case EXPR_UNARY_NOT: return false;
8605 case EXPR_UNARY_DEREFERENCE: return false;
8606 case EXPR_UNARY_TAKE_ADDRESS: return false;
8607 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8608 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8609 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8610 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8612 /* Treat void casts as if they have an effect in order to being able to
8613 * suppress the warning */
8614 case EXPR_UNARY_CAST: {
8615 type_t *const type = skip_typeref(expr->base.type);
8616 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8619 case EXPR_UNARY_ASSUME: return true;
8620 case EXPR_UNARY_DELETE: return true;
8621 case EXPR_UNARY_DELETE_ARRAY: return true;
8622 case EXPR_UNARY_THROW: return true;
8624 case EXPR_BINARY_ADD: return false;
8625 case EXPR_BINARY_SUB: return false;
8626 case EXPR_BINARY_MUL: return false;
8627 case EXPR_BINARY_DIV: return false;
8628 case EXPR_BINARY_MOD: return false;
8629 case EXPR_BINARY_EQUAL: return false;
8630 case EXPR_BINARY_NOTEQUAL: return false;
8631 case EXPR_BINARY_LESS: return false;
8632 case EXPR_BINARY_LESSEQUAL: return false;
8633 case EXPR_BINARY_GREATER: return false;
8634 case EXPR_BINARY_GREATEREQUAL: return false;
8635 case EXPR_BINARY_BITWISE_AND: return false;
8636 case EXPR_BINARY_BITWISE_OR: return false;
8637 case EXPR_BINARY_BITWISE_XOR: return false;
8638 case EXPR_BINARY_SHIFTLEFT: return false;
8639 case EXPR_BINARY_SHIFTRIGHT: return false;
8640 case EXPR_BINARY_ASSIGN: return true;
8641 case EXPR_BINARY_MUL_ASSIGN: return true;
8642 case EXPR_BINARY_DIV_ASSIGN: return true;
8643 case EXPR_BINARY_MOD_ASSIGN: return true;
8644 case EXPR_BINARY_ADD_ASSIGN: return true;
8645 case EXPR_BINARY_SUB_ASSIGN: return true;
8646 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8647 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8648 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8649 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8650 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8652 /* Only examine the right hand side of && and ||, because the left hand
8653 * side already has the effect of controlling the execution of the right
8655 case EXPR_BINARY_LOGICAL_AND:
8656 case EXPR_BINARY_LOGICAL_OR:
8657 /* Only examine the right hand side of a comma expression, because the left
8658 * hand side has a separate warning */
8659 case EXPR_BINARY_COMMA:
8660 return expression_has_effect(expr->binary.right);
8662 case EXPR_BINARY_ISGREATER: return false;
8663 case EXPR_BINARY_ISGREATEREQUAL: return false;
8664 case EXPR_BINARY_ISLESS: return false;
8665 case EXPR_BINARY_ISLESSEQUAL: return false;
8666 case EXPR_BINARY_ISLESSGREATER: return false;
8667 case EXPR_BINARY_ISUNORDERED: return false;
8670 internal_errorf(HERE, "unexpected expression");
8673 static void semantic_comma(binary_expression_t *expression)
8675 const expression_t *const left = expression->left;
8676 if (!expression_has_effect(left)) {
8677 source_position_t const *const pos = &left->base.source_position;
8678 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8680 expression->base.type = expression->right->base.type;
8684 * @param prec_r precedence of the right operand
8686 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8687 static expression_t *parse_##binexpression_type(expression_t *left) \
8689 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8690 binexpr->binary.left = left; \
8693 expression_t *right = parse_subexpression(prec_r); \
8695 binexpr->binary.right = right; \
8696 sfunc(&binexpr->binary); \
8701 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8702 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8703 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8704 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8705 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8706 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8707 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8708 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8709 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8710 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8711 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8712 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8713 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8714 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8715 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8716 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8717 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8718 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8719 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8720 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8721 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8722 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8723 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8724 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8725 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8726 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8727 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8728 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8729 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8730 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8733 static expression_t *parse_subexpression(precedence_t precedence)
8735 if (token.kind < 0) {
8736 return expected_expression_error();
8739 expression_parser_function_t *parser
8740 = &expression_parsers[token.kind];
8743 if (parser->parser != NULL) {
8744 left = parser->parser();
8746 left = parse_primary_expression();
8748 assert(left != NULL);
8751 if (token.kind < 0) {
8752 return expected_expression_error();
8755 parser = &expression_parsers[token.kind];
8756 if (parser->infix_parser == NULL)
8758 if (parser->infix_precedence < precedence)
8761 left = parser->infix_parser(left);
8763 assert(left != NULL);
8770 * Parse an expression.
8772 static expression_t *parse_expression(void)
8774 return parse_subexpression(PREC_EXPRESSION);
8778 * Register a parser for a prefix-like operator.
8780 * @param parser the parser function
8781 * @param token_kind the token type of the prefix token
8783 static void register_expression_parser(parse_expression_function parser,
8786 expression_parser_function_t *entry = &expression_parsers[token_kind];
8788 if (entry->parser != NULL) {
8789 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8790 panic("trying to register multiple expression parsers for a token");
8792 entry->parser = parser;
8796 * Register a parser for an infix operator with given precedence.
8798 * @param parser the parser function
8799 * @param token_kind the token type of the infix operator
8800 * @param precedence the precedence of the operator
8802 static void register_infix_parser(parse_expression_infix_function parser,
8803 int token_kind, precedence_t precedence)
8805 expression_parser_function_t *entry = &expression_parsers[token_kind];
8807 if (entry->infix_parser != NULL) {
8808 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8809 panic("trying to register multiple infix expression parsers for a "
8812 entry->infix_parser = parser;
8813 entry->infix_precedence = precedence;
8817 * Initialize the expression parsers.
8819 static void init_expression_parsers(void)
8821 memset(&expression_parsers, 0, sizeof(expression_parsers));
8823 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8824 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8825 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8826 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8827 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8828 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8829 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8830 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8831 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8832 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8833 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8834 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8835 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8836 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8837 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8838 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8839 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8840 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8841 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8842 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8843 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8844 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8845 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8846 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8847 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8848 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8849 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8850 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8851 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8852 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8853 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8854 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8855 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8856 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8857 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8858 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8859 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8861 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8862 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8863 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8864 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8865 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8866 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8867 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8868 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8869 register_expression_parser(parse_sizeof, T_sizeof);
8870 register_expression_parser(parse_alignof, T___alignof__);
8871 register_expression_parser(parse_extension, T___extension__);
8872 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8873 register_expression_parser(parse_delete, T_delete);
8874 register_expression_parser(parse_throw, T_throw);
8878 * Parse a asm statement arguments specification.
8880 static asm_argument_t *parse_asm_arguments(bool is_out)
8882 asm_argument_t *result = NULL;
8883 asm_argument_t **anchor = &result;
8885 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8886 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8887 memset(argument, 0, sizeof(argument[0]));
8890 if (token.kind != T_IDENTIFIER) {
8891 parse_error_expected("while parsing asm argument",
8892 T_IDENTIFIER, NULL);
8895 argument->symbol = token.identifier.symbol;
8897 expect(']', end_error);
8900 argument->constraints = parse_string_literals();
8901 expect('(', end_error);
8902 add_anchor_token(')');
8903 expression_t *expression = parse_expression();
8904 rem_anchor_token(')');
8906 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8907 * change size or type representation (e.g. int -> long is ok, but
8908 * int -> float is not) */
8909 if (expression->kind == EXPR_UNARY_CAST) {
8910 type_t *const type = expression->base.type;
8911 type_kind_t const kind = type->kind;
8912 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8915 if (kind == TYPE_ATOMIC) {
8916 atomic_type_kind_t const akind = type->atomic.akind;
8917 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8918 size = get_atomic_type_size(akind);
8920 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8921 size = get_type_size(type_void_ptr);
8925 expression_t *const value = expression->unary.value;
8926 type_t *const value_type = value->base.type;
8927 type_kind_t const value_kind = value_type->kind;
8929 unsigned value_flags;
8930 unsigned value_size;
8931 if (value_kind == TYPE_ATOMIC) {
8932 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8933 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8934 value_size = get_atomic_type_size(value_akind);
8935 } else if (value_kind == TYPE_POINTER) {
8936 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8937 value_size = get_type_size(type_void_ptr);
8942 if (value_flags != flags || value_size != size)
8946 } while (expression->kind == EXPR_UNARY_CAST);
8950 if (!is_lvalue(expression)) {
8951 errorf(&expression->base.source_position,
8952 "asm output argument is not an lvalue");
8955 if (argument->constraints.begin[0] == '=')
8956 determine_lhs_ent(expression, NULL);
8958 mark_vars_read(expression, NULL);
8960 mark_vars_read(expression, NULL);
8962 argument->expression = expression;
8963 expect(')', end_error);
8965 set_address_taken(expression, true);
8968 anchor = &argument->next;
8980 * Parse a asm statement clobber specification.
8982 static asm_clobber_t *parse_asm_clobbers(void)
8984 asm_clobber_t *result = NULL;
8985 asm_clobber_t **anchor = &result;
8987 while (token.kind == T_STRING_LITERAL) {
8988 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8989 clobber->clobber = parse_string_literals();
8992 anchor = &clobber->next;
9002 * Parse an asm statement.
9004 static statement_t *parse_asm_statement(void)
9006 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9007 asm_statement_t *asm_statement = &statement->asms;
9011 if (next_if(T_volatile))
9012 asm_statement->is_volatile = true;
9014 expect('(', end_error);
9015 add_anchor_token(')');
9016 if (token.kind != T_STRING_LITERAL) {
9017 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9020 asm_statement->asm_text = parse_string_literals();
9022 add_anchor_token(':');
9023 if (!next_if(':')) {
9024 rem_anchor_token(':');
9028 asm_statement->outputs = parse_asm_arguments(true);
9029 if (!next_if(':')) {
9030 rem_anchor_token(':');
9034 asm_statement->inputs = parse_asm_arguments(false);
9035 if (!next_if(':')) {
9036 rem_anchor_token(':');
9039 rem_anchor_token(':');
9041 asm_statement->clobbers = parse_asm_clobbers();
9044 rem_anchor_token(')');
9045 expect(')', end_error);
9046 expect(';', end_error);
9048 if (asm_statement->outputs == NULL) {
9049 /* GCC: An 'asm' instruction without any output operands will be treated
9050 * identically to a volatile 'asm' instruction. */
9051 asm_statement->is_volatile = true;
9056 return create_error_statement();
9059 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9061 statement_t *inner_stmt;
9062 switch (token.kind) {
9064 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9065 inner_stmt = create_error_statement();
9069 if (label->kind == STATEMENT_LABEL) {
9070 /* Eat an empty statement here, to avoid the warning about an empty
9071 * statement after a label. label:; is commonly used to have a label
9072 * before a closing brace. */
9073 inner_stmt = create_empty_statement();
9080 inner_stmt = parse_statement();
9081 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9082 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9083 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9084 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9092 * Parse a case statement.
9094 static statement_t *parse_case_statement(void)
9096 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9097 source_position_t *const pos = &statement->base.source_position;
9101 expression_t *const expression = parse_expression();
9102 statement->case_label.expression = expression;
9103 expression_classification_t const expr_class = is_constant_expression(expression);
9104 if (expr_class != EXPR_CLASS_CONSTANT) {
9105 if (expr_class != EXPR_CLASS_ERROR) {
9106 errorf(pos, "case label does not reduce to an integer constant");
9108 statement->case_label.is_bad = true;
9110 long const val = fold_constant_to_int(expression);
9111 statement->case_label.first_case = val;
9112 statement->case_label.last_case = val;
9116 if (next_if(T_DOTDOTDOT)) {
9117 expression_t *const end_range = parse_expression();
9118 statement->case_label.end_range = end_range;
9119 expression_classification_t const end_class = is_constant_expression(end_range);
9120 if (end_class != EXPR_CLASS_CONSTANT) {
9121 if (end_class != EXPR_CLASS_ERROR) {
9122 errorf(pos, "case range does not reduce to an integer constant");
9124 statement->case_label.is_bad = true;
9126 long const val = fold_constant_to_int(end_range);
9127 statement->case_label.last_case = val;
9129 if (val < statement->case_label.first_case) {
9130 statement->case_label.is_empty_range = true;
9131 warningf(WARN_OTHER, pos, "empty range specified");
9137 PUSH_PARENT(statement);
9139 expect(':', end_error);
9142 if (current_switch != NULL) {
9143 if (! statement->case_label.is_bad) {
9144 /* Check for duplicate case values */
9145 case_label_statement_t *c = &statement->case_label;
9146 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9147 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9150 if (c->last_case < l->first_case || c->first_case > l->last_case)
9153 errorf(pos, "duplicate case value (previously used %P)",
9154 &l->base.source_position);
9158 /* link all cases into the switch statement */
9159 if (current_switch->last_case == NULL) {
9160 current_switch->first_case = &statement->case_label;
9162 current_switch->last_case->next = &statement->case_label;
9164 current_switch->last_case = &statement->case_label;
9166 errorf(pos, "case label not within a switch statement");
9169 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9176 * Parse a default statement.
9178 static statement_t *parse_default_statement(void)
9180 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9184 PUSH_PARENT(statement);
9186 expect(':', end_error);
9189 if (current_switch != NULL) {
9190 const case_label_statement_t *def_label = current_switch->default_label;
9191 if (def_label != NULL) {
9192 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9194 current_switch->default_label = &statement->case_label;
9196 /* link all cases into the switch statement */
9197 if (current_switch->last_case == NULL) {
9198 current_switch->first_case = &statement->case_label;
9200 current_switch->last_case->next = &statement->case_label;
9202 current_switch->last_case = &statement->case_label;
9205 errorf(&statement->base.source_position,
9206 "'default' label not within a switch statement");
9209 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9216 * Parse a label statement.
9218 static statement_t *parse_label_statement(void)
9220 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9221 label_t *const label = get_label();
9222 statement->label.label = label;
9224 PUSH_PARENT(statement);
9226 /* if statement is already set then the label is defined twice,
9227 * otherwise it was just mentioned in a goto/local label declaration so far
9229 source_position_t const* const pos = &statement->base.source_position;
9230 if (label->statement != NULL) {
9231 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9233 label->base.source_position = *pos;
9234 label->statement = statement;
9239 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9240 parse_attributes(NULL); // TODO process attributes
9243 statement->label.statement = parse_label_inner_statement(statement, "label");
9245 /* remember the labels in a list for later checking */
9246 *label_anchor = &statement->label;
9247 label_anchor = &statement->label.next;
9253 static statement_t *parse_inner_statement(void)
9255 statement_t *const stmt = parse_statement();
9256 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9257 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9258 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9259 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9265 * Parse an if statement.
9267 static statement_t *parse_if(void)
9269 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9273 PUSH_PARENT(statement);
9275 add_anchor_token('{');
9277 expect('(', end_error);
9278 add_anchor_token(')');
9279 expression_t *const expr = parse_expression();
9280 statement->ifs.condition = expr;
9281 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9283 semantic_condition(expr, "condition of 'if'-statment");
9284 mark_vars_read(expr, NULL);
9285 rem_anchor_token(')');
9286 expect(')', end_error);
9289 rem_anchor_token('{');
9291 add_anchor_token(T_else);
9292 statement_t *const true_stmt = parse_inner_statement();
9293 statement->ifs.true_statement = true_stmt;
9294 rem_anchor_token(T_else);
9296 if (true_stmt->kind == STATEMENT_EMPTY) {
9297 warningf(WARN_EMPTY_BODY, HERE,
9298 "suggest braces around empty body in an ‘if’ statement");
9301 if (next_if(T_else)) {
9302 statement->ifs.false_statement = parse_inner_statement();
9304 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9305 warningf(WARN_EMPTY_BODY, HERE,
9306 "suggest braces around empty body in an ‘if’ statement");
9308 } else if (true_stmt->kind == STATEMENT_IF &&
9309 true_stmt->ifs.false_statement != NULL) {
9310 source_position_t const *const pos = &true_stmt->base.source_position;
9311 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9319 * Check that all enums are handled in a switch.
9321 * @param statement the switch statement to check
9323 static void check_enum_cases(const switch_statement_t *statement)
9325 if (!is_warn_on(WARN_SWITCH_ENUM))
9327 const type_t *type = skip_typeref(statement->expression->base.type);
9328 if (! is_type_enum(type))
9330 const enum_type_t *enumt = &type->enumt;
9332 /* if we have a default, no warnings */
9333 if (statement->default_label != NULL)
9336 /* FIXME: calculation of value should be done while parsing */
9337 /* TODO: quadratic algorithm here. Change to an n log n one */
9338 long last_value = -1;
9339 const entity_t *entry = enumt->enume->base.next;
9340 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9341 entry = entry->base.next) {
9342 const expression_t *expression = entry->enum_value.value;
9343 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9345 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9346 if (l->expression == NULL)
9348 if (l->first_case <= value && value <= l->last_case) {
9354 source_position_t const *const pos = &statement->base.source_position;
9355 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9362 * Parse a switch statement.
9364 static statement_t *parse_switch(void)
9366 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9370 PUSH_PARENT(statement);
9372 expect('(', end_error);
9373 add_anchor_token(')');
9374 expression_t *const expr = parse_expression();
9375 mark_vars_read(expr, NULL);
9376 type_t * type = skip_typeref(expr->base.type);
9377 if (is_type_integer(type)) {
9378 type = promote_integer(type);
9379 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9380 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9382 } else if (is_type_valid(type)) {
9383 errorf(&expr->base.source_position,
9384 "switch quantity is not an integer, but '%T'", type);
9385 type = type_error_type;
9387 statement->switchs.expression = create_implicit_cast(expr, type);
9388 expect(')', end_error);
9389 rem_anchor_token(')');
9391 switch_statement_t *rem = current_switch;
9392 current_switch = &statement->switchs;
9393 statement->switchs.body = parse_inner_statement();
9394 current_switch = rem;
9396 if (statement->switchs.default_label == NULL) {
9397 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9399 check_enum_cases(&statement->switchs);
9405 return create_error_statement();
9408 static statement_t *parse_loop_body(statement_t *const loop)
9410 statement_t *const rem = current_loop;
9411 current_loop = loop;
9413 statement_t *const body = parse_inner_statement();
9420 * Parse a while statement.
9422 static statement_t *parse_while(void)
9424 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9428 PUSH_PARENT(statement);
9430 expect('(', end_error);
9431 add_anchor_token(')');
9432 expression_t *const cond = parse_expression();
9433 statement->whiles.condition = cond;
9434 /* §6.8.5:2 The controlling expression of an iteration statement shall
9435 * have scalar type. */
9436 semantic_condition(cond, "condition of 'while'-statement");
9437 mark_vars_read(cond, NULL);
9438 rem_anchor_token(')');
9439 expect(')', end_error);
9441 statement->whiles.body = parse_loop_body(statement);
9447 return create_error_statement();
9451 * Parse a do statement.
9453 static statement_t *parse_do(void)
9455 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9459 PUSH_PARENT(statement);
9461 add_anchor_token(T_while);
9462 statement->do_while.body = parse_loop_body(statement);
9463 rem_anchor_token(T_while);
9465 expect(T_while, end_error);
9466 expect('(', end_error);
9467 add_anchor_token(')');
9468 expression_t *const cond = parse_expression();
9469 statement->do_while.condition = cond;
9470 /* §6.8.5:2 The controlling expression of an iteration statement shall
9471 * have scalar type. */
9472 semantic_condition(cond, "condition of 'do-while'-statement");
9473 mark_vars_read(cond, NULL);
9474 rem_anchor_token(')');
9475 expect(')', end_error);
9476 expect(';', end_error);
9482 return create_error_statement();
9486 * Parse a for statement.
9488 static statement_t *parse_for(void)
9490 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9494 expect('(', end_error1);
9495 add_anchor_token(')');
9497 PUSH_PARENT(statement);
9498 PUSH_SCOPE(&statement->fors.scope);
9503 } else if (is_declaration_specifier(&token)) {
9504 parse_declaration(record_entity, DECL_FLAGS_NONE);
9506 add_anchor_token(';');
9507 expression_t *const init = parse_expression();
9508 statement->fors.initialisation = init;
9509 mark_vars_read(init, ENT_ANY);
9510 if (!expression_has_effect(init)) {
9511 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9513 rem_anchor_token(';');
9514 expect(';', end_error2);
9519 if (token.kind != ';') {
9520 add_anchor_token(';');
9521 expression_t *const cond = parse_expression();
9522 statement->fors.condition = cond;
9523 /* §6.8.5:2 The controlling expression of an iteration statement
9524 * shall have scalar type. */
9525 semantic_condition(cond, "condition of 'for'-statement");
9526 mark_vars_read(cond, NULL);
9527 rem_anchor_token(';');
9529 expect(';', end_error2);
9530 if (token.kind != ')') {
9531 expression_t *const step = parse_expression();
9532 statement->fors.step = step;
9533 mark_vars_read(step, ENT_ANY);
9534 if (!expression_has_effect(step)) {
9535 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9538 expect(')', end_error2);
9539 rem_anchor_token(')');
9540 statement->fors.body = parse_loop_body(statement);
9548 rem_anchor_token(')');
9553 return create_error_statement();
9557 * Parse a goto statement.
9559 static statement_t *parse_goto(void)
9561 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9564 if (GNU_MODE && next_if('*')) {
9565 expression_t *expression = parse_expression();
9566 mark_vars_read(expression, NULL);
9568 /* Argh: although documentation says the expression must be of type void*,
9569 * gcc accepts anything that can be casted into void* without error */
9570 type_t *type = expression->base.type;
9572 if (type != type_error_type) {
9573 if (!is_type_pointer(type) && !is_type_integer(type)) {
9574 errorf(&expression->base.source_position,
9575 "cannot convert to a pointer type");
9576 } else if (type != type_void_ptr) {
9577 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9579 expression = create_implicit_cast(expression, type_void_ptr);
9582 statement->gotos.expression = expression;
9583 } else if (token.kind == T_IDENTIFIER) {
9584 label_t *const label = get_label();
9586 statement->gotos.label = label;
9589 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9591 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9593 return create_error_statement();
9596 /* remember the goto's in a list for later checking */
9597 *goto_anchor = &statement->gotos;
9598 goto_anchor = &statement->gotos.next;
9600 expect(';', end_error);
9607 * Parse a continue statement.
9609 static statement_t *parse_continue(void)
9611 if (current_loop == NULL) {
9612 errorf(HERE, "continue statement not within loop");
9615 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9618 expect(';', end_error);
9625 * Parse a break statement.
9627 static statement_t *parse_break(void)
9629 if (current_switch == NULL && current_loop == NULL) {
9630 errorf(HERE, "break statement not within loop or switch");
9633 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9636 expect(';', end_error);
9643 * Parse a __leave statement.
9645 static statement_t *parse_leave_statement(void)
9647 if (current_try == NULL) {
9648 errorf(HERE, "__leave statement not within __try");
9651 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9654 expect(';', end_error);
9661 * Check if a given entity represents a local variable.
9663 static bool is_local_variable(const entity_t *entity)
9665 if (entity->kind != ENTITY_VARIABLE)
9668 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9669 case STORAGE_CLASS_AUTO:
9670 case STORAGE_CLASS_REGISTER: {
9671 const type_t *type = skip_typeref(entity->declaration.type);
9672 if (is_type_function(type)) {
9684 * Check if a given expression represents a local variable.
9686 static bool expression_is_local_variable(const expression_t *expression)
9688 if (expression->base.kind != EXPR_REFERENCE) {
9691 const entity_t *entity = expression->reference.entity;
9692 return is_local_variable(entity);
9696 * Check if a given expression represents a local variable and
9697 * return its declaration then, else return NULL.
9699 entity_t *expression_is_variable(const expression_t *expression)
9701 if (expression->base.kind != EXPR_REFERENCE) {
9704 entity_t *entity = expression->reference.entity;
9705 if (entity->kind != ENTITY_VARIABLE)
9712 * Parse a return statement.
9714 static statement_t *parse_return(void)
9716 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9719 expression_t *return_value = NULL;
9720 if (token.kind != ';') {
9721 return_value = parse_expression();
9722 mark_vars_read(return_value, NULL);
9725 const type_t *const func_type = skip_typeref(current_function->base.type);
9726 assert(is_type_function(func_type));
9727 type_t *const return_type = skip_typeref(func_type->function.return_type);
9729 source_position_t const *const pos = &statement->base.source_position;
9730 if (return_value != NULL) {
9731 type_t *return_value_type = skip_typeref(return_value->base.type);
9733 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9734 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9735 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9736 /* Only warn in C mode, because GCC does the same */
9737 if (c_mode & _CXX || strict_mode) {
9739 "'return' with a value, in function returning 'void'");
9741 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9743 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9744 /* Only warn in C mode, because GCC does the same */
9747 "'return' with expression in function returning 'void'");
9749 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9753 assign_error_t error = semantic_assign(return_type, return_value);
9754 report_assign_error(error, return_type, return_value, "'return'",
9757 return_value = create_implicit_cast(return_value, return_type);
9758 /* check for returning address of a local var */
9759 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9760 const expression_t *expression = return_value->unary.value;
9761 if (expression_is_local_variable(expression)) {
9762 warningf(WARN_OTHER, pos, "function returns address of local variable");
9765 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9766 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9767 if (c_mode & _CXX || strict_mode) {
9769 "'return' without value, in function returning non-void");
9771 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9774 statement->returns.value = return_value;
9776 expect(';', end_error);
9783 * Parse a declaration statement.
9785 static statement_t *parse_declaration_statement(void)
9787 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9789 entity_t *before = current_scope->last_entity;
9791 parse_external_declaration();
9793 parse_declaration(record_entity, DECL_FLAGS_NONE);
9796 declaration_statement_t *const decl = &statement->declaration;
9797 entity_t *const begin =
9798 before != NULL ? before->base.next : current_scope->entities;
9799 decl->declarations_begin = begin;
9800 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9806 * Parse an expression statement, ie. expr ';'.
9808 static statement_t *parse_expression_statement(void)
9810 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9812 expression_t *const expr = parse_expression();
9813 statement->expression.expression = expr;
9814 mark_vars_read(expr, ENT_ANY);
9816 expect(';', end_error);
9823 * Parse a microsoft __try { } __finally { } or
9824 * __try{ } __except() { }
9826 static statement_t *parse_ms_try_statment(void)
9828 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9831 PUSH_PARENT(statement);
9833 ms_try_statement_t *rem = current_try;
9834 current_try = &statement->ms_try;
9835 statement->ms_try.try_statement = parse_compound_statement(false);
9840 if (next_if(T___except)) {
9841 expect('(', end_error);
9842 add_anchor_token(')');
9843 expression_t *const expr = parse_expression();
9844 mark_vars_read(expr, NULL);
9845 type_t * type = skip_typeref(expr->base.type);
9846 if (is_type_integer(type)) {
9847 type = promote_integer(type);
9848 } else if (is_type_valid(type)) {
9849 errorf(&expr->base.source_position,
9850 "__expect expression is not an integer, but '%T'", type);
9851 type = type_error_type;
9853 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9854 rem_anchor_token(')');
9855 expect(')', end_error);
9856 statement->ms_try.final_statement = parse_compound_statement(false);
9857 } else if (next_if(T__finally)) {
9858 statement->ms_try.final_statement = parse_compound_statement(false);
9860 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9861 return create_error_statement();
9865 return create_error_statement();
9868 static statement_t *parse_empty_statement(void)
9870 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9871 statement_t *const statement = create_empty_statement();
9876 static statement_t *parse_local_label_declaration(void)
9878 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9882 entity_t *begin = NULL;
9883 entity_t *end = NULL;
9884 entity_t **anchor = &begin;
9886 if (token.kind != T_IDENTIFIER) {
9887 parse_error_expected("while parsing local label declaration",
9888 T_IDENTIFIER, NULL);
9891 symbol_t *symbol = token.identifier.symbol;
9892 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9893 if (entity != NULL && entity->base.parent_scope == current_scope) {
9894 source_position_t const *const ppos = &entity->base.source_position;
9895 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9897 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9898 entity->base.parent_scope = current_scope;
9899 entity->base.source_position = token.base.source_position;
9902 anchor = &entity->base.next;
9905 environment_push(entity);
9908 } while (next_if(','));
9909 expect(';', end_error);
9911 statement->declaration.declarations_begin = begin;
9912 statement->declaration.declarations_end = end;
9916 static void parse_namespace_definition(void)
9920 entity_t *entity = NULL;
9921 symbol_t *symbol = NULL;
9923 if (token.kind == T_IDENTIFIER) {
9924 symbol = token.identifier.symbol;
9927 entity = get_entity(symbol, NAMESPACE_NORMAL);
9929 && entity->kind != ENTITY_NAMESPACE
9930 && entity->base.parent_scope == current_scope) {
9931 if (is_entity_valid(entity)) {
9932 error_redefined_as_different_kind(&token.base.source_position,
9933 entity, ENTITY_NAMESPACE);
9939 if (entity == NULL) {
9940 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9941 entity->base.source_position = token.base.source_position;
9942 entity->base.parent_scope = current_scope;
9945 if (token.kind == '=') {
9946 /* TODO: parse namespace alias */
9947 panic("namespace alias definition not supported yet");
9950 environment_push(entity);
9951 append_entity(current_scope, entity);
9953 PUSH_SCOPE(&entity->namespacee.members);
9955 entity_t *old_current_entity = current_entity;
9956 current_entity = entity;
9958 expect('{', end_error);
9960 expect('}', end_error);
9963 assert(current_entity == entity);
9964 current_entity = old_current_entity;
9969 * Parse a statement.
9970 * There's also parse_statement() which additionally checks for
9971 * "statement has no effect" warnings
9973 static statement_t *intern_parse_statement(void)
9975 statement_t *statement = NULL;
9977 /* declaration or statement */
9978 add_anchor_token(';');
9979 switch (token.kind) {
9980 case T_IDENTIFIER: {
9981 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9982 if (la1_type == ':') {
9983 statement = parse_label_statement();
9984 } else if (is_typedef_symbol(token.identifier.symbol)) {
9985 statement = parse_declaration_statement();
9987 /* it's an identifier, the grammar says this must be an
9988 * expression statement. However it is common that users mistype
9989 * declaration types, so we guess a bit here to improve robustness
9990 * for incorrect programs */
9994 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9996 statement = parse_expression_statement();
10000 statement = parse_declaration_statement();
10008 case T___extension__: {
10009 /* This can be a prefix to a declaration or an expression statement.
10010 * We simply eat it now and parse the rest with tail recursion. */
10012 statement = intern_parse_statement();
10018 statement = parse_declaration_statement();
10022 statement = parse_local_label_declaration();
10025 case ';': statement = parse_empty_statement(); break;
10026 case '{': statement = parse_compound_statement(false); break;
10027 case T___leave: statement = parse_leave_statement(); break;
10028 case T___try: statement = parse_ms_try_statment(); break;
10029 case T_asm: statement = parse_asm_statement(); break;
10030 case T_break: statement = parse_break(); break;
10031 case T_case: statement = parse_case_statement(); break;
10032 case T_continue: statement = parse_continue(); break;
10033 case T_default: statement = parse_default_statement(); break;
10034 case T_do: statement = parse_do(); break;
10035 case T_for: statement = parse_for(); break;
10036 case T_goto: statement = parse_goto(); break;
10037 case T_if: statement = parse_if(); break;
10038 case T_return: statement = parse_return(); break;
10039 case T_switch: statement = parse_switch(); break;
10040 case T_while: statement = parse_while(); break;
10043 statement = parse_expression_statement();
10047 errorf(HERE, "unexpected token %K while parsing statement", &token);
10048 statement = create_error_statement();
10053 rem_anchor_token(';');
10055 assert(statement != NULL
10056 && statement->base.source_position.input_name != NULL);
10062 * parse a statement and emits "statement has no effect" warning if needed
10063 * (This is really a wrapper around intern_parse_statement with check for 1
10064 * single warning. It is needed, because for statement expressions we have
10065 * to avoid the warning on the last statement)
10067 static statement_t *parse_statement(void)
10069 statement_t *statement = intern_parse_statement();
10071 if (statement->kind == STATEMENT_EXPRESSION) {
10072 expression_t *expression = statement->expression.expression;
10073 if (!expression_has_effect(expression)) {
10074 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10082 * Parse a compound statement.
10084 static statement_t *parse_compound_statement(bool inside_expression_statement)
10086 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10088 PUSH_PARENT(statement);
10089 PUSH_SCOPE(&statement->compound.scope);
10092 add_anchor_token('}');
10093 /* tokens, which can start a statement */
10094 /* TODO MS, __builtin_FOO */
10095 add_anchor_token('!');
10096 add_anchor_token('&');
10097 add_anchor_token('(');
10098 add_anchor_token('*');
10099 add_anchor_token('+');
10100 add_anchor_token('-');
10101 add_anchor_token('{');
10102 add_anchor_token('~');
10103 add_anchor_token(T_CHARACTER_CONSTANT);
10104 add_anchor_token(T_COLONCOLON);
10105 add_anchor_token(T_FLOATINGPOINT);
10106 add_anchor_token(T_IDENTIFIER);
10107 add_anchor_token(T_INTEGER);
10108 add_anchor_token(T_MINUSMINUS);
10109 add_anchor_token(T_PLUSPLUS);
10110 add_anchor_token(T_STRING_LITERAL);
10111 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10112 add_anchor_token(T_WIDE_STRING_LITERAL);
10113 add_anchor_token(T__Bool);
10114 add_anchor_token(T__Complex);
10115 add_anchor_token(T__Imaginary);
10116 add_anchor_token(T___FUNCTION__);
10117 add_anchor_token(T___PRETTY_FUNCTION__);
10118 add_anchor_token(T___alignof__);
10119 add_anchor_token(T___attribute__);
10120 add_anchor_token(T___builtin_va_start);
10121 add_anchor_token(T___extension__);
10122 add_anchor_token(T___func__);
10123 add_anchor_token(T___imag__);
10124 add_anchor_token(T___label__);
10125 add_anchor_token(T___real__);
10126 add_anchor_token(T___thread);
10127 add_anchor_token(T_asm);
10128 add_anchor_token(T_auto);
10129 add_anchor_token(T_bool);
10130 add_anchor_token(T_break);
10131 add_anchor_token(T_case);
10132 add_anchor_token(T_char);
10133 add_anchor_token(T_class);
10134 add_anchor_token(T_const);
10135 add_anchor_token(T_const_cast);
10136 add_anchor_token(T_continue);
10137 add_anchor_token(T_default);
10138 add_anchor_token(T_delete);
10139 add_anchor_token(T_double);
10140 add_anchor_token(T_do);
10141 add_anchor_token(T_dynamic_cast);
10142 add_anchor_token(T_enum);
10143 add_anchor_token(T_extern);
10144 add_anchor_token(T_false);
10145 add_anchor_token(T_float);
10146 add_anchor_token(T_for);
10147 add_anchor_token(T_goto);
10148 add_anchor_token(T_if);
10149 add_anchor_token(T_inline);
10150 add_anchor_token(T_int);
10151 add_anchor_token(T_long);
10152 add_anchor_token(T_new);
10153 add_anchor_token(T_operator);
10154 add_anchor_token(T_register);
10155 add_anchor_token(T_reinterpret_cast);
10156 add_anchor_token(T_restrict);
10157 add_anchor_token(T_return);
10158 add_anchor_token(T_short);
10159 add_anchor_token(T_signed);
10160 add_anchor_token(T_sizeof);
10161 add_anchor_token(T_static);
10162 add_anchor_token(T_static_cast);
10163 add_anchor_token(T_struct);
10164 add_anchor_token(T_switch);
10165 add_anchor_token(T_template);
10166 add_anchor_token(T_this);
10167 add_anchor_token(T_throw);
10168 add_anchor_token(T_true);
10169 add_anchor_token(T_try);
10170 add_anchor_token(T_typedef);
10171 add_anchor_token(T_typeid);
10172 add_anchor_token(T_typename);
10173 add_anchor_token(T_typeof);
10174 add_anchor_token(T_union);
10175 add_anchor_token(T_unsigned);
10176 add_anchor_token(T_using);
10177 add_anchor_token(T_void);
10178 add_anchor_token(T_volatile);
10179 add_anchor_token(T_wchar_t);
10180 add_anchor_token(T_while);
10182 statement_t **anchor = &statement->compound.statements;
10183 bool only_decls_so_far = true;
10184 while (token.kind != '}') {
10185 if (token.kind == T_EOF) {
10186 errorf(&statement->base.source_position,
10187 "EOF while parsing compound statement");
10190 statement_t *sub_statement = intern_parse_statement();
10191 if (sub_statement->kind == STATEMENT_ERROR) {
10192 /* an error occurred. if we are at an anchor, return */
10198 if (sub_statement->kind != STATEMENT_DECLARATION) {
10199 only_decls_so_far = false;
10200 } else if (!only_decls_so_far) {
10201 source_position_t const *const pos = &sub_statement->base.source_position;
10202 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10205 *anchor = sub_statement;
10207 while (sub_statement->base.next != NULL)
10208 sub_statement = sub_statement->base.next;
10210 anchor = &sub_statement->base.next;
10214 /* look over all statements again to produce no effect warnings */
10215 if (is_warn_on(WARN_UNUSED_VALUE)) {
10216 statement_t *sub_statement = statement->compound.statements;
10217 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10218 if (sub_statement->kind != STATEMENT_EXPRESSION)
10220 /* don't emit a warning for the last expression in an expression
10221 * statement as it has always an effect */
10222 if (inside_expression_statement && sub_statement->base.next == NULL)
10225 expression_t *expression = sub_statement->expression.expression;
10226 if (!expression_has_effect(expression)) {
10227 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10233 rem_anchor_token(T_while);
10234 rem_anchor_token(T_wchar_t);
10235 rem_anchor_token(T_volatile);
10236 rem_anchor_token(T_void);
10237 rem_anchor_token(T_using);
10238 rem_anchor_token(T_unsigned);
10239 rem_anchor_token(T_union);
10240 rem_anchor_token(T_typeof);
10241 rem_anchor_token(T_typename);
10242 rem_anchor_token(T_typeid);
10243 rem_anchor_token(T_typedef);
10244 rem_anchor_token(T_try);
10245 rem_anchor_token(T_true);
10246 rem_anchor_token(T_throw);
10247 rem_anchor_token(T_this);
10248 rem_anchor_token(T_template);
10249 rem_anchor_token(T_switch);
10250 rem_anchor_token(T_struct);
10251 rem_anchor_token(T_static_cast);
10252 rem_anchor_token(T_static);
10253 rem_anchor_token(T_sizeof);
10254 rem_anchor_token(T_signed);
10255 rem_anchor_token(T_short);
10256 rem_anchor_token(T_return);
10257 rem_anchor_token(T_restrict);
10258 rem_anchor_token(T_reinterpret_cast);
10259 rem_anchor_token(T_register);
10260 rem_anchor_token(T_operator);
10261 rem_anchor_token(T_new);
10262 rem_anchor_token(T_long);
10263 rem_anchor_token(T_int);
10264 rem_anchor_token(T_inline);
10265 rem_anchor_token(T_if);
10266 rem_anchor_token(T_goto);
10267 rem_anchor_token(T_for);
10268 rem_anchor_token(T_float);
10269 rem_anchor_token(T_false);
10270 rem_anchor_token(T_extern);
10271 rem_anchor_token(T_enum);
10272 rem_anchor_token(T_dynamic_cast);
10273 rem_anchor_token(T_do);
10274 rem_anchor_token(T_double);
10275 rem_anchor_token(T_delete);
10276 rem_anchor_token(T_default);
10277 rem_anchor_token(T_continue);
10278 rem_anchor_token(T_const_cast);
10279 rem_anchor_token(T_const);
10280 rem_anchor_token(T_class);
10281 rem_anchor_token(T_char);
10282 rem_anchor_token(T_case);
10283 rem_anchor_token(T_break);
10284 rem_anchor_token(T_bool);
10285 rem_anchor_token(T_auto);
10286 rem_anchor_token(T_asm);
10287 rem_anchor_token(T___thread);
10288 rem_anchor_token(T___real__);
10289 rem_anchor_token(T___label__);
10290 rem_anchor_token(T___imag__);
10291 rem_anchor_token(T___func__);
10292 rem_anchor_token(T___extension__);
10293 rem_anchor_token(T___builtin_va_start);
10294 rem_anchor_token(T___attribute__);
10295 rem_anchor_token(T___alignof__);
10296 rem_anchor_token(T___PRETTY_FUNCTION__);
10297 rem_anchor_token(T___FUNCTION__);
10298 rem_anchor_token(T__Imaginary);
10299 rem_anchor_token(T__Complex);
10300 rem_anchor_token(T__Bool);
10301 rem_anchor_token(T_WIDE_STRING_LITERAL);
10302 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10303 rem_anchor_token(T_STRING_LITERAL);
10304 rem_anchor_token(T_PLUSPLUS);
10305 rem_anchor_token(T_MINUSMINUS);
10306 rem_anchor_token(T_INTEGER);
10307 rem_anchor_token(T_IDENTIFIER);
10308 rem_anchor_token(T_FLOATINGPOINT);
10309 rem_anchor_token(T_COLONCOLON);
10310 rem_anchor_token(T_CHARACTER_CONSTANT);
10311 rem_anchor_token('~');
10312 rem_anchor_token('{');
10313 rem_anchor_token('-');
10314 rem_anchor_token('+');
10315 rem_anchor_token('*');
10316 rem_anchor_token('(');
10317 rem_anchor_token('&');
10318 rem_anchor_token('!');
10319 rem_anchor_token('}');
10327 * Check for unused global static functions and variables
10329 static void check_unused_globals(void)
10331 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10334 for (const entity_t *entity = file_scope->entities; entity != NULL;
10335 entity = entity->base.next) {
10336 if (!is_declaration(entity))
10339 const declaration_t *declaration = &entity->declaration;
10340 if (declaration->used ||
10341 declaration->modifiers & DM_UNUSED ||
10342 declaration->modifiers & DM_USED ||
10343 declaration->storage_class != STORAGE_CLASS_STATIC)
10348 if (entity->kind == ENTITY_FUNCTION) {
10349 /* inhibit warning for static inline functions */
10350 if (entity->function.is_inline)
10353 why = WARN_UNUSED_FUNCTION;
10354 s = entity->function.statement != NULL ? "defined" : "declared";
10356 why = WARN_UNUSED_VARIABLE;
10360 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10364 static void parse_global_asm(void)
10366 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10369 expect('(', end_error);
10371 statement->asms.asm_text = parse_string_literals();
10372 statement->base.next = unit->global_asm;
10373 unit->global_asm = statement;
10375 expect(')', end_error);
10376 expect(';', end_error);
10381 static void parse_linkage_specification(void)
10385 source_position_t const pos = *HERE;
10386 char const *const linkage = parse_string_literals().begin;
10388 linkage_kind_t old_linkage = current_linkage;
10389 linkage_kind_t new_linkage;
10390 if (strcmp(linkage, "C") == 0) {
10391 new_linkage = LINKAGE_C;
10392 } else if (strcmp(linkage, "C++") == 0) {
10393 new_linkage = LINKAGE_CXX;
10395 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10396 new_linkage = LINKAGE_C;
10398 current_linkage = new_linkage;
10400 if (next_if('{')) {
10402 expect('}', end_error);
10408 assert(current_linkage == new_linkage);
10409 current_linkage = old_linkage;
10412 static void parse_external(void)
10414 switch (token.kind) {
10416 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10417 parse_linkage_specification();
10419 DECLARATION_START_NO_EXTERN
10421 case T___extension__:
10422 /* tokens below are for implicit int */
10423 case '&': /* & x; -> int& x; (and error later, because C++ has no
10425 case '*': /* * x; -> int* x; */
10426 case '(': /* (x); -> int (x); */
10428 parse_external_declaration();
10434 parse_global_asm();
10438 parse_namespace_definition();
10442 if (!strict_mode) {
10443 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10450 errorf(HERE, "stray %K outside of function", &token);
10451 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10452 eat_until_matching_token(token.kind);
10458 static void parse_externals(void)
10460 add_anchor_token('}');
10461 add_anchor_token(T_EOF);
10464 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10465 unsigned short token_anchor_copy[T_LAST_TOKEN];
10466 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10469 while (token.kind != T_EOF && token.kind != '}') {
10471 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10472 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10474 /* the anchor set and its copy differs */
10475 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10478 if (in_gcc_extension) {
10479 /* an gcc extension scope was not closed */
10480 internal_errorf(HERE, "Leaked __extension__");
10487 rem_anchor_token(T_EOF);
10488 rem_anchor_token('}');
10492 * Parse a translation unit.
10494 static void parse_translation_unit(void)
10496 add_anchor_token(T_EOF);
10501 if (token.kind == T_EOF)
10504 errorf(HERE, "stray %K outside of function", &token);
10505 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10506 eat_until_matching_token(token.kind);
10511 void set_default_visibility(elf_visibility_tag_t visibility)
10513 default_visibility = visibility;
10519 * @return the translation unit or NULL if errors occurred.
10521 void start_parsing(void)
10523 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10524 label_stack = NEW_ARR_F(stack_entry_t, 0);
10525 diagnostic_count = 0;
10529 print_to_file(stderr);
10531 assert(unit == NULL);
10532 unit = allocate_ast_zero(sizeof(unit[0]));
10534 assert(file_scope == NULL);
10535 file_scope = &unit->scope;
10537 assert(current_scope == NULL);
10538 scope_push(&unit->scope);
10540 create_gnu_builtins();
10542 create_microsoft_intrinsics();
10545 translation_unit_t *finish_parsing(void)
10547 assert(current_scope == &unit->scope);
10550 assert(file_scope == &unit->scope);
10551 check_unused_globals();
10554 DEL_ARR_F(environment_stack);
10555 DEL_ARR_F(label_stack);
10557 translation_unit_t *result = unit;
10562 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10563 * are given length one. */
10564 static void complete_incomplete_arrays(void)
10566 size_t n = ARR_LEN(incomplete_arrays);
10567 for (size_t i = 0; i != n; ++i) {
10568 declaration_t *const decl = incomplete_arrays[i];
10569 type_t *const type = skip_typeref(decl->type);
10571 if (!is_type_incomplete(type))
10574 source_position_t const *const pos = &decl->base.source_position;
10575 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10577 type_t *const new_type = duplicate_type(type);
10578 new_type->array.size_constant = true;
10579 new_type->array.has_implicit_size = true;
10580 new_type->array.size = 1;
10582 type_t *const result = identify_new_type(new_type);
10584 decl->type = result;
10588 void prepare_main_collect2(entity_t *entity)
10590 // create call to __main
10591 symbol_t *symbol = symbol_table_insert("__main");
10592 entity_t *subsubmain_ent
10593 = create_implicit_function(symbol, &builtin_source_position);
10595 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10596 type_t *ftype = subsubmain_ent->declaration.type;
10597 ref->base.source_position = builtin_source_position;
10598 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10599 ref->reference.entity = subsubmain_ent;
10601 expression_t *call = allocate_expression_zero(EXPR_CALL);
10602 call->base.source_position = builtin_source_position;
10603 call->base.type = type_void;
10604 call->call.function = ref;
10606 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10607 expr_statement->base.source_position = builtin_source_position;
10608 expr_statement->expression.expression = call;
10610 statement_t *statement = entity->function.statement;
10611 assert(statement->kind == STATEMENT_COMPOUND);
10612 compound_statement_t *compounds = &statement->compound;
10614 expr_statement->base.next = compounds->statements;
10615 compounds->statements = expr_statement;
10620 lookahead_bufpos = 0;
10621 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10624 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10625 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10626 parse_translation_unit();
10627 complete_incomplete_arrays();
10628 DEL_ARR_F(incomplete_arrays);
10629 incomplete_arrays = NULL;
10633 * Initialize the parser.
10635 void init_parser(void)
10637 sym_anonymous = symbol_table_insert("<anonymous>");
10639 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10641 init_expression_parsers();
10642 obstack_init(&temp_obst);
10646 * Terminate the parser.
10648 void exit_parser(void)
10650 obstack_free(&temp_obst, NULL);