2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_PARENT(stmt) \
113 statement_t *const new_parent = (stmt); \
114 statement_t *const old_parent = current_parent; \
115 ((void)(current_parent = new_parent))
116 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
118 #define PUSH_SCOPE(scope) \
119 size_t const top = environment_top(); \
120 scope_t *const new_scope = (scope); \
121 scope_t *const old_scope = scope_push(new_scope)
122 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
124 #define PUSH_EXTENSION() \
126 bool const old_gcc_extension = in_gcc_extension; \
127 while (next_if(T___extension__)) { \
128 in_gcc_extension = true; \
131 #define POP_EXTENSION() \
132 ((void)(in_gcc_extension = old_gcc_extension))
134 /** special symbol used for anonymous entities. */
135 static symbol_t *sym_anonymous = NULL;
137 /** The token anchor set */
138 static unsigned short token_anchor_set[T_LAST_TOKEN];
140 /** The current source position. */
141 #define HERE (&token.base.source_position)
143 /** true if we are in GCC mode. */
144 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
146 static statement_t *parse_compound_statement(bool inside_expression_statement);
147 static statement_t *parse_statement(void);
149 static expression_t *parse_subexpression(precedence_t);
150 static expression_t *parse_expression(void);
151 static type_t *parse_typename(void);
152 static void parse_externals(void);
153 static void parse_external(void);
155 static void parse_compound_type_entries(compound_t *compound_declaration);
157 static void check_call_argument(type_t *expected_type,
158 call_argument_t *argument, unsigned pos);
160 typedef enum declarator_flags_t {
162 DECL_MAY_BE_ABSTRACT = 1U << 0,
163 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
164 DECL_IS_PARAMETER = 1U << 2
165 } declarator_flags_t;
167 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
168 declarator_flags_t flags);
170 static void semantic_comparison(binary_expression_t *expression);
172 #define STORAGE_CLASSES \
173 STORAGE_CLASSES_NO_EXTERN \
176 #define STORAGE_CLASSES_NO_EXTERN \
183 #define TYPE_QUALIFIERS \
188 case T__forceinline: \
189 case T___attribute__:
191 #define COMPLEX_SPECIFIERS \
193 #define IMAGINARY_SPECIFIERS \
196 #define TYPE_SPECIFIERS \
198 case T___builtin_va_list: \
223 #define DECLARATION_START \
228 #define DECLARATION_START_NO_EXTERN \
229 STORAGE_CLASSES_NO_EXTERN \
233 #define EXPRESSION_START \
242 case T_CHARACTER_CONSTANT: \
243 case T_FLOATINGPOINT: \
244 case T_FLOATINGPOINT_HEXADECIMAL: \
246 case T_INTEGER_HEXADECIMAL: \
247 case T_INTEGER_OCTAL: \
250 case T_STRING_LITERAL: \
251 case T_WIDE_CHARACTER_CONSTANT: \
252 case T_WIDE_STRING_LITERAL: \
253 case T___FUNCDNAME__: \
254 case T___FUNCSIG__: \
255 case T___FUNCTION__: \
256 case T___PRETTY_FUNCTION__: \
257 case T___alignof__: \
258 case T___builtin_classify_type: \
259 case T___builtin_constant_p: \
260 case T___builtin_isgreater: \
261 case T___builtin_isgreaterequal: \
262 case T___builtin_isless: \
263 case T___builtin_islessequal: \
264 case T___builtin_islessgreater: \
265 case T___builtin_isunordered: \
266 case T___builtin_offsetof: \
267 case T___builtin_va_arg: \
268 case T___builtin_va_copy: \
269 case T___builtin_va_start: \
280 * Returns the size of a statement node.
282 * @param kind the statement kind
284 static size_t get_statement_struct_size(statement_kind_t kind)
286 static const size_t sizes[] = {
287 [STATEMENT_ERROR] = sizeof(statement_base_t),
288 [STATEMENT_EMPTY] = sizeof(statement_base_t),
289 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
290 [STATEMENT_RETURN] = sizeof(return_statement_t),
291 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
292 [STATEMENT_IF] = sizeof(if_statement_t),
293 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
294 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
295 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
296 [STATEMENT_BREAK] = sizeof(statement_base_t),
297 [STATEMENT_GOTO] = sizeof(goto_statement_t),
298 [STATEMENT_LABEL] = sizeof(label_statement_t),
299 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
300 [STATEMENT_WHILE] = sizeof(while_statement_t),
301 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
302 [STATEMENT_FOR] = sizeof(for_statement_t),
303 [STATEMENT_ASM] = sizeof(asm_statement_t),
304 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
305 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
307 assert((size_t)kind < lengthof(sizes));
308 assert(sizes[kind] != 0);
313 * Returns the size of an expression node.
315 * @param kind the expression kind
317 static size_t get_expression_struct_size(expression_kind_t kind)
319 static const size_t sizes[] = {
320 [EXPR_ERROR] = sizeof(expression_base_t),
321 [EXPR_REFERENCE] = sizeof(reference_expression_t),
322 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
323 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
324 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
327 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
331 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
332 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
333 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
334 [EXPR_CALL] = sizeof(call_expression_t),
335 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
336 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
337 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
338 [EXPR_SELECT] = sizeof(select_expression_t),
339 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
340 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
341 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
342 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
343 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
344 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
345 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
346 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
347 [EXPR_VA_START] = sizeof(va_start_expression_t),
348 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
349 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
350 [EXPR_STATEMENT] = sizeof(statement_expression_t),
351 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
353 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
354 return sizes[EXPR_UNARY_FIRST];
356 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
357 return sizes[EXPR_BINARY_FIRST];
359 assert((size_t)kind < lengthof(sizes));
360 assert(sizes[kind] != 0);
365 * Allocate a statement node of given kind and initialize all
366 * fields with zero. Sets its source position to the position
367 * of the current token.
369 static statement_t *allocate_statement_zero(statement_kind_t kind)
371 size_t size = get_statement_struct_size(kind);
372 statement_t *res = allocate_ast_zero(size);
374 res->base.kind = kind;
375 res->base.parent = current_parent;
376 res->base.source_position = token.base.source_position;
381 * Allocate an expression node of given kind and initialize all
384 * @param kind the kind of the expression to allocate
386 static expression_t *allocate_expression_zero(expression_kind_t kind)
388 size_t size = get_expression_struct_size(kind);
389 expression_t *res = allocate_ast_zero(size);
391 res->base.kind = kind;
392 res->base.type = type_error_type;
393 res->base.source_position = token.base.source_position;
398 * Creates a new invalid expression at the source position
399 * of the current token.
401 static expression_t *create_error_expression(void)
403 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
404 expression->base.type = type_error_type;
409 * Creates a new invalid statement.
411 static statement_t *create_error_statement(void)
413 return allocate_statement_zero(STATEMENT_ERROR);
417 * Allocate a new empty statement.
419 static statement_t *create_empty_statement(void)
421 return allocate_statement_zero(STATEMENT_EMPTY);
425 * Returns the size of an initializer node.
427 * @param kind the initializer kind
429 static size_t get_initializer_size(initializer_kind_t kind)
431 static const size_t sizes[] = {
432 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
433 [INITIALIZER_STRING] = sizeof(initializer_string_t),
434 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
435 [INITIALIZER_LIST] = sizeof(initializer_list_t),
436 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
438 assert((size_t)kind < lengthof(sizes));
439 assert(sizes[kind] != 0);
444 * Allocate an initializer node of given kind and initialize all
447 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
449 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
456 * Returns the index of the top element of the environment stack.
458 static size_t environment_top(void)
460 return ARR_LEN(environment_stack);
464 * Returns the index of the top element of the global label stack.
466 static size_t label_top(void)
468 return ARR_LEN(label_stack);
472 * Return the next token.
474 static inline void next_token(void)
476 token = lookahead_buffer[lookahead_bufpos];
477 lookahead_buffer[lookahead_bufpos] = lexer_token;
480 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
483 print_token(stderr, &token);
484 fprintf(stderr, "\n");
488 static inline bool next_if(int const type)
490 if (token.kind == type) {
499 * Return the next token with a given lookahead.
501 static inline const token_t *look_ahead(size_t num)
503 assert(0 < num && num <= MAX_LOOKAHEAD);
504 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
505 return &lookahead_buffer[pos];
509 * Adds a token type to the token type anchor set (a multi-set).
511 static void add_anchor_token(int token_kind)
513 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
514 ++token_anchor_set[token_kind];
518 * Set the number of tokens types of the given type
519 * to zero and return the old count.
521 static int save_and_reset_anchor_state(int token_kind)
523 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
524 int count = token_anchor_set[token_kind];
525 token_anchor_set[token_kind] = 0;
530 * Restore the number of token types to the given count.
532 static void restore_anchor_state(int token_kind, int count)
534 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
535 token_anchor_set[token_kind] = count;
539 * Remove a token type from the token type anchor set (a multi-set).
541 static void rem_anchor_token(int token_kind)
543 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
544 assert(token_anchor_set[token_kind] != 0);
545 --token_anchor_set[token_kind];
549 * Return true if the token type of the current token is
552 static bool at_anchor(void)
556 return token_anchor_set[token.kind];
560 * Eat tokens until a matching token type is found.
562 static void eat_until_matching_token(int type)
566 case '(': end_token = ')'; break;
567 case '{': end_token = '}'; break;
568 case '[': end_token = ']'; break;
569 default: end_token = type; break;
572 unsigned parenthesis_count = 0;
573 unsigned brace_count = 0;
574 unsigned bracket_count = 0;
575 while (token.kind != end_token ||
576 parenthesis_count != 0 ||
578 bracket_count != 0) {
579 switch (token.kind) {
581 case '(': ++parenthesis_count; break;
582 case '{': ++brace_count; break;
583 case '[': ++bracket_count; break;
586 if (parenthesis_count > 0)
596 if (bracket_count > 0)
599 if (token.kind == end_token &&
600 parenthesis_count == 0 &&
614 * Eat input tokens until an anchor is found.
616 static void eat_until_anchor(void)
618 while (token_anchor_set[token.kind] == 0) {
619 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
620 eat_until_matching_token(token.kind);
626 * Eat a whole block from input tokens.
628 static void eat_block(void)
630 eat_until_matching_token('{');
634 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
637 * Report a parse error because an expected token was not found.
640 #if defined __GNUC__ && __GNUC__ >= 4
641 __attribute__((sentinel))
643 void parse_error_expected(const char *message, ...)
645 if (message != NULL) {
646 errorf(HERE, "%s", message);
649 va_start(ap, message);
650 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
655 * Report an incompatible type.
657 static void type_error_incompatible(const char *msg,
658 const source_position_t *source_position, type_t *type1, type_t *type2)
660 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
665 * Expect the current token is the expected token.
666 * If not, generate an error, eat the current statement,
667 * and goto the error_label label.
669 #define expect(expected, error_label) \
671 if (UNLIKELY(token.kind != (expected))) { \
672 parse_error_expected(NULL, (expected), NULL); \
673 add_anchor_token(expected); \
674 eat_until_anchor(); \
675 rem_anchor_token(expected); \
676 if (token.kind != (expected)) \
683 * Push a given scope on the scope stack and make it the
686 static scope_t *scope_push(scope_t *new_scope)
688 if (current_scope != NULL) {
689 new_scope->depth = current_scope->depth + 1;
692 scope_t *old_scope = current_scope;
693 current_scope = new_scope;
698 * Pop the current scope from the scope stack.
700 static void scope_pop(scope_t *old_scope)
702 current_scope = old_scope;
706 * Search an entity by its symbol in a given namespace.
708 static entity_t *get_entity(const symbol_t *const symbol,
709 namespace_tag_t namespc)
711 entity_t *entity = symbol->entity;
712 for (; entity != NULL; entity = entity->base.symbol_next) {
713 if ((namespace_tag_t)entity->base.namespc == namespc)
720 /* §6.2.3:1 24) There is only one name space for tags even though three are
722 static entity_t *get_tag(symbol_t const *const symbol,
723 entity_kind_tag_t const kind)
725 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
726 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
728 "'%Y' defined as wrong kind of tag (previous definition %P)",
729 symbol, &entity->base.source_position);
736 * pushs an entity on the environment stack and links the corresponding symbol
739 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
741 symbol_t *symbol = entity->base.symbol;
742 entity_namespace_t namespc = entity->base.namespc;
743 assert(namespc != 0);
745 /* replace/add entity into entity list of the symbol */
748 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
753 /* replace an entry? */
754 if (iter->base.namespc == namespc) {
755 entity->base.symbol_next = iter->base.symbol_next;
761 /* remember old declaration */
763 entry.symbol = symbol;
764 entry.old_entity = iter;
765 entry.namespc = namespc;
766 ARR_APP1(stack_entry_t, *stack_ptr, entry);
770 * Push an entity on the environment stack.
772 static void environment_push(entity_t *entity)
774 assert(entity->base.source_position.input_name != NULL);
775 assert(entity->base.parent_scope != NULL);
776 stack_push(&environment_stack, entity);
780 * Push a declaration on the global label stack.
782 * @param declaration the declaration
784 static void label_push(entity_t *label)
786 /* we abuse the parameters scope as parent for the labels */
787 label->base.parent_scope = ¤t_function->parameters;
788 stack_push(&label_stack, label);
792 * pops symbols from the environment stack until @p new_top is the top element
794 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
796 stack_entry_t *stack = *stack_ptr;
797 size_t top = ARR_LEN(stack);
800 assert(new_top <= top);
804 for (i = top; i > new_top; --i) {
805 stack_entry_t *entry = &stack[i - 1];
807 entity_t *old_entity = entry->old_entity;
808 symbol_t *symbol = entry->symbol;
809 entity_namespace_t namespc = entry->namespc;
811 /* replace with old_entity/remove */
814 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
816 assert(iter != NULL);
817 /* replace an entry? */
818 if (iter->base.namespc == namespc)
822 /* restore definition from outer scopes (if there was one) */
823 if (old_entity != NULL) {
824 old_entity->base.symbol_next = iter->base.symbol_next;
825 *anchor = old_entity;
827 /* remove entry from list */
828 *anchor = iter->base.symbol_next;
832 ARR_SHRINKLEN(*stack_ptr, new_top);
836 * Pop all entries from the environment stack until the new_top
839 * @param new_top the new stack top
841 static void environment_pop_to(size_t new_top)
843 stack_pop_to(&environment_stack, new_top);
847 * Pop all entries from the global label stack until the new_top
850 * @param new_top the new stack top
852 static void label_pop_to(size_t new_top)
854 stack_pop_to(&label_stack, new_top);
857 static atomic_type_kind_t get_akind(const type_t *type)
859 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
860 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
861 return type->atomic.akind;
865 * §6.3.1.1:2 Do integer promotion for a given type.
867 * @param type the type to promote
868 * @return the promoted type
870 static type_t *promote_integer(type_t *type)
872 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
879 * Check if a given expression represents a null pointer constant.
881 * @param expression the expression to check
883 static bool is_null_pointer_constant(const expression_t *expression)
885 /* skip void* cast */
886 if (expression->kind == EXPR_UNARY_CAST) {
887 type_t *const type = skip_typeref(expression->base.type);
888 if (types_compatible(type, type_void_ptr))
889 expression = expression->unary.value;
892 type_t *const type = skip_typeref(expression->base.type);
893 if (!is_type_integer(type))
895 switch (is_constant_expression(expression)) {
896 case EXPR_CLASS_ERROR: return true;
897 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
898 default: return false;
903 * Create an implicit cast expression.
905 * @param expression the expression to cast
906 * @param dest_type the destination type
908 static expression_t *create_implicit_cast(expression_t *expression,
911 type_t *const source_type = expression->base.type;
913 if (source_type == dest_type)
916 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
917 cast->unary.value = expression;
918 cast->base.type = dest_type;
919 cast->base.implicit = true;
924 typedef enum assign_error_t {
926 ASSIGN_ERROR_INCOMPATIBLE,
927 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
928 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
929 ASSIGN_WARNING_POINTER_FROM_INT,
930 ASSIGN_WARNING_INT_FROM_POINTER
933 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)
935 type_t *const orig_type_right = right->base.type;
936 type_t *const type_left = skip_typeref(orig_type_left);
937 type_t *const type_right = skip_typeref(orig_type_right);
942 case ASSIGN_ERROR_INCOMPATIBLE:
943 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
946 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
947 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
948 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
950 /* the left type has all qualifiers from the right type */
951 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
952 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);
956 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
957 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
960 case ASSIGN_WARNING_POINTER_FROM_INT:
961 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
964 case ASSIGN_WARNING_INT_FROM_POINTER:
965 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
969 panic("invalid error value");
973 /** Implements the rules from §6.5.16.1 */
974 static assign_error_t semantic_assign(type_t *orig_type_left,
975 const expression_t *const right)
977 type_t *const orig_type_right = right->base.type;
978 type_t *const type_left = skip_typeref(orig_type_left);
979 type_t *const type_right = skip_typeref(orig_type_right);
981 if (is_type_pointer(type_left)) {
982 if (is_null_pointer_constant(right)) {
983 return ASSIGN_SUCCESS;
984 } else if (is_type_pointer(type_right)) {
985 type_t *points_to_left
986 = skip_typeref(type_left->pointer.points_to);
987 type_t *points_to_right
988 = skip_typeref(type_right->pointer.points_to);
989 assign_error_t res = ASSIGN_SUCCESS;
991 /* the left type has all qualifiers from the right type */
992 unsigned missing_qualifiers
993 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
994 if (missing_qualifiers != 0) {
995 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
998 points_to_left = get_unqualified_type(points_to_left);
999 points_to_right = get_unqualified_type(points_to_right);
1001 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1004 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1005 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1006 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1009 if (!types_compatible(points_to_left, points_to_right)) {
1010 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1014 } else if (is_type_integer(type_right)) {
1015 return ASSIGN_WARNING_POINTER_FROM_INT;
1017 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1018 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1019 && is_type_pointer(type_right))) {
1020 return ASSIGN_SUCCESS;
1021 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1022 type_t *const unqual_type_left = get_unqualified_type(type_left);
1023 type_t *const unqual_type_right = get_unqualified_type(type_right);
1024 if (types_compatible(unqual_type_left, unqual_type_right)) {
1025 return ASSIGN_SUCCESS;
1027 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1028 return ASSIGN_WARNING_INT_FROM_POINTER;
1031 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1032 return ASSIGN_SUCCESS;
1034 return ASSIGN_ERROR_INCOMPATIBLE;
1037 static expression_t *parse_constant_expression(void)
1039 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1041 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1042 errorf(&result->base.source_position,
1043 "expression '%E' is not constant", result);
1049 static expression_t *parse_assignment_expression(void)
1051 return parse_subexpression(PREC_ASSIGNMENT);
1054 static void warn_string_concat(const source_position_t *pos)
1056 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1059 static string_t parse_string_literals(void)
1061 assert(token.kind == T_STRING_LITERAL);
1062 string_t result = token.string.string;
1066 while (token.kind == T_STRING_LITERAL) {
1067 warn_string_concat(&token.base.source_position);
1068 result = concat_strings(&result, &token.string.string);
1075 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1077 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1078 attribute->kind = kind;
1079 attribute->source_position = *HERE;
1084 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1087 * __attribute__ ( ( attribute-list ) )
1091 * attribute_list , attrib
1096 * any-word ( identifier )
1097 * any-word ( identifier , nonempty-expr-list )
1098 * any-word ( expr-list )
1100 * where the "identifier" must not be declared as a type, and
1101 * "any-word" may be any identifier (including one declared as a
1102 * type), a reserved word storage class specifier, type specifier or
1103 * type qualifier. ??? This still leaves out most reserved keywords
1104 * (following the old parser), shouldn't we include them, and why not
1105 * allow identifiers declared as types to start the arguments?
1107 * Matze: this all looks confusing and little systematic, so we're even less
1108 * strict and parse any list of things which are identifiers or
1109 * (assignment-)expressions.
1111 static attribute_argument_t *parse_attribute_arguments(void)
1113 attribute_argument_t *first = NULL;
1114 attribute_argument_t **anchor = &first;
1115 if (token.kind != ')') do {
1116 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1118 /* is it an identifier */
1119 if (token.kind == T_IDENTIFIER
1120 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1121 symbol_t *symbol = token.identifier.symbol;
1122 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1123 argument->v.symbol = symbol;
1126 /* must be an expression */
1127 expression_t *expression = parse_assignment_expression();
1129 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1130 argument->v.expression = expression;
1133 /* append argument */
1135 anchor = &argument->next;
1136 } while (next_if(','));
1137 expect(')', end_error);
1146 static attribute_t *parse_attribute_asm(void)
1148 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1151 expect('(', end_error);
1152 attribute->a.arguments = parse_attribute_arguments();
1159 static symbol_t *get_symbol_from_token(void)
1161 switch(token.kind) {
1163 return token.identifier.symbol;
1192 /* maybe we need more tokens ... add them on demand */
1193 return get_token_kind_symbol(token.kind);
1199 static attribute_t *parse_attribute_gnu_single(void)
1201 /* parse "any-word" */
1202 symbol_t *symbol = get_symbol_from_token();
1203 if (symbol == NULL) {
1204 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1208 attribute_kind_t kind;
1209 char const *const name = symbol->string;
1210 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1211 if (kind > ATTRIBUTE_GNU_LAST) {
1212 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1213 /* TODO: we should still save the attribute in the list... */
1214 kind = ATTRIBUTE_UNKNOWN;
1218 const char *attribute_name = get_attribute_name(kind);
1219 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1223 attribute_t *attribute = allocate_attribute_zero(kind);
1226 /* parse arguments */
1228 attribute->a.arguments = parse_attribute_arguments();
1233 static attribute_t *parse_attribute_gnu(void)
1235 attribute_t *first = NULL;
1236 attribute_t **anchor = &first;
1238 eat(T___attribute__);
1239 expect('(', end_error);
1240 expect('(', end_error);
1242 if (token.kind != ')') do {
1243 attribute_t *attribute = parse_attribute_gnu_single();
1244 if (attribute == NULL)
1247 *anchor = attribute;
1248 anchor = &attribute->next;
1249 } while (next_if(','));
1250 expect(')', end_error);
1251 expect(')', end_error);
1257 /** Parse attributes. */
1258 static attribute_t *parse_attributes(attribute_t *first)
1260 attribute_t **anchor = &first;
1262 while (*anchor != NULL)
1263 anchor = &(*anchor)->next;
1265 attribute_t *attribute;
1266 switch (token.kind) {
1267 case T___attribute__:
1268 attribute = parse_attribute_gnu();
1269 if (attribute == NULL)
1274 attribute = parse_attribute_asm();
1278 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1283 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1287 case T__forceinline:
1288 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1289 eat(T__forceinline);
1293 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1298 /* TODO record modifier */
1299 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1300 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1308 *anchor = attribute;
1309 anchor = &attribute->next;
1313 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1315 static entity_t *determine_lhs_ent(expression_t *const expr,
1318 switch (expr->kind) {
1319 case EXPR_REFERENCE: {
1320 entity_t *const entity = expr->reference.entity;
1321 /* we should only find variables as lvalues... */
1322 if (entity->base.kind != ENTITY_VARIABLE
1323 && entity->base.kind != ENTITY_PARAMETER)
1329 case EXPR_ARRAY_ACCESS: {
1330 expression_t *const ref = expr->array_access.array_ref;
1331 entity_t * ent = NULL;
1332 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1333 ent = determine_lhs_ent(ref, lhs_ent);
1336 mark_vars_read(ref, lhs_ent);
1338 mark_vars_read(expr->array_access.index, lhs_ent);
1343 mark_vars_read(expr->select.compound, lhs_ent);
1344 if (is_type_compound(skip_typeref(expr->base.type)))
1345 return determine_lhs_ent(expr->select.compound, lhs_ent);
1349 case EXPR_UNARY_DEREFERENCE: {
1350 expression_t *const val = expr->unary.value;
1351 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1353 return determine_lhs_ent(val->unary.value, lhs_ent);
1355 mark_vars_read(val, NULL);
1361 mark_vars_read(expr, NULL);
1366 #define ENT_ANY ((entity_t*)-1)
1369 * Mark declarations, which are read. This is used to detect variables, which
1373 * x is not marked as "read", because it is only read to calculate its own new
1377 * x and y are not detected as "not read", because multiple variables are
1380 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1382 switch (expr->kind) {
1383 case EXPR_REFERENCE: {
1384 entity_t *const entity = expr->reference.entity;
1385 if (entity->kind != ENTITY_VARIABLE
1386 && entity->kind != ENTITY_PARAMETER)
1389 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1390 if (entity->kind == ENTITY_VARIABLE) {
1391 entity->variable.read = true;
1393 entity->parameter.read = true;
1400 // TODO respect pure/const
1401 mark_vars_read(expr->call.function, NULL);
1402 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1403 mark_vars_read(arg->expression, NULL);
1407 case EXPR_CONDITIONAL:
1408 // TODO lhs_decl should depend on whether true/false have an effect
1409 mark_vars_read(expr->conditional.condition, NULL);
1410 if (expr->conditional.true_expression != NULL)
1411 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1412 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1416 if (lhs_ent == ENT_ANY
1417 && !is_type_compound(skip_typeref(expr->base.type)))
1419 mark_vars_read(expr->select.compound, lhs_ent);
1422 case EXPR_ARRAY_ACCESS: {
1423 mark_vars_read(expr->array_access.index, lhs_ent);
1424 expression_t *const ref = expr->array_access.array_ref;
1425 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1426 if (lhs_ent == ENT_ANY)
1429 mark_vars_read(ref, lhs_ent);
1434 mark_vars_read(expr->va_arge.ap, lhs_ent);
1438 mark_vars_read(expr->va_copye.src, lhs_ent);
1441 case EXPR_UNARY_CAST:
1442 /* Special case: Use void cast to mark a variable as "read" */
1443 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1448 case EXPR_UNARY_THROW:
1449 if (expr->unary.value == NULL)
1452 case EXPR_UNARY_DEREFERENCE:
1453 case EXPR_UNARY_DELETE:
1454 case EXPR_UNARY_DELETE_ARRAY:
1455 if (lhs_ent == ENT_ANY)
1459 case EXPR_UNARY_NEGATE:
1460 case EXPR_UNARY_PLUS:
1461 case EXPR_UNARY_BITWISE_NEGATE:
1462 case EXPR_UNARY_NOT:
1463 case EXPR_UNARY_TAKE_ADDRESS:
1464 case EXPR_UNARY_POSTFIX_INCREMENT:
1465 case EXPR_UNARY_POSTFIX_DECREMENT:
1466 case EXPR_UNARY_PREFIX_INCREMENT:
1467 case EXPR_UNARY_PREFIX_DECREMENT:
1468 case EXPR_UNARY_ASSUME:
1470 mark_vars_read(expr->unary.value, lhs_ent);
1473 case EXPR_BINARY_ADD:
1474 case EXPR_BINARY_SUB:
1475 case EXPR_BINARY_MUL:
1476 case EXPR_BINARY_DIV:
1477 case EXPR_BINARY_MOD:
1478 case EXPR_BINARY_EQUAL:
1479 case EXPR_BINARY_NOTEQUAL:
1480 case EXPR_BINARY_LESS:
1481 case EXPR_BINARY_LESSEQUAL:
1482 case EXPR_BINARY_GREATER:
1483 case EXPR_BINARY_GREATEREQUAL:
1484 case EXPR_BINARY_BITWISE_AND:
1485 case EXPR_BINARY_BITWISE_OR:
1486 case EXPR_BINARY_BITWISE_XOR:
1487 case EXPR_BINARY_LOGICAL_AND:
1488 case EXPR_BINARY_LOGICAL_OR:
1489 case EXPR_BINARY_SHIFTLEFT:
1490 case EXPR_BINARY_SHIFTRIGHT:
1491 case EXPR_BINARY_COMMA:
1492 case EXPR_BINARY_ISGREATER:
1493 case EXPR_BINARY_ISGREATEREQUAL:
1494 case EXPR_BINARY_ISLESS:
1495 case EXPR_BINARY_ISLESSEQUAL:
1496 case EXPR_BINARY_ISLESSGREATER:
1497 case EXPR_BINARY_ISUNORDERED:
1498 mark_vars_read(expr->binary.left, lhs_ent);
1499 mark_vars_read(expr->binary.right, lhs_ent);
1502 case EXPR_BINARY_ASSIGN:
1503 case EXPR_BINARY_MUL_ASSIGN:
1504 case EXPR_BINARY_DIV_ASSIGN:
1505 case EXPR_BINARY_MOD_ASSIGN:
1506 case EXPR_BINARY_ADD_ASSIGN:
1507 case EXPR_BINARY_SUB_ASSIGN:
1508 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1509 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1510 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1511 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1512 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1513 if (lhs_ent == ENT_ANY)
1515 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1516 mark_vars_read(expr->binary.right, lhs_ent);
1521 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1526 case EXPR_STRING_LITERAL:
1527 case EXPR_WIDE_STRING_LITERAL:
1528 case EXPR_COMPOUND_LITERAL: // TODO init?
1530 case EXPR_CLASSIFY_TYPE:
1533 case EXPR_BUILTIN_CONSTANT_P:
1534 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1536 case EXPR_STATEMENT: // TODO
1537 case EXPR_LABEL_ADDRESS:
1538 case EXPR_REFERENCE_ENUM_VALUE:
1542 panic("unhandled expression");
1545 static designator_t *parse_designation(void)
1547 designator_t *result = NULL;
1548 designator_t **anchor = &result;
1551 designator_t *designator;
1552 switch (token.kind) {
1554 designator = allocate_ast_zero(sizeof(designator[0]));
1555 designator->source_position = token.base.source_position;
1557 add_anchor_token(']');
1558 designator->array_index = parse_constant_expression();
1559 rem_anchor_token(']');
1560 expect(']', end_error);
1563 designator = allocate_ast_zero(sizeof(designator[0]));
1564 designator->source_position = token.base.source_position;
1566 if (token.kind != T_IDENTIFIER) {
1567 parse_error_expected("while parsing designator",
1568 T_IDENTIFIER, NULL);
1571 designator->symbol = token.identifier.symbol;
1575 expect('=', end_error);
1579 assert(designator != NULL);
1580 *anchor = designator;
1581 anchor = &designator->next;
1587 static initializer_t *initializer_from_string(array_type_t *const type,
1588 const string_t *const string)
1590 /* TODO: check len vs. size of array type */
1593 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1594 initializer->string.string = *string;
1599 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1600 const string_t *const string)
1602 /* TODO: check len vs. size of array type */
1605 initializer_t *const initializer =
1606 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1607 initializer->wide_string.string = *string;
1613 * Build an initializer from a given expression.
1615 static initializer_t *initializer_from_expression(type_t *orig_type,
1616 expression_t *expression)
1618 /* TODO check that expression is a constant expression */
1620 /* §6.7.8.14/15 char array may be initialized by string literals */
1621 type_t *type = skip_typeref(orig_type);
1622 type_t *expr_type_orig = expression->base.type;
1623 type_t *expr_type = skip_typeref(expr_type_orig);
1625 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1626 array_type_t *const array_type = &type->array;
1627 type_t *const element_type = skip_typeref(array_type->element_type);
1629 if (element_type->kind == TYPE_ATOMIC) {
1630 atomic_type_kind_t akind = element_type->atomic.akind;
1631 switch (expression->kind) {
1632 case EXPR_STRING_LITERAL:
1633 if (akind == ATOMIC_TYPE_CHAR
1634 || akind == ATOMIC_TYPE_SCHAR
1635 || akind == ATOMIC_TYPE_UCHAR) {
1636 return initializer_from_string(array_type,
1637 &expression->string_literal.value);
1641 case EXPR_WIDE_STRING_LITERAL: {
1642 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1643 if (get_unqualified_type(element_type) == bare_wchar_type) {
1644 return initializer_from_wide_string(array_type,
1645 &expression->string_literal.value);
1656 assign_error_t error = semantic_assign(type, expression);
1657 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1659 report_assign_error(error, type, expression, "initializer",
1660 &expression->base.source_position);
1662 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1663 result->value.value = create_implicit_cast(expression, type);
1669 * Parses an scalar initializer.
1671 * §6.7.8.11; eat {} without warning
1673 static initializer_t *parse_scalar_initializer(type_t *type,
1674 bool must_be_constant)
1676 /* there might be extra {} hierarchies */
1678 if (token.kind == '{') {
1679 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1683 } while (token.kind == '{');
1686 expression_t *expression = parse_assignment_expression();
1687 mark_vars_read(expression, NULL);
1688 if (must_be_constant && !is_linker_constant(expression)) {
1689 errorf(&expression->base.source_position,
1690 "initialisation expression '%E' is not constant",
1694 initializer_t *initializer = initializer_from_expression(type, expression);
1696 if (initializer == NULL) {
1697 errorf(&expression->base.source_position,
1698 "expression '%E' (type '%T') doesn't match expected type '%T'",
1699 expression, expression->base.type, type);
1704 bool additional_warning_displayed = false;
1705 while (braces > 0) {
1707 if (token.kind != '}') {
1708 if (!additional_warning_displayed) {
1709 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1710 additional_warning_displayed = true;
1721 * An entry in the type path.
1723 typedef struct type_path_entry_t type_path_entry_t;
1724 struct type_path_entry_t {
1725 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1727 size_t index; /**< For array types: the current index. */
1728 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1733 * A type path expression a position inside compound or array types.
1735 typedef struct type_path_t type_path_t;
1736 struct type_path_t {
1737 type_path_entry_t *path; /**< An flexible array containing the current path. */
1738 type_t *top_type; /**< type of the element the path points */
1739 size_t max_index; /**< largest index in outermost array */
1743 * Prints a type path for debugging.
1745 static __attribute__((unused)) void debug_print_type_path(
1746 const type_path_t *path)
1748 size_t len = ARR_LEN(path->path);
1750 for (size_t i = 0; i < len; ++i) {
1751 const type_path_entry_t *entry = & path->path[i];
1753 type_t *type = skip_typeref(entry->type);
1754 if (is_type_compound(type)) {
1755 /* in gcc mode structs can have no members */
1756 if (entry->v.compound_entry == NULL) {
1760 fprintf(stderr, ".%s",
1761 entry->v.compound_entry->base.symbol->string);
1762 } else if (is_type_array(type)) {
1763 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1765 fprintf(stderr, "-INVALID-");
1768 if (path->top_type != NULL) {
1769 fprintf(stderr, " (");
1770 print_type(path->top_type);
1771 fprintf(stderr, ")");
1776 * Return the top type path entry, ie. in a path
1777 * (type).a.b returns the b.
1779 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1781 size_t len = ARR_LEN(path->path);
1783 return &path->path[len-1];
1787 * Enlarge the type path by an (empty) element.
1789 static type_path_entry_t *append_to_type_path(type_path_t *path)
1791 size_t len = ARR_LEN(path->path);
1792 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1794 type_path_entry_t *result = & path->path[len];
1795 memset(result, 0, sizeof(result[0]));
1800 * Descending into a sub-type. Enter the scope of the current top_type.
1802 static void descend_into_subtype(type_path_t *path)
1804 type_t *orig_top_type = path->top_type;
1805 type_t *top_type = skip_typeref(orig_top_type);
1807 type_path_entry_t *top = append_to_type_path(path);
1808 top->type = top_type;
1810 if (is_type_compound(top_type)) {
1811 compound_t *const compound = top_type->compound.compound;
1812 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1814 if (entry != NULL) {
1815 top->v.compound_entry = &entry->declaration;
1816 path->top_type = entry->declaration.type;
1818 path->top_type = NULL;
1820 } else if (is_type_array(top_type)) {
1822 path->top_type = top_type->array.element_type;
1824 assert(!is_type_valid(top_type));
1829 * Pop an entry from the given type path, ie. returning from
1830 * (type).a.b to (type).a
1832 static void ascend_from_subtype(type_path_t *path)
1834 type_path_entry_t *top = get_type_path_top(path);
1836 path->top_type = top->type;
1838 size_t len = ARR_LEN(path->path);
1839 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1843 * Pop entries from the given type path until the given
1844 * path level is reached.
1846 static void ascend_to(type_path_t *path, size_t top_path_level)
1848 size_t len = ARR_LEN(path->path);
1850 while (len > top_path_level) {
1851 ascend_from_subtype(path);
1852 len = ARR_LEN(path->path);
1856 static bool walk_designator(type_path_t *path, const designator_t *designator,
1857 bool used_in_offsetof)
1859 for (; designator != NULL; designator = designator->next) {
1860 type_path_entry_t *top = get_type_path_top(path);
1861 type_t *orig_type = top->type;
1863 type_t *type = skip_typeref(orig_type);
1865 if (designator->symbol != NULL) {
1866 symbol_t *symbol = designator->symbol;
1867 if (!is_type_compound(type)) {
1868 if (is_type_valid(type)) {
1869 errorf(&designator->source_position,
1870 "'.%Y' designator used for non-compound type '%T'",
1874 top->type = type_error_type;
1875 top->v.compound_entry = NULL;
1876 orig_type = type_error_type;
1878 compound_t *compound = type->compound.compound;
1879 entity_t *iter = compound->members.entities;
1880 for (; iter != NULL; iter = iter->base.next) {
1881 if (iter->base.symbol == symbol) {
1886 errorf(&designator->source_position,
1887 "'%T' has no member named '%Y'", orig_type, symbol);
1890 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1891 if (used_in_offsetof && iter->compound_member.bitfield) {
1892 errorf(&designator->source_position,
1893 "offsetof designator '%Y' must not specify bitfield",
1898 top->type = orig_type;
1899 top->v.compound_entry = &iter->declaration;
1900 orig_type = iter->declaration.type;
1903 expression_t *array_index = designator->array_index;
1904 assert(designator->array_index != NULL);
1906 if (!is_type_array(type)) {
1907 if (is_type_valid(type)) {
1908 errorf(&designator->source_position,
1909 "[%E] designator used for non-array type '%T'",
1910 array_index, orig_type);
1915 long index = fold_constant_to_int(array_index);
1916 if (!used_in_offsetof) {
1918 errorf(&designator->source_position,
1919 "array index [%E] must be positive", array_index);
1920 } else if (type->array.size_constant) {
1921 long array_size = type->array.size;
1922 if (index >= array_size) {
1923 errorf(&designator->source_position,
1924 "designator [%E] (%d) exceeds array size %d",
1925 array_index, index, array_size);
1930 top->type = orig_type;
1931 top->v.index = (size_t) index;
1932 orig_type = type->array.element_type;
1934 path->top_type = orig_type;
1936 if (designator->next != NULL) {
1937 descend_into_subtype(path);
1943 static void advance_current_object(type_path_t *path, size_t top_path_level)
1945 type_path_entry_t *top = get_type_path_top(path);
1947 type_t *type = skip_typeref(top->type);
1948 if (is_type_union(type)) {
1949 /* in unions only the first element is initialized */
1950 top->v.compound_entry = NULL;
1951 } else if (is_type_struct(type)) {
1952 declaration_t *entry = top->v.compound_entry;
1954 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1955 if (next_entity != NULL) {
1956 assert(is_declaration(next_entity));
1957 entry = &next_entity->declaration;
1962 top->v.compound_entry = entry;
1963 if (entry != NULL) {
1964 path->top_type = entry->type;
1967 } else if (is_type_array(type)) {
1968 assert(is_type_array(type));
1972 if (!type->array.size_constant || top->v.index < type->array.size) {
1976 assert(!is_type_valid(type));
1980 /* we're past the last member of the current sub-aggregate, try if we
1981 * can ascend in the type hierarchy and continue with another subobject */
1982 size_t len = ARR_LEN(path->path);
1984 if (len > top_path_level) {
1985 ascend_from_subtype(path);
1986 advance_current_object(path, top_path_level);
1988 path->top_type = NULL;
1993 * skip any {...} blocks until a closing bracket is reached.
1995 static void skip_initializers(void)
1999 while (token.kind != '}') {
2000 if (token.kind == T_EOF)
2002 if (token.kind == '{') {
2010 static initializer_t *create_empty_initializer(void)
2012 static initializer_t empty_initializer
2013 = { .list = { { INITIALIZER_LIST }, 0 } };
2014 return &empty_initializer;
2018 * Parse a part of an initialiser for a struct or union,
2020 static initializer_t *parse_sub_initializer(type_path_t *path,
2021 type_t *outer_type, size_t top_path_level,
2022 parse_initializer_env_t *env)
2024 if (token.kind == '}') {
2025 /* empty initializer */
2026 return create_empty_initializer();
2029 type_t *orig_type = path->top_type;
2030 type_t *type = NULL;
2032 if (orig_type == NULL) {
2033 /* We are initializing an empty compound. */
2035 type = skip_typeref(orig_type);
2038 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2041 designator_t *designator = NULL;
2042 if (token.kind == '.' || token.kind == '[') {
2043 designator = parse_designation();
2044 goto finish_designator;
2045 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2046 /* GNU-style designator ("identifier: value") */
2047 designator = allocate_ast_zero(sizeof(designator[0]));
2048 designator->source_position = token.base.source_position;
2049 designator->symbol = token.identifier.symbol;
2054 /* reset path to toplevel, evaluate designator from there */
2055 ascend_to(path, top_path_level);
2056 if (!walk_designator(path, designator, false)) {
2057 /* can't continue after designation error */
2061 initializer_t *designator_initializer
2062 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2063 designator_initializer->designator.designator = designator;
2064 ARR_APP1(initializer_t*, initializers, designator_initializer);
2066 orig_type = path->top_type;
2067 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2072 if (token.kind == '{') {
2073 if (type != NULL && is_type_scalar(type)) {
2074 sub = parse_scalar_initializer(type, env->must_be_constant);
2077 if (env->entity != NULL) {
2079 "extra brace group at end of initializer for '%Y'",
2080 env->entity->base.symbol);
2082 errorf(HERE, "extra brace group at end of initializer");
2087 descend_into_subtype(path);
2090 add_anchor_token('}');
2091 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2093 rem_anchor_token('}');
2096 ascend_from_subtype(path);
2097 expect('}', end_error);
2099 expect('}', end_error);
2100 goto error_parse_next;
2104 /* must be an expression */
2105 expression_t *expression = parse_assignment_expression();
2106 mark_vars_read(expression, NULL);
2108 if (env->must_be_constant && !is_linker_constant(expression)) {
2109 errorf(&expression->base.source_position,
2110 "Initialisation expression '%E' is not constant",
2115 /* we are already outside, ... */
2116 if (outer_type == NULL)
2117 goto error_parse_next;
2118 type_t *const outer_type_skip = skip_typeref(outer_type);
2119 if (is_type_compound(outer_type_skip) &&
2120 !outer_type_skip->compound.compound->complete) {
2121 goto error_parse_next;
2124 source_position_t const* const pos = &expression->base.source_position;
2125 if (env->entity != NULL) {
2126 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2128 warningf(WARN_OTHER, pos, "excess elements in initializer");
2130 goto error_parse_next;
2133 /* handle { "string" } special case */
2134 if ((expression->kind == EXPR_STRING_LITERAL
2135 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2136 && outer_type != NULL) {
2137 sub = initializer_from_expression(outer_type, expression);
2140 if (token.kind != '}') {
2141 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2143 /* TODO: eat , ... */
2148 /* descend into subtypes until expression matches type */
2150 orig_type = path->top_type;
2151 type = skip_typeref(orig_type);
2153 sub = initializer_from_expression(orig_type, expression);
2157 if (!is_type_valid(type)) {
2160 if (is_type_scalar(type)) {
2161 errorf(&expression->base.source_position,
2162 "expression '%E' doesn't match expected type '%T'",
2163 expression, orig_type);
2167 descend_into_subtype(path);
2171 /* update largest index of top array */
2172 const type_path_entry_t *first = &path->path[0];
2173 type_t *first_type = first->type;
2174 first_type = skip_typeref(first_type);
2175 if (is_type_array(first_type)) {
2176 size_t index = first->v.index;
2177 if (index > path->max_index)
2178 path->max_index = index;
2181 /* append to initializers list */
2182 ARR_APP1(initializer_t*, initializers, sub);
2185 if (token.kind == '}') {
2188 expect(',', end_error);
2189 if (token.kind == '}') {
2194 /* advance to the next declaration if we are not at the end */
2195 advance_current_object(path, top_path_level);
2196 orig_type = path->top_type;
2197 if (orig_type != NULL)
2198 type = skip_typeref(orig_type);
2204 size_t len = ARR_LEN(initializers);
2205 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2206 initializer_t *result = allocate_ast_zero(size);
2207 result->kind = INITIALIZER_LIST;
2208 result->list.len = len;
2209 memcpy(&result->list.initializers, initializers,
2210 len * sizeof(initializers[0]));
2212 DEL_ARR_F(initializers);
2213 ascend_to(path, top_path_level+1);
2218 skip_initializers();
2219 DEL_ARR_F(initializers);
2220 ascend_to(path, top_path_level+1);
2224 static expression_t *make_size_literal(size_t value)
2226 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2227 literal->base.type = type_size_t;
2230 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2231 literal->literal.value = make_string(buf);
2237 * Parses an initializer. Parsers either a compound literal
2238 * (env->declaration == NULL) or an initializer of a declaration.
2240 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2242 type_t *type = skip_typeref(env->type);
2243 size_t max_index = 0;
2244 initializer_t *result;
2246 if (is_type_scalar(type)) {
2247 result = parse_scalar_initializer(type, env->must_be_constant);
2248 } else if (token.kind == '{') {
2252 memset(&path, 0, sizeof(path));
2253 path.top_type = env->type;
2254 path.path = NEW_ARR_F(type_path_entry_t, 0);
2256 descend_into_subtype(&path);
2258 add_anchor_token('}');
2259 result = parse_sub_initializer(&path, env->type, 1, env);
2260 rem_anchor_token('}');
2262 max_index = path.max_index;
2263 DEL_ARR_F(path.path);
2265 expect('}', end_error);
2268 /* parse_scalar_initializer() also works in this case: we simply
2269 * have an expression without {} around it */
2270 result = parse_scalar_initializer(type, env->must_be_constant);
2273 /* §6.7.8:22 array initializers for arrays with unknown size determine
2274 * the array type size */
2275 if (is_type_array(type) && type->array.size_expression == NULL
2276 && result != NULL) {
2278 switch (result->kind) {
2279 case INITIALIZER_LIST:
2280 assert(max_index != 0xdeadbeaf);
2281 size = max_index + 1;
2284 case INITIALIZER_STRING:
2285 size = result->string.string.size;
2288 case INITIALIZER_WIDE_STRING:
2289 size = result->wide_string.string.size;
2292 case INITIALIZER_DESIGNATOR:
2293 case INITIALIZER_VALUE:
2294 /* can happen for parse errors */
2299 internal_errorf(HERE, "invalid initializer type");
2302 type_t *new_type = duplicate_type(type);
2304 new_type->array.size_expression = make_size_literal(size);
2305 new_type->array.size_constant = true;
2306 new_type->array.has_implicit_size = true;
2307 new_type->array.size = size;
2308 env->type = new_type;
2314 static void append_entity(scope_t *scope, entity_t *entity)
2316 if (scope->last_entity != NULL) {
2317 scope->last_entity->base.next = entity;
2319 scope->entities = entity;
2321 entity->base.parent_entity = current_entity;
2322 scope->last_entity = entity;
2326 static compound_t *parse_compound_type_specifier(bool is_struct)
2328 source_position_t const pos = *HERE;
2329 eat(is_struct ? T_struct : T_union);
2331 symbol_t *symbol = NULL;
2332 entity_t *entity = NULL;
2333 attribute_t *attributes = NULL;
2335 if (token.kind == T___attribute__) {
2336 attributes = parse_attributes(NULL);
2339 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2340 if (token.kind == T_IDENTIFIER) {
2341 /* the compound has a name, check if we have seen it already */
2342 symbol = token.identifier.symbol;
2343 entity = get_tag(symbol, kind);
2346 if (entity != NULL) {
2347 if (entity->base.parent_scope != current_scope &&
2348 (token.kind == '{' || token.kind == ';')) {
2349 /* we're in an inner scope and have a definition. Shadow
2350 * existing definition in outer scope */
2352 } else if (entity->compound.complete && token.kind == '{') {
2353 source_position_t const *const ppos = &entity->base.source_position;
2354 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2355 /* clear members in the hope to avoid further errors */
2356 entity->compound.members.entities = NULL;
2359 } else if (token.kind != '{') {
2360 char const *const msg =
2361 is_struct ? "while parsing struct type specifier" :
2362 "while parsing union type specifier";
2363 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2368 if (entity == NULL) {
2369 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2370 entity->compound.alignment = 1;
2371 entity->base.source_position = pos;
2372 entity->base.parent_scope = current_scope;
2373 if (symbol != NULL) {
2374 environment_push(entity);
2376 append_entity(current_scope, entity);
2379 if (token.kind == '{') {
2380 parse_compound_type_entries(&entity->compound);
2382 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2383 if (symbol == NULL) {
2384 assert(anonymous_entity == NULL);
2385 anonymous_entity = entity;
2389 if (attributes != NULL) {
2390 handle_entity_attributes(attributes, entity);
2393 return &entity->compound;
2396 static void parse_enum_entries(type_t *const enum_type)
2400 if (token.kind == '}') {
2401 errorf(HERE, "empty enum not allowed");
2406 add_anchor_token('}');
2408 if (token.kind != T_IDENTIFIER) {
2409 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2411 rem_anchor_token('}');
2415 symbol_t *symbol = token.identifier.symbol;
2416 entity_t *const entity
2417 = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol);
2418 entity->enum_value.enum_type = enum_type;
2419 entity->base.source_position = token.base.source_position;
2423 expression_t *value = parse_constant_expression();
2425 value = create_implicit_cast(value, enum_type);
2426 entity->enum_value.value = value;
2431 record_entity(entity, false);
2432 } while (next_if(',') && token.kind != '}');
2433 rem_anchor_token('}');
2435 expect('}', end_error);
2441 static type_t *parse_enum_specifier(void)
2443 source_position_t const pos = *HERE;
2448 switch (token.kind) {
2450 symbol = token.identifier.symbol;
2451 entity = get_tag(symbol, ENTITY_ENUM);
2454 if (entity != NULL) {
2455 if (entity->base.parent_scope != current_scope &&
2456 (token.kind == '{' || token.kind == ';')) {
2457 /* we're in an inner scope and have a definition. Shadow
2458 * existing definition in outer scope */
2460 } else if (entity->enume.complete && token.kind == '{') {
2461 source_position_t const *const ppos = &entity->base.source_position;
2462 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2473 parse_error_expected("while parsing enum type specifier",
2474 T_IDENTIFIER, '{', NULL);
2478 if (entity == NULL) {
2479 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2480 entity->base.source_position = pos;
2481 entity->base.parent_scope = current_scope;
2484 type_t *const type = allocate_type_zero(TYPE_ENUM);
2485 type->enumt.enume = &entity->enume;
2486 type->enumt.base.akind = ATOMIC_TYPE_INT;
2488 if (token.kind == '{') {
2489 if (symbol != NULL) {
2490 environment_push(entity);
2492 append_entity(current_scope, entity);
2493 entity->enume.complete = true;
2495 parse_enum_entries(type);
2496 parse_attributes(NULL);
2498 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2499 if (symbol == NULL) {
2500 assert(anonymous_entity == NULL);
2501 anonymous_entity = entity;
2503 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2504 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2511 * if a symbol is a typedef to another type, return true
2513 static bool is_typedef_symbol(symbol_t *symbol)
2515 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2516 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2519 static type_t *parse_typeof(void)
2525 expect('(', end_error);
2526 add_anchor_token(')');
2528 expression_t *expression = NULL;
2530 switch (token.kind) {
2532 if (is_typedef_symbol(token.identifier.symbol)) {
2534 type = parse_typename();
2537 expression = parse_expression();
2538 type = revert_automatic_type_conversion(expression);
2543 rem_anchor_token(')');
2544 expect(')', end_error);
2546 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2547 typeof_type->typeoft.expression = expression;
2548 typeof_type->typeoft.typeof_type = type;
2555 typedef enum specifiers_t {
2556 SPECIFIER_SIGNED = 1 << 0,
2557 SPECIFIER_UNSIGNED = 1 << 1,
2558 SPECIFIER_LONG = 1 << 2,
2559 SPECIFIER_INT = 1 << 3,
2560 SPECIFIER_DOUBLE = 1 << 4,
2561 SPECIFIER_CHAR = 1 << 5,
2562 SPECIFIER_WCHAR_T = 1 << 6,
2563 SPECIFIER_SHORT = 1 << 7,
2564 SPECIFIER_LONG_LONG = 1 << 8,
2565 SPECIFIER_FLOAT = 1 << 9,
2566 SPECIFIER_BOOL = 1 << 10,
2567 SPECIFIER_VOID = 1 << 11,
2568 SPECIFIER_INT8 = 1 << 12,
2569 SPECIFIER_INT16 = 1 << 13,
2570 SPECIFIER_INT32 = 1 << 14,
2571 SPECIFIER_INT64 = 1 << 15,
2572 SPECIFIER_INT128 = 1 << 16,
2573 SPECIFIER_COMPLEX = 1 << 17,
2574 SPECIFIER_IMAGINARY = 1 << 18,
2577 static type_t *get_typedef_type(symbol_t *symbol)
2579 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2580 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2583 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2584 type->typedeft.typedefe = &entity->typedefe;
2589 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2591 expect('(', end_error);
2593 attribute_property_argument_t *property
2594 = allocate_ast_zero(sizeof(*property));
2597 if (token.kind != T_IDENTIFIER) {
2598 parse_error_expected("while parsing property declspec",
2599 T_IDENTIFIER, NULL);
2604 symbol_t *symbol = token.identifier.symbol;
2605 if (streq(symbol->string, "put")) {
2606 prop = &property->put_symbol;
2607 } else if (streq(symbol->string, "get")) {
2608 prop = &property->get_symbol;
2610 errorf(HERE, "expected put or get in property declspec");
2614 expect('=', end_error);
2615 if (token.kind != T_IDENTIFIER) {
2616 parse_error_expected("while parsing property declspec",
2617 T_IDENTIFIER, NULL);
2621 *prop = token.identifier.symbol;
2623 } while (next_if(','));
2625 attribute->a.property = property;
2627 expect(')', end_error);
2633 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2635 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2636 if (next_if(T_restrict)) {
2637 kind = ATTRIBUTE_MS_RESTRICT;
2638 } else if (token.kind == T_IDENTIFIER) {
2639 const char *name = token.identifier.symbol->string;
2640 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2642 const char *attribute_name = get_attribute_name(k);
2643 if (attribute_name != NULL && streq(attribute_name, name)) {
2649 if (kind == ATTRIBUTE_UNKNOWN) {
2650 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2653 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2657 attribute_t *attribute = allocate_attribute_zero(kind);
2660 if (kind == ATTRIBUTE_MS_PROPERTY) {
2661 return parse_attribute_ms_property(attribute);
2664 /* parse arguments */
2666 attribute->a.arguments = parse_attribute_arguments();
2671 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2675 expect('(', end_error);
2680 add_anchor_token(')');
2682 attribute_t **anchor = &first;
2684 while (*anchor != NULL)
2685 anchor = &(*anchor)->next;
2687 attribute_t *attribute
2688 = parse_microsoft_extended_decl_modifier_single();
2689 if (attribute == NULL)
2692 *anchor = attribute;
2693 anchor = &attribute->next;
2694 } while (next_if(','));
2696 rem_anchor_token(')');
2697 expect(')', end_error);
2701 rem_anchor_token(')');
2705 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2707 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2708 entity->base.source_position = *HERE;
2709 if (is_declaration(entity)) {
2710 entity->declaration.type = type_error_type;
2711 entity->declaration.implicit = true;
2712 } else if (kind == ENTITY_TYPEDEF) {
2713 entity->typedefe.type = type_error_type;
2714 entity->typedefe.builtin = true;
2716 if (kind != ENTITY_COMPOUND_MEMBER)
2717 record_entity(entity, false);
2721 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2723 type_t *type = NULL;
2724 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2725 unsigned type_specifiers = 0;
2726 bool newtype = false;
2727 bool saw_error = false;
2729 memset(specifiers, 0, sizeof(*specifiers));
2730 specifiers->source_position = token.base.source_position;
2733 specifiers->attributes = parse_attributes(specifiers->attributes);
2735 switch (token.kind) {
2737 #define MATCH_STORAGE_CLASS(token, class) \
2739 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2740 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2742 specifiers->storage_class = class; \
2743 if (specifiers->thread_local) \
2744 goto check_thread_storage_class; \
2748 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2749 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2750 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2751 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2752 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2755 specifiers->attributes
2756 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2760 if (specifiers->thread_local) {
2761 errorf(HERE, "duplicate '__thread'");
2763 specifiers->thread_local = true;
2764 check_thread_storage_class:
2765 switch (specifiers->storage_class) {
2766 case STORAGE_CLASS_EXTERN:
2767 case STORAGE_CLASS_NONE:
2768 case STORAGE_CLASS_STATIC:
2772 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2773 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2774 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2775 wrong_thread_storage_class:
2776 errorf(HERE, "'__thread' used with '%s'", wrong);
2783 /* type qualifiers */
2784 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2786 qualifiers |= qualifier; \
2790 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2791 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2792 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2793 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2794 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2795 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2796 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2797 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2799 /* type specifiers */
2800 #define MATCH_SPECIFIER(token, specifier, name) \
2802 if (type_specifiers & specifier) { \
2803 errorf(HERE, "multiple " name " type specifiers given"); \
2805 type_specifiers |= specifier; \
2810 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2811 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2812 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2813 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2814 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2815 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2816 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2817 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2818 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2819 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2820 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2821 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2822 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2823 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2824 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2825 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2826 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2827 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2831 specifiers->is_inline = true;
2835 case T__forceinline:
2837 specifiers->modifiers |= DM_FORCEINLINE;
2842 if (type_specifiers & SPECIFIER_LONG_LONG) {
2843 errorf(HERE, "too many long type specifiers given");
2844 } else if (type_specifiers & SPECIFIER_LONG) {
2845 type_specifiers |= SPECIFIER_LONG_LONG;
2847 type_specifiers |= SPECIFIER_LONG;
2852 #define CHECK_DOUBLE_TYPE() \
2853 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2856 CHECK_DOUBLE_TYPE();
2857 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2859 type->compound.compound = parse_compound_type_specifier(true);
2862 CHECK_DOUBLE_TYPE();
2863 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2864 type->compound.compound = parse_compound_type_specifier(false);
2867 CHECK_DOUBLE_TYPE();
2868 type = parse_enum_specifier();
2871 CHECK_DOUBLE_TYPE();
2872 type = parse_typeof();
2874 case T___builtin_va_list:
2875 CHECK_DOUBLE_TYPE();
2876 type = duplicate_type(type_valist);
2880 case T_IDENTIFIER: {
2881 /* only parse identifier if we haven't found a type yet */
2882 if (type != NULL || type_specifiers != 0) {
2883 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2884 * declaration, so it doesn't generate errors about expecting '(' or
2886 switch (look_ahead(1)->kind) {
2893 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2897 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2902 goto finish_specifiers;
2906 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2907 if (typedef_type == NULL) {
2908 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2909 * declaration, so it doesn't generate 'implicit int' followed by more
2910 * errors later on. */
2911 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2917 errorf(HERE, "%K does not name a type", &token);
2919 symbol_t *symbol = token.identifier.symbol;
2921 = create_error_entity(symbol, ENTITY_TYPEDEF);
2923 type = allocate_type_zero(TYPE_TYPEDEF);
2924 type->typedeft.typedefe = &entity->typedefe;
2932 goto finish_specifiers;
2937 type = typedef_type;
2941 /* function specifier */
2943 goto finish_specifiers;
2948 specifiers->attributes = parse_attributes(specifiers->attributes);
2950 if (type == NULL || (saw_error && type_specifiers != 0)) {
2951 atomic_type_kind_t atomic_type;
2953 /* match valid basic types */
2954 switch (type_specifiers) {
2955 case SPECIFIER_VOID:
2956 atomic_type = ATOMIC_TYPE_VOID;
2958 case SPECIFIER_WCHAR_T:
2959 atomic_type = ATOMIC_TYPE_WCHAR_T;
2961 case SPECIFIER_CHAR:
2962 atomic_type = ATOMIC_TYPE_CHAR;
2964 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2965 atomic_type = ATOMIC_TYPE_SCHAR;
2967 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2968 atomic_type = ATOMIC_TYPE_UCHAR;
2970 case SPECIFIER_SHORT:
2971 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2972 case SPECIFIER_SHORT | SPECIFIER_INT:
2973 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2974 atomic_type = ATOMIC_TYPE_SHORT;
2976 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2977 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2978 atomic_type = ATOMIC_TYPE_USHORT;
2981 case SPECIFIER_SIGNED:
2982 case SPECIFIER_SIGNED | SPECIFIER_INT:
2983 atomic_type = ATOMIC_TYPE_INT;
2985 case SPECIFIER_UNSIGNED:
2986 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2987 atomic_type = ATOMIC_TYPE_UINT;
2989 case SPECIFIER_LONG:
2990 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2991 case SPECIFIER_LONG | SPECIFIER_INT:
2992 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2993 atomic_type = ATOMIC_TYPE_LONG;
2995 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2996 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2997 atomic_type = ATOMIC_TYPE_ULONG;
3000 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3001 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3002 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3003 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3005 atomic_type = ATOMIC_TYPE_LONGLONG;
3006 goto warn_about_long_long;
3008 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3009 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3011 atomic_type = ATOMIC_TYPE_ULONGLONG;
3012 warn_about_long_long:
3013 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3016 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3017 atomic_type = unsigned_int8_type_kind;
3020 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3021 atomic_type = unsigned_int16_type_kind;
3024 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3025 atomic_type = unsigned_int32_type_kind;
3028 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3029 atomic_type = unsigned_int64_type_kind;
3032 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3033 atomic_type = unsigned_int128_type_kind;
3036 case SPECIFIER_INT8:
3037 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3038 atomic_type = int8_type_kind;
3041 case SPECIFIER_INT16:
3042 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3043 atomic_type = int16_type_kind;
3046 case SPECIFIER_INT32:
3047 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3048 atomic_type = int32_type_kind;
3051 case SPECIFIER_INT64:
3052 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3053 atomic_type = int64_type_kind;
3056 case SPECIFIER_INT128:
3057 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3058 atomic_type = int128_type_kind;
3061 case SPECIFIER_FLOAT:
3062 atomic_type = ATOMIC_TYPE_FLOAT;
3064 case SPECIFIER_DOUBLE:
3065 atomic_type = ATOMIC_TYPE_DOUBLE;
3067 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3068 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3070 case SPECIFIER_BOOL:
3071 atomic_type = ATOMIC_TYPE_BOOL;
3073 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3074 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3075 atomic_type = ATOMIC_TYPE_FLOAT;
3077 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3078 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3079 atomic_type = ATOMIC_TYPE_DOUBLE;
3081 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3082 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3083 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3086 /* invalid specifier combination, give an error message */
3087 source_position_t const* const pos = &specifiers->source_position;
3088 if (type_specifiers == 0) {
3090 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3091 if (!(c_mode & _CXX) && !strict_mode) {
3092 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3093 atomic_type = ATOMIC_TYPE_INT;
3096 errorf(pos, "no type specifiers given in declaration");
3099 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3100 (type_specifiers & SPECIFIER_UNSIGNED)) {
3101 errorf(pos, "signed and unsigned specifiers given");
3102 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3103 errorf(pos, "only integer types can be signed or unsigned");
3105 errorf(pos, "multiple datatypes in declaration");
3111 if (type_specifiers & SPECIFIER_COMPLEX) {
3112 type = allocate_type_zero(TYPE_COMPLEX);
3113 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3114 type = allocate_type_zero(TYPE_IMAGINARY);
3116 type = allocate_type_zero(TYPE_ATOMIC);
3118 type->atomic.akind = atomic_type;
3120 } else if (type_specifiers != 0) {
3121 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3124 /* FIXME: check type qualifiers here */
3125 type->base.qualifiers = qualifiers;
3128 type = identify_new_type(type);
3130 type = typehash_insert(type);
3133 if (specifiers->attributes != NULL)
3134 type = handle_type_attributes(specifiers->attributes, type);
3135 specifiers->type = type;
3139 specifiers->type = type_error_type;
3142 static type_qualifiers_t parse_type_qualifiers(void)
3144 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3147 switch (token.kind) {
3148 /* type qualifiers */
3149 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3150 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3151 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3152 /* microsoft extended type modifiers */
3153 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3154 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3155 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3156 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3157 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3166 * Parses an K&R identifier list
3168 static void parse_identifier_list(scope_t *scope)
3170 assert(token.kind == T_IDENTIFIER);
3172 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol);
3173 entity->base.source_position = token.base.source_position;
3174 /* a K&R parameter has no type, yet */
3178 append_entity(scope, entity);
3179 } while (next_if(',') && token.kind == T_IDENTIFIER);
3182 static entity_t *parse_parameter(void)
3184 declaration_specifiers_t specifiers;
3185 parse_declaration_specifiers(&specifiers);
3187 entity_t *entity = parse_declarator(&specifiers,
3188 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3189 anonymous_entity = NULL;
3193 static void semantic_parameter_incomplete(const entity_t *entity)
3195 assert(entity->kind == ENTITY_PARAMETER);
3197 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3198 * list in a function declarator that is part of a
3199 * definition of that function shall not have
3200 * incomplete type. */
3201 type_t *type = skip_typeref(entity->declaration.type);
3202 if (is_type_incomplete(type)) {
3203 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3207 static bool has_parameters(void)
3209 /* func(void) is not a parameter */
3210 if (token.kind == T_IDENTIFIER) {
3211 entity_t const *const entity
3212 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3215 if (entity->kind != ENTITY_TYPEDEF)
3217 if (skip_typeref(entity->typedefe.type) != type_void)
3219 } else if (token.kind != T_void) {
3222 if (look_ahead(1)->kind != ')')
3229 * Parses function type parameters (and optionally creates variable_t entities
3230 * for them in a scope)
3232 static void parse_parameters(function_type_t *type, scope_t *scope)
3235 add_anchor_token(')');
3236 int saved_comma_state = save_and_reset_anchor_state(',');
3238 if (token.kind == T_IDENTIFIER
3239 && !is_typedef_symbol(token.identifier.symbol)) {
3240 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3241 if (la1_type == ',' || la1_type == ')') {
3242 type->kr_style_parameters = true;
3243 parse_identifier_list(scope);
3244 goto parameters_finished;
3248 if (token.kind == ')') {
3249 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3250 if (!(c_mode & _CXX))
3251 type->unspecified_parameters = true;
3252 } else if (has_parameters()) {
3253 function_parameter_t **anchor = &type->parameters;
3255 switch (token.kind) {
3258 type->variadic = true;
3259 goto parameters_finished;
3264 entity_t *entity = parse_parameter();
3265 if (entity->kind == ENTITY_TYPEDEF) {
3266 errorf(&entity->base.source_position,
3267 "typedef not allowed as function parameter");
3270 assert(is_declaration(entity));
3272 semantic_parameter_incomplete(entity);
3274 function_parameter_t *const parameter =
3275 allocate_parameter(entity->declaration.type);
3277 if (scope != NULL) {
3278 append_entity(scope, entity);
3281 *anchor = parameter;
3282 anchor = ¶meter->next;
3287 goto parameters_finished;
3289 } while (next_if(','));
3292 parameters_finished:
3293 rem_anchor_token(')');
3294 expect(')', end_error);
3297 restore_anchor_state(',', saved_comma_state);
3300 typedef enum construct_type_kind_t {
3301 CONSTRUCT_POINTER = 1,
3302 CONSTRUCT_REFERENCE,
3305 } construct_type_kind_t;
3307 typedef union construct_type_t construct_type_t;
3309 typedef struct construct_type_base_t {
3310 construct_type_kind_t kind;
3311 source_position_t pos;
3312 construct_type_t *next;
3313 } construct_type_base_t;
3315 typedef struct parsed_pointer_t {
3316 construct_type_base_t base;
3317 type_qualifiers_t type_qualifiers;
3318 variable_t *base_variable; /**< MS __based extension. */
3321 typedef struct parsed_reference_t {
3322 construct_type_base_t base;
3323 } parsed_reference_t;
3325 typedef struct construct_function_type_t {
3326 construct_type_base_t base;
3327 type_t *function_type;
3328 } construct_function_type_t;
3330 typedef struct parsed_array_t {
3331 construct_type_base_t base;
3332 type_qualifiers_t type_qualifiers;
3338 union construct_type_t {
3339 construct_type_kind_t kind;
3340 construct_type_base_t base;
3341 parsed_pointer_t pointer;
3342 parsed_reference_t reference;
3343 construct_function_type_t function;
3344 parsed_array_t array;
3347 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3349 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3350 memset(cons, 0, size);
3352 cons->base.pos = *HERE;
3357 static construct_type_t *parse_pointer_declarator(void)
3359 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3361 cons->pointer.type_qualifiers = parse_type_qualifiers();
3362 //cons->pointer.base_variable = base_variable;
3367 /* ISO/IEC 14882:1998(E) §8.3.2 */
3368 static construct_type_t *parse_reference_declarator(void)
3370 if (!(c_mode & _CXX))
3371 errorf(HERE, "references are only available for C++");
3373 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3380 static construct_type_t *parse_array_declarator(void)
3382 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3383 parsed_array_t *const array = &cons->array;
3386 add_anchor_token(']');
3388 bool is_static = next_if(T_static);
3390 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3393 is_static = next_if(T_static);
3395 array->type_qualifiers = type_qualifiers;
3396 array->is_static = is_static;
3398 expression_t *size = NULL;
3399 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3400 array->is_variable = true;
3402 } else if (token.kind != ']') {
3403 size = parse_assignment_expression();
3405 /* §6.7.5.2:1 Array size must have integer type */
3406 type_t *const orig_type = size->base.type;
3407 type_t *const type = skip_typeref(orig_type);
3408 if (!is_type_integer(type) && is_type_valid(type)) {
3409 errorf(&size->base.source_position,
3410 "array size '%E' must have integer type but has type '%T'",
3415 mark_vars_read(size, NULL);
3418 if (is_static && size == NULL)
3419 errorf(&array->base.pos, "static array parameters require a size");
3421 rem_anchor_token(']');
3422 expect(']', end_error);
3429 static construct_type_t *parse_function_declarator(scope_t *scope)
3431 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3433 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3434 function_type_t *ftype = &type->function;
3436 ftype->linkage = current_linkage;
3437 ftype->calling_convention = CC_DEFAULT;
3439 parse_parameters(ftype, scope);
3441 cons->function.function_type = type;
3446 typedef struct parse_declarator_env_t {
3447 bool may_be_abstract : 1;
3448 bool must_be_abstract : 1;
3449 decl_modifiers_t modifiers;
3451 source_position_t source_position;
3453 attribute_t *attributes;
3454 } parse_declarator_env_t;
3457 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3459 /* construct a single linked list of construct_type_t's which describe
3460 * how to construct the final declarator type */
3461 construct_type_t *first = NULL;
3462 construct_type_t **anchor = &first;
3464 env->attributes = parse_attributes(env->attributes);
3467 construct_type_t *type;
3468 //variable_t *based = NULL; /* MS __based extension */
3469 switch (token.kind) {
3471 type = parse_reference_declarator();
3475 panic("based not supported anymore");
3480 type = parse_pointer_declarator();
3484 goto ptr_operator_end;
3488 anchor = &type->base.next;
3490 /* TODO: find out if this is correct */
3491 env->attributes = parse_attributes(env->attributes);
3495 construct_type_t *inner_types = NULL;
3497 switch (token.kind) {
3499 if (env->must_be_abstract) {
3500 errorf(HERE, "no identifier expected in typename");
3502 env->symbol = token.identifier.symbol;
3503 env->source_position = token.base.source_position;
3509 /* Parenthesized declarator or function declarator? */
3510 token_t const *const la1 = look_ahead(1);
3511 switch (la1->kind) {
3513 if (is_typedef_symbol(la1->identifier.symbol)) {
3515 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3516 * interpreted as ``function with no parameter specification'', rather
3517 * than redundant parentheses around the omitted identifier. */
3519 /* Function declarator. */
3520 if (!env->may_be_abstract) {
3521 errorf(HERE, "function declarator must have a name");
3528 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3529 /* Paranthesized declarator. */
3531 add_anchor_token(')');
3532 inner_types = parse_inner_declarator(env);
3533 if (inner_types != NULL) {
3534 /* All later declarators only modify the return type */
3535 env->must_be_abstract = true;
3537 rem_anchor_token(')');
3538 expect(')', end_error);
3546 if (env->may_be_abstract)
3548 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3553 construct_type_t **const p = anchor;
3556 construct_type_t *type;
3557 switch (token.kind) {
3559 scope_t *scope = NULL;
3560 if (!env->must_be_abstract) {
3561 scope = &env->parameters;
3564 type = parse_function_declarator(scope);
3568 type = parse_array_declarator();
3571 goto declarator_finished;
3574 /* insert in the middle of the list (at p) */
3575 type->base.next = *p;
3578 anchor = &type->base.next;
3581 declarator_finished:
3582 /* append inner_types at the end of the list, we don't to set anchor anymore
3583 * as it's not needed anymore */
3584 *anchor = inner_types;
3591 static type_t *construct_declarator_type(construct_type_t *construct_list,
3594 construct_type_t *iter = construct_list;
3595 for (; iter != NULL; iter = iter->base.next) {
3596 source_position_t const* const pos = &iter->base.pos;
3597 switch (iter->kind) {
3598 case CONSTRUCT_FUNCTION: {
3599 construct_function_type_t *function = &iter->function;
3600 type_t *function_type = function->function_type;
3602 function_type->function.return_type = type;
3604 type_t *skipped_return_type = skip_typeref(type);
3606 if (is_type_function(skipped_return_type)) {
3607 errorf(pos, "function returning function is not allowed");
3608 } else if (is_type_array(skipped_return_type)) {
3609 errorf(pos, "function returning array is not allowed");
3611 if (skipped_return_type->base.qualifiers != 0) {
3612 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3616 /* The function type was constructed earlier. Freeing it here will
3617 * destroy other types. */
3618 type = typehash_insert(function_type);
3622 case CONSTRUCT_POINTER: {
3623 if (is_type_reference(skip_typeref(type)))
3624 errorf(pos, "cannot declare a pointer to reference");
3626 parsed_pointer_t *pointer = &iter->pointer;
3627 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3631 case CONSTRUCT_REFERENCE:
3632 if (is_type_reference(skip_typeref(type)))
3633 errorf(pos, "cannot declare a reference to reference");
3635 type = make_reference_type(type);
3638 case CONSTRUCT_ARRAY: {
3639 if (is_type_reference(skip_typeref(type)))
3640 errorf(pos, "cannot declare an array of references");
3642 parsed_array_t *array = &iter->array;
3643 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3645 expression_t *size_expression = array->size;
3646 if (size_expression != NULL) {
3648 = create_implicit_cast(size_expression, type_size_t);
3651 array_type->base.qualifiers = array->type_qualifiers;
3652 array_type->array.element_type = type;
3653 array_type->array.is_static = array->is_static;
3654 array_type->array.is_variable = array->is_variable;
3655 array_type->array.size_expression = size_expression;
3657 if (size_expression != NULL) {
3658 switch (is_constant_expression(size_expression)) {
3659 case EXPR_CLASS_CONSTANT: {
3660 long const size = fold_constant_to_int(size_expression);
3661 array_type->array.size = size;
3662 array_type->array.size_constant = true;
3663 /* §6.7.5.2:1 If the expression is a constant expression,
3664 * it shall have a value greater than zero. */
3666 errorf(&size_expression->base.source_position,
3667 "size of array must be greater than zero");
3668 } else if (size == 0 && !GNU_MODE) {
3669 errorf(&size_expression->base.source_position,
3670 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3675 case EXPR_CLASS_VARIABLE:
3676 array_type->array.is_vla = true;
3679 case EXPR_CLASS_ERROR:
3684 type_t *skipped_type = skip_typeref(type);
3686 if (is_type_incomplete(skipped_type)) {
3687 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3688 } else if (is_type_function(skipped_type)) {
3689 errorf(pos, "array of functions is not allowed");
3691 type = identify_new_type(array_type);
3695 internal_errorf(pos, "invalid type construction found");
3701 static type_t *automatic_type_conversion(type_t *orig_type);
3703 static type_t *semantic_parameter(const source_position_t *pos,
3705 const declaration_specifiers_t *specifiers,
3706 entity_t const *const param)
3708 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3709 * shall be adjusted to ``qualified pointer to type'',
3711 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3712 * type'' shall be adjusted to ``pointer to function
3713 * returning type'', as in 6.3.2.1. */
3714 type = automatic_type_conversion(type);
3716 if (specifiers->is_inline && is_type_valid(type)) {
3717 errorf(pos, "'%N' declared 'inline'", param);
3720 /* §6.9.1:6 The declarations in the declaration list shall contain
3721 * no storage-class specifier other than register and no
3722 * initializations. */
3723 if (specifiers->thread_local || (
3724 specifiers->storage_class != STORAGE_CLASS_NONE &&
3725 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3727 errorf(pos, "invalid storage class for '%N'", param);
3730 /* delay test for incomplete type, because we might have (void)
3731 * which is legal but incomplete... */
3736 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3737 declarator_flags_t flags)
3739 parse_declarator_env_t env;
3740 memset(&env, 0, sizeof(env));
3741 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3743 construct_type_t *construct_type = parse_inner_declarator(&env);
3745 construct_declarator_type(construct_type, specifiers->type);
3746 type_t *type = skip_typeref(orig_type);
3748 if (construct_type != NULL) {
3749 obstack_free(&temp_obst, construct_type);
3752 attribute_t *attributes = parse_attributes(env.attributes);
3753 /* append (shared) specifier attribute behind attributes of this
3755 attribute_t **anchor = &attributes;
3756 while (*anchor != NULL)
3757 anchor = &(*anchor)->next;
3758 *anchor = specifiers->attributes;
3761 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3762 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3763 entity->base.source_position = env.source_position;
3764 entity->typedefe.type = orig_type;
3766 if (anonymous_entity != NULL) {
3767 if (is_type_compound(type)) {
3768 assert(anonymous_entity->compound.alias == NULL);
3769 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3770 anonymous_entity->kind == ENTITY_UNION);
3771 anonymous_entity->compound.alias = entity;
3772 anonymous_entity = NULL;
3773 } else if (is_type_enum(type)) {
3774 assert(anonymous_entity->enume.alias == NULL);
3775 assert(anonymous_entity->kind == ENTITY_ENUM);
3776 anonymous_entity->enume.alias = entity;
3777 anonymous_entity = NULL;
3781 /* create a declaration type entity */
3782 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3783 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3785 if (env.symbol != NULL) {
3786 if (specifiers->is_inline && is_type_valid(type)) {
3787 errorf(&env.source_position,
3788 "compound member '%Y' declared 'inline'", env.symbol);
3791 if (specifiers->thread_local ||
3792 specifiers->storage_class != STORAGE_CLASS_NONE) {
3793 errorf(&env.source_position,
3794 "compound member '%Y' must have no storage class",
3798 } else if (flags & DECL_IS_PARAMETER) {
3799 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3800 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3801 } else if (is_type_function(type)) {
3802 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3803 entity->function.is_inline = specifiers->is_inline;
3804 entity->function.elf_visibility = default_visibility;
3805 entity->function.parameters = env.parameters;
3807 if (env.symbol != NULL) {
3808 /* this needs fixes for C++ */
3809 bool in_function_scope = current_function != NULL;
3811 if (specifiers->thread_local || (
3812 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3813 specifiers->storage_class != STORAGE_CLASS_NONE &&
3814 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3816 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3820 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3821 entity->variable.elf_visibility = default_visibility;
3822 entity->variable.thread_local = specifiers->thread_local;
3824 if (env.symbol != NULL) {
3825 if (specifiers->is_inline && is_type_valid(type)) {
3826 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3829 bool invalid_storage_class = false;
3830 if (current_scope == file_scope) {
3831 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3832 specifiers->storage_class != STORAGE_CLASS_NONE &&
3833 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3834 invalid_storage_class = true;
3837 if (specifiers->thread_local &&
3838 specifiers->storage_class == STORAGE_CLASS_NONE) {
3839 invalid_storage_class = true;
3842 if (invalid_storage_class) {
3843 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3848 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3849 entity->declaration.type = orig_type;
3850 entity->declaration.alignment = get_type_alignment(orig_type);
3851 entity->declaration.modifiers = env.modifiers;
3852 entity->declaration.attributes = attributes;
3854 storage_class_t storage_class = specifiers->storage_class;
3855 entity->declaration.declared_storage_class = storage_class;
3857 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3858 storage_class = STORAGE_CLASS_AUTO;
3859 entity->declaration.storage_class = storage_class;
3862 if (attributes != NULL) {
3863 handle_entity_attributes(attributes, entity);
3866 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3867 adapt_special_functions(&entity->function);
3873 static type_t *parse_abstract_declarator(type_t *base_type)
3875 parse_declarator_env_t env;
3876 memset(&env, 0, sizeof(env));
3877 env.may_be_abstract = true;
3878 env.must_be_abstract = true;
3880 construct_type_t *construct_type = parse_inner_declarator(&env);
3882 type_t *result = construct_declarator_type(construct_type, base_type);
3883 if (construct_type != NULL) {
3884 obstack_free(&temp_obst, construct_type);
3886 result = handle_type_attributes(env.attributes, result);
3892 * Check if the declaration of main is suspicious. main should be a
3893 * function with external linkage, returning int, taking either zero
3894 * arguments, two, or three arguments of appropriate types, ie.
3896 * int main([ int argc, char **argv [, char **env ] ]).
3898 * @param decl the declaration to check
3899 * @param type the function type of the declaration
3901 static void check_main(const entity_t *entity)
3903 const source_position_t *pos = &entity->base.source_position;
3904 if (entity->kind != ENTITY_FUNCTION) {
3905 warningf(WARN_MAIN, pos, "'main' is not a function");
3909 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3910 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3913 type_t *type = skip_typeref(entity->declaration.type);
3914 assert(is_type_function(type));
3916 function_type_t const *const func_type = &type->function;
3917 type_t *const ret_type = func_type->return_type;
3918 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3919 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3921 const function_parameter_t *parm = func_type->parameters;
3923 type_t *const first_type = skip_typeref(parm->type);
3924 type_t *const first_type_unqual = get_unqualified_type(first_type);
3925 if (!types_compatible(first_type_unqual, type_int)) {
3926 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3930 type_t *const second_type = skip_typeref(parm->type);
3931 type_t *const second_type_unqual
3932 = get_unqualified_type(second_type);
3933 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3934 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3938 type_t *const third_type = skip_typeref(parm->type);
3939 type_t *const third_type_unqual
3940 = get_unqualified_type(third_type);
3941 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3942 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3946 goto warn_arg_count;
3950 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3956 * Check if a symbol is the equal to "main".
3958 static bool is_sym_main(const symbol_t *const sym)
3960 return streq(sym->string, "main");
3963 static void error_redefined_as_different_kind(const source_position_t *pos,
3964 const entity_t *old, entity_kind_t new_kind)
3966 char const *const what = get_entity_kind_name(new_kind);
3967 source_position_t const *const ppos = &old->base.source_position;
3968 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3971 static bool is_entity_valid(entity_t *const ent)
3973 if (is_declaration(ent)) {
3974 return is_type_valid(skip_typeref(ent->declaration.type));
3975 } else if (ent->kind == ENTITY_TYPEDEF) {
3976 return is_type_valid(skip_typeref(ent->typedefe.type));
3981 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3983 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3984 if (attributes_equal(tattr, attr))
3991 * test wether new_list contains any attributes not included in old_list
3993 static bool has_new_attributes(const attribute_t *old_list,
3994 const attribute_t *new_list)
3996 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3997 if (!contains_attribute(old_list, attr))
4004 * Merge in attributes from an attribute list (probably from a previous
4005 * declaration with the same name). Warning: destroys the old structure
4006 * of the attribute list - don't reuse attributes after this call.
4008 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4011 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4013 if (contains_attribute(decl->attributes, attr))
4016 /* move attribute to new declarations attributes list */
4017 attr->next = decl->attributes;
4018 decl->attributes = attr;
4023 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4024 * for various problems that occur for multiple definitions
4026 entity_t *record_entity(entity_t *entity, const bool is_definition)
4028 const symbol_t *const symbol = entity->base.symbol;
4029 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4030 const source_position_t *pos = &entity->base.source_position;
4032 /* can happen in error cases */
4036 entity_t *const previous_entity = get_entity(symbol, namespc);
4037 /* pushing the same entity twice will break the stack structure */
4038 assert(previous_entity != entity);
4040 if (entity->kind == ENTITY_FUNCTION) {
4041 type_t *const orig_type = entity->declaration.type;
4042 type_t *const type = skip_typeref(orig_type);
4044 assert(is_type_function(type));
4045 if (type->function.unspecified_parameters &&
4046 previous_entity == NULL &&
4047 !entity->declaration.implicit) {
4048 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4051 if (current_scope == file_scope && is_sym_main(symbol)) {
4056 if (is_declaration(entity) &&
4057 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4058 current_scope != file_scope &&
4059 !entity->declaration.implicit) {
4060 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4063 if (previous_entity != NULL) {
4064 source_position_t const *const ppos = &previous_entity->base.source_position;
4066 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4067 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4068 assert(previous_entity->kind == ENTITY_PARAMETER);
4069 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4073 if (previous_entity->base.parent_scope == current_scope) {
4074 if (previous_entity->kind != entity->kind) {
4075 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4076 error_redefined_as_different_kind(pos, previous_entity,
4081 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4082 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4085 if (previous_entity->kind == ENTITY_TYPEDEF) {
4086 type_t *const type = skip_typeref(entity->typedefe.type);
4087 type_t *const prev_type
4088 = skip_typeref(previous_entity->typedefe.type);
4089 if (c_mode & _CXX) {
4090 /* C++ allows double typedef if they are identical
4091 * (after skipping typedefs) */
4092 if (type == prev_type)
4095 /* GCC extension: redef in system headers is allowed */
4096 if ((pos->is_system_header || ppos->is_system_header) &&
4097 types_compatible(type, prev_type))
4100 errorf(pos, "redefinition of '%N' (declared %P)",
4105 /* at this point we should have only VARIABLES or FUNCTIONS */
4106 assert(is_declaration(previous_entity) && is_declaration(entity));
4108 declaration_t *const prev_decl = &previous_entity->declaration;
4109 declaration_t *const decl = &entity->declaration;
4111 /* can happen for K&R style declarations */
4112 if (prev_decl->type == NULL &&
4113 previous_entity->kind == ENTITY_PARAMETER &&
4114 entity->kind == ENTITY_PARAMETER) {
4115 prev_decl->type = decl->type;
4116 prev_decl->storage_class = decl->storage_class;
4117 prev_decl->declared_storage_class = decl->declared_storage_class;
4118 prev_decl->modifiers = decl->modifiers;
4119 return previous_entity;
4122 type_t *const type = skip_typeref(decl->type);
4123 type_t *const prev_type = skip_typeref(prev_decl->type);
4125 if (!types_compatible(type, prev_type)) {
4126 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4128 unsigned old_storage_class = prev_decl->storage_class;
4130 if (is_definition &&
4132 !(prev_decl->modifiers & DM_USED) &&
4133 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4134 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4137 storage_class_t new_storage_class = decl->storage_class;
4139 /* pretend no storage class means extern for function
4140 * declarations (except if the previous declaration is neither
4141 * none nor extern) */
4142 if (entity->kind == ENTITY_FUNCTION) {
4143 /* the previous declaration could have unspecified parameters or
4144 * be a typedef, so use the new type */
4145 if (prev_type->function.unspecified_parameters || is_definition)
4146 prev_decl->type = type;
4148 switch (old_storage_class) {
4149 case STORAGE_CLASS_NONE:
4150 old_storage_class = STORAGE_CLASS_EXTERN;
4153 case STORAGE_CLASS_EXTERN:
4154 if (is_definition) {
4155 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4156 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4158 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4159 new_storage_class = STORAGE_CLASS_EXTERN;
4166 } else if (is_type_incomplete(prev_type)) {
4167 prev_decl->type = type;
4170 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4171 new_storage_class == STORAGE_CLASS_EXTERN) {
4173 warn_redundant_declaration: ;
4175 = has_new_attributes(prev_decl->attributes,
4177 if (has_new_attrs) {
4178 merge_in_attributes(decl, prev_decl->attributes);
4179 } else if (!is_definition &&
4180 is_type_valid(prev_type) &&
4181 !pos->is_system_header) {
4182 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4184 } else if (current_function == NULL) {
4185 if (old_storage_class != STORAGE_CLASS_STATIC &&
4186 new_storage_class == STORAGE_CLASS_STATIC) {
4187 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4188 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4189 prev_decl->storage_class = STORAGE_CLASS_NONE;
4190 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4192 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4194 goto error_redeclaration;
4195 goto warn_redundant_declaration;
4197 } else if (is_type_valid(prev_type)) {
4198 if (old_storage_class == new_storage_class) {
4199 error_redeclaration:
4200 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4202 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4207 prev_decl->modifiers |= decl->modifiers;
4208 if (entity->kind == ENTITY_FUNCTION) {
4209 previous_entity->function.is_inline |= entity->function.is_inline;
4211 return previous_entity;
4215 if (is_warn_on(why = WARN_SHADOW) ||
4216 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4217 char const *const what = get_entity_kind_name(previous_entity->kind);
4218 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4222 if (entity->kind == ENTITY_FUNCTION) {
4223 if (is_definition &&
4224 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4225 !is_sym_main(symbol)) {
4226 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4227 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4229 goto warn_missing_declaration;
4232 } else if (entity->kind == ENTITY_VARIABLE) {
4233 if (current_scope == file_scope &&
4234 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4235 !entity->declaration.implicit) {
4236 warn_missing_declaration:
4237 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4242 assert(entity->base.parent_scope == NULL);
4243 assert(current_scope != NULL);
4245 entity->base.parent_scope = current_scope;
4246 environment_push(entity);
4247 append_entity(current_scope, entity);
4252 static void parser_error_multiple_definition(entity_t *entity,
4253 const source_position_t *source_position)
4255 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4256 entity->base.symbol, &entity->base.source_position);
4259 static bool is_declaration_specifier(const token_t *token)
4261 switch (token->kind) {
4265 return is_typedef_symbol(token->identifier.symbol);
4272 static void parse_init_declarator_rest(entity_t *entity)
4274 type_t *orig_type = type_error_type;
4276 if (entity->base.kind == ENTITY_TYPEDEF) {
4277 source_position_t const *const pos = &entity->base.source_position;
4278 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4280 assert(is_declaration(entity));
4281 orig_type = entity->declaration.type;
4284 type_t *type = skip_typeref(orig_type);
4286 if (entity->kind == ENTITY_VARIABLE
4287 && entity->variable.initializer != NULL) {
4288 parser_error_multiple_definition(entity, HERE);
4292 declaration_t *const declaration = &entity->declaration;
4293 bool must_be_constant = false;
4294 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4295 entity->base.parent_scope == file_scope) {
4296 must_be_constant = true;
4299 if (is_type_function(type)) {
4300 source_position_t const *const pos = &entity->base.source_position;
4301 errorf(pos, "'%N' is initialized like a variable", entity);
4302 orig_type = type_error_type;
4305 parse_initializer_env_t env;
4306 env.type = orig_type;
4307 env.must_be_constant = must_be_constant;
4308 env.entity = entity;
4310 initializer_t *initializer = parse_initializer(&env);
4312 if (entity->kind == ENTITY_VARIABLE) {
4313 /* §6.7.5:22 array initializers for arrays with unknown size
4314 * determine the array type size */
4315 declaration->type = env.type;
4316 entity->variable.initializer = initializer;
4320 /* parse rest of a declaration without any declarator */
4321 static void parse_anonymous_declaration_rest(
4322 const declaration_specifiers_t *specifiers)
4325 anonymous_entity = NULL;
4327 source_position_t const *const pos = &specifiers->source_position;
4328 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4329 specifiers->thread_local) {
4330 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4333 type_t *type = specifiers->type;
4334 switch (type->kind) {
4335 case TYPE_COMPOUND_STRUCT:
4336 case TYPE_COMPOUND_UNION: {
4337 if (type->compound.compound->base.symbol == NULL) {
4338 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4347 warningf(WARN_OTHER, pos, "empty declaration");
4352 static void check_variable_type_complete(entity_t *ent)
4354 if (ent->kind != ENTITY_VARIABLE)
4357 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4358 * type for the object shall be complete [...] */
4359 declaration_t *decl = &ent->declaration;
4360 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4361 decl->storage_class == STORAGE_CLASS_STATIC)
4364 type_t *const type = skip_typeref(decl->type);
4365 if (!is_type_incomplete(type))
4368 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4369 * are given length one. */
4370 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4371 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4375 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4379 static void parse_declaration_rest(entity_t *ndeclaration,
4380 const declaration_specifiers_t *specifiers,
4381 parsed_declaration_func finished_declaration,
4382 declarator_flags_t flags)
4384 add_anchor_token(';');
4385 add_anchor_token(',');
4387 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4389 if (token.kind == '=') {
4390 parse_init_declarator_rest(entity);
4391 } else if (entity->kind == ENTITY_VARIABLE) {
4392 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4393 * [...] where the extern specifier is explicitly used. */
4394 declaration_t *decl = &entity->declaration;
4395 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4396 type_t *type = decl->type;
4397 if (is_type_reference(skip_typeref(type))) {
4398 source_position_t const *const pos = &entity->base.source_position;
4399 errorf(pos, "reference '%#N' must be initialized", entity);
4404 check_variable_type_complete(entity);
4409 add_anchor_token('=');
4410 ndeclaration = parse_declarator(specifiers, flags);
4411 rem_anchor_token('=');
4413 expect(';', end_error);
4416 anonymous_entity = NULL;
4417 rem_anchor_token(';');
4418 rem_anchor_token(',');
4421 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4423 symbol_t *symbol = entity->base.symbol;
4427 assert(entity->base.namespc == NAMESPACE_NORMAL);
4428 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4429 if (previous_entity == NULL
4430 || previous_entity->base.parent_scope != current_scope) {
4431 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4436 if (is_definition) {
4437 errorf(HERE, "'%N' is initialised", entity);
4440 return record_entity(entity, false);
4443 static void parse_declaration(parsed_declaration_func finished_declaration,
4444 declarator_flags_t flags)
4446 add_anchor_token(';');
4447 declaration_specifiers_t specifiers;
4448 parse_declaration_specifiers(&specifiers);
4449 rem_anchor_token(';');
4451 if (token.kind == ';') {
4452 parse_anonymous_declaration_rest(&specifiers);
4454 entity_t *entity = parse_declarator(&specifiers, flags);
4455 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4460 static type_t *get_default_promoted_type(type_t *orig_type)
4462 type_t *result = orig_type;
4464 type_t *type = skip_typeref(orig_type);
4465 if (is_type_integer(type)) {
4466 result = promote_integer(type);
4467 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4468 result = type_double;
4474 static void parse_kr_declaration_list(entity_t *entity)
4476 if (entity->kind != ENTITY_FUNCTION)
4479 type_t *type = skip_typeref(entity->declaration.type);
4480 assert(is_type_function(type));
4481 if (!type->function.kr_style_parameters)
4484 add_anchor_token('{');
4486 PUSH_SCOPE(&entity->function.parameters);
4488 entity_t *parameter = entity->function.parameters.entities;
4489 for ( ; parameter != NULL; parameter = parameter->base.next) {
4490 assert(parameter->base.parent_scope == NULL);
4491 parameter->base.parent_scope = current_scope;
4492 environment_push(parameter);
4495 /* parse declaration list */
4497 switch (token.kind) {
4499 /* This covers symbols, which are no type, too, and results in
4500 * better error messages. The typical cases are misspelled type
4501 * names and missing includes. */
4503 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4513 /* update function type */
4514 type_t *new_type = duplicate_type(type);
4516 function_parameter_t *parameters = NULL;
4517 function_parameter_t **anchor = ¶meters;
4519 /* did we have an earlier prototype? */
4520 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4521 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4524 function_parameter_t *proto_parameter = NULL;
4525 if (proto_type != NULL) {
4526 type_t *proto_type_type = proto_type->declaration.type;
4527 proto_parameter = proto_type_type->function.parameters;
4528 /* If a K&R function definition has a variadic prototype earlier, then
4529 * make the function definition variadic, too. This should conform to
4530 * §6.7.5.3:15 and §6.9.1:8. */
4531 new_type->function.variadic = proto_type_type->function.variadic;
4533 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4535 new_type->function.unspecified_parameters = true;
4538 bool need_incompatible_warning = false;
4539 parameter = entity->function.parameters.entities;
4540 for (; parameter != NULL; parameter = parameter->base.next,
4542 proto_parameter == NULL ? NULL : proto_parameter->next) {
4543 if (parameter->kind != ENTITY_PARAMETER)
4546 type_t *parameter_type = parameter->declaration.type;
4547 if (parameter_type == NULL) {
4548 source_position_t const* const pos = ¶meter->base.source_position;
4550 errorf(pos, "no type specified for function '%N'", parameter);
4551 parameter_type = type_error_type;
4553 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4554 parameter_type = type_int;
4556 parameter->declaration.type = parameter_type;
4559 semantic_parameter_incomplete(parameter);
4561 /* we need the default promoted types for the function type */
4562 type_t *not_promoted = parameter_type;
4563 parameter_type = get_default_promoted_type(parameter_type);
4565 /* gcc special: if the type of the prototype matches the unpromoted
4566 * type don't promote */
4567 if (!strict_mode && proto_parameter != NULL) {
4568 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4569 type_t *promo_skip = skip_typeref(parameter_type);
4570 type_t *param_skip = skip_typeref(not_promoted);
4571 if (!types_compatible(proto_p_type, promo_skip)
4572 && types_compatible(proto_p_type, param_skip)) {
4574 need_incompatible_warning = true;
4575 parameter_type = not_promoted;
4578 function_parameter_t *const function_parameter
4579 = allocate_parameter(parameter_type);
4581 *anchor = function_parameter;
4582 anchor = &function_parameter->next;
4585 new_type->function.parameters = parameters;
4586 new_type = identify_new_type(new_type);
4588 if (need_incompatible_warning) {
4589 symbol_t const *const sym = entity->base.symbol;
4590 source_position_t const *const pos = &entity->base.source_position;
4591 source_position_t const *const ppos = &proto_type->base.source_position;
4592 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4594 entity->declaration.type = new_type;
4596 rem_anchor_token('{');
4599 static bool first_err = true;
4602 * When called with first_err set, prints the name of the current function,
4605 static void print_in_function(void)
4609 char const *const file = current_function->base.base.source_position.input_name;
4610 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4615 * Check if all labels are defined in the current function.
4616 * Check if all labels are used in the current function.
4618 static void check_labels(void)
4620 for (const goto_statement_t *goto_statement = goto_first;
4621 goto_statement != NULL;
4622 goto_statement = goto_statement->next) {
4623 /* skip computed gotos */
4624 if (goto_statement->expression != NULL)
4627 label_t *label = goto_statement->label;
4628 if (label->base.source_position.input_name == NULL) {
4629 print_in_function();
4630 source_position_t const *const pos = &goto_statement->base.source_position;
4631 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4635 if (is_warn_on(WARN_UNUSED_LABEL)) {
4636 for (const label_statement_t *label_statement = label_first;
4637 label_statement != NULL;
4638 label_statement = label_statement->next) {
4639 label_t *label = label_statement->label;
4641 if (! label->used) {
4642 print_in_function();
4643 source_position_t const *const pos = &label_statement->base.source_position;
4644 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4650 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4652 entity_t const *const end = last != NULL ? last->base.next : NULL;
4653 for (; entity != end; entity = entity->base.next) {
4654 if (!is_declaration(entity))
4657 declaration_t *declaration = &entity->declaration;
4658 if (declaration->implicit)
4661 if (!declaration->used) {
4662 print_in_function();
4663 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4664 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4665 print_in_function();
4666 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4671 static void check_unused_variables(statement_t *const stmt, void *const env)
4675 switch (stmt->kind) {
4676 case STATEMENT_DECLARATION: {
4677 declaration_statement_t const *const decls = &stmt->declaration;
4678 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4683 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4692 * Check declarations of current_function for unused entities.
4694 static void check_declarations(void)
4696 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4697 const scope_t *scope = ¤t_function->parameters;
4699 /* do not issue unused warnings for main */
4700 if (!is_sym_main(current_function->base.base.symbol)) {
4701 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4704 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4705 walk_statements(current_function->statement, check_unused_variables,
4710 static int determine_truth(expression_t const* const cond)
4713 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4714 fold_constant_to_bool(cond) ? 1 :
4718 static void check_reachable(statement_t *);
4719 static bool reaches_end;
4721 static bool expression_returns(expression_t const *const expr)
4723 switch (expr->kind) {
4725 expression_t const *const func = expr->call.function;
4726 type_t const *const type = skip_typeref(func->base.type);
4727 if (type->kind == TYPE_POINTER) {
4728 type_t const *const points_to
4729 = skip_typeref(type->pointer.points_to);
4730 if (points_to->kind == TYPE_FUNCTION
4731 && points_to->function.modifiers & DM_NORETURN)
4735 if (!expression_returns(func))
4738 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4739 if (!expression_returns(arg->expression))
4746 case EXPR_REFERENCE:
4747 case EXPR_REFERENCE_ENUM_VALUE:
4749 case EXPR_STRING_LITERAL:
4750 case EXPR_WIDE_STRING_LITERAL:
4751 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4752 case EXPR_LABEL_ADDRESS:
4753 case EXPR_CLASSIFY_TYPE:
4754 case EXPR_SIZEOF: // TODO handle obscure VLA case
4757 case EXPR_BUILTIN_CONSTANT_P:
4758 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4763 case EXPR_STATEMENT: {
4764 bool old_reaches_end = reaches_end;
4765 reaches_end = false;
4766 check_reachable(expr->statement.statement);
4767 bool returns = reaches_end;
4768 reaches_end = old_reaches_end;
4772 case EXPR_CONDITIONAL:
4773 // TODO handle constant expression
4775 if (!expression_returns(expr->conditional.condition))
4778 if (expr->conditional.true_expression != NULL
4779 && expression_returns(expr->conditional.true_expression))
4782 return expression_returns(expr->conditional.false_expression);
4785 return expression_returns(expr->select.compound);
4787 case EXPR_ARRAY_ACCESS:
4789 expression_returns(expr->array_access.array_ref) &&
4790 expression_returns(expr->array_access.index);
4793 return expression_returns(expr->va_starte.ap);
4796 return expression_returns(expr->va_arge.ap);
4799 return expression_returns(expr->va_copye.src);
4801 EXPR_UNARY_CASES_MANDATORY
4802 return expression_returns(expr->unary.value);
4804 case EXPR_UNARY_THROW:
4808 // TODO handle constant lhs of && and ||
4810 expression_returns(expr->binary.left) &&
4811 expression_returns(expr->binary.right);
4814 panic("unhandled expression");
4817 static bool initializer_returns(initializer_t const *const init)
4819 switch (init->kind) {
4820 case INITIALIZER_VALUE:
4821 return expression_returns(init->value.value);
4823 case INITIALIZER_LIST: {
4824 initializer_t * const* i = init->list.initializers;
4825 initializer_t * const* const end = i + init->list.len;
4826 bool returns = true;
4827 for (; i != end; ++i) {
4828 if (!initializer_returns(*i))
4834 case INITIALIZER_STRING:
4835 case INITIALIZER_WIDE_STRING:
4836 case INITIALIZER_DESIGNATOR: // designators have no payload
4839 panic("unhandled initializer");
4842 static bool noreturn_candidate;
4844 static void check_reachable(statement_t *const stmt)
4846 if (stmt->base.reachable)
4848 if (stmt->kind != STATEMENT_DO_WHILE)
4849 stmt->base.reachable = true;
4851 statement_t *last = stmt;
4853 switch (stmt->kind) {
4854 case STATEMENT_ERROR:
4855 case STATEMENT_EMPTY:
4857 next = stmt->base.next;
4860 case STATEMENT_DECLARATION: {
4861 declaration_statement_t const *const decl = &stmt->declaration;
4862 entity_t const * ent = decl->declarations_begin;
4863 entity_t const *const last_decl = decl->declarations_end;
4865 for (;; ent = ent->base.next) {
4866 if (ent->kind == ENTITY_VARIABLE &&
4867 ent->variable.initializer != NULL &&
4868 !initializer_returns(ent->variable.initializer)) {
4871 if (ent == last_decl)
4875 next = stmt->base.next;
4879 case STATEMENT_COMPOUND:
4880 next = stmt->compound.statements;
4882 next = stmt->base.next;
4885 case STATEMENT_RETURN: {
4886 expression_t const *const val = stmt->returns.value;
4887 if (val == NULL || expression_returns(val))
4888 noreturn_candidate = false;
4892 case STATEMENT_IF: {
4893 if_statement_t const *const ifs = &stmt->ifs;
4894 expression_t const *const cond = ifs->condition;
4896 if (!expression_returns(cond))
4899 int const val = determine_truth(cond);
4902 check_reachable(ifs->true_statement);
4907 if (ifs->false_statement != NULL) {
4908 check_reachable(ifs->false_statement);
4912 next = stmt->base.next;
4916 case STATEMENT_SWITCH: {
4917 switch_statement_t const *const switchs = &stmt->switchs;
4918 expression_t const *const expr = switchs->expression;
4920 if (!expression_returns(expr))
4923 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4924 long const val = fold_constant_to_int(expr);
4925 case_label_statement_t * defaults = NULL;
4926 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4927 if (i->expression == NULL) {
4932 if (i->first_case <= val && val <= i->last_case) {
4933 check_reachable((statement_t*)i);
4938 if (defaults != NULL) {
4939 check_reachable((statement_t*)defaults);
4943 bool has_default = false;
4944 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4945 if (i->expression == NULL)
4948 check_reachable((statement_t*)i);
4955 next = stmt->base.next;
4959 case STATEMENT_EXPRESSION: {
4960 /* Check for noreturn function call */
4961 expression_t const *const expr = stmt->expression.expression;
4962 if (!expression_returns(expr))
4965 next = stmt->base.next;
4969 case STATEMENT_CONTINUE:
4970 for (statement_t *parent = stmt;;) {
4971 parent = parent->base.parent;
4972 if (parent == NULL) /* continue not within loop */
4976 switch (parent->kind) {
4977 case STATEMENT_WHILE: goto continue_while;
4978 case STATEMENT_DO_WHILE: goto continue_do_while;
4979 case STATEMENT_FOR: goto continue_for;
4985 case STATEMENT_BREAK:
4986 for (statement_t *parent = stmt;;) {
4987 parent = parent->base.parent;
4988 if (parent == NULL) /* break not within loop/switch */
4991 switch (parent->kind) {
4992 case STATEMENT_SWITCH:
4993 case STATEMENT_WHILE:
4994 case STATEMENT_DO_WHILE:
4997 next = parent->base.next;
4998 goto found_break_parent;
5006 case STATEMENT_GOTO:
5007 if (stmt->gotos.expression) {
5008 if (!expression_returns(stmt->gotos.expression))
5011 statement_t *parent = stmt->base.parent;
5012 if (parent == NULL) /* top level goto */
5016 next = stmt->gotos.label->statement;
5017 if (next == NULL) /* missing label */
5022 case STATEMENT_LABEL:
5023 next = stmt->label.statement;
5026 case STATEMENT_CASE_LABEL:
5027 next = stmt->case_label.statement;
5030 case STATEMENT_WHILE: {
5031 while_statement_t const *const whiles = &stmt->whiles;
5032 expression_t const *const cond = whiles->condition;
5034 if (!expression_returns(cond))
5037 int const val = determine_truth(cond);
5040 check_reachable(whiles->body);
5045 next = stmt->base.next;
5049 case STATEMENT_DO_WHILE:
5050 next = stmt->do_while.body;
5053 case STATEMENT_FOR: {
5054 for_statement_t *const fors = &stmt->fors;
5056 if (fors->condition_reachable)
5058 fors->condition_reachable = true;
5060 expression_t const *const cond = fors->condition;
5065 } else if (expression_returns(cond)) {
5066 val = determine_truth(cond);
5072 check_reachable(fors->body);
5077 next = stmt->base.next;
5081 case STATEMENT_MS_TRY: {
5082 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5083 check_reachable(ms_try->try_statement);
5084 next = ms_try->final_statement;
5088 case STATEMENT_LEAVE: {
5089 statement_t *parent = stmt;
5091 parent = parent->base.parent;
5092 if (parent == NULL) /* __leave not within __try */
5095 if (parent->kind == STATEMENT_MS_TRY) {
5097 next = parent->ms_try.final_statement;
5105 panic("invalid statement kind");
5108 while (next == NULL) {
5109 next = last->base.parent;
5111 noreturn_candidate = false;
5113 type_t *const type = skip_typeref(current_function->base.type);
5114 assert(is_type_function(type));
5115 type_t *const ret = skip_typeref(type->function.return_type);
5116 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5117 is_type_valid(ret) &&
5118 !is_sym_main(current_function->base.base.symbol)) {
5119 source_position_t const *const pos = &stmt->base.source_position;
5120 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5125 switch (next->kind) {
5126 case STATEMENT_ERROR:
5127 case STATEMENT_EMPTY:
5128 case STATEMENT_DECLARATION:
5129 case STATEMENT_EXPRESSION:
5131 case STATEMENT_RETURN:
5132 case STATEMENT_CONTINUE:
5133 case STATEMENT_BREAK:
5134 case STATEMENT_GOTO:
5135 case STATEMENT_LEAVE:
5136 panic("invalid control flow in function");
5138 case STATEMENT_COMPOUND:
5139 if (next->compound.stmt_expr) {
5145 case STATEMENT_SWITCH:
5146 case STATEMENT_LABEL:
5147 case STATEMENT_CASE_LABEL:
5149 next = next->base.next;
5152 case STATEMENT_WHILE: {
5154 if (next->base.reachable)
5156 next->base.reachable = true;
5158 while_statement_t const *const whiles = &next->whiles;
5159 expression_t const *const cond = whiles->condition;
5161 if (!expression_returns(cond))
5164 int const val = determine_truth(cond);
5167 check_reachable(whiles->body);
5173 next = next->base.next;
5177 case STATEMENT_DO_WHILE: {
5179 if (next->base.reachable)
5181 next->base.reachable = true;
5183 do_while_statement_t const *const dw = &next->do_while;
5184 expression_t const *const cond = dw->condition;
5186 if (!expression_returns(cond))
5189 int const val = determine_truth(cond);
5192 check_reachable(dw->body);
5198 next = next->base.next;
5202 case STATEMENT_FOR: {
5204 for_statement_t *const fors = &next->fors;
5206 fors->step_reachable = true;
5208 if (fors->condition_reachable)
5210 fors->condition_reachable = true;
5212 expression_t const *const cond = fors->condition;
5217 } else if (expression_returns(cond)) {
5218 val = determine_truth(cond);
5224 check_reachable(fors->body);
5230 next = next->base.next;
5234 case STATEMENT_MS_TRY:
5236 next = next->ms_try.final_statement;
5241 check_reachable(next);
5244 static void check_unreachable(statement_t* const stmt, void *const env)
5248 switch (stmt->kind) {
5249 case STATEMENT_DO_WHILE:
5250 if (!stmt->base.reachable) {
5251 expression_t const *const cond = stmt->do_while.condition;
5252 if (determine_truth(cond) >= 0) {
5253 source_position_t const *const pos = &cond->base.source_position;
5254 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5259 case STATEMENT_FOR: {
5260 for_statement_t const* const fors = &stmt->fors;
5262 // if init and step are unreachable, cond is unreachable, too
5263 if (!stmt->base.reachable && !fors->step_reachable) {
5264 goto warn_unreachable;
5266 if (!stmt->base.reachable && fors->initialisation != NULL) {
5267 source_position_t const *const pos = &fors->initialisation->base.source_position;
5268 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5271 if (!fors->condition_reachable && fors->condition != NULL) {
5272 source_position_t const *const pos = &fors->condition->base.source_position;
5273 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5276 if (!fors->step_reachable && fors->step != NULL) {
5277 source_position_t const *const pos = &fors->step->base.source_position;
5278 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5284 case STATEMENT_COMPOUND:
5285 if (stmt->compound.statements != NULL)
5287 goto warn_unreachable;
5289 case STATEMENT_DECLARATION: {
5290 /* Only warn if there is at least one declarator with an initializer.
5291 * This typically occurs in switch statements. */
5292 declaration_statement_t const *const decl = &stmt->declaration;
5293 entity_t const * ent = decl->declarations_begin;
5294 entity_t const *const last = decl->declarations_end;
5296 for (;; ent = ent->base.next) {
5297 if (ent->kind == ENTITY_VARIABLE &&
5298 ent->variable.initializer != NULL) {
5299 goto warn_unreachable;
5309 if (!stmt->base.reachable) {
5310 source_position_t const *const pos = &stmt->base.source_position;
5311 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5317 static bool is_main(entity_t *entity)
5319 static symbol_t *sym_main = NULL;
5320 if (sym_main == NULL) {
5321 sym_main = symbol_table_insert("main");
5324 if (entity->base.symbol != sym_main)
5326 /* must be in outermost scope */
5327 if (entity->base.parent_scope != file_scope)
5333 static void parse_external_declaration(void)
5335 /* function-definitions and declarations both start with declaration
5337 add_anchor_token(';');
5338 declaration_specifiers_t specifiers;
5339 parse_declaration_specifiers(&specifiers);
5340 rem_anchor_token(';');
5342 /* must be a declaration */
5343 if (token.kind == ';') {
5344 parse_anonymous_declaration_rest(&specifiers);
5348 add_anchor_token(',');
5349 add_anchor_token('=');
5350 add_anchor_token(';');
5351 add_anchor_token('{');
5353 /* declarator is common to both function-definitions and declarations */
5354 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5356 rem_anchor_token('{');
5357 rem_anchor_token(';');
5358 rem_anchor_token('=');
5359 rem_anchor_token(',');
5361 /* must be a declaration */
5362 switch (token.kind) {
5366 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5371 /* must be a function definition */
5372 parse_kr_declaration_list(ndeclaration);
5374 if (token.kind != '{') {
5375 parse_error_expected("while parsing function definition", '{', NULL);
5376 eat_until_matching_token(';');
5380 assert(is_declaration(ndeclaration));
5381 type_t *const orig_type = ndeclaration->declaration.type;
5382 type_t * type = skip_typeref(orig_type);
5384 if (!is_type_function(type)) {
5385 if (is_type_valid(type)) {
5386 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5392 source_position_t const *const pos = &ndeclaration->base.source_position;
5393 if (is_typeref(orig_type)) {
5395 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5398 if (is_type_compound(skip_typeref(type->function.return_type))) {
5399 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5401 if (type->function.unspecified_parameters) {
5402 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5404 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5407 /* §6.7.5.3:14 a function definition with () means no
5408 * parameters (and not unspecified parameters) */
5409 if (type->function.unspecified_parameters &&
5410 type->function.parameters == NULL) {
5411 type_t *copy = duplicate_type(type);
5412 copy->function.unspecified_parameters = false;
5413 type = identify_new_type(copy);
5415 ndeclaration->declaration.type = type;
5418 entity_t *const entity = record_entity(ndeclaration, true);
5419 assert(entity->kind == ENTITY_FUNCTION);
5420 assert(ndeclaration->kind == ENTITY_FUNCTION);
5422 function_t *const function = &entity->function;
5423 if (ndeclaration != entity) {
5424 function->parameters = ndeclaration->function.parameters;
5426 assert(is_declaration(entity));
5427 type = skip_typeref(entity->declaration.type);
5429 PUSH_SCOPE(&function->parameters);
5431 entity_t *parameter = function->parameters.entities;
5432 for (; parameter != NULL; parameter = parameter->base.next) {
5433 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5434 parameter->base.parent_scope = current_scope;
5436 assert(parameter->base.parent_scope == NULL
5437 || parameter->base.parent_scope == current_scope);
5438 parameter->base.parent_scope = current_scope;
5439 if (parameter->base.symbol == NULL) {
5440 errorf(¶meter->base.source_position, "parameter name omitted");
5443 environment_push(parameter);
5446 if (function->statement != NULL) {
5447 parser_error_multiple_definition(entity, HERE);
5450 /* parse function body */
5451 int label_stack_top = label_top();
5452 function_t *old_current_function = current_function;
5453 entity_t *old_current_entity = current_entity;
5454 current_function = function;
5455 current_entity = entity;
5459 goto_anchor = &goto_first;
5461 label_anchor = &label_first;
5463 statement_t *const body = parse_compound_statement(false);
5464 function->statement = body;
5467 check_declarations();
5468 if (is_warn_on(WARN_RETURN_TYPE) ||
5469 is_warn_on(WARN_UNREACHABLE_CODE) ||
5470 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5471 noreturn_candidate = true;
5472 check_reachable(body);
5473 if (is_warn_on(WARN_UNREACHABLE_CODE))
5474 walk_statements(body, check_unreachable, NULL);
5475 if (noreturn_candidate &&
5476 !(function->base.modifiers & DM_NORETURN)) {
5477 source_position_t const *const pos = &body->base.source_position;
5478 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5482 if (is_main(entity) && enable_main_collect2_hack)
5483 prepare_main_collect2(entity);
5486 assert(current_function == function);
5487 assert(current_entity == entity);
5488 current_entity = old_current_entity;
5489 current_function = old_current_function;
5490 label_pop_to(label_stack_top);
5496 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5498 entity_t *iter = compound->members.entities;
5499 for (; iter != NULL; iter = iter->base.next) {
5500 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5503 if (iter->base.symbol == symbol) {
5505 } else if (iter->base.symbol == NULL) {
5506 /* search in anonymous structs and unions */
5507 type_t *type = skip_typeref(iter->declaration.type);
5508 if (is_type_compound(type)) {
5509 if (find_compound_entry(type->compound.compound, symbol)
5520 static void check_deprecated(const source_position_t *source_position,
5521 const entity_t *entity)
5523 if (!is_declaration(entity))
5525 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5528 source_position_t const *const epos = &entity->base.source_position;
5529 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5531 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5533 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5538 static expression_t *create_select(const source_position_t *pos,
5540 type_qualifiers_t qualifiers,
5543 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5545 check_deprecated(pos, entry);
5547 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5548 select->select.compound = addr;
5549 select->select.compound_entry = entry;
5551 type_t *entry_type = entry->declaration.type;
5552 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5554 /* bitfields need special treatment */
5555 if (entry->compound_member.bitfield) {
5556 unsigned bit_size = entry->compound_member.bit_size;
5557 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5558 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5559 res_type = type_int;
5563 /* we always do the auto-type conversions; the & and sizeof parser contains
5564 * code to revert this! */
5565 select->base.type = automatic_type_conversion(res_type);
5572 * Find entry with symbol in compound. Search anonymous structs and unions and
5573 * creates implicit select expressions for them.
5574 * Returns the adress for the innermost compound.
5576 static expression_t *find_create_select(const source_position_t *pos,
5578 type_qualifiers_t qualifiers,
5579 compound_t *compound, symbol_t *symbol)
5581 entity_t *iter = compound->members.entities;
5582 for (; iter != NULL; iter = iter->base.next) {
5583 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5586 symbol_t *iter_symbol = iter->base.symbol;
5587 if (iter_symbol == NULL) {
5588 type_t *type = iter->declaration.type;
5589 if (type->kind != TYPE_COMPOUND_STRUCT
5590 && type->kind != TYPE_COMPOUND_UNION)
5593 compound_t *sub_compound = type->compound.compound;
5595 if (find_compound_entry(sub_compound, symbol) == NULL)
5598 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5599 sub_addr->base.source_position = *pos;
5600 sub_addr->base.implicit = true;
5601 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5605 if (iter_symbol == symbol) {
5606 return create_select(pos, addr, qualifiers, iter);
5613 static void parse_bitfield_member(entity_t *entity)
5617 expression_t *size = parse_constant_expression();
5620 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5621 type_t *type = entity->declaration.type;
5622 if (!is_type_integer(skip_typeref(type))) {
5623 errorf(HERE, "bitfield base type '%T' is not an integer type",
5627 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5628 /* error already reported by parse_constant_expression */
5629 size_long = get_type_size(type) * 8;
5631 size_long = fold_constant_to_int(size);
5633 const symbol_t *symbol = entity->base.symbol;
5634 const symbol_t *user_symbol
5635 = symbol == NULL ? sym_anonymous : symbol;
5636 unsigned bit_size = get_type_size(type) * 8;
5637 if (size_long < 0) {
5638 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5639 } else if (size_long == 0 && symbol != NULL) {
5640 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5641 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5642 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5645 /* hope that people don't invent crazy types with more bits
5646 * than our struct can hold */
5648 (1 << sizeof(entity->compound_member.bit_size)*8));
5652 entity->compound_member.bitfield = true;
5653 entity->compound_member.bit_size = (unsigned char)size_long;
5656 static void parse_compound_declarators(compound_t *compound,
5657 const declaration_specifiers_t *specifiers)
5662 if (token.kind == ':') {
5663 /* anonymous bitfield */
5664 type_t *type = specifiers->type;
5665 entity_t *entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER,
5666 NAMESPACE_NORMAL, NULL);
5667 entity->base.source_position = *HERE;
5668 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5669 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5670 entity->declaration.type = type;
5672 parse_bitfield_member(entity);
5674 attribute_t *attributes = parse_attributes(NULL);
5675 attribute_t **anchor = &attributes;
5676 while (*anchor != NULL)
5677 anchor = &(*anchor)->next;
5678 *anchor = specifiers->attributes;
5679 if (attributes != NULL) {
5680 handle_entity_attributes(attributes, entity);
5682 entity->declaration.attributes = attributes;
5684 append_entity(&compound->members, entity);
5686 entity = parse_declarator(specifiers,
5687 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5688 source_position_t const *const pos = &entity->base.source_position;
5689 if (entity->kind == ENTITY_TYPEDEF) {
5690 errorf(pos, "typedef not allowed as compound member");
5692 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5694 /* make sure we don't define a symbol multiple times */
5695 symbol_t *symbol = entity->base.symbol;
5696 if (symbol != NULL) {
5697 entity_t *prev = find_compound_entry(compound, symbol);
5699 source_position_t const *const ppos = &prev->base.source_position;
5700 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5704 if (token.kind == ':') {
5705 parse_bitfield_member(entity);
5707 attribute_t *attributes = parse_attributes(NULL);
5708 handle_entity_attributes(attributes, entity);
5710 type_t *orig_type = entity->declaration.type;
5711 type_t *type = skip_typeref(orig_type);
5712 if (is_type_function(type)) {
5713 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5714 } else if (is_type_incomplete(type)) {
5715 /* §6.7.2.1:16 flexible array member */
5716 if (!is_type_array(type) ||
5717 token.kind != ';' ||
5718 look_ahead(1)->kind != '}') {
5719 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5720 } else if (compound->members.entities == NULL) {
5721 errorf(pos, "flexible array member in otherwise empty struct");
5726 append_entity(&compound->members, entity);
5729 } while (next_if(','));
5730 expect(';', end_error);
5733 anonymous_entity = NULL;
5736 static void parse_compound_type_entries(compound_t *compound)
5739 add_anchor_token('}');
5742 switch (token.kind) {
5744 case T___extension__:
5745 case T_IDENTIFIER: {
5747 declaration_specifiers_t specifiers;
5748 parse_declaration_specifiers(&specifiers);
5749 parse_compound_declarators(compound, &specifiers);
5755 rem_anchor_token('}');
5756 expect('}', end_error);
5759 compound->complete = true;
5765 static type_t *parse_typename(void)
5767 declaration_specifiers_t specifiers;
5768 parse_declaration_specifiers(&specifiers);
5769 if (specifiers.storage_class != STORAGE_CLASS_NONE
5770 || specifiers.thread_local) {
5771 /* TODO: improve error message, user does probably not know what a
5772 * storage class is...
5774 errorf(&specifiers.source_position, "typename must not have a storage class");
5777 type_t *result = parse_abstract_declarator(specifiers.type);
5785 typedef expression_t* (*parse_expression_function)(void);
5786 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5788 typedef struct expression_parser_function_t expression_parser_function_t;
5789 struct expression_parser_function_t {
5790 parse_expression_function parser;
5791 precedence_t infix_precedence;
5792 parse_expression_infix_function infix_parser;
5795 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5798 * Prints an error message if an expression was expected but not read
5800 static expression_t *expected_expression_error(void)
5802 /* skip the error message if the error token was read */
5803 if (token.kind != T_ERROR) {
5804 errorf(HERE, "expected expression, got token %K", &token);
5808 return create_error_expression();
5811 static type_t *get_string_type(void)
5813 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5816 static type_t *get_wide_string_type(void)
5818 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5822 * Parse a string constant.
5824 static expression_t *parse_string_literal(void)
5826 source_position_t begin = token.base.source_position;
5827 string_t res = token.string.string;
5828 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5831 while (token.kind == T_STRING_LITERAL
5832 || token.kind == T_WIDE_STRING_LITERAL) {
5833 warn_string_concat(&token.base.source_position);
5834 res = concat_strings(&res, &token.string.string);
5836 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5839 expression_t *literal;
5841 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5842 literal->base.type = get_wide_string_type();
5844 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5845 literal->base.type = get_string_type();
5847 literal->base.source_position = begin;
5848 literal->literal.value = res;
5854 * Parse a boolean constant.
5856 static expression_t *parse_boolean_literal(bool value)
5858 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5859 literal->base.type = type_bool;
5860 literal->literal.value.begin = value ? "true" : "false";
5861 literal->literal.value.size = value ? 4 : 5;
5867 static void warn_traditional_suffix(void)
5869 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5870 &token.number.suffix);
5873 static void check_integer_suffix(void)
5875 const string_t *suffix = &token.number.suffix;
5876 if (suffix->size == 0)
5879 bool not_traditional = false;
5880 const char *c = suffix->begin;
5881 if (*c == 'l' || *c == 'L') {
5884 not_traditional = true;
5886 if (*c == 'u' || *c == 'U') {
5889 } else if (*c == 'u' || *c == 'U') {
5890 not_traditional = true;
5893 } else if (*c == 'u' || *c == 'U') {
5894 not_traditional = true;
5896 if (*c == 'l' || *c == 'L') {
5904 errorf(&token.base.source_position,
5905 "invalid suffix '%S' on integer constant", suffix);
5906 } else if (not_traditional) {
5907 warn_traditional_suffix();
5911 static type_t *check_floatingpoint_suffix(void)
5913 const string_t *suffix = &token.number.suffix;
5914 type_t *type = type_double;
5915 if (suffix->size == 0)
5918 bool not_traditional = false;
5919 const char *c = suffix->begin;
5920 if (*c == 'f' || *c == 'F') {
5923 } else if (*c == 'l' || *c == 'L') {
5925 type = type_long_double;
5928 errorf(&token.base.source_position,
5929 "invalid suffix '%S' on floatingpoint constant", suffix);
5930 } else if (not_traditional) {
5931 warn_traditional_suffix();
5938 * Parse an integer constant.
5940 static expression_t *parse_number_literal(void)
5942 expression_kind_t kind;
5945 switch (token.kind) {
5947 kind = EXPR_LITERAL_INTEGER;
5948 check_integer_suffix();
5951 case T_INTEGER_OCTAL:
5952 kind = EXPR_LITERAL_INTEGER_OCTAL;
5953 check_integer_suffix();
5956 case T_INTEGER_HEXADECIMAL:
5957 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5958 check_integer_suffix();
5961 case T_FLOATINGPOINT:
5962 kind = EXPR_LITERAL_FLOATINGPOINT;
5963 type = check_floatingpoint_suffix();
5965 case T_FLOATINGPOINT_HEXADECIMAL:
5966 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5967 type = check_floatingpoint_suffix();
5970 panic("unexpected token type in parse_number_literal");
5973 expression_t *literal = allocate_expression_zero(kind);
5974 literal->base.type = type;
5975 literal->literal.value = token.number.number;
5976 literal->literal.suffix = token.number.suffix;
5979 /* integer type depends on the size of the number and the size
5980 * representable by the types. The backend/codegeneration has to determine
5983 determine_literal_type(&literal->literal);
5988 * Parse a character constant.
5990 static expression_t *parse_character_constant(void)
5992 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5993 literal->base.type = c_mode & _CXX ? type_char : type_int;
5994 literal->literal.value = token.string.string;
5996 size_t len = literal->literal.value.size;
5998 if (!GNU_MODE && !(c_mode & _C99)) {
5999 errorf(HERE, "more than 1 character in character constant");
6001 literal->base.type = type_int;
6002 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6011 * Parse a wide character constant.
6013 static expression_t *parse_wide_character_constant(void)
6015 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6016 literal->base.type = type_int;
6017 literal->literal.value = token.string.string;
6019 size_t len = wstrlen(&literal->literal.value);
6021 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6028 static entity_t *create_implicit_function(symbol_t *symbol,
6029 const source_position_t *source_position)
6031 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6032 ntype->function.return_type = type_int;
6033 ntype->function.unspecified_parameters = true;
6034 ntype->function.linkage = LINKAGE_C;
6035 type_t *type = identify_new_type(ntype);
6037 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6038 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6039 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6040 entity->declaration.type = type;
6041 entity->declaration.implicit = true;
6042 entity->base.source_position = *source_position;
6044 if (current_scope != NULL)
6045 record_entity(entity, false);
6051 * Performs automatic type cast as described in §6.3.2.1.
6053 * @param orig_type the original type
6055 static type_t *automatic_type_conversion(type_t *orig_type)
6057 type_t *type = skip_typeref(orig_type);
6058 if (is_type_array(type)) {
6059 array_type_t *array_type = &type->array;
6060 type_t *element_type = array_type->element_type;
6061 unsigned qualifiers = array_type->base.qualifiers;
6063 return make_pointer_type(element_type, qualifiers);
6066 if (is_type_function(type)) {
6067 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6074 * reverts the automatic casts of array to pointer types and function
6075 * to function-pointer types as defined §6.3.2.1
6077 type_t *revert_automatic_type_conversion(const expression_t *expression)
6079 switch (expression->kind) {
6080 case EXPR_REFERENCE: {
6081 entity_t *entity = expression->reference.entity;
6082 if (is_declaration(entity)) {
6083 return entity->declaration.type;
6084 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6085 return entity->enum_value.enum_type;
6087 panic("no declaration or enum in reference");
6092 entity_t *entity = expression->select.compound_entry;
6093 assert(is_declaration(entity));
6094 type_t *type = entity->declaration.type;
6095 return get_qualified_type(type, expression->base.type->base.qualifiers);
6098 case EXPR_UNARY_DEREFERENCE: {
6099 const expression_t *const value = expression->unary.value;
6100 type_t *const type = skip_typeref(value->base.type);
6101 if (!is_type_pointer(type))
6102 return type_error_type;
6103 return type->pointer.points_to;
6106 case EXPR_ARRAY_ACCESS: {
6107 const expression_t *array_ref = expression->array_access.array_ref;
6108 type_t *type_left = skip_typeref(array_ref->base.type);
6109 if (!is_type_pointer(type_left))
6110 return type_error_type;
6111 return type_left->pointer.points_to;
6114 case EXPR_STRING_LITERAL: {
6115 size_t size = expression->string_literal.value.size;
6116 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6119 case EXPR_WIDE_STRING_LITERAL: {
6120 size_t size = wstrlen(&expression->string_literal.value);
6121 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6124 case EXPR_COMPOUND_LITERAL:
6125 return expression->compound_literal.type;
6130 return expression->base.type;
6134 * Find an entity matching a symbol in a scope.
6135 * Uses current scope if scope is NULL
6137 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6138 namespace_tag_t namespc)
6140 if (scope == NULL) {
6141 return get_entity(symbol, namespc);
6144 /* we should optimize here, if scope grows above a certain size we should
6145 construct a hashmap here... */
6146 entity_t *entity = scope->entities;
6147 for ( ; entity != NULL; entity = entity->base.next) {
6148 if (entity->base.symbol == symbol
6149 && (namespace_tag_t)entity->base.namespc == namespc)
6156 static entity_t *parse_qualified_identifier(void)
6158 /* namespace containing the symbol */
6160 source_position_t pos;
6161 const scope_t *lookup_scope = NULL;
6163 if (next_if(T_COLONCOLON))
6164 lookup_scope = &unit->scope;
6168 if (token.kind != T_IDENTIFIER) {
6169 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6170 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6172 symbol = token.identifier.symbol;
6177 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6179 if (!next_if(T_COLONCOLON))
6182 switch (entity->kind) {
6183 case ENTITY_NAMESPACE:
6184 lookup_scope = &entity->namespacee.members;
6189 lookup_scope = &entity->compound.members;
6192 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6193 symbol, get_entity_kind_name(entity->kind));
6195 /* skip further qualifications */
6196 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6198 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6202 if (entity == NULL) {
6203 if (!strict_mode && token.kind == '(') {
6204 /* an implicitly declared function */
6205 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6206 "implicit declaration of function '%Y'", symbol);
6207 entity = create_implicit_function(symbol, &pos);
6209 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6210 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6217 static expression_t *parse_reference(void)
6219 source_position_t const pos = token.base.source_position;
6220 entity_t *const entity = parse_qualified_identifier();
6223 if (is_declaration(entity)) {
6224 orig_type = entity->declaration.type;
6225 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6226 orig_type = entity->enum_value.enum_type;
6228 panic("expected declaration or enum value in reference");
6231 /* we always do the auto-type conversions; the & and sizeof parser contains
6232 * code to revert this! */
6233 type_t *type = automatic_type_conversion(orig_type);
6235 expression_kind_t kind = EXPR_REFERENCE;
6236 if (entity->kind == ENTITY_ENUM_VALUE)
6237 kind = EXPR_REFERENCE_ENUM_VALUE;
6239 expression_t *expression = allocate_expression_zero(kind);
6240 expression->base.source_position = pos;
6241 expression->base.type = type;
6242 expression->reference.entity = entity;
6244 /* this declaration is used */
6245 if (is_declaration(entity)) {
6246 entity->declaration.used = true;
6249 if (entity->base.parent_scope != file_scope
6250 && (current_function != NULL
6251 && entity->base.parent_scope->depth < current_function->parameters.depth)
6252 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6253 if (entity->kind == ENTITY_VARIABLE) {
6254 /* access of a variable from an outer function */
6255 entity->variable.address_taken = true;
6256 } else if (entity->kind == ENTITY_PARAMETER) {
6257 entity->parameter.address_taken = true;
6259 current_function->need_closure = true;
6262 check_deprecated(&pos, entity);
6267 static bool semantic_cast(expression_t *cast)
6269 expression_t *expression = cast->unary.value;
6270 type_t *orig_dest_type = cast->base.type;
6271 type_t *orig_type_right = expression->base.type;
6272 type_t const *dst_type = skip_typeref(orig_dest_type);
6273 type_t const *src_type = skip_typeref(orig_type_right);
6274 source_position_t const *pos = &cast->base.source_position;
6276 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6277 if (dst_type == type_void)
6280 /* only integer and pointer can be casted to pointer */
6281 if (is_type_pointer(dst_type) &&
6282 !is_type_pointer(src_type) &&
6283 !is_type_integer(src_type) &&
6284 is_type_valid(src_type)) {
6285 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6289 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6290 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6294 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6295 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6299 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6300 type_t *src = skip_typeref(src_type->pointer.points_to);
6301 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6302 unsigned missing_qualifiers =
6303 src->base.qualifiers & ~dst->base.qualifiers;
6304 if (missing_qualifiers != 0) {
6305 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6311 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6313 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6314 expression->base.source_position = *pos;
6316 parse_initializer_env_t env;
6319 env.must_be_constant = false;
6320 initializer_t *initializer = parse_initializer(&env);
6323 expression->compound_literal.initializer = initializer;
6324 expression->compound_literal.type = type;
6325 expression->base.type = automatic_type_conversion(type);
6331 * Parse a cast expression.
6333 static expression_t *parse_cast(void)
6335 source_position_t const pos = *HERE;
6338 add_anchor_token(')');
6340 type_t *type = parse_typename();
6342 rem_anchor_token(')');
6343 expect(')', end_error);
6345 if (token.kind == '{') {
6346 return parse_compound_literal(&pos, type);
6349 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6350 cast->base.source_position = pos;
6352 expression_t *value = parse_subexpression(PREC_CAST);
6353 cast->base.type = type;
6354 cast->unary.value = value;
6356 if (! semantic_cast(cast)) {
6357 /* TODO: record the error in the AST. else it is impossible to detect it */
6362 return create_error_expression();
6366 * Parse a statement expression.
6368 static expression_t *parse_statement_expression(void)
6370 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6373 add_anchor_token(')');
6375 statement_t *statement = parse_compound_statement(true);
6376 statement->compound.stmt_expr = true;
6377 expression->statement.statement = statement;
6379 /* find last statement and use its type */
6380 type_t *type = type_void;
6381 const statement_t *stmt = statement->compound.statements;
6383 while (stmt->base.next != NULL)
6384 stmt = stmt->base.next;
6386 if (stmt->kind == STATEMENT_EXPRESSION) {
6387 type = stmt->expression.expression->base.type;
6390 source_position_t const *const pos = &expression->base.source_position;
6391 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6393 expression->base.type = type;
6395 rem_anchor_token(')');
6396 expect(')', end_error);
6403 * Parse a parenthesized expression.
6405 static expression_t *parse_parenthesized_expression(void)
6407 token_t const* const la1 = look_ahead(1);
6408 switch (la1->kind) {
6410 /* gcc extension: a statement expression */
6411 return parse_statement_expression();
6414 if (is_typedef_symbol(la1->identifier.symbol)) {
6416 return parse_cast();
6421 add_anchor_token(')');
6422 expression_t *result = parse_expression();
6423 result->base.parenthesized = true;
6424 rem_anchor_token(')');
6425 expect(')', end_error);
6431 static expression_t *parse_function_keyword(void)
6435 if (current_function == NULL) {
6436 errorf(HERE, "'__func__' used outside of a function");
6439 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6440 expression->base.type = type_char_ptr;
6441 expression->funcname.kind = FUNCNAME_FUNCTION;
6448 static expression_t *parse_pretty_function_keyword(void)
6450 if (current_function == NULL) {
6451 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6454 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6455 expression->base.type = type_char_ptr;
6456 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6458 eat(T___PRETTY_FUNCTION__);
6463 static expression_t *parse_funcsig_keyword(void)
6465 if (current_function == NULL) {
6466 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6469 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6470 expression->base.type = type_char_ptr;
6471 expression->funcname.kind = FUNCNAME_FUNCSIG;
6478 static expression_t *parse_funcdname_keyword(void)
6480 if (current_function == NULL) {
6481 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6484 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6485 expression->base.type = type_char_ptr;
6486 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6488 eat(T___FUNCDNAME__);
6493 static designator_t *parse_designator(void)
6495 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6496 result->source_position = *HERE;
6498 if (token.kind != T_IDENTIFIER) {
6499 parse_error_expected("while parsing member designator",
6500 T_IDENTIFIER, NULL);
6503 result->symbol = token.identifier.symbol;
6506 designator_t *last_designator = result;
6509 if (token.kind != T_IDENTIFIER) {
6510 parse_error_expected("while parsing member designator",
6511 T_IDENTIFIER, NULL);
6514 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6515 designator->source_position = *HERE;
6516 designator->symbol = token.identifier.symbol;
6519 last_designator->next = designator;
6520 last_designator = designator;
6524 add_anchor_token(']');
6525 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6526 designator->source_position = *HERE;
6527 designator->array_index = parse_expression();
6528 rem_anchor_token(']');
6529 expect(']', end_error);
6530 if (designator->array_index == NULL) {
6534 last_designator->next = designator;
6535 last_designator = designator;
6547 * Parse the __builtin_offsetof() expression.
6549 static expression_t *parse_offsetof(void)
6551 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6552 expression->base.type = type_size_t;
6554 eat(T___builtin_offsetof);
6556 expect('(', end_error);
6557 add_anchor_token(',');
6558 type_t *type = parse_typename();
6559 rem_anchor_token(',');
6560 expect(',', end_error);
6561 add_anchor_token(')');
6562 designator_t *designator = parse_designator();
6563 rem_anchor_token(')');
6564 expect(')', end_error);
6566 expression->offsetofe.type = type;
6567 expression->offsetofe.designator = designator;
6570 memset(&path, 0, sizeof(path));
6571 path.top_type = type;
6572 path.path = NEW_ARR_F(type_path_entry_t, 0);
6574 descend_into_subtype(&path);
6576 if (!walk_designator(&path, designator, true)) {
6577 return create_error_expression();
6580 DEL_ARR_F(path.path);
6584 return create_error_expression();
6588 * Parses a _builtin_va_start() expression.
6590 static expression_t *parse_va_start(void)
6592 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6594 eat(T___builtin_va_start);
6596 expect('(', end_error);
6597 add_anchor_token(',');
6598 expression->va_starte.ap = parse_assignment_expression();
6599 rem_anchor_token(',');
6600 expect(',', end_error);
6601 expression_t *const expr = parse_assignment_expression();
6602 if (expr->kind == EXPR_REFERENCE) {
6603 entity_t *const entity = expr->reference.entity;
6604 if (!current_function->base.type->function.variadic) {
6605 errorf(&expr->base.source_position,
6606 "'va_start' used in non-variadic function");
6607 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6608 entity->base.next != NULL ||
6609 entity->kind != ENTITY_PARAMETER) {
6610 errorf(&expr->base.source_position,
6611 "second argument of 'va_start' must be last parameter of the current function");
6613 expression->va_starte.parameter = &entity->variable;
6615 expect(')', end_error);
6618 expect(')', end_error);
6620 return create_error_expression();
6624 * Parses a __builtin_va_arg() expression.
6626 static expression_t *parse_va_arg(void)
6628 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6630 eat(T___builtin_va_arg);
6632 expect('(', end_error);
6634 ap.expression = parse_assignment_expression();
6635 expression->va_arge.ap = ap.expression;
6636 check_call_argument(type_valist, &ap, 1);
6638 expect(',', end_error);
6639 expression->base.type = parse_typename();
6640 expect(')', end_error);
6644 return create_error_expression();
6648 * Parses a __builtin_va_copy() expression.
6650 static expression_t *parse_va_copy(void)
6652 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6654 eat(T___builtin_va_copy);
6656 expect('(', end_error);
6657 expression_t *dst = parse_assignment_expression();
6658 assign_error_t error = semantic_assign(type_valist, dst);
6659 report_assign_error(error, type_valist, dst, "call argument 1",
6660 &dst->base.source_position);
6661 expression->va_copye.dst = dst;
6663 expect(',', end_error);
6665 call_argument_t src;
6666 src.expression = parse_assignment_expression();
6667 check_call_argument(type_valist, &src, 2);
6668 expression->va_copye.src = src.expression;
6669 expect(')', end_error);
6673 return create_error_expression();
6677 * Parses a __builtin_constant_p() expression.
6679 static expression_t *parse_builtin_constant(void)
6681 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6683 eat(T___builtin_constant_p);
6685 expect('(', end_error);
6686 add_anchor_token(')');
6687 expression->builtin_constant.value = parse_assignment_expression();
6688 rem_anchor_token(')');
6689 expect(')', end_error);
6690 expression->base.type = type_int;
6694 return create_error_expression();
6698 * Parses a __builtin_types_compatible_p() expression.
6700 static expression_t *parse_builtin_types_compatible(void)
6702 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6704 eat(T___builtin_types_compatible_p);
6706 expect('(', end_error);
6707 add_anchor_token(')');
6708 add_anchor_token(',');
6709 expression->builtin_types_compatible.left = parse_typename();
6710 rem_anchor_token(',');
6711 expect(',', end_error);
6712 expression->builtin_types_compatible.right = parse_typename();
6713 rem_anchor_token(')');
6714 expect(')', end_error);
6715 expression->base.type = type_int;
6719 return create_error_expression();
6723 * Parses a __builtin_is_*() compare expression.
6725 static expression_t *parse_compare_builtin(void)
6727 expression_t *expression;
6729 switch (token.kind) {
6730 case T___builtin_isgreater:
6731 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6733 case T___builtin_isgreaterequal:
6734 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6736 case T___builtin_isless:
6737 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6739 case T___builtin_islessequal:
6740 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6742 case T___builtin_islessgreater:
6743 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6745 case T___builtin_isunordered:
6746 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6749 internal_errorf(HERE, "invalid compare builtin found");
6751 expression->base.source_position = *HERE;
6754 expect('(', end_error);
6755 expression->binary.left = parse_assignment_expression();
6756 expect(',', end_error);
6757 expression->binary.right = parse_assignment_expression();
6758 expect(')', end_error);
6760 type_t *const orig_type_left = expression->binary.left->base.type;
6761 type_t *const orig_type_right = expression->binary.right->base.type;
6763 type_t *const type_left = skip_typeref(orig_type_left);
6764 type_t *const type_right = skip_typeref(orig_type_right);
6765 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6766 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6767 type_error_incompatible("invalid operands in comparison",
6768 &expression->base.source_position, orig_type_left, orig_type_right);
6771 semantic_comparison(&expression->binary);
6776 return create_error_expression();
6780 * Parses a MS assume() expression.
6782 static expression_t *parse_assume(void)
6784 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6788 expect('(', end_error);
6789 add_anchor_token(')');
6790 expression->unary.value = parse_assignment_expression();
6791 rem_anchor_token(')');
6792 expect(')', end_error);
6794 expression->base.type = type_void;
6797 return create_error_expression();
6801 * Return the label for the current symbol or create a new one.
6803 static label_t *get_label(void)
6805 assert(token.kind == T_IDENTIFIER);
6806 assert(current_function != NULL);
6808 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6809 /* If we find a local label, we already created the declaration. */
6810 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6811 if (label->base.parent_scope != current_scope) {
6812 assert(label->base.parent_scope->depth < current_scope->depth);
6813 current_function->goto_to_outer = true;
6815 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6816 /* There is no matching label in the same function, so create a new one. */
6817 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol);
6822 return &label->label;
6826 * Parses a GNU && label address expression.
6828 static expression_t *parse_label_address(void)
6830 source_position_t source_position = token.base.source_position;
6832 if (token.kind != T_IDENTIFIER) {
6833 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6834 return create_error_expression();
6837 label_t *const label = get_label();
6839 label->address_taken = true;
6841 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6842 expression->base.source_position = source_position;
6844 /* label address is treated as a void pointer */
6845 expression->base.type = type_void_ptr;
6846 expression->label_address.label = label;
6851 * Parse a microsoft __noop expression.
6853 static expression_t *parse_noop_expression(void)
6855 /* the result is a (int)0 */
6856 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6857 literal->base.type = type_int;
6858 literal->literal.value.begin = "__noop";
6859 literal->literal.value.size = 6;
6863 if (token.kind == '(') {
6864 /* parse arguments */
6866 add_anchor_token(')');
6867 add_anchor_token(',');
6869 if (token.kind != ')') do {
6870 (void)parse_assignment_expression();
6871 } while (next_if(','));
6873 rem_anchor_token(',');
6874 rem_anchor_token(')');
6875 expect(')', end_error);
6882 * Parses a primary expression.
6884 static expression_t *parse_primary_expression(void)
6886 switch (token.kind) {
6887 case T_false: return parse_boolean_literal(false);
6888 case T_true: return parse_boolean_literal(true);
6890 case T_INTEGER_OCTAL:
6891 case T_INTEGER_HEXADECIMAL:
6892 case T_FLOATINGPOINT:
6893 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6894 case T_CHARACTER_CONSTANT: return parse_character_constant();
6895 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6896 case T_STRING_LITERAL:
6897 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6898 case T___FUNCTION__:
6899 case T___func__: return parse_function_keyword();
6900 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6901 case T___FUNCSIG__: return parse_funcsig_keyword();
6902 case T___FUNCDNAME__: return parse_funcdname_keyword();
6903 case T___builtin_offsetof: return parse_offsetof();
6904 case T___builtin_va_start: return parse_va_start();
6905 case T___builtin_va_arg: return parse_va_arg();
6906 case T___builtin_va_copy: return parse_va_copy();
6907 case T___builtin_isgreater:
6908 case T___builtin_isgreaterequal:
6909 case T___builtin_isless:
6910 case T___builtin_islessequal:
6911 case T___builtin_islessgreater:
6912 case T___builtin_isunordered: return parse_compare_builtin();
6913 case T___builtin_constant_p: return parse_builtin_constant();
6914 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6915 case T__assume: return parse_assume();
6918 return parse_label_address();
6921 case '(': return parse_parenthesized_expression();
6922 case T___noop: return parse_noop_expression();
6924 /* Gracefully handle type names while parsing expressions. */
6926 return parse_reference();
6928 if (!is_typedef_symbol(token.identifier.symbol)) {
6929 return parse_reference();
6933 source_position_t const pos = *HERE;
6934 declaration_specifiers_t specifiers;
6935 parse_declaration_specifiers(&specifiers);
6936 type_t const *const type = parse_abstract_declarator(specifiers.type);
6937 errorf(&pos, "encountered type '%T' while parsing expression", type);
6938 return create_error_expression();
6942 errorf(HERE, "unexpected token %K, expected an expression", &token);
6944 return create_error_expression();
6947 static expression_t *parse_array_expression(expression_t *left)
6949 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6950 array_access_expression_t *const arr = &expr->array_access;
6953 add_anchor_token(']');
6955 expression_t *const inside = parse_expression();
6957 type_t *const orig_type_left = left->base.type;
6958 type_t *const orig_type_inside = inside->base.type;
6960 type_t *const type_left = skip_typeref(orig_type_left);
6961 type_t *const type_inside = skip_typeref(orig_type_inside);
6967 if (is_type_pointer(type_left)) {
6970 idx_type = type_inside;
6971 res_type = type_left->pointer.points_to;
6973 } else if (is_type_pointer(type_inside)) {
6974 arr->flipped = true;
6977 idx_type = type_left;
6978 res_type = type_inside->pointer.points_to;
6980 res_type = automatic_type_conversion(res_type);
6981 if (!is_type_integer(idx_type)) {
6982 errorf(&idx->base.source_position, "array subscript must have integer type");
6983 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6984 source_position_t const *const pos = &idx->base.source_position;
6985 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6988 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6989 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6991 res_type = type_error_type;
6996 arr->array_ref = ref;
6998 arr->base.type = res_type;
7000 rem_anchor_token(']');
7001 expect(']', end_error);
7006 static bool is_bitfield(const expression_t *expression)
7008 return expression->kind == EXPR_SELECT
7009 && expression->select.compound_entry->compound_member.bitfield;
7012 static expression_t *parse_typeprop(expression_kind_t const kind)
7014 expression_t *tp_expression = allocate_expression_zero(kind);
7015 tp_expression->base.type = type_size_t;
7017 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7020 expression_t *expression;
7021 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
7022 source_position_t const pos = *HERE;
7024 add_anchor_token(')');
7025 orig_type = parse_typename();
7026 rem_anchor_token(')');
7027 expect(')', end_error);
7029 if (token.kind == '{') {
7030 /* It was not sizeof(type) after all. It is sizeof of an expression
7031 * starting with a compound literal */
7032 expression = parse_compound_literal(&pos, orig_type);
7033 goto typeprop_expression;
7036 expression = parse_subexpression(PREC_UNARY);
7038 typeprop_expression:
7039 if (is_bitfield(expression)) {
7040 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7041 errorf(&tp_expression->base.source_position,
7042 "operand of %s expression must not be a bitfield", what);
7045 tp_expression->typeprop.tp_expression = expression;
7047 orig_type = revert_automatic_type_conversion(expression);
7048 expression->base.type = orig_type;
7051 tp_expression->typeprop.type = orig_type;
7052 type_t const* const type = skip_typeref(orig_type);
7053 char const* wrong_type = NULL;
7054 if (is_type_incomplete(type)) {
7055 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7056 wrong_type = "incomplete";
7057 } else if (type->kind == TYPE_FUNCTION) {
7059 /* function types are allowed (and return 1) */
7060 source_position_t const *const pos = &tp_expression->base.source_position;
7061 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7062 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7064 wrong_type = "function";
7068 if (wrong_type != NULL) {
7069 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7070 errorf(&tp_expression->base.source_position,
7071 "operand of %s expression must not be of %s type '%T'",
7072 what, wrong_type, orig_type);
7076 return tp_expression;
7079 static expression_t *parse_sizeof(void)
7081 return parse_typeprop(EXPR_SIZEOF);
7084 static expression_t *parse_alignof(void)
7086 return parse_typeprop(EXPR_ALIGNOF);
7089 static expression_t *parse_select_expression(expression_t *addr)
7091 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7092 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7093 source_position_t const pos = *HERE;
7096 if (token.kind != T_IDENTIFIER) {
7097 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7098 return create_error_expression();
7100 symbol_t *symbol = token.identifier.symbol;
7103 type_t *const orig_type = addr->base.type;
7104 type_t *const type = skip_typeref(orig_type);
7107 bool saw_error = false;
7108 if (is_type_pointer(type)) {
7109 if (!select_left_arrow) {
7111 "request for member '%Y' in something not a struct or union, but '%T'",
7115 type_left = skip_typeref(type->pointer.points_to);
7117 if (select_left_arrow && is_type_valid(type)) {
7118 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7124 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7125 type_left->kind != TYPE_COMPOUND_UNION) {
7127 if (is_type_valid(type_left) && !saw_error) {
7129 "request for member '%Y' in something not a struct or union, but '%T'",
7132 return create_error_expression();
7135 compound_t *compound = type_left->compound.compound;
7136 if (!compound->complete) {
7137 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7139 return create_error_expression();
7142 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7143 expression_t *result =
7144 find_create_select(&pos, addr, qualifiers, compound, symbol);
7146 if (result == NULL) {
7147 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7148 return create_error_expression();
7154 static void check_call_argument(type_t *expected_type,
7155 call_argument_t *argument, unsigned pos)
7157 type_t *expected_type_skip = skip_typeref(expected_type);
7158 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7159 expression_t *arg_expr = argument->expression;
7160 type_t *arg_type = skip_typeref(arg_expr->base.type);
7162 /* handle transparent union gnu extension */
7163 if (is_type_union(expected_type_skip)
7164 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7165 compound_t *union_decl = expected_type_skip->compound.compound;
7166 type_t *best_type = NULL;
7167 entity_t *entry = union_decl->members.entities;
7168 for ( ; entry != NULL; entry = entry->base.next) {
7169 assert(is_declaration(entry));
7170 type_t *decl_type = entry->declaration.type;
7171 error = semantic_assign(decl_type, arg_expr);
7172 if (error == ASSIGN_ERROR_INCOMPATIBLE
7173 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7176 if (error == ASSIGN_SUCCESS) {
7177 best_type = decl_type;
7178 } else if (best_type == NULL) {
7179 best_type = decl_type;
7183 if (best_type != NULL) {
7184 expected_type = best_type;
7188 error = semantic_assign(expected_type, arg_expr);
7189 argument->expression = create_implicit_cast(arg_expr, expected_type);
7191 if (error != ASSIGN_SUCCESS) {
7192 /* report exact scope in error messages (like "in argument 3") */
7194 snprintf(buf, sizeof(buf), "call argument %u", pos);
7195 report_assign_error(error, expected_type, arg_expr, buf,
7196 &arg_expr->base.source_position);
7198 type_t *const promoted_type = get_default_promoted_type(arg_type);
7199 if (!types_compatible(expected_type_skip, promoted_type) &&
7200 !types_compatible(expected_type_skip, type_void_ptr) &&
7201 !types_compatible(type_void_ptr, promoted_type)) {
7202 /* Deliberately show the skipped types in this warning */
7203 source_position_t const *const apos = &arg_expr->base.source_position;
7204 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7210 * Handle the semantic restrictions of builtin calls
7212 static void handle_builtin_argument_restrictions(call_expression_t *call)
7214 entity_t *entity = call->function->reference.entity;
7215 switch (entity->function.btk) {
7217 switch (entity->function.b.firm_builtin_kind) {
7218 case ir_bk_return_address:
7219 case ir_bk_frame_address: {
7220 /* argument must be constant */
7221 call_argument_t *argument = call->arguments;
7223 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7224 errorf(&call->base.source_position,
7225 "argument of '%Y' must be a constant expression",
7226 call->function->reference.entity->base.symbol);
7230 case ir_bk_prefetch:
7231 /* second and third argument must be constant if existent */
7232 if (call->arguments == NULL)
7234 call_argument_t *rw = call->arguments->next;
7235 call_argument_t *locality = NULL;
7238 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7239 errorf(&call->base.source_position,
7240 "second argument of '%Y' must be a constant expression",
7241 call->function->reference.entity->base.symbol);
7243 locality = rw->next;
7245 if (locality != NULL) {
7246 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7247 errorf(&call->base.source_position,
7248 "third argument of '%Y' must be a constant expression",
7249 call->function->reference.entity->base.symbol);
7251 locality = rw->next;
7258 case BUILTIN_OBJECT_SIZE:
7259 if (call->arguments == NULL)
7262 call_argument_t *arg = call->arguments->next;
7263 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7264 errorf(&call->base.source_position,
7265 "second argument of '%Y' must be a constant expression",
7266 call->function->reference.entity->base.symbol);
7275 * Parse a call expression, ie. expression '( ... )'.
7277 * @param expression the function address
7279 static expression_t *parse_call_expression(expression_t *expression)
7281 expression_t *result = allocate_expression_zero(EXPR_CALL);
7282 call_expression_t *call = &result->call;
7283 call->function = expression;
7285 type_t *const orig_type = expression->base.type;
7286 type_t *const type = skip_typeref(orig_type);
7288 function_type_t *function_type = NULL;
7289 if (is_type_pointer(type)) {
7290 type_t *const to_type = skip_typeref(type->pointer.points_to);
7292 if (is_type_function(to_type)) {
7293 function_type = &to_type->function;
7294 call->base.type = function_type->return_type;
7298 if (function_type == NULL && is_type_valid(type)) {
7300 "called object '%E' (type '%T') is not a pointer to a function",
7301 expression, orig_type);
7304 /* parse arguments */
7306 add_anchor_token(')');
7307 add_anchor_token(',');
7309 if (token.kind != ')') {
7310 call_argument_t **anchor = &call->arguments;
7312 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7313 argument->expression = parse_assignment_expression();
7316 anchor = &argument->next;
7317 } while (next_if(','));
7319 rem_anchor_token(',');
7320 rem_anchor_token(')');
7321 expect(')', end_error);
7323 if (function_type == NULL)
7326 /* check type and count of call arguments */
7327 function_parameter_t *parameter = function_type->parameters;
7328 call_argument_t *argument = call->arguments;
7329 if (!function_type->unspecified_parameters) {
7330 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7331 parameter = parameter->next, argument = argument->next) {
7332 check_call_argument(parameter->type, argument, ++pos);
7335 if (parameter != NULL) {
7336 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7337 } else if (argument != NULL && !function_type->variadic) {
7338 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7342 /* do default promotion for other arguments */
7343 for (; argument != NULL; argument = argument->next) {
7344 type_t *argument_type = argument->expression->base.type;
7345 if (!is_type_object(skip_typeref(argument_type))) {
7346 errorf(&argument->expression->base.source_position,
7347 "call argument '%E' must not be void", argument->expression);
7350 argument_type = get_default_promoted_type(argument_type);
7352 argument->expression
7353 = create_implicit_cast(argument->expression, argument_type);
7358 if (is_type_compound(skip_typeref(function_type->return_type))) {
7359 source_position_t const *const pos = &expression->base.source_position;
7360 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7363 if (expression->kind == EXPR_REFERENCE) {
7364 reference_expression_t *reference = &expression->reference;
7365 if (reference->entity->kind == ENTITY_FUNCTION &&
7366 reference->entity->function.btk != BUILTIN_NONE)
7367 handle_builtin_argument_restrictions(call);
7374 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7376 static bool same_compound_type(const type_t *type1, const type_t *type2)
7379 is_type_compound(type1) &&
7380 type1->kind == type2->kind &&
7381 type1->compound.compound == type2->compound.compound;
7384 static expression_t const *get_reference_address(expression_t const *expr)
7386 bool regular_take_address = true;
7388 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7389 expr = expr->unary.value;
7391 regular_take_address = false;
7394 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7397 expr = expr->unary.value;
7400 if (expr->kind != EXPR_REFERENCE)
7403 /* special case for functions which are automatically converted to a
7404 * pointer to function without an extra TAKE_ADDRESS operation */
7405 if (!regular_take_address &&
7406 expr->reference.entity->kind != ENTITY_FUNCTION) {
7413 static void warn_reference_address_as_bool(expression_t const* expr)
7415 expr = get_reference_address(expr);
7417 source_position_t const *const pos = &expr->base.source_position;
7418 entity_t const *const ent = expr->reference.entity;
7419 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7423 static void warn_assignment_in_condition(const expression_t *const expr)
7425 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7427 if (expr->base.parenthesized)
7429 source_position_t const *const pos = &expr->base.source_position;
7430 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7433 static void semantic_condition(expression_t const *const expr,
7434 char const *const context)
7436 type_t *const type = skip_typeref(expr->base.type);
7437 if (is_type_scalar(type)) {
7438 warn_reference_address_as_bool(expr);
7439 warn_assignment_in_condition(expr);
7440 } else if (is_type_valid(type)) {
7441 errorf(&expr->base.source_position,
7442 "%s must have scalar type", context);
7447 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7449 * @param expression the conditional expression
7451 static expression_t *parse_conditional_expression(expression_t *expression)
7453 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7455 conditional_expression_t *conditional = &result->conditional;
7456 conditional->condition = expression;
7459 add_anchor_token(':');
7461 /* §6.5.15:2 The first operand shall have scalar type. */
7462 semantic_condition(expression, "condition of conditional operator");
7464 expression_t *true_expression = expression;
7465 bool gnu_cond = false;
7466 if (GNU_MODE && token.kind == ':') {
7469 true_expression = parse_expression();
7471 rem_anchor_token(':');
7472 expect(':', end_error);
7474 expression_t *false_expression =
7475 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7477 type_t *const orig_true_type = true_expression->base.type;
7478 type_t *const orig_false_type = false_expression->base.type;
7479 type_t *const true_type = skip_typeref(orig_true_type);
7480 type_t *const false_type = skip_typeref(orig_false_type);
7483 source_position_t const *const pos = &conditional->base.source_position;
7484 type_t *result_type;
7485 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7486 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7487 /* ISO/IEC 14882:1998(E) §5.16:2 */
7488 if (true_expression->kind == EXPR_UNARY_THROW) {
7489 result_type = false_type;
7490 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7491 result_type = true_type;
7493 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7494 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7495 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7497 result_type = type_void;
7499 } else if (is_type_arithmetic(true_type)
7500 && is_type_arithmetic(false_type)) {
7501 result_type = semantic_arithmetic(true_type, false_type);
7502 } else if (same_compound_type(true_type, false_type)) {
7503 /* just take 1 of the 2 types */
7504 result_type = true_type;
7505 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7506 type_t *pointer_type;
7508 expression_t *other_expression;
7509 if (is_type_pointer(true_type) &&
7510 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7511 pointer_type = true_type;
7512 other_type = false_type;
7513 other_expression = false_expression;
7515 pointer_type = false_type;
7516 other_type = true_type;
7517 other_expression = true_expression;
7520 if (is_null_pointer_constant(other_expression)) {
7521 result_type = pointer_type;
7522 } else if (is_type_pointer(other_type)) {
7523 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7524 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7527 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7528 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7530 } else if (types_compatible(get_unqualified_type(to1),
7531 get_unqualified_type(to2))) {
7534 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7538 type_t *const type =
7539 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7540 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7541 } else if (is_type_integer(other_type)) {
7542 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7543 result_type = pointer_type;
7545 goto types_incompatible;
7549 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7550 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7552 result_type = type_error_type;
7555 conditional->true_expression
7556 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7557 conditional->false_expression
7558 = create_implicit_cast(false_expression, result_type);
7559 conditional->base.type = result_type;
7564 * Parse an extension expression.
7566 static expression_t *parse_extension(void)
7569 expression_t *expression = parse_subexpression(PREC_UNARY);
7575 * Parse a __builtin_classify_type() expression.
7577 static expression_t *parse_builtin_classify_type(void)
7579 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7580 result->base.type = type_int;
7582 eat(T___builtin_classify_type);
7584 expect('(', end_error);
7585 add_anchor_token(')');
7586 expression_t *expression = parse_expression();
7587 rem_anchor_token(')');
7588 expect(')', end_error);
7589 result->classify_type.type_expression = expression;
7593 return create_error_expression();
7597 * Parse a delete expression
7598 * ISO/IEC 14882:1998(E) §5.3.5
7600 static expression_t *parse_delete(void)
7602 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7603 result->base.type = type_void;
7608 result->kind = EXPR_UNARY_DELETE_ARRAY;
7609 expect(']', end_error);
7613 expression_t *const value = parse_subexpression(PREC_CAST);
7614 result->unary.value = value;
7616 type_t *const type = skip_typeref(value->base.type);
7617 if (!is_type_pointer(type)) {
7618 if (is_type_valid(type)) {
7619 errorf(&value->base.source_position,
7620 "operand of delete must have pointer type");
7622 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7623 source_position_t const *const pos = &value->base.source_position;
7624 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7631 * Parse a throw expression
7632 * ISO/IEC 14882:1998(E) §15:1
7634 static expression_t *parse_throw(void)
7636 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7637 result->base.type = type_void;
7641 expression_t *value = NULL;
7642 switch (token.kind) {
7644 value = parse_assignment_expression();
7645 /* ISO/IEC 14882:1998(E) §15.1:3 */
7646 type_t *const orig_type = value->base.type;
7647 type_t *const type = skip_typeref(orig_type);
7648 if (is_type_incomplete(type)) {
7649 errorf(&value->base.source_position,
7650 "cannot throw object of incomplete type '%T'", orig_type);
7651 } else if (is_type_pointer(type)) {
7652 type_t *const points_to = skip_typeref(type->pointer.points_to);
7653 if (is_type_incomplete(points_to) &&
7654 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7655 errorf(&value->base.source_position,
7656 "cannot throw pointer to incomplete type '%T'", orig_type);
7664 result->unary.value = value;
7669 static bool check_pointer_arithmetic(const source_position_t *source_position,
7670 type_t *pointer_type,
7671 type_t *orig_pointer_type)
7673 type_t *points_to = pointer_type->pointer.points_to;
7674 points_to = skip_typeref(points_to);
7676 if (is_type_incomplete(points_to)) {
7677 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7678 errorf(source_position,
7679 "arithmetic with pointer to incomplete type '%T' not allowed",
7683 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7685 } else if (is_type_function(points_to)) {
7687 errorf(source_position,
7688 "arithmetic with pointer to function type '%T' not allowed",
7692 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7698 static bool is_lvalue(const expression_t *expression)
7700 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7701 switch (expression->kind) {
7702 case EXPR_ARRAY_ACCESS:
7703 case EXPR_COMPOUND_LITERAL:
7704 case EXPR_REFERENCE:
7706 case EXPR_UNARY_DEREFERENCE:
7710 type_t *type = skip_typeref(expression->base.type);
7712 /* ISO/IEC 14882:1998(E) §3.10:3 */
7713 is_type_reference(type) ||
7714 /* Claim it is an lvalue, if the type is invalid. There was a parse
7715 * error before, which maybe prevented properly recognizing it as
7717 !is_type_valid(type);
7722 static void semantic_incdec(unary_expression_t *expression)
7724 type_t *const orig_type = expression->value->base.type;
7725 type_t *const type = skip_typeref(orig_type);
7726 if (is_type_pointer(type)) {
7727 if (!check_pointer_arithmetic(&expression->base.source_position,
7731 } else if (!is_type_real(type) && is_type_valid(type)) {
7732 /* TODO: improve error message */
7733 errorf(&expression->base.source_position,
7734 "operation needs an arithmetic or pointer type");
7737 if (!is_lvalue(expression->value)) {
7738 /* TODO: improve error message */
7739 errorf(&expression->base.source_position, "lvalue required as operand");
7741 expression->base.type = orig_type;
7744 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7746 type_t *const res_type = promote_integer(type);
7747 expr->base.type = res_type;
7748 expr->value = create_implicit_cast(expr->value, res_type);
7751 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7753 type_t *const orig_type = expression->value->base.type;
7754 type_t *const type = skip_typeref(orig_type);
7755 if (!is_type_arithmetic(type)) {
7756 if (is_type_valid(type)) {
7757 /* TODO: improve error message */
7758 errorf(&expression->base.source_position,
7759 "operation needs an arithmetic type");
7762 } else if (is_type_integer(type)) {
7763 promote_unary_int_expr(expression, type);
7765 expression->base.type = orig_type;
7769 static void semantic_unexpr_plus(unary_expression_t *expression)
7771 semantic_unexpr_arithmetic(expression);
7772 source_position_t const *const pos = &expression->base.source_position;
7773 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7776 static void semantic_not(unary_expression_t *expression)
7778 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7779 semantic_condition(expression->value, "operand of !");
7780 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7783 static void semantic_unexpr_integer(unary_expression_t *expression)
7785 type_t *const orig_type = expression->value->base.type;
7786 type_t *const type = skip_typeref(orig_type);
7787 if (!is_type_integer(type)) {
7788 if (is_type_valid(type)) {
7789 errorf(&expression->base.source_position,
7790 "operand of ~ must be of integer type");
7795 promote_unary_int_expr(expression, type);
7798 static void semantic_dereference(unary_expression_t *expression)
7800 type_t *const orig_type = expression->value->base.type;
7801 type_t *const type = skip_typeref(orig_type);
7802 if (!is_type_pointer(type)) {
7803 if (is_type_valid(type)) {
7804 errorf(&expression->base.source_position,
7805 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7810 type_t *result_type = type->pointer.points_to;
7811 result_type = automatic_type_conversion(result_type);
7812 expression->base.type = result_type;
7816 * Record that an address is taken (expression represents an lvalue).
7818 * @param expression the expression
7819 * @param may_be_register if true, the expression might be an register
7821 static void set_address_taken(expression_t *expression, bool may_be_register)
7823 if (expression->kind != EXPR_REFERENCE)
7826 entity_t *const entity = expression->reference.entity;
7828 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7831 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7832 && !may_be_register) {
7833 source_position_t const *const pos = &expression->base.source_position;
7834 errorf(pos, "address of register '%N' requested", entity);
7837 if (entity->kind == ENTITY_VARIABLE) {
7838 entity->variable.address_taken = true;
7840 assert(entity->kind == ENTITY_PARAMETER);
7841 entity->parameter.address_taken = true;
7846 * Check the semantic of the address taken expression.
7848 static void semantic_take_addr(unary_expression_t *expression)
7850 expression_t *value = expression->value;
7851 value->base.type = revert_automatic_type_conversion(value);
7853 type_t *orig_type = value->base.type;
7854 type_t *type = skip_typeref(orig_type);
7855 if (!is_type_valid(type))
7859 if (!is_lvalue(value)) {
7860 errorf(&expression->base.source_position, "'&' requires an lvalue");
7862 if (is_bitfield(value)) {
7863 errorf(&expression->base.source_position,
7864 "'&' not allowed on bitfield");
7867 set_address_taken(value, false);
7869 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7872 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7873 static expression_t *parse_##unexpression_type(void) \
7875 expression_t *unary_expression \
7876 = allocate_expression_zero(unexpression_type); \
7878 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7880 sfunc(&unary_expression->unary); \
7882 return unary_expression; \
7885 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7886 semantic_unexpr_arithmetic)
7887 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7888 semantic_unexpr_plus)
7889 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7891 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7892 semantic_dereference)
7893 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7895 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7896 semantic_unexpr_integer)
7897 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7899 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7902 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7904 static expression_t *parse_##unexpression_type(expression_t *left) \
7906 expression_t *unary_expression \
7907 = allocate_expression_zero(unexpression_type); \
7909 unary_expression->unary.value = left; \
7911 sfunc(&unary_expression->unary); \
7913 return unary_expression; \
7916 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7917 EXPR_UNARY_POSTFIX_INCREMENT,
7919 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7920 EXPR_UNARY_POSTFIX_DECREMENT,
7923 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7925 /* TODO: handle complex + imaginary types */
7927 type_left = get_unqualified_type(type_left);
7928 type_right = get_unqualified_type(type_right);
7930 /* §6.3.1.8 Usual arithmetic conversions */
7931 if (type_left == type_long_double || type_right == type_long_double) {
7932 return type_long_double;
7933 } else if (type_left == type_double || type_right == type_double) {
7935 } else if (type_left == type_float || type_right == type_float) {
7939 type_left = promote_integer(type_left);
7940 type_right = promote_integer(type_right);
7942 if (type_left == type_right)
7945 bool const signed_left = is_type_signed(type_left);
7946 bool const signed_right = is_type_signed(type_right);
7947 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7948 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7950 if (signed_left == signed_right)
7951 return rank_left >= rank_right ? type_left : type_right;
7955 atomic_type_kind_t s_akind;
7956 atomic_type_kind_t u_akind;
7961 u_type = type_right;
7963 s_type = type_right;
7966 s_akind = get_akind(s_type);
7967 u_akind = get_akind(u_type);
7968 s_rank = get_akind_rank(s_akind);
7969 u_rank = get_akind_rank(u_akind);
7971 if (u_rank >= s_rank)
7974 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7978 case ATOMIC_TYPE_INT: return type_unsigned_int;
7979 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7980 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7982 default: panic("invalid atomic type");
7987 * Check the semantic restrictions for a binary expression.
7989 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7991 expression_t *const left = expression->left;
7992 expression_t *const right = expression->right;
7993 type_t *const orig_type_left = left->base.type;
7994 type_t *const orig_type_right = right->base.type;
7995 type_t *const type_left = skip_typeref(orig_type_left);
7996 type_t *const type_right = skip_typeref(orig_type_right);
7998 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7999 /* TODO: improve error message */
8000 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8001 errorf(&expression->base.source_position,
8002 "operation needs arithmetic types");
8007 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8008 expression->left = create_implicit_cast(left, arithmetic_type);
8009 expression->right = create_implicit_cast(right, arithmetic_type);
8010 expression->base.type = arithmetic_type;
8013 static void semantic_binexpr_integer(binary_expression_t *const expression)
8015 expression_t *const left = expression->left;
8016 expression_t *const right = expression->right;
8017 type_t *const orig_type_left = left->base.type;
8018 type_t *const orig_type_right = right->base.type;
8019 type_t *const type_left = skip_typeref(orig_type_left);
8020 type_t *const type_right = skip_typeref(orig_type_right);
8022 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8023 /* TODO: improve error message */
8024 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8025 errorf(&expression->base.source_position,
8026 "operation needs integer types");
8031 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8032 expression->left = create_implicit_cast(left, result_type);
8033 expression->right = create_implicit_cast(right, result_type);
8034 expression->base.type = result_type;
8037 static void warn_div_by_zero(binary_expression_t const *const expression)
8039 if (!is_type_integer(expression->base.type))
8042 expression_t const *const right = expression->right;
8043 /* The type of the right operand can be different for /= */
8044 if (is_type_integer(right->base.type) &&
8045 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8046 !fold_constant_to_bool(right)) {
8047 source_position_t const *const pos = &expression->base.source_position;
8048 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8053 * Check the semantic restrictions for a div/mod expression.
8055 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8057 semantic_binexpr_arithmetic(expression);
8058 warn_div_by_zero(expression);
8061 static void warn_addsub_in_shift(const expression_t *const expr)
8063 if (expr->base.parenthesized)
8067 switch (expr->kind) {
8068 case EXPR_BINARY_ADD: op = '+'; break;
8069 case EXPR_BINARY_SUB: op = '-'; break;
8073 source_position_t const *const pos = &expr->base.source_position;
8074 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8077 static bool semantic_shift(binary_expression_t *expression)
8079 expression_t *const left = expression->left;
8080 expression_t *const right = expression->right;
8081 type_t *const orig_type_left = left->base.type;
8082 type_t *const orig_type_right = right->base.type;
8083 type_t * type_left = skip_typeref(orig_type_left);
8084 type_t * type_right = skip_typeref(orig_type_right);
8086 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8087 /* TODO: improve error message */
8088 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8089 errorf(&expression->base.source_position,
8090 "operands of shift operation must have integer types");
8095 type_left = promote_integer(type_left);
8097 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8098 source_position_t const *const pos = &right->base.source_position;
8099 long const count = fold_constant_to_int(right);
8101 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8102 } else if ((unsigned long)count >=
8103 get_atomic_type_size(type_left->atomic.akind) * 8) {
8104 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8108 type_right = promote_integer(type_right);
8109 expression->right = create_implicit_cast(right, type_right);
8114 static void semantic_shift_op(binary_expression_t *expression)
8116 expression_t *const left = expression->left;
8117 expression_t *const right = expression->right;
8119 if (!semantic_shift(expression))
8122 warn_addsub_in_shift(left);
8123 warn_addsub_in_shift(right);
8125 type_t *const orig_type_left = left->base.type;
8126 type_t * type_left = skip_typeref(orig_type_left);
8128 type_left = promote_integer(type_left);
8129 expression->left = create_implicit_cast(left, type_left);
8130 expression->base.type = type_left;
8133 static void semantic_add(binary_expression_t *expression)
8135 expression_t *const left = expression->left;
8136 expression_t *const right = expression->right;
8137 type_t *const orig_type_left = left->base.type;
8138 type_t *const orig_type_right = right->base.type;
8139 type_t *const type_left = skip_typeref(orig_type_left);
8140 type_t *const type_right = skip_typeref(orig_type_right);
8143 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8144 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8145 expression->left = create_implicit_cast(left, arithmetic_type);
8146 expression->right = create_implicit_cast(right, arithmetic_type);
8147 expression->base.type = arithmetic_type;
8148 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8149 check_pointer_arithmetic(&expression->base.source_position,
8150 type_left, orig_type_left);
8151 expression->base.type = type_left;
8152 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8153 check_pointer_arithmetic(&expression->base.source_position,
8154 type_right, orig_type_right);
8155 expression->base.type = type_right;
8156 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8157 errorf(&expression->base.source_position,
8158 "invalid operands to binary + ('%T', '%T')",
8159 orig_type_left, orig_type_right);
8163 static void semantic_sub(binary_expression_t *expression)
8165 expression_t *const left = expression->left;
8166 expression_t *const right = expression->right;
8167 type_t *const orig_type_left = left->base.type;
8168 type_t *const orig_type_right = right->base.type;
8169 type_t *const type_left = skip_typeref(orig_type_left);
8170 type_t *const type_right = skip_typeref(orig_type_right);
8171 source_position_t const *const pos = &expression->base.source_position;
8174 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8175 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8176 expression->left = create_implicit_cast(left, arithmetic_type);
8177 expression->right = create_implicit_cast(right, arithmetic_type);
8178 expression->base.type = arithmetic_type;
8179 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8180 check_pointer_arithmetic(&expression->base.source_position,
8181 type_left, orig_type_left);
8182 expression->base.type = type_left;
8183 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8184 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8185 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8186 if (!types_compatible(unqual_left, unqual_right)) {
8188 "subtracting pointers to incompatible types '%T' and '%T'",
8189 orig_type_left, orig_type_right);
8190 } else if (!is_type_object(unqual_left)) {
8191 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8192 errorf(pos, "subtracting pointers to non-object types '%T'",
8195 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8198 expression->base.type = type_ptrdiff_t;
8199 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8200 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8201 orig_type_left, orig_type_right);
8205 static void warn_string_literal_address(expression_t const* expr)
8207 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8208 expr = expr->unary.value;
8209 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8211 expr = expr->unary.value;
8214 if (expr->kind == EXPR_STRING_LITERAL
8215 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8216 source_position_t const *const pos = &expr->base.source_position;
8217 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8221 static bool maybe_negative(expression_t const *const expr)
8223 switch (is_constant_expression(expr)) {
8224 case EXPR_CLASS_ERROR: return false;
8225 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8226 default: return true;
8230 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8232 warn_string_literal_address(expr);
8234 expression_t const* const ref = get_reference_address(expr);
8235 if (ref != NULL && is_null_pointer_constant(other)) {
8236 entity_t const *const ent = ref->reference.entity;
8237 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8240 if (!expr->base.parenthesized) {
8241 switch (expr->base.kind) {
8242 case EXPR_BINARY_LESS:
8243 case EXPR_BINARY_GREATER:
8244 case EXPR_BINARY_LESSEQUAL:
8245 case EXPR_BINARY_GREATEREQUAL:
8246 case EXPR_BINARY_NOTEQUAL:
8247 case EXPR_BINARY_EQUAL:
8248 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8257 * Check the semantics of comparison expressions.
8259 * @param expression The expression to check.
8261 static void semantic_comparison(binary_expression_t *expression)
8263 source_position_t const *const pos = &expression->base.source_position;
8264 expression_t *const left = expression->left;
8265 expression_t *const right = expression->right;
8267 warn_comparison(pos, left, right);
8268 warn_comparison(pos, right, left);
8270 type_t *orig_type_left = left->base.type;
8271 type_t *orig_type_right = right->base.type;
8272 type_t *type_left = skip_typeref(orig_type_left);
8273 type_t *type_right = skip_typeref(orig_type_right);
8275 /* TODO non-arithmetic types */
8276 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8277 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8279 /* test for signed vs unsigned compares */
8280 if (is_type_integer(arithmetic_type)) {
8281 bool const signed_left = is_type_signed(type_left);
8282 bool const signed_right = is_type_signed(type_right);
8283 if (signed_left != signed_right) {
8284 /* FIXME long long needs better const folding magic */
8285 /* TODO check whether constant value can be represented by other type */
8286 if ((signed_left && maybe_negative(left)) ||
8287 (signed_right && maybe_negative(right))) {
8288 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8293 expression->left = create_implicit_cast(left, arithmetic_type);
8294 expression->right = create_implicit_cast(right, arithmetic_type);
8295 expression->base.type = arithmetic_type;
8296 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8297 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8298 is_type_float(arithmetic_type)) {
8299 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8301 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8302 /* TODO check compatibility */
8303 } else if (is_type_pointer(type_left)) {
8304 expression->right = create_implicit_cast(right, type_left);
8305 } else if (is_type_pointer(type_right)) {
8306 expression->left = create_implicit_cast(left, type_right);
8307 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8308 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8310 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8314 * Checks if a compound type has constant fields.
8316 static bool has_const_fields(const compound_type_t *type)
8318 compound_t *compound = type->compound;
8319 entity_t *entry = compound->members.entities;
8321 for (; entry != NULL; entry = entry->base.next) {
8322 if (!is_declaration(entry))
8325 const type_t *decl_type = skip_typeref(entry->declaration.type);
8326 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8333 static bool is_valid_assignment_lhs(expression_t const* const left)
8335 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8336 type_t *const type_left = skip_typeref(orig_type_left);
8338 if (!is_lvalue(left)) {
8339 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8344 if (left->kind == EXPR_REFERENCE
8345 && left->reference.entity->kind == ENTITY_FUNCTION) {
8346 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8350 if (is_type_array(type_left)) {
8351 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8354 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8355 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8359 if (is_type_incomplete(type_left)) {
8360 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8361 left, orig_type_left);
8364 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8365 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8366 left, orig_type_left);
8373 static void semantic_arithmetic_assign(binary_expression_t *expression)
8375 expression_t *left = expression->left;
8376 expression_t *right = expression->right;
8377 type_t *orig_type_left = left->base.type;
8378 type_t *orig_type_right = right->base.type;
8380 if (!is_valid_assignment_lhs(left))
8383 type_t *type_left = skip_typeref(orig_type_left);
8384 type_t *type_right = skip_typeref(orig_type_right);
8386 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8387 /* TODO: improve error message */
8388 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8389 errorf(&expression->base.source_position,
8390 "operation needs arithmetic types");
8395 /* combined instructions are tricky. We can't create an implicit cast on
8396 * the left side, because we need the uncasted form for the store.
8397 * The ast2firm pass has to know that left_type must be right_type
8398 * for the arithmetic operation and create a cast by itself */
8399 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8400 expression->right = create_implicit_cast(right, arithmetic_type);
8401 expression->base.type = type_left;
8404 static void semantic_divmod_assign(binary_expression_t *expression)
8406 semantic_arithmetic_assign(expression);
8407 warn_div_by_zero(expression);
8410 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8412 expression_t *const left = expression->left;
8413 expression_t *const right = expression->right;
8414 type_t *const orig_type_left = left->base.type;
8415 type_t *const orig_type_right = right->base.type;
8416 type_t *const type_left = skip_typeref(orig_type_left);
8417 type_t *const type_right = skip_typeref(orig_type_right);
8419 if (!is_valid_assignment_lhs(left))
8422 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8423 /* combined instructions are tricky. We can't create an implicit cast on
8424 * the left side, because we need the uncasted form for the store.
8425 * The ast2firm pass has to know that left_type must be right_type
8426 * for the arithmetic operation and create a cast by itself */
8427 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8428 expression->right = create_implicit_cast(right, arithmetic_type);
8429 expression->base.type = type_left;
8430 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8431 check_pointer_arithmetic(&expression->base.source_position,
8432 type_left, orig_type_left);
8433 expression->base.type = type_left;
8434 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8435 errorf(&expression->base.source_position,
8436 "incompatible types '%T' and '%T' in assignment",
8437 orig_type_left, orig_type_right);
8441 static void semantic_integer_assign(binary_expression_t *expression)
8443 expression_t *left = expression->left;
8444 expression_t *right = expression->right;
8445 type_t *orig_type_left = left->base.type;
8446 type_t *orig_type_right = right->base.type;
8448 if (!is_valid_assignment_lhs(left))
8451 type_t *type_left = skip_typeref(orig_type_left);
8452 type_t *type_right = skip_typeref(orig_type_right);
8454 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8455 /* TODO: improve error message */
8456 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8457 errorf(&expression->base.source_position,
8458 "operation needs integer types");
8463 /* combined instructions are tricky. We can't create an implicit cast on
8464 * the left side, because we need the uncasted form for the store.
8465 * The ast2firm pass has to know that left_type must be right_type
8466 * for the arithmetic operation and create a cast by itself */
8467 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8468 expression->right = create_implicit_cast(right, arithmetic_type);
8469 expression->base.type = type_left;
8472 static void semantic_shift_assign(binary_expression_t *expression)
8474 expression_t *left = expression->left;
8476 if (!is_valid_assignment_lhs(left))
8479 if (!semantic_shift(expression))
8482 expression->base.type = skip_typeref(left->base.type);
8485 static void warn_logical_and_within_or(const expression_t *const expr)
8487 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8489 if (expr->base.parenthesized)
8491 source_position_t const *const pos = &expr->base.source_position;
8492 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8496 * Check the semantic restrictions of a logical expression.
8498 static void semantic_logical_op(binary_expression_t *expression)
8500 /* §6.5.13:2 Each of the operands shall have scalar type.
8501 * §6.5.14:2 Each of the operands shall have scalar type. */
8502 semantic_condition(expression->left, "left operand of logical operator");
8503 semantic_condition(expression->right, "right operand of logical operator");
8504 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8505 warn_logical_and_within_or(expression->left);
8506 warn_logical_and_within_or(expression->right);
8508 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8512 * Check the semantic restrictions of a binary assign expression.
8514 static void semantic_binexpr_assign(binary_expression_t *expression)
8516 expression_t *left = expression->left;
8517 type_t *orig_type_left = left->base.type;
8519 if (!is_valid_assignment_lhs(left))
8522 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8523 report_assign_error(error, orig_type_left, expression->right,
8524 "assignment", &left->base.source_position);
8525 expression->right = create_implicit_cast(expression->right, orig_type_left);
8526 expression->base.type = orig_type_left;
8530 * Determine if the outermost operation (or parts thereof) of the given
8531 * expression has no effect in order to generate a warning about this fact.
8532 * Therefore in some cases this only examines some of the operands of the
8533 * expression (see comments in the function and examples below).
8535 * f() + 23; // warning, because + has no effect
8536 * x || f(); // no warning, because x controls execution of f()
8537 * x ? y : f(); // warning, because y has no effect
8538 * (void)x; // no warning to be able to suppress the warning
8539 * This function can NOT be used for an "expression has definitely no effect"-
8541 static bool expression_has_effect(const expression_t *const expr)
8543 switch (expr->kind) {
8544 case EXPR_ERROR: return true; /* do NOT warn */
8545 case EXPR_REFERENCE: return false;
8546 case EXPR_REFERENCE_ENUM_VALUE: return false;
8547 case EXPR_LABEL_ADDRESS: return false;
8549 /* suppress the warning for microsoft __noop operations */
8550 case EXPR_LITERAL_MS_NOOP: return true;
8551 case EXPR_LITERAL_BOOLEAN:
8552 case EXPR_LITERAL_CHARACTER:
8553 case EXPR_LITERAL_WIDE_CHARACTER:
8554 case EXPR_LITERAL_INTEGER:
8555 case EXPR_LITERAL_INTEGER_OCTAL:
8556 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8557 case EXPR_LITERAL_FLOATINGPOINT:
8558 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8559 case EXPR_STRING_LITERAL: return false;
8560 case EXPR_WIDE_STRING_LITERAL: return false;
8563 const call_expression_t *const call = &expr->call;
8564 if (call->function->kind != EXPR_REFERENCE)
8567 switch (call->function->reference.entity->function.btk) {
8568 /* FIXME: which builtins have no effect? */
8569 default: return true;
8573 /* Generate the warning if either the left or right hand side of a
8574 * conditional expression has no effect */
8575 case EXPR_CONDITIONAL: {
8576 conditional_expression_t const *const cond = &expr->conditional;
8577 expression_t const *const t = cond->true_expression;
8579 (t == NULL || expression_has_effect(t)) &&
8580 expression_has_effect(cond->false_expression);
8583 case EXPR_SELECT: return false;
8584 case EXPR_ARRAY_ACCESS: return false;
8585 case EXPR_SIZEOF: return false;
8586 case EXPR_CLASSIFY_TYPE: return false;
8587 case EXPR_ALIGNOF: return false;
8589 case EXPR_FUNCNAME: return false;
8590 case EXPR_BUILTIN_CONSTANT_P: return false;
8591 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8592 case EXPR_OFFSETOF: return false;
8593 case EXPR_VA_START: return true;
8594 case EXPR_VA_ARG: return true;
8595 case EXPR_VA_COPY: return true;
8596 case EXPR_STATEMENT: return true; // TODO
8597 case EXPR_COMPOUND_LITERAL: return false;
8599 case EXPR_UNARY_NEGATE: return false;
8600 case EXPR_UNARY_PLUS: return false;
8601 case EXPR_UNARY_BITWISE_NEGATE: return false;
8602 case EXPR_UNARY_NOT: return false;
8603 case EXPR_UNARY_DEREFERENCE: return false;
8604 case EXPR_UNARY_TAKE_ADDRESS: return false;
8605 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8606 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8607 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8608 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8610 /* Treat void casts as if they have an effect in order to being able to
8611 * suppress the warning */
8612 case EXPR_UNARY_CAST: {
8613 type_t *const type = skip_typeref(expr->base.type);
8614 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8617 case EXPR_UNARY_ASSUME: return true;
8618 case EXPR_UNARY_DELETE: return true;
8619 case EXPR_UNARY_DELETE_ARRAY: return true;
8620 case EXPR_UNARY_THROW: return true;
8622 case EXPR_BINARY_ADD: return false;
8623 case EXPR_BINARY_SUB: return false;
8624 case EXPR_BINARY_MUL: return false;
8625 case EXPR_BINARY_DIV: return false;
8626 case EXPR_BINARY_MOD: return false;
8627 case EXPR_BINARY_EQUAL: return false;
8628 case EXPR_BINARY_NOTEQUAL: return false;
8629 case EXPR_BINARY_LESS: return false;
8630 case EXPR_BINARY_LESSEQUAL: return false;
8631 case EXPR_BINARY_GREATER: return false;
8632 case EXPR_BINARY_GREATEREQUAL: return false;
8633 case EXPR_BINARY_BITWISE_AND: return false;
8634 case EXPR_BINARY_BITWISE_OR: return false;
8635 case EXPR_BINARY_BITWISE_XOR: return false;
8636 case EXPR_BINARY_SHIFTLEFT: return false;
8637 case EXPR_BINARY_SHIFTRIGHT: return false;
8638 case EXPR_BINARY_ASSIGN: return true;
8639 case EXPR_BINARY_MUL_ASSIGN: return true;
8640 case EXPR_BINARY_DIV_ASSIGN: return true;
8641 case EXPR_BINARY_MOD_ASSIGN: return true;
8642 case EXPR_BINARY_ADD_ASSIGN: return true;
8643 case EXPR_BINARY_SUB_ASSIGN: return true;
8644 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8645 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8646 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8647 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8648 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8650 /* Only examine the right hand side of && and ||, because the left hand
8651 * side already has the effect of controlling the execution of the right
8653 case EXPR_BINARY_LOGICAL_AND:
8654 case EXPR_BINARY_LOGICAL_OR:
8655 /* Only examine the right hand side of a comma expression, because the left
8656 * hand side has a separate warning */
8657 case EXPR_BINARY_COMMA:
8658 return expression_has_effect(expr->binary.right);
8660 case EXPR_BINARY_ISGREATER: return false;
8661 case EXPR_BINARY_ISGREATEREQUAL: return false;
8662 case EXPR_BINARY_ISLESS: return false;
8663 case EXPR_BINARY_ISLESSEQUAL: return false;
8664 case EXPR_BINARY_ISLESSGREATER: return false;
8665 case EXPR_BINARY_ISUNORDERED: return false;
8668 internal_errorf(HERE, "unexpected expression");
8671 static void semantic_comma(binary_expression_t *expression)
8673 const expression_t *const left = expression->left;
8674 if (!expression_has_effect(left)) {
8675 source_position_t const *const pos = &left->base.source_position;
8676 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8678 expression->base.type = expression->right->base.type;
8682 * @param prec_r precedence of the right operand
8684 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8685 static expression_t *parse_##binexpression_type(expression_t *left) \
8687 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8688 binexpr->binary.left = left; \
8691 expression_t *right = parse_subexpression(prec_r); \
8693 binexpr->binary.right = right; \
8694 sfunc(&binexpr->binary); \
8699 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8700 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8701 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8702 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8703 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8704 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8705 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8706 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8707 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8708 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8709 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8710 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8711 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8712 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8713 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8714 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8715 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8716 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8717 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8718 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8719 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8720 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8721 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8722 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8723 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8724 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8725 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8726 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8727 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8728 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8731 static expression_t *parse_subexpression(precedence_t precedence)
8733 if (token.kind < 0) {
8734 return expected_expression_error();
8737 expression_parser_function_t *parser
8738 = &expression_parsers[token.kind];
8741 if (parser->parser != NULL) {
8742 left = parser->parser();
8744 left = parse_primary_expression();
8746 assert(left != NULL);
8749 if (token.kind < 0) {
8750 return expected_expression_error();
8753 parser = &expression_parsers[token.kind];
8754 if (parser->infix_parser == NULL)
8756 if (parser->infix_precedence < precedence)
8759 left = parser->infix_parser(left);
8761 assert(left != NULL);
8768 * Parse an expression.
8770 static expression_t *parse_expression(void)
8772 return parse_subexpression(PREC_EXPRESSION);
8776 * Register a parser for a prefix-like operator.
8778 * @param parser the parser function
8779 * @param token_kind the token type of the prefix token
8781 static void register_expression_parser(parse_expression_function parser,
8784 expression_parser_function_t *entry = &expression_parsers[token_kind];
8786 if (entry->parser != NULL) {
8787 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8788 panic("trying to register multiple expression parsers for a token");
8790 entry->parser = parser;
8794 * Register a parser for an infix operator with given precedence.
8796 * @param parser the parser function
8797 * @param token_kind the token type of the infix operator
8798 * @param precedence the precedence of the operator
8800 static void register_infix_parser(parse_expression_infix_function parser,
8801 int token_kind, precedence_t precedence)
8803 expression_parser_function_t *entry = &expression_parsers[token_kind];
8805 if (entry->infix_parser != NULL) {
8806 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8807 panic("trying to register multiple infix expression parsers for a "
8810 entry->infix_parser = parser;
8811 entry->infix_precedence = precedence;
8815 * Initialize the expression parsers.
8817 static void init_expression_parsers(void)
8819 memset(&expression_parsers, 0, sizeof(expression_parsers));
8821 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8822 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8823 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8824 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8825 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8826 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8827 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8828 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8829 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8830 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8831 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8832 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8833 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8834 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8835 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8836 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8837 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8838 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8839 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8840 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8841 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8842 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8843 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8844 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8845 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8846 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8847 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8848 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8849 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8850 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8851 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8852 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8853 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8854 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8855 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8856 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8857 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8859 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8860 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8861 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8862 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8863 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8864 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8865 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8866 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8867 register_expression_parser(parse_sizeof, T_sizeof);
8868 register_expression_parser(parse_alignof, T___alignof__);
8869 register_expression_parser(parse_extension, T___extension__);
8870 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8871 register_expression_parser(parse_delete, T_delete);
8872 register_expression_parser(parse_throw, T_throw);
8876 * Parse a asm statement arguments specification.
8878 static asm_argument_t *parse_asm_arguments(bool is_out)
8880 asm_argument_t *result = NULL;
8881 asm_argument_t **anchor = &result;
8883 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8884 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8885 memset(argument, 0, sizeof(argument[0]));
8888 if (token.kind != T_IDENTIFIER) {
8889 parse_error_expected("while parsing asm argument",
8890 T_IDENTIFIER, NULL);
8893 argument->symbol = token.identifier.symbol;
8895 expect(']', end_error);
8898 argument->constraints = parse_string_literals();
8899 expect('(', end_error);
8900 add_anchor_token(')');
8901 expression_t *expression = parse_expression();
8902 rem_anchor_token(')');
8904 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8905 * change size or type representation (e.g. int -> long is ok, but
8906 * int -> float is not) */
8907 if (expression->kind == EXPR_UNARY_CAST) {
8908 type_t *const type = expression->base.type;
8909 type_kind_t const kind = type->kind;
8910 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8913 if (kind == TYPE_ATOMIC) {
8914 atomic_type_kind_t const akind = type->atomic.akind;
8915 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8916 size = get_atomic_type_size(akind);
8918 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8919 size = get_type_size(type_void_ptr);
8923 expression_t *const value = expression->unary.value;
8924 type_t *const value_type = value->base.type;
8925 type_kind_t const value_kind = value_type->kind;
8927 unsigned value_flags;
8928 unsigned value_size;
8929 if (value_kind == TYPE_ATOMIC) {
8930 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8931 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8932 value_size = get_atomic_type_size(value_akind);
8933 } else if (value_kind == TYPE_POINTER) {
8934 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8935 value_size = get_type_size(type_void_ptr);
8940 if (value_flags != flags || value_size != size)
8944 } while (expression->kind == EXPR_UNARY_CAST);
8948 if (!is_lvalue(expression)) {
8949 errorf(&expression->base.source_position,
8950 "asm output argument is not an lvalue");
8953 if (argument->constraints.begin[0] == '=')
8954 determine_lhs_ent(expression, NULL);
8956 mark_vars_read(expression, NULL);
8958 mark_vars_read(expression, NULL);
8960 argument->expression = expression;
8961 expect(')', end_error);
8963 set_address_taken(expression, true);
8966 anchor = &argument->next;
8978 * Parse a asm statement clobber specification.
8980 static asm_clobber_t *parse_asm_clobbers(void)
8982 asm_clobber_t *result = NULL;
8983 asm_clobber_t **anchor = &result;
8985 while (token.kind == T_STRING_LITERAL) {
8986 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8987 clobber->clobber = parse_string_literals();
8990 anchor = &clobber->next;
9000 * Parse an asm statement.
9002 static statement_t *parse_asm_statement(void)
9004 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9005 asm_statement_t *asm_statement = &statement->asms;
9009 if (next_if(T_volatile))
9010 asm_statement->is_volatile = true;
9012 expect('(', end_error);
9013 add_anchor_token(')');
9014 if (token.kind != T_STRING_LITERAL) {
9015 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9018 asm_statement->asm_text = parse_string_literals();
9020 add_anchor_token(':');
9021 if (!next_if(':')) {
9022 rem_anchor_token(':');
9026 asm_statement->outputs = parse_asm_arguments(true);
9027 if (!next_if(':')) {
9028 rem_anchor_token(':');
9032 asm_statement->inputs = parse_asm_arguments(false);
9033 if (!next_if(':')) {
9034 rem_anchor_token(':');
9037 rem_anchor_token(':');
9039 asm_statement->clobbers = parse_asm_clobbers();
9042 rem_anchor_token(')');
9043 expect(')', end_error);
9044 expect(';', end_error);
9046 if (asm_statement->outputs == NULL) {
9047 /* GCC: An 'asm' instruction without any output operands will be treated
9048 * identically to a volatile 'asm' instruction. */
9049 asm_statement->is_volatile = true;
9054 return create_error_statement();
9057 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9059 statement_t *inner_stmt;
9060 switch (token.kind) {
9062 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9063 inner_stmt = create_error_statement();
9067 if (label->kind == STATEMENT_LABEL) {
9068 /* Eat an empty statement here, to avoid the warning about an empty
9069 * statement after a label. label:; is commonly used to have a label
9070 * before a closing brace. */
9071 inner_stmt = create_empty_statement();
9078 inner_stmt = parse_statement();
9079 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9080 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9081 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9082 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9090 * Parse a case statement.
9092 static statement_t *parse_case_statement(void)
9094 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9095 source_position_t *const pos = &statement->base.source_position;
9099 expression_t *expression = parse_expression();
9100 type_t *expression_type = expression->base.type;
9101 type_t *skipped = skip_typeref(expression_type);
9102 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9103 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9104 expression, expression_type);
9107 type_t *type = expression_type;
9108 if (current_switch != NULL) {
9109 type_t *switch_type = current_switch->expression->base.type;
9110 if (is_type_valid(switch_type)) {
9111 expression = create_implicit_cast(expression, switch_type);
9115 statement->case_label.expression = expression;
9116 expression_classification_t const expr_class = is_constant_expression(expression);
9117 if (expr_class != EXPR_CLASS_CONSTANT) {
9118 if (expr_class != EXPR_CLASS_ERROR) {
9119 errorf(pos, "case label does not reduce to an integer constant");
9121 statement->case_label.is_bad = true;
9123 long const val = fold_constant_to_int(expression);
9124 statement->case_label.first_case = val;
9125 statement->case_label.last_case = val;
9129 if (next_if(T_DOTDOTDOT)) {
9130 expression_t *end_range = parse_expression();
9131 expression_type = expression->base.type;
9132 skipped = skip_typeref(expression_type);
9133 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9134 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9135 expression, expression_type);
9138 end_range = create_implicit_cast(end_range, type);
9139 statement->case_label.end_range = end_range;
9140 expression_classification_t const end_class = is_constant_expression(end_range);
9141 if (end_class != EXPR_CLASS_CONSTANT) {
9142 if (end_class != EXPR_CLASS_ERROR) {
9143 errorf(pos, "case range does not reduce to an integer constant");
9145 statement->case_label.is_bad = true;
9147 long const val = fold_constant_to_int(end_range);
9148 statement->case_label.last_case = val;
9150 if (val < statement->case_label.first_case) {
9151 statement->case_label.is_empty_range = true;
9152 warningf(WARN_OTHER, pos, "empty range specified");
9158 PUSH_PARENT(statement);
9160 expect(':', end_error);
9163 if (current_switch != NULL) {
9164 if (! statement->case_label.is_bad) {
9165 /* Check for duplicate case values */
9166 case_label_statement_t *c = &statement->case_label;
9167 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9168 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9171 if (c->last_case < l->first_case || c->first_case > l->last_case)
9174 errorf(pos, "duplicate case value (previously used %P)",
9175 &l->base.source_position);
9179 /* link all cases into the switch statement */
9180 if (current_switch->last_case == NULL) {
9181 current_switch->first_case = &statement->case_label;
9183 current_switch->last_case->next = &statement->case_label;
9185 current_switch->last_case = &statement->case_label;
9187 errorf(pos, "case label not within a switch statement");
9190 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9197 * Parse a default statement.
9199 static statement_t *parse_default_statement(void)
9201 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9205 PUSH_PARENT(statement);
9207 expect(':', end_error);
9210 if (current_switch != NULL) {
9211 const case_label_statement_t *def_label = current_switch->default_label;
9212 if (def_label != NULL) {
9213 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9215 current_switch->default_label = &statement->case_label;
9217 /* link all cases into the switch statement */
9218 if (current_switch->last_case == NULL) {
9219 current_switch->first_case = &statement->case_label;
9221 current_switch->last_case->next = &statement->case_label;
9223 current_switch->last_case = &statement->case_label;
9226 errorf(&statement->base.source_position,
9227 "'default' label not within a switch statement");
9230 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9237 * Parse a label statement.
9239 static statement_t *parse_label_statement(void)
9241 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9242 label_t *const label = get_label();
9243 statement->label.label = label;
9245 PUSH_PARENT(statement);
9247 /* if statement is already set then the label is defined twice,
9248 * otherwise it was just mentioned in a goto/local label declaration so far
9250 source_position_t const* const pos = &statement->base.source_position;
9251 if (label->statement != NULL) {
9252 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9254 label->base.source_position = *pos;
9255 label->statement = statement;
9260 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9261 parse_attributes(NULL); // TODO process attributes
9264 statement->label.statement = parse_label_inner_statement(statement, "label");
9266 /* remember the labels in a list for later checking */
9267 *label_anchor = &statement->label;
9268 label_anchor = &statement->label.next;
9274 static statement_t *parse_inner_statement(void)
9276 statement_t *const stmt = parse_statement();
9277 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9278 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9279 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9280 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9286 * Parse an if statement.
9288 static statement_t *parse_if(void)
9290 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9294 PUSH_PARENT(statement);
9296 add_anchor_token('{');
9298 expect('(', end_error);
9299 add_anchor_token(')');
9300 expression_t *const expr = parse_expression();
9301 statement->ifs.condition = expr;
9302 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9304 semantic_condition(expr, "condition of 'if'-statment");
9305 mark_vars_read(expr, NULL);
9306 rem_anchor_token(')');
9307 expect(')', end_error);
9310 rem_anchor_token('{');
9312 add_anchor_token(T_else);
9313 statement_t *const true_stmt = parse_inner_statement();
9314 statement->ifs.true_statement = true_stmt;
9315 rem_anchor_token(T_else);
9317 if (true_stmt->kind == STATEMENT_EMPTY) {
9318 warningf(WARN_EMPTY_BODY, HERE,
9319 "suggest braces around empty body in an ‘if’ statement");
9322 if (next_if(T_else)) {
9323 statement->ifs.false_statement = parse_inner_statement();
9325 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9326 warningf(WARN_EMPTY_BODY, HERE,
9327 "suggest braces around empty body in an ‘if’ statement");
9329 } else if (true_stmt->kind == STATEMENT_IF &&
9330 true_stmt->ifs.false_statement != NULL) {
9331 source_position_t const *const pos = &true_stmt->base.source_position;
9332 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9340 * Check that all enums are handled in a switch.
9342 * @param statement the switch statement to check
9344 static void check_enum_cases(const switch_statement_t *statement)
9346 if (!is_warn_on(WARN_SWITCH_ENUM))
9348 const type_t *type = skip_typeref(statement->expression->base.type);
9349 if (! is_type_enum(type))
9351 const enum_type_t *enumt = &type->enumt;
9353 /* if we have a default, no warnings */
9354 if (statement->default_label != NULL)
9357 /* FIXME: calculation of value should be done while parsing */
9358 /* TODO: quadratic algorithm here. Change to an n log n one */
9359 long last_value = -1;
9360 const entity_t *entry = enumt->enume->base.next;
9361 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9362 entry = entry->base.next) {
9363 const expression_t *expression = entry->enum_value.value;
9364 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9366 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9367 if (l->expression == NULL)
9369 if (l->first_case <= value && value <= l->last_case) {
9375 source_position_t const *const pos = &statement->base.source_position;
9376 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9383 * Parse a switch statement.
9385 static statement_t *parse_switch(void)
9387 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9391 PUSH_PARENT(statement);
9393 expect('(', end_error);
9394 add_anchor_token(')');
9395 expression_t *const expr = parse_expression();
9396 mark_vars_read(expr, NULL);
9397 type_t * type = skip_typeref(expr->base.type);
9398 if (is_type_integer(type)) {
9399 type = promote_integer(type);
9400 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9401 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9403 } else if (is_type_valid(type)) {
9404 errorf(&expr->base.source_position,
9405 "switch quantity is not an integer, but '%T'", type);
9406 type = type_error_type;
9408 statement->switchs.expression = create_implicit_cast(expr, type);
9409 expect(')', end_error);
9410 rem_anchor_token(')');
9412 switch_statement_t *rem = current_switch;
9413 current_switch = &statement->switchs;
9414 statement->switchs.body = parse_inner_statement();
9415 current_switch = rem;
9417 if (statement->switchs.default_label == NULL) {
9418 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9420 check_enum_cases(&statement->switchs);
9426 return create_error_statement();
9429 static statement_t *parse_loop_body(statement_t *const loop)
9431 statement_t *const rem = current_loop;
9432 current_loop = loop;
9434 statement_t *const body = parse_inner_statement();
9441 * Parse a while statement.
9443 static statement_t *parse_while(void)
9445 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9449 PUSH_PARENT(statement);
9451 expect('(', end_error);
9452 add_anchor_token(')');
9453 expression_t *const cond = parse_expression();
9454 statement->whiles.condition = cond;
9455 /* §6.8.5:2 The controlling expression of an iteration statement shall
9456 * have scalar type. */
9457 semantic_condition(cond, "condition of 'while'-statement");
9458 mark_vars_read(cond, NULL);
9459 rem_anchor_token(')');
9460 expect(')', end_error);
9462 statement->whiles.body = parse_loop_body(statement);
9468 return create_error_statement();
9472 * Parse a do statement.
9474 static statement_t *parse_do(void)
9476 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9480 PUSH_PARENT(statement);
9482 add_anchor_token(T_while);
9483 statement->do_while.body = parse_loop_body(statement);
9484 rem_anchor_token(T_while);
9486 expect(T_while, end_error);
9487 expect('(', end_error);
9488 add_anchor_token(')');
9489 expression_t *const cond = parse_expression();
9490 statement->do_while.condition = cond;
9491 /* §6.8.5:2 The controlling expression of an iteration statement shall
9492 * have scalar type. */
9493 semantic_condition(cond, "condition of 'do-while'-statement");
9494 mark_vars_read(cond, NULL);
9495 rem_anchor_token(')');
9496 expect(')', end_error);
9497 expect(';', end_error);
9503 return create_error_statement();
9507 * Parse a for statement.
9509 static statement_t *parse_for(void)
9511 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9515 expect('(', end_error1);
9516 add_anchor_token(')');
9518 PUSH_PARENT(statement);
9519 PUSH_SCOPE(&statement->fors.scope);
9524 } else if (is_declaration_specifier(&token)) {
9525 parse_declaration(record_entity, DECL_FLAGS_NONE);
9527 add_anchor_token(';');
9528 expression_t *const init = parse_expression();
9529 statement->fors.initialisation = init;
9530 mark_vars_read(init, ENT_ANY);
9531 if (!expression_has_effect(init)) {
9532 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9534 rem_anchor_token(';');
9535 expect(';', end_error2);
9540 if (token.kind != ';') {
9541 add_anchor_token(';');
9542 expression_t *const cond = parse_expression();
9543 statement->fors.condition = cond;
9544 /* §6.8.5:2 The controlling expression of an iteration statement
9545 * shall have scalar type. */
9546 semantic_condition(cond, "condition of 'for'-statement");
9547 mark_vars_read(cond, NULL);
9548 rem_anchor_token(';');
9550 expect(';', end_error2);
9551 if (token.kind != ')') {
9552 expression_t *const step = parse_expression();
9553 statement->fors.step = step;
9554 mark_vars_read(step, ENT_ANY);
9555 if (!expression_has_effect(step)) {
9556 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9559 expect(')', end_error2);
9560 rem_anchor_token(')');
9561 statement->fors.body = parse_loop_body(statement);
9569 rem_anchor_token(')');
9574 return create_error_statement();
9578 * Parse a goto statement.
9580 static statement_t *parse_goto(void)
9582 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9585 if (GNU_MODE && next_if('*')) {
9586 expression_t *expression = parse_expression();
9587 mark_vars_read(expression, NULL);
9589 /* Argh: although documentation says the expression must be of type void*,
9590 * gcc accepts anything that can be casted into void* without error */
9591 type_t *type = expression->base.type;
9593 if (type != type_error_type) {
9594 if (!is_type_pointer(type) && !is_type_integer(type)) {
9595 errorf(&expression->base.source_position,
9596 "cannot convert to a pointer type");
9597 } else if (type != type_void_ptr) {
9598 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9600 expression = create_implicit_cast(expression, type_void_ptr);
9603 statement->gotos.expression = expression;
9604 } else if (token.kind == T_IDENTIFIER) {
9605 label_t *const label = get_label();
9607 statement->gotos.label = label;
9610 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9612 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9614 return create_error_statement();
9617 /* remember the goto's in a list for later checking */
9618 *goto_anchor = &statement->gotos;
9619 goto_anchor = &statement->gotos.next;
9621 expect(';', end_error);
9628 * Parse a continue statement.
9630 static statement_t *parse_continue(void)
9632 if (current_loop == NULL) {
9633 errorf(HERE, "continue statement not within loop");
9636 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9639 expect(';', end_error);
9646 * Parse a break statement.
9648 static statement_t *parse_break(void)
9650 if (current_switch == NULL && current_loop == NULL) {
9651 errorf(HERE, "break statement not within loop or switch");
9654 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9657 expect(';', end_error);
9664 * Parse a __leave statement.
9666 static statement_t *parse_leave_statement(void)
9668 if (current_try == NULL) {
9669 errorf(HERE, "__leave statement not within __try");
9672 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9675 expect(';', end_error);
9682 * Check if a given entity represents a local variable.
9684 static bool is_local_variable(const entity_t *entity)
9686 if (entity->kind != ENTITY_VARIABLE)
9689 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9690 case STORAGE_CLASS_AUTO:
9691 case STORAGE_CLASS_REGISTER: {
9692 const type_t *type = skip_typeref(entity->declaration.type);
9693 if (is_type_function(type)) {
9705 * Check if a given expression represents a local variable.
9707 static bool expression_is_local_variable(const expression_t *expression)
9709 if (expression->base.kind != EXPR_REFERENCE) {
9712 const entity_t *entity = expression->reference.entity;
9713 return is_local_variable(entity);
9717 * Check if a given expression represents a local variable and
9718 * return its declaration then, else return NULL.
9720 entity_t *expression_is_variable(const expression_t *expression)
9722 if (expression->base.kind != EXPR_REFERENCE) {
9725 entity_t *entity = expression->reference.entity;
9726 if (entity->kind != ENTITY_VARIABLE)
9733 * Parse a return statement.
9735 static statement_t *parse_return(void)
9737 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9740 expression_t *return_value = NULL;
9741 if (token.kind != ';') {
9742 return_value = parse_expression();
9743 mark_vars_read(return_value, NULL);
9746 const type_t *const func_type = skip_typeref(current_function->base.type);
9747 assert(is_type_function(func_type));
9748 type_t *const return_type = skip_typeref(func_type->function.return_type);
9750 source_position_t const *const pos = &statement->base.source_position;
9751 if (return_value != NULL) {
9752 type_t *return_value_type = skip_typeref(return_value->base.type);
9754 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9755 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9756 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9757 /* Only warn in C mode, because GCC does the same */
9758 if (c_mode & _CXX || strict_mode) {
9760 "'return' with a value, in function returning 'void'");
9762 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9764 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9765 /* Only warn in C mode, because GCC does the same */
9768 "'return' with expression in function returning 'void'");
9770 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9774 assign_error_t error = semantic_assign(return_type, return_value);
9775 report_assign_error(error, return_type, return_value, "'return'",
9778 return_value = create_implicit_cast(return_value, return_type);
9779 /* check for returning address of a local var */
9780 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9781 const expression_t *expression = return_value->unary.value;
9782 if (expression_is_local_variable(expression)) {
9783 warningf(WARN_OTHER, pos, "function returns address of local variable");
9786 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9787 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9788 if (c_mode & _CXX || strict_mode) {
9790 "'return' without value, in function returning non-void");
9792 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9795 statement->returns.value = return_value;
9797 expect(';', end_error);
9804 * Parse a declaration statement.
9806 static statement_t *parse_declaration_statement(void)
9808 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9810 entity_t *before = current_scope->last_entity;
9812 parse_external_declaration();
9814 parse_declaration(record_entity, DECL_FLAGS_NONE);
9817 declaration_statement_t *const decl = &statement->declaration;
9818 entity_t *const begin =
9819 before != NULL ? before->base.next : current_scope->entities;
9820 decl->declarations_begin = begin;
9821 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9827 * Parse an expression statement, ie. expr ';'.
9829 static statement_t *parse_expression_statement(void)
9831 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9833 expression_t *const expr = parse_expression();
9834 statement->expression.expression = expr;
9835 mark_vars_read(expr, ENT_ANY);
9837 expect(';', end_error);
9844 * Parse a microsoft __try { } __finally { } or
9845 * __try{ } __except() { }
9847 static statement_t *parse_ms_try_statment(void)
9849 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9852 PUSH_PARENT(statement);
9854 ms_try_statement_t *rem = current_try;
9855 current_try = &statement->ms_try;
9856 statement->ms_try.try_statement = parse_compound_statement(false);
9861 if (next_if(T___except)) {
9862 expect('(', end_error);
9863 add_anchor_token(')');
9864 expression_t *const expr = parse_expression();
9865 mark_vars_read(expr, NULL);
9866 type_t * type = skip_typeref(expr->base.type);
9867 if (is_type_integer(type)) {
9868 type = promote_integer(type);
9869 } else if (is_type_valid(type)) {
9870 errorf(&expr->base.source_position,
9871 "__expect expression is not an integer, but '%T'", type);
9872 type = type_error_type;
9874 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9875 rem_anchor_token(')');
9876 expect(')', end_error);
9877 statement->ms_try.final_statement = parse_compound_statement(false);
9878 } else if (next_if(T__finally)) {
9879 statement->ms_try.final_statement = parse_compound_statement(false);
9881 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9882 return create_error_statement();
9886 return create_error_statement();
9889 static statement_t *parse_empty_statement(void)
9891 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9892 statement_t *const statement = create_empty_statement();
9897 static statement_t *parse_local_label_declaration(void)
9899 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9903 entity_t *begin = NULL;
9904 entity_t *end = NULL;
9905 entity_t **anchor = &begin;
9907 if (token.kind != T_IDENTIFIER) {
9908 parse_error_expected("while parsing local label declaration",
9909 T_IDENTIFIER, NULL);
9912 symbol_t *symbol = token.identifier.symbol;
9913 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9914 if (entity != NULL && entity->base.parent_scope == current_scope) {
9915 source_position_t const *const ppos = &entity->base.source_position;
9916 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9918 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9919 entity->base.parent_scope = current_scope;
9920 entity->base.source_position = token.base.source_position;
9923 anchor = &entity->base.next;
9926 environment_push(entity);
9929 } while (next_if(','));
9930 expect(';', end_error);
9932 statement->declaration.declarations_begin = begin;
9933 statement->declaration.declarations_end = end;
9937 static void parse_namespace_definition(void)
9941 entity_t *entity = NULL;
9942 symbol_t *symbol = NULL;
9944 if (token.kind == T_IDENTIFIER) {
9945 symbol = token.identifier.symbol;
9948 entity = get_entity(symbol, NAMESPACE_NORMAL);
9950 && entity->kind != ENTITY_NAMESPACE
9951 && entity->base.parent_scope == current_scope) {
9952 if (is_entity_valid(entity)) {
9953 error_redefined_as_different_kind(&token.base.source_position,
9954 entity, ENTITY_NAMESPACE);
9960 if (entity == NULL) {
9961 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9962 entity->base.source_position = token.base.source_position;
9963 entity->base.parent_scope = current_scope;
9966 if (token.kind == '=') {
9967 /* TODO: parse namespace alias */
9968 panic("namespace alias definition not supported yet");
9971 environment_push(entity);
9972 append_entity(current_scope, entity);
9974 PUSH_SCOPE(&entity->namespacee.members);
9976 entity_t *old_current_entity = current_entity;
9977 current_entity = entity;
9979 expect('{', end_error);
9981 expect('}', end_error);
9984 assert(current_entity == entity);
9985 current_entity = old_current_entity;
9990 * Parse a statement.
9991 * There's also parse_statement() which additionally checks for
9992 * "statement has no effect" warnings
9994 static statement_t *intern_parse_statement(void)
9996 statement_t *statement = NULL;
9998 /* declaration or statement */
9999 add_anchor_token(';');
10000 switch (token.kind) {
10001 case T_IDENTIFIER: {
10002 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
10003 if (la1_type == ':') {
10004 statement = parse_label_statement();
10005 } else if (is_typedef_symbol(token.identifier.symbol)) {
10006 statement = parse_declaration_statement();
10008 /* it's an identifier, the grammar says this must be an
10009 * expression statement. However it is common that users mistype
10010 * declaration types, so we guess a bit here to improve robustness
10011 * for incorrect programs */
10012 switch (la1_type) {
10015 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
10017 statement = parse_expression_statement();
10021 statement = parse_declaration_statement();
10029 case T___extension__: {
10030 /* This can be a prefix to a declaration or an expression statement.
10031 * We simply eat it now and parse the rest with tail recursion. */
10033 statement = intern_parse_statement();
10039 statement = parse_declaration_statement();
10043 statement = parse_local_label_declaration();
10046 case ';': statement = parse_empty_statement(); break;
10047 case '{': statement = parse_compound_statement(false); break;
10048 case T___leave: statement = parse_leave_statement(); break;
10049 case T___try: statement = parse_ms_try_statment(); break;
10050 case T_asm: statement = parse_asm_statement(); break;
10051 case T_break: statement = parse_break(); break;
10052 case T_case: statement = parse_case_statement(); break;
10053 case T_continue: statement = parse_continue(); break;
10054 case T_default: statement = parse_default_statement(); break;
10055 case T_do: statement = parse_do(); break;
10056 case T_for: statement = parse_for(); break;
10057 case T_goto: statement = parse_goto(); break;
10058 case T_if: statement = parse_if(); break;
10059 case T_return: statement = parse_return(); break;
10060 case T_switch: statement = parse_switch(); break;
10061 case T_while: statement = parse_while(); break;
10064 statement = parse_expression_statement();
10068 errorf(HERE, "unexpected token %K while parsing statement", &token);
10069 statement = create_error_statement();
10074 rem_anchor_token(';');
10076 assert(statement != NULL
10077 && statement->base.source_position.input_name != NULL);
10083 * parse a statement and emits "statement has no effect" warning if needed
10084 * (This is really a wrapper around intern_parse_statement with check for 1
10085 * single warning. It is needed, because for statement expressions we have
10086 * to avoid the warning on the last statement)
10088 static statement_t *parse_statement(void)
10090 statement_t *statement = intern_parse_statement();
10092 if (statement->kind == STATEMENT_EXPRESSION) {
10093 expression_t *expression = statement->expression.expression;
10094 if (!expression_has_effect(expression)) {
10095 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10103 * Parse a compound statement.
10105 static statement_t *parse_compound_statement(bool inside_expression_statement)
10107 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10109 PUSH_PARENT(statement);
10110 PUSH_SCOPE(&statement->compound.scope);
10113 add_anchor_token('}');
10114 /* tokens, which can start a statement */
10115 /* TODO MS, __builtin_FOO */
10116 add_anchor_token('!');
10117 add_anchor_token('&');
10118 add_anchor_token('(');
10119 add_anchor_token('*');
10120 add_anchor_token('+');
10121 add_anchor_token('-');
10122 add_anchor_token('{');
10123 add_anchor_token('~');
10124 add_anchor_token(T_CHARACTER_CONSTANT);
10125 add_anchor_token(T_COLONCOLON);
10126 add_anchor_token(T_FLOATINGPOINT);
10127 add_anchor_token(T_IDENTIFIER);
10128 add_anchor_token(T_INTEGER);
10129 add_anchor_token(T_MINUSMINUS);
10130 add_anchor_token(T_PLUSPLUS);
10131 add_anchor_token(T_STRING_LITERAL);
10132 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10133 add_anchor_token(T_WIDE_STRING_LITERAL);
10134 add_anchor_token(T__Bool);
10135 add_anchor_token(T__Complex);
10136 add_anchor_token(T__Imaginary);
10137 add_anchor_token(T___FUNCTION__);
10138 add_anchor_token(T___PRETTY_FUNCTION__);
10139 add_anchor_token(T___alignof__);
10140 add_anchor_token(T___attribute__);
10141 add_anchor_token(T___builtin_va_start);
10142 add_anchor_token(T___extension__);
10143 add_anchor_token(T___func__);
10144 add_anchor_token(T___imag__);
10145 add_anchor_token(T___label__);
10146 add_anchor_token(T___real__);
10147 add_anchor_token(T___thread);
10148 add_anchor_token(T_asm);
10149 add_anchor_token(T_auto);
10150 add_anchor_token(T_bool);
10151 add_anchor_token(T_break);
10152 add_anchor_token(T_case);
10153 add_anchor_token(T_char);
10154 add_anchor_token(T_class);
10155 add_anchor_token(T_const);
10156 add_anchor_token(T_const_cast);
10157 add_anchor_token(T_continue);
10158 add_anchor_token(T_default);
10159 add_anchor_token(T_delete);
10160 add_anchor_token(T_double);
10161 add_anchor_token(T_do);
10162 add_anchor_token(T_dynamic_cast);
10163 add_anchor_token(T_enum);
10164 add_anchor_token(T_extern);
10165 add_anchor_token(T_false);
10166 add_anchor_token(T_float);
10167 add_anchor_token(T_for);
10168 add_anchor_token(T_goto);
10169 add_anchor_token(T_if);
10170 add_anchor_token(T_inline);
10171 add_anchor_token(T_int);
10172 add_anchor_token(T_long);
10173 add_anchor_token(T_new);
10174 add_anchor_token(T_operator);
10175 add_anchor_token(T_register);
10176 add_anchor_token(T_reinterpret_cast);
10177 add_anchor_token(T_restrict);
10178 add_anchor_token(T_return);
10179 add_anchor_token(T_short);
10180 add_anchor_token(T_signed);
10181 add_anchor_token(T_sizeof);
10182 add_anchor_token(T_static);
10183 add_anchor_token(T_static_cast);
10184 add_anchor_token(T_struct);
10185 add_anchor_token(T_switch);
10186 add_anchor_token(T_template);
10187 add_anchor_token(T_this);
10188 add_anchor_token(T_throw);
10189 add_anchor_token(T_true);
10190 add_anchor_token(T_try);
10191 add_anchor_token(T_typedef);
10192 add_anchor_token(T_typeid);
10193 add_anchor_token(T_typename);
10194 add_anchor_token(T_typeof);
10195 add_anchor_token(T_union);
10196 add_anchor_token(T_unsigned);
10197 add_anchor_token(T_using);
10198 add_anchor_token(T_void);
10199 add_anchor_token(T_volatile);
10200 add_anchor_token(T_wchar_t);
10201 add_anchor_token(T_while);
10203 statement_t **anchor = &statement->compound.statements;
10204 bool only_decls_so_far = true;
10205 while (token.kind != '}') {
10206 if (token.kind == T_EOF) {
10207 errorf(&statement->base.source_position,
10208 "EOF while parsing compound statement");
10211 statement_t *sub_statement = intern_parse_statement();
10212 if (sub_statement->kind == STATEMENT_ERROR) {
10213 /* an error occurred. if we are at an anchor, return */
10219 if (sub_statement->kind != STATEMENT_DECLARATION) {
10220 only_decls_so_far = false;
10221 } else if (!only_decls_so_far) {
10222 source_position_t const *const pos = &sub_statement->base.source_position;
10223 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10226 *anchor = sub_statement;
10228 while (sub_statement->base.next != NULL)
10229 sub_statement = sub_statement->base.next;
10231 anchor = &sub_statement->base.next;
10235 /* look over all statements again to produce no effect warnings */
10236 if (is_warn_on(WARN_UNUSED_VALUE)) {
10237 statement_t *sub_statement = statement->compound.statements;
10238 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10239 if (sub_statement->kind != STATEMENT_EXPRESSION)
10241 /* don't emit a warning for the last expression in an expression
10242 * statement as it has always an effect */
10243 if (inside_expression_statement && sub_statement->base.next == NULL)
10246 expression_t *expression = sub_statement->expression.expression;
10247 if (!expression_has_effect(expression)) {
10248 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10254 rem_anchor_token(T_while);
10255 rem_anchor_token(T_wchar_t);
10256 rem_anchor_token(T_volatile);
10257 rem_anchor_token(T_void);
10258 rem_anchor_token(T_using);
10259 rem_anchor_token(T_unsigned);
10260 rem_anchor_token(T_union);
10261 rem_anchor_token(T_typeof);
10262 rem_anchor_token(T_typename);
10263 rem_anchor_token(T_typeid);
10264 rem_anchor_token(T_typedef);
10265 rem_anchor_token(T_try);
10266 rem_anchor_token(T_true);
10267 rem_anchor_token(T_throw);
10268 rem_anchor_token(T_this);
10269 rem_anchor_token(T_template);
10270 rem_anchor_token(T_switch);
10271 rem_anchor_token(T_struct);
10272 rem_anchor_token(T_static_cast);
10273 rem_anchor_token(T_static);
10274 rem_anchor_token(T_sizeof);
10275 rem_anchor_token(T_signed);
10276 rem_anchor_token(T_short);
10277 rem_anchor_token(T_return);
10278 rem_anchor_token(T_restrict);
10279 rem_anchor_token(T_reinterpret_cast);
10280 rem_anchor_token(T_register);
10281 rem_anchor_token(T_operator);
10282 rem_anchor_token(T_new);
10283 rem_anchor_token(T_long);
10284 rem_anchor_token(T_int);
10285 rem_anchor_token(T_inline);
10286 rem_anchor_token(T_if);
10287 rem_anchor_token(T_goto);
10288 rem_anchor_token(T_for);
10289 rem_anchor_token(T_float);
10290 rem_anchor_token(T_false);
10291 rem_anchor_token(T_extern);
10292 rem_anchor_token(T_enum);
10293 rem_anchor_token(T_dynamic_cast);
10294 rem_anchor_token(T_do);
10295 rem_anchor_token(T_double);
10296 rem_anchor_token(T_delete);
10297 rem_anchor_token(T_default);
10298 rem_anchor_token(T_continue);
10299 rem_anchor_token(T_const_cast);
10300 rem_anchor_token(T_const);
10301 rem_anchor_token(T_class);
10302 rem_anchor_token(T_char);
10303 rem_anchor_token(T_case);
10304 rem_anchor_token(T_break);
10305 rem_anchor_token(T_bool);
10306 rem_anchor_token(T_auto);
10307 rem_anchor_token(T_asm);
10308 rem_anchor_token(T___thread);
10309 rem_anchor_token(T___real__);
10310 rem_anchor_token(T___label__);
10311 rem_anchor_token(T___imag__);
10312 rem_anchor_token(T___func__);
10313 rem_anchor_token(T___extension__);
10314 rem_anchor_token(T___builtin_va_start);
10315 rem_anchor_token(T___attribute__);
10316 rem_anchor_token(T___alignof__);
10317 rem_anchor_token(T___PRETTY_FUNCTION__);
10318 rem_anchor_token(T___FUNCTION__);
10319 rem_anchor_token(T__Imaginary);
10320 rem_anchor_token(T__Complex);
10321 rem_anchor_token(T__Bool);
10322 rem_anchor_token(T_WIDE_STRING_LITERAL);
10323 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10324 rem_anchor_token(T_STRING_LITERAL);
10325 rem_anchor_token(T_PLUSPLUS);
10326 rem_anchor_token(T_MINUSMINUS);
10327 rem_anchor_token(T_INTEGER);
10328 rem_anchor_token(T_IDENTIFIER);
10329 rem_anchor_token(T_FLOATINGPOINT);
10330 rem_anchor_token(T_COLONCOLON);
10331 rem_anchor_token(T_CHARACTER_CONSTANT);
10332 rem_anchor_token('~');
10333 rem_anchor_token('{');
10334 rem_anchor_token('-');
10335 rem_anchor_token('+');
10336 rem_anchor_token('*');
10337 rem_anchor_token('(');
10338 rem_anchor_token('&');
10339 rem_anchor_token('!');
10340 rem_anchor_token('}');
10348 * Check for unused global static functions and variables
10350 static void check_unused_globals(void)
10352 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10355 for (const entity_t *entity = file_scope->entities; entity != NULL;
10356 entity = entity->base.next) {
10357 if (!is_declaration(entity))
10360 const declaration_t *declaration = &entity->declaration;
10361 if (declaration->used ||
10362 declaration->modifiers & DM_UNUSED ||
10363 declaration->modifiers & DM_USED ||
10364 declaration->storage_class != STORAGE_CLASS_STATIC)
10369 if (entity->kind == ENTITY_FUNCTION) {
10370 /* inhibit warning for static inline functions */
10371 if (entity->function.is_inline)
10374 why = WARN_UNUSED_FUNCTION;
10375 s = entity->function.statement != NULL ? "defined" : "declared";
10377 why = WARN_UNUSED_VARIABLE;
10381 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10385 static void parse_global_asm(void)
10387 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10390 expect('(', end_error);
10392 statement->asms.asm_text = parse_string_literals();
10393 statement->base.next = unit->global_asm;
10394 unit->global_asm = statement;
10396 expect(')', end_error);
10397 expect(';', end_error);
10402 static void parse_linkage_specification(void)
10406 source_position_t const pos = *HERE;
10407 char const *const linkage = parse_string_literals().begin;
10409 linkage_kind_t old_linkage = current_linkage;
10410 linkage_kind_t new_linkage;
10411 if (streq(linkage, "C")) {
10412 new_linkage = LINKAGE_C;
10413 } else if (streq(linkage, "C++")) {
10414 new_linkage = LINKAGE_CXX;
10416 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10417 new_linkage = LINKAGE_C;
10419 current_linkage = new_linkage;
10421 if (next_if('{')) {
10423 expect('}', end_error);
10429 assert(current_linkage == new_linkage);
10430 current_linkage = old_linkage;
10433 static void parse_external(void)
10435 switch (token.kind) {
10437 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10438 parse_linkage_specification();
10440 DECLARATION_START_NO_EXTERN
10442 case T___extension__:
10443 /* tokens below are for implicit int */
10444 case '&': /* & x; -> int& x; (and error later, because C++ has no
10446 case '*': /* * x; -> int* x; */
10447 case '(': /* (x); -> int (x); */
10449 parse_external_declaration();
10455 parse_global_asm();
10459 parse_namespace_definition();
10463 if (!strict_mode) {
10464 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10471 errorf(HERE, "stray %K outside of function", &token);
10472 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10473 eat_until_matching_token(token.kind);
10479 static void parse_externals(void)
10481 add_anchor_token('}');
10482 add_anchor_token(T_EOF);
10485 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10486 unsigned short token_anchor_copy[T_LAST_TOKEN];
10487 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10490 while (token.kind != T_EOF && token.kind != '}') {
10492 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10493 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10495 /* the anchor set and its copy differs */
10496 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10499 if (in_gcc_extension) {
10500 /* an gcc extension scope was not closed */
10501 internal_errorf(HERE, "Leaked __extension__");
10508 rem_anchor_token(T_EOF);
10509 rem_anchor_token('}');
10513 * Parse a translation unit.
10515 static void parse_translation_unit(void)
10517 add_anchor_token(T_EOF);
10522 if (token.kind == T_EOF)
10525 errorf(HERE, "stray %K outside of function", &token);
10526 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10527 eat_until_matching_token(token.kind);
10532 void set_default_visibility(elf_visibility_tag_t visibility)
10534 default_visibility = visibility;
10540 * @return the translation unit or NULL if errors occurred.
10542 void start_parsing(void)
10544 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10545 label_stack = NEW_ARR_F(stack_entry_t, 0);
10546 diagnostic_count = 0;
10550 print_to_file(stderr);
10552 assert(unit == NULL);
10553 unit = allocate_ast_zero(sizeof(unit[0]));
10555 assert(file_scope == NULL);
10556 file_scope = &unit->scope;
10558 assert(current_scope == NULL);
10559 scope_push(&unit->scope);
10561 create_gnu_builtins();
10563 create_microsoft_intrinsics();
10566 translation_unit_t *finish_parsing(void)
10568 assert(current_scope == &unit->scope);
10571 assert(file_scope == &unit->scope);
10572 check_unused_globals();
10575 DEL_ARR_F(environment_stack);
10576 DEL_ARR_F(label_stack);
10578 translation_unit_t *result = unit;
10583 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10584 * are given length one. */
10585 static void complete_incomplete_arrays(void)
10587 size_t n = ARR_LEN(incomplete_arrays);
10588 for (size_t i = 0; i != n; ++i) {
10589 declaration_t *const decl = incomplete_arrays[i];
10590 type_t *const type = skip_typeref(decl->type);
10592 if (!is_type_incomplete(type))
10595 source_position_t const *const pos = &decl->base.source_position;
10596 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10598 type_t *const new_type = duplicate_type(type);
10599 new_type->array.size_constant = true;
10600 new_type->array.has_implicit_size = true;
10601 new_type->array.size = 1;
10603 type_t *const result = identify_new_type(new_type);
10605 decl->type = result;
10609 void prepare_main_collect2(entity_t *entity)
10611 PUSH_SCOPE(&entity->function.statement->compound.scope);
10613 // create call to __main
10614 symbol_t *symbol = symbol_table_insert("__main");
10615 entity_t *subsubmain_ent
10616 = create_implicit_function(symbol, &builtin_source_position);
10618 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10619 type_t *ftype = subsubmain_ent->declaration.type;
10620 ref->base.source_position = builtin_source_position;
10621 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10622 ref->reference.entity = subsubmain_ent;
10624 expression_t *call = allocate_expression_zero(EXPR_CALL);
10625 call->base.source_position = builtin_source_position;
10626 call->base.type = type_void;
10627 call->call.function = ref;
10629 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10630 expr_statement->base.source_position = builtin_source_position;
10631 expr_statement->expression.expression = call;
10633 statement_t *statement = entity->function.statement;
10634 assert(statement->kind == STATEMENT_COMPOUND);
10635 compound_statement_t *compounds = &statement->compound;
10637 expr_statement->base.next = compounds->statements;
10638 compounds->statements = expr_statement;
10645 lookahead_bufpos = 0;
10646 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10649 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10650 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10651 parse_translation_unit();
10652 complete_incomplete_arrays();
10653 DEL_ARR_F(incomplete_arrays);
10654 incomplete_arrays = NULL;
10658 * Initialize the parser.
10660 void init_parser(void)
10662 sym_anonymous = symbol_table_insert("<anonymous>");
10664 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10666 init_expression_parsers();
10667 obstack_init(&temp_obst);
10671 * Terminate the parser.
10673 void exit_parser(void)
10675 obstack_free(&temp_obst, NULL);