2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = 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 = LINKAGE_INVALID;
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 a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_PARENT(stmt) \
115 statement_t *const prev_parent = current_parent; \
116 ((void)(current_parent = (stmt)))
117 #define POP_PARENT ((void)(current_parent = prev_parent))
119 /** special symbol used for anonymous entities. */
120 static symbol_t *sym_anonymous = NULL;
122 /** The token anchor set */
123 static unsigned char token_anchor_set[T_LAST_TOKEN];
125 /** The current source position. */
126 #define HERE (&token.source_position)
128 /** true if we are in GCC mode. */
129 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
131 static statement_t *parse_compound_statement(bool inside_expression_statement);
132 static statement_t *parse_statement(void);
134 static expression_t *parse_subexpression(precedence_t);
135 static expression_t *parse_expression(void);
136 static type_t *parse_typename(void);
137 static void parse_externals(void);
138 static void parse_external(void);
140 static void parse_compound_type_entries(compound_t *compound_declaration);
142 static void check_call_argument(type_t *expected_type,
143 call_argument_t *argument, unsigned pos);
145 typedef enum declarator_flags_t {
147 DECL_MAY_BE_ABSTRACT = 1U << 0,
148 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
149 DECL_IS_PARAMETER = 1U << 2
150 } declarator_flags_t;
152 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
153 declarator_flags_t flags);
155 static void semantic_comparison(binary_expression_t *expression);
157 #define STORAGE_CLASSES \
158 STORAGE_CLASSES_NO_EXTERN \
161 #define STORAGE_CLASSES_NO_EXTERN \
168 #define TYPE_QUALIFIERS \
173 case T__forceinline: \
174 case T___attribute__:
176 #define COMPLEX_SPECIFIERS \
178 #define IMAGINARY_SPECIFIERS \
181 #define TYPE_SPECIFIERS \
183 case T___builtin_va_list: \
208 #define DECLARATION_START \
213 #define DECLARATION_START_NO_EXTERN \
214 STORAGE_CLASSES_NO_EXTERN \
218 #define EXPRESSION_START \
227 case T_CHARACTER_CONSTANT: \
228 case T_FLOATINGPOINT: \
229 case T_FLOATINGPOINT_HEXADECIMAL: \
231 case T_INTEGER_HEXADECIMAL: \
232 case T_INTEGER_OCTAL: \
235 case T_STRING_LITERAL: \
236 case T_WIDE_CHARACTER_CONSTANT: \
237 case T_WIDE_STRING_LITERAL: \
238 case T___FUNCDNAME__: \
239 case T___FUNCSIG__: \
240 case T___FUNCTION__: \
241 case T___PRETTY_FUNCTION__: \
242 case T___alignof__: \
243 case T___builtin_classify_type: \
244 case T___builtin_constant_p: \
245 case T___builtin_isgreater: \
246 case T___builtin_isgreaterequal: \
247 case T___builtin_isless: \
248 case T___builtin_islessequal: \
249 case T___builtin_islessgreater: \
250 case T___builtin_isunordered: \
251 case T___builtin_offsetof: \
252 case T___builtin_va_arg: \
253 case T___builtin_va_copy: \
254 case T___builtin_va_start: \
265 * Returns the size of a statement node.
267 * @param kind the statement kind
269 static size_t get_statement_struct_size(statement_kind_t kind)
271 static const size_t sizes[] = {
272 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
273 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
274 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
275 [STATEMENT_RETURN] = sizeof(return_statement_t),
276 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
277 [STATEMENT_IF] = sizeof(if_statement_t),
278 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
279 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
280 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
281 [STATEMENT_BREAK] = sizeof(statement_base_t),
282 [STATEMENT_GOTO] = sizeof(goto_statement_t),
283 [STATEMENT_LABEL] = sizeof(label_statement_t),
284 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
285 [STATEMENT_WHILE] = sizeof(while_statement_t),
286 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
287 [STATEMENT_FOR] = sizeof(for_statement_t),
288 [STATEMENT_ASM] = sizeof(asm_statement_t),
289 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
290 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
292 assert((size_t)kind < lengthof(sizes));
293 assert(sizes[kind] != 0);
298 * Returns the size of an expression node.
300 * @param kind the expression kind
302 static size_t get_expression_struct_size(expression_kind_t kind)
304 static const size_t sizes[] = {
305 [EXPR_INVALID] = sizeof(expression_base_t),
306 [EXPR_REFERENCE] = sizeof(reference_expression_t),
307 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
308 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
309 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
310 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
311 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
312 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
314 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
316 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
317 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
318 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
319 [EXPR_CALL] = sizeof(call_expression_t),
320 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
321 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
322 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
323 [EXPR_SELECT] = sizeof(select_expression_t),
324 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
325 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
326 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
327 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
328 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
329 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
330 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
331 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
332 [EXPR_VA_START] = sizeof(va_start_expression_t),
333 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
334 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
335 [EXPR_STATEMENT] = sizeof(statement_expression_t),
336 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
338 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
339 return sizes[EXPR_UNARY_FIRST];
341 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
342 return sizes[EXPR_BINARY_FIRST];
344 assert((size_t)kind < lengthof(sizes));
345 assert(sizes[kind] != 0);
350 * Allocate a statement node of given kind and initialize all
351 * fields with zero. Sets its source position to the position
352 * of the current token.
354 static statement_t *allocate_statement_zero(statement_kind_t kind)
356 size_t size = get_statement_struct_size(kind);
357 statement_t *res = allocate_ast_zero(size);
359 res->base.kind = kind;
360 res->base.parent = current_parent;
361 res->base.source_position = token.source_position;
366 * Allocate an expression node of given kind and initialize all
369 * @param kind the kind of the expression to allocate
371 static expression_t *allocate_expression_zero(expression_kind_t kind)
373 size_t size = get_expression_struct_size(kind);
374 expression_t *res = allocate_ast_zero(size);
376 res->base.kind = kind;
377 res->base.type = type_error_type;
378 res->base.source_position = token.source_position;
383 * Creates a new invalid expression at the source position
384 * of the current token.
386 static expression_t *create_invalid_expression(void)
388 return allocate_expression_zero(EXPR_INVALID);
392 * Creates a new invalid statement.
394 static statement_t *create_invalid_statement(void)
396 return allocate_statement_zero(STATEMENT_INVALID);
400 * Allocate a new empty statement.
402 static statement_t *create_empty_statement(void)
404 return allocate_statement_zero(STATEMENT_EMPTY);
407 static function_parameter_t *allocate_parameter(type_t *const type)
409 function_parameter_t *const param
410 = obstack_alloc(type_obst, sizeof(*param));
411 memset(param, 0, sizeof(*param));
417 * Returns the size of an initializer node.
419 * @param kind the initializer kind
421 static size_t get_initializer_size(initializer_kind_t kind)
423 static const size_t sizes[] = {
424 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
425 [INITIALIZER_STRING] = sizeof(initializer_string_t),
426 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
427 [INITIALIZER_LIST] = sizeof(initializer_list_t),
428 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
430 assert((size_t)kind < lengthof(sizes));
431 assert(sizes[kind] != 0);
436 * Allocate an initializer node of given kind and initialize all
439 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
441 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
448 * Returns the index of the top element of the environment stack.
450 static size_t environment_top(void)
452 return ARR_LEN(environment_stack);
456 * Returns the index of the top element of the global label stack.
458 static size_t label_top(void)
460 return ARR_LEN(label_stack);
464 * Return the next token.
466 static inline void next_token(void)
468 token = lookahead_buffer[lookahead_bufpos];
469 lookahead_buffer[lookahead_bufpos] = lexer_token;
472 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
475 print_token(stderr, &token);
476 fprintf(stderr, "\n");
480 static inline bool next_if(int const type)
482 if (token.type == type) {
491 * Return the next token with a given lookahead.
493 static inline const token_t *look_ahead(size_t num)
495 assert(0 < num && num <= MAX_LOOKAHEAD);
496 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
497 return &lookahead_buffer[pos];
501 * Adds a token type to the token type anchor set (a multi-set).
503 static void add_anchor_token(int token_type)
505 assert(0 <= token_type && token_type < T_LAST_TOKEN);
506 ++token_anchor_set[token_type];
510 * Set the number of tokens types of the given type
511 * to zero and return the old count.
513 static int save_and_reset_anchor_state(int token_type)
515 assert(0 <= token_type && token_type < T_LAST_TOKEN);
516 int count = token_anchor_set[token_type];
517 token_anchor_set[token_type] = 0;
522 * Restore the number of token types to the given count.
524 static void restore_anchor_state(int token_type, int count)
526 assert(0 <= token_type && token_type < T_LAST_TOKEN);
527 token_anchor_set[token_type] = count;
531 * Remove a token type from the token type anchor set (a multi-set).
533 static void rem_anchor_token(int token_type)
535 assert(0 <= token_type && token_type < T_LAST_TOKEN);
536 assert(token_anchor_set[token_type] != 0);
537 --token_anchor_set[token_type];
541 * Return true if the token type of the current token is
544 static bool at_anchor(void)
548 return token_anchor_set[token.type];
552 * Eat tokens until a matching token type is found.
554 static void eat_until_matching_token(int type)
558 case '(': end_token = ')'; break;
559 case '{': end_token = '}'; break;
560 case '[': end_token = ']'; break;
561 default: end_token = type; break;
564 unsigned parenthesis_count = 0;
565 unsigned brace_count = 0;
566 unsigned bracket_count = 0;
567 while (token.type != end_token ||
568 parenthesis_count != 0 ||
570 bracket_count != 0) {
571 switch (token.type) {
573 case '(': ++parenthesis_count; break;
574 case '{': ++brace_count; break;
575 case '[': ++bracket_count; break;
578 if (parenthesis_count > 0)
588 if (bracket_count > 0)
591 if (token.type == end_token &&
592 parenthesis_count == 0 &&
606 * Eat input tokens until an anchor is found.
608 static void eat_until_anchor(void)
610 while (token_anchor_set[token.type] == 0) {
611 if (token.type == '(' || token.type == '{' || token.type == '[')
612 eat_until_matching_token(token.type);
618 * Eat a whole block from input tokens.
620 static void eat_block(void)
622 eat_until_matching_token('{');
626 #define eat(token_type) (assert(token.type == (token_type)), next_token())
629 * Report a parse error because an expected token was not found.
632 #if defined __GNUC__ && __GNUC__ >= 4
633 __attribute__((sentinel))
635 void parse_error_expected(const char *message, ...)
637 if (message != NULL) {
638 errorf(HERE, "%s", message);
641 va_start(ap, message);
642 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
647 * Report an incompatible type.
649 static void type_error_incompatible(const char *msg,
650 const source_position_t *source_position, type_t *type1, type_t *type2)
652 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
657 * Expect the current token is the expected token.
658 * If not, generate an error, eat the current statement,
659 * and goto the error_label label.
661 #define expect(expected, error_label) \
663 if (UNLIKELY(token.type != (expected))) { \
664 parse_error_expected(NULL, (expected), NULL); \
665 add_anchor_token(expected); \
666 eat_until_anchor(); \
667 next_if((expected)); \
668 rem_anchor_token(expected); \
675 * Push a given scope on the scope stack and make it the
678 static scope_t *scope_push(scope_t *new_scope)
680 if (current_scope != NULL) {
681 new_scope->depth = current_scope->depth + 1;
684 scope_t *old_scope = current_scope;
685 current_scope = new_scope;
690 * Pop the current scope from the scope stack.
692 static void scope_pop(scope_t *old_scope)
694 current_scope = old_scope;
698 * Search an entity by its symbol in a given namespace.
700 static entity_t *get_entity(const symbol_t *const symbol,
701 namespace_tag_t namespc)
703 assert(namespc != NAMESPACE_INVALID);
704 entity_t *entity = symbol->entity;
705 for (; entity != NULL; entity = entity->base.symbol_next) {
706 if ((namespace_tag_t)entity->base.namespc == namespc)
713 /* §6.2.3:1 24) There is only one name space for tags even though three are
715 static entity_t *get_tag(symbol_t const *const symbol,
716 entity_kind_tag_t const kind)
718 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
719 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
721 "'%Y' defined as wrong kind of tag (previous definition %P)",
722 symbol, &entity->base.source_position);
729 * pushs an entity on the environment stack and links the corresponding symbol
732 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
734 symbol_t *symbol = entity->base.symbol;
735 entity_namespace_t namespc = entity->base.namespc;
736 assert(namespc != NAMESPACE_INVALID);
738 /* replace/add entity into entity list of the symbol */
741 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
746 /* replace an entry? */
747 if (iter->base.namespc == namespc) {
748 entity->base.symbol_next = iter->base.symbol_next;
754 /* remember old declaration */
756 entry.symbol = symbol;
757 entry.old_entity = iter;
758 entry.namespc = namespc;
759 ARR_APP1(stack_entry_t, *stack_ptr, entry);
763 * Push an entity on the environment stack.
765 static void environment_push(entity_t *entity)
767 assert(entity->base.source_position.input_name != NULL);
768 assert(entity->base.parent_scope != NULL);
769 stack_push(&environment_stack, entity);
773 * Push a declaration on the global label stack.
775 * @param declaration the declaration
777 static void label_push(entity_t *label)
779 /* we abuse the parameters scope as parent for the labels */
780 label->base.parent_scope = ¤t_function->parameters;
781 stack_push(&label_stack, label);
785 * pops symbols from the environment stack until @p new_top is the top element
787 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
789 stack_entry_t *stack = *stack_ptr;
790 size_t top = ARR_LEN(stack);
793 assert(new_top <= top);
797 for (i = top; i > new_top; --i) {
798 stack_entry_t *entry = &stack[i - 1];
800 entity_t *old_entity = entry->old_entity;
801 symbol_t *symbol = entry->symbol;
802 entity_namespace_t namespc = entry->namespc;
804 /* replace with old_entity/remove */
807 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
809 assert(iter != NULL);
810 /* replace an entry? */
811 if (iter->base.namespc == namespc)
815 /* restore definition from outer scopes (if there was one) */
816 if (old_entity != NULL) {
817 old_entity->base.symbol_next = iter->base.symbol_next;
818 *anchor = old_entity;
820 /* remove entry from list */
821 *anchor = iter->base.symbol_next;
825 ARR_SHRINKLEN(*stack_ptr, new_top);
829 * Pop all entries from the environment stack until the new_top
832 * @param new_top the new stack top
834 static void environment_pop_to(size_t new_top)
836 stack_pop_to(&environment_stack, new_top);
840 * Pop all entries from the global label stack until the new_top
843 * @param new_top the new stack top
845 static void label_pop_to(size_t new_top)
847 stack_pop_to(&label_stack, new_top);
850 static int get_akind_rank(atomic_type_kind_t akind)
856 * Return the type rank for an atomic type.
858 static int get_rank(const type_t *type)
860 assert(!is_typeref(type));
861 if (type->kind == TYPE_ENUM)
862 return get_akind_rank(type->enumt.akind);
864 assert(type->kind == TYPE_ATOMIC);
865 return get_akind_rank(type->atomic.akind);
869 * §6.3.1.1:2 Do integer promotion for a given type.
871 * @param type the type to promote
872 * @return the promoted type
874 static type_t *promote_integer(type_t *type)
876 if (type->kind == TYPE_BITFIELD)
877 type = type->bitfield.base_type;
879 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
886 * Create a cast expression.
888 * @param expression the expression to cast
889 * @param dest_type the destination type
891 static expression_t *create_cast_expression(expression_t *expression,
894 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
896 cast->unary.value = expression;
897 cast->base.type = dest_type;
903 * Check if a given expression represents a null pointer constant.
905 * @param expression the expression to check
907 static bool is_null_pointer_constant(const expression_t *expression)
909 /* skip void* cast */
910 if (expression->kind == EXPR_UNARY_CAST ||
911 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
912 type_t *const type = skip_typeref(expression->base.type);
913 if (types_compatible(type, type_void_ptr))
914 expression = expression->unary.value;
917 type_t *const type = skip_typeref(expression->base.type);
918 if (!is_type_integer(type))
920 switch (is_constant_expression(expression)) {
921 case EXPR_CLASS_ERROR: return true;
922 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
923 default: return false;
928 * Create an implicit cast expression.
930 * @param expression the expression to cast
931 * @param dest_type the destination type
933 static expression_t *create_implicit_cast(expression_t *expression,
936 type_t *const source_type = expression->base.type;
938 if (source_type == dest_type)
941 return create_cast_expression(expression, dest_type);
944 typedef enum assign_error_t {
946 ASSIGN_ERROR_INCOMPATIBLE,
947 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
948 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
949 ASSIGN_WARNING_POINTER_FROM_INT,
950 ASSIGN_WARNING_INT_FROM_POINTER
953 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)
955 type_t *const orig_type_right = right->base.type;
956 type_t *const type_left = skip_typeref(orig_type_left);
957 type_t *const type_right = skip_typeref(orig_type_right);
962 case ASSIGN_ERROR_INCOMPATIBLE:
963 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
966 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
967 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
968 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
970 /* the left type has all qualifiers from the right type */
971 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
972 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);
976 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
977 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
980 case ASSIGN_WARNING_POINTER_FROM_INT:
981 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
984 case ASSIGN_WARNING_INT_FROM_POINTER:
985 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
989 panic("invalid error value");
993 /** Implements the rules from §6.5.16.1 */
994 static assign_error_t semantic_assign(type_t *orig_type_left,
995 const expression_t *const right)
997 type_t *const orig_type_right = right->base.type;
998 type_t *const type_left = skip_typeref(orig_type_left);
999 type_t *const type_right = skip_typeref(orig_type_right);
1001 if (is_type_pointer(type_left)) {
1002 if (is_null_pointer_constant(right)) {
1003 return ASSIGN_SUCCESS;
1004 } else if (is_type_pointer(type_right)) {
1005 type_t *points_to_left
1006 = skip_typeref(type_left->pointer.points_to);
1007 type_t *points_to_right
1008 = skip_typeref(type_right->pointer.points_to);
1009 assign_error_t res = ASSIGN_SUCCESS;
1011 /* the left type has all qualifiers from the right type */
1012 unsigned missing_qualifiers
1013 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1014 if (missing_qualifiers != 0) {
1015 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1018 points_to_left = get_unqualified_type(points_to_left);
1019 points_to_right = get_unqualified_type(points_to_right);
1021 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1024 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1025 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1026 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1029 if (!types_compatible(points_to_left, points_to_right)) {
1030 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1034 } else if (is_type_integer(type_right)) {
1035 return ASSIGN_WARNING_POINTER_FROM_INT;
1037 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1038 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1039 && is_type_pointer(type_right))) {
1040 return ASSIGN_SUCCESS;
1041 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1042 type_t *const unqual_type_left = get_unqualified_type(type_left);
1043 type_t *const unqual_type_right = get_unqualified_type(type_right);
1044 if (types_compatible(unqual_type_left, unqual_type_right)) {
1045 return ASSIGN_SUCCESS;
1047 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1048 return ASSIGN_WARNING_INT_FROM_POINTER;
1051 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1052 return ASSIGN_SUCCESS;
1054 return ASSIGN_ERROR_INCOMPATIBLE;
1057 static expression_t *parse_constant_expression(void)
1059 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1061 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1062 errorf(&result->base.source_position,
1063 "expression '%E' is not constant", result);
1069 static expression_t *parse_assignment_expression(void)
1071 return parse_subexpression(PREC_ASSIGNMENT);
1074 static void warn_string_concat(const source_position_t *pos)
1076 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1079 static string_t parse_string_literals(void)
1081 assert(token.type == T_STRING_LITERAL);
1082 string_t result = token.literal;
1086 while (token.type == T_STRING_LITERAL) {
1087 warn_string_concat(&token.source_position);
1088 result = concat_strings(&result, &token.literal);
1096 * compare two string, ignoring double underscores on the second.
1098 static int strcmp_underscore(const char *s1, const char *s2)
1100 if (s2[0] == '_' && s2[1] == '_') {
1101 size_t len2 = strlen(s2);
1102 size_t len1 = strlen(s1);
1103 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1104 return strncmp(s1, s2+2, len2-4);
1108 return strcmp(s1, s2);
1111 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1113 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1114 attribute->kind = kind;
1119 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1122 * __attribute__ ( ( attribute-list ) )
1126 * attribute_list , attrib
1131 * any-word ( identifier )
1132 * any-word ( identifier , nonempty-expr-list )
1133 * any-word ( expr-list )
1135 * where the "identifier" must not be declared as a type, and
1136 * "any-word" may be any identifier (including one declared as a
1137 * type), a reserved word storage class specifier, type specifier or
1138 * type qualifier. ??? This still leaves out most reserved keywords
1139 * (following the old parser), shouldn't we include them, and why not
1140 * allow identifiers declared as types to start the arguments?
1142 * Matze: this all looks confusing and little systematic, so we're even less
1143 * strict and parse any list of things which are identifiers or
1144 * (assignment-)expressions.
1146 static attribute_argument_t *parse_attribute_arguments(void)
1148 attribute_argument_t *first = NULL;
1149 attribute_argument_t **anchor = &first;
1150 if (token.type != ')') do {
1151 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1153 /* is it an identifier */
1154 if (token.type == T_IDENTIFIER
1155 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1156 symbol_t *symbol = token.symbol;
1157 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1158 argument->v.symbol = symbol;
1161 /* must be an expression */
1162 expression_t *expression = parse_assignment_expression();
1164 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1165 argument->v.expression = expression;
1168 /* append argument */
1170 anchor = &argument->next;
1171 } while (next_if(','));
1172 expect(')', end_error);
1181 static attribute_t *parse_attribute_asm(void)
1185 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1187 expect('(', end_error);
1188 attribute->a.arguments = parse_attribute_arguments();
1195 static symbol_t *get_symbol_from_token(void)
1197 switch(token.type) {
1199 return token.symbol;
1228 /* maybe we need more tokens ... add them on demand */
1229 return get_token_symbol(&token);
1235 static attribute_t *parse_attribute_gnu_single(void)
1237 /* parse "any-word" */
1238 symbol_t *symbol = get_symbol_from_token();
1239 if (symbol == NULL) {
1240 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1244 attribute_kind_t kind;
1245 char const *const name = symbol->string;
1246 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1247 if (kind > ATTRIBUTE_GNU_LAST) {
1248 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1249 /* TODO: we should still save the attribute in the list... */
1250 kind = ATTRIBUTE_UNKNOWN;
1254 const char *attribute_name = get_attribute_name(kind);
1255 if (attribute_name != NULL
1256 && strcmp_underscore(attribute_name, name) == 0)
1262 attribute_t *attribute = allocate_attribute_zero(kind);
1264 /* parse arguments */
1266 attribute->a.arguments = parse_attribute_arguments();
1271 static attribute_t *parse_attribute_gnu(void)
1273 attribute_t *first = NULL;
1274 attribute_t **anchor = &first;
1276 eat(T___attribute__);
1277 expect('(', end_error);
1278 expect('(', end_error);
1280 if (token.type != ')') do {
1281 attribute_t *attribute = parse_attribute_gnu_single();
1282 if (attribute == NULL)
1285 *anchor = attribute;
1286 anchor = &attribute->next;
1287 } while (next_if(','));
1288 expect(')', end_error);
1289 expect(')', end_error);
1295 /** Parse attributes. */
1296 static attribute_t *parse_attributes(attribute_t *first)
1298 attribute_t **anchor = &first;
1300 while (*anchor != NULL)
1301 anchor = &(*anchor)->next;
1303 attribute_t *attribute;
1304 switch (token.type) {
1305 case T___attribute__:
1306 attribute = parse_attribute_gnu();
1307 if (attribute == NULL)
1312 attribute = parse_attribute_asm();
1317 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1322 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1325 case T__forceinline:
1327 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1332 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1336 /* TODO record modifier */
1337 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1339 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1346 *anchor = attribute;
1347 anchor = &attribute->next;
1351 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1353 static entity_t *determine_lhs_ent(expression_t *const expr,
1356 switch (expr->kind) {
1357 case EXPR_REFERENCE: {
1358 entity_t *const entity = expr->reference.entity;
1359 /* we should only find variables as lvalues... */
1360 if (entity->base.kind != ENTITY_VARIABLE
1361 && entity->base.kind != ENTITY_PARAMETER)
1367 case EXPR_ARRAY_ACCESS: {
1368 expression_t *const ref = expr->array_access.array_ref;
1369 entity_t * ent = NULL;
1370 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1371 ent = determine_lhs_ent(ref, lhs_ent);
1374 mark_vars_read(expr->select.compound, lhs_ent);
1376 mark_vars_read(expr->array_access.index, lhs_ent);
1381 if (is_type_compound(skip_typeref(expr->base.type))) {
1382 return determine_lhs_ent(expr->select.compound, lhs_ent);
1384 mark_vars_read(expr->select.compound, lhs_ent);
1389 case EXPR_UNARY_DEREFERENCE: {
1390 expression_t *const val = expr->unary.value;
1391 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1393 return determine_lhs_ent(val->unary.value, lhs_ent);
1395 mark_vars_read(val, NULL);
1401 mark_vars_read(expr, NULL);
1406 #define ENT_ANY ((entity_t*)-1)
1409 * Mark declarations, which are read. This is used to detect variables, which
1413 * x is not marked as "read", because it is only read to calculate its own new
1417 * x and y are not detected as "not read", because multiple variables are
1420 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1422 switch (expr->kind) {
1423 case EXPR_REFERENCE: {
1424 entity_t *const entity = expr->reference.entity;
1425 if (entity->kind != ENTITY_VARIABLE
1426 && entity->kind != ENTITY_PARAMETER)
1429 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1430 if (entity->kind == ENTITY_VARIABLE) {
1431 entity->variable.read = true;
1433 entity->parameter.read = true;
1440 // TODO respect pure/const
1441 mark_vars_read(expr->call.function, NULL);
1442 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1443 mark_vars_read(arg->expression, NULL);
1447 case EXPR_CONDITIONAL:
1448 // TODO lhs_decl should depend on whether true/false have an effect
1449 mark_vars_read(expr->conditional.condition, NULL);
1450 if (expr->conditional.true_expression != NULL)
1451 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1452 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1456 if (lhs_ent == ENT_ANY
1457 && !is_type_compound(skip_typeref(expr->base.type)))
1459 mark_vars_read(expr->select.compound, lhs_ent);
1462 case EXPR_ARRAY_ACCESS: {
1463 expression_t *const ref = expr->array_access.array_ref;
1464 mark_vars_read(ref, lhs_ent);
1465 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1466 mark_vars_read(expr->array_access.index, lhs_ent);
1471 mark_vars_read(expr->va_arge.ap, lhs_ent);
1475 mark_vars_read(expr->va_copye.src, lhs_ent);
1478 case EXPR_UNARY_CAST:
1479 /* Special case: Use void cast to mark a variable as "read" */
1480 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1485 case EXPR_UNARY_THROW:
1486 if (expr->unary.value == NULL)
1489 case EXPR_UNARY_DEREFERENCE:
1490 case EXPR_UNARY_DELETE:
1491 case EXPR_UNARY_DELETE_ARRAY:
1492 if (lhs_ent == ENT_ANY)
1496 case EXPR_UNARY_NEGATE:
1497 case EXPR_UNARY_PLUS:
1498 case EXPR_UNARY_BITWISE_NEGATE:
1499 case EXPR_UNARY_NOT:
1500 case EXPR_UNARY_TAKE_ADDRESS:
1501 case EXPR_UNARY_POSTFIX_INCREMENT:
1502 case EXPR_UNARY_POSTFIX_DECREMENT:
1503 case EXPR_UNARY_PREFIX_INCREMENT:
1504 case EXPR_UNARY_PREFIX_DECREMENT:
1505 case EXPR_UNARY_CAST_IMPLICIT:
1506 case EXPR_UNARY_ASSUME:
1508 mark_vars_read(expr->unary.value, lhs_ent);
1511 case EXPR_BINARY_ADD:
1512 case EXPR_BINARY_SUB:
1513 case EXPR_BINARY_MUL:
1514 case EXPR_BINARY_DIV:
1515 case EXPR_BINARY_MOD:
1516 case EXPR_BINARY_EQUAL:
1517 case EXPR_BINARY_NOTEQUAL:
1518 case EXPR_BINARY_LESS:
1519 case EXPR_BINARY_LESSEQUAL:
1520 case EXPR_BINARY_GREATER:
1521 case EXPR_BINARY_GREATEREQUAL:
1522 case EXPR_BINARY_BITWISE_AND:
1523 case EXPR_BINARY_BITWISE_OR:
1524 case EXPR_BINARY_BITWISE_XOR:
1525 case EXPR_BINARY_LOGICAL_AND:
1526 case EXPR_BINARY_LOGICAL_OR:
1527 case EXPR_BINARY_SHIFTLEFT:
1528 case EXPR_BINARY_SHIFTRIGHT:
1529 case EXPR_BINARY_COMMA:
1530 case EXPR_BINARY_ISGREATER:
1531 case EXPR_BINARY_ISGREATEREQUAL:
1532 case EXPR_BINARY_ISLESS:
1533 case EXPR_BINARY_ISLESSEQUAL:
1534 case EXPR_BINARY_ISLESSGREATER:
1535 case EXPR_BINARY_ISUNORDERED:
1536 mark_vars_read(expr->binary.left, lhs_ent);
1537 mark_vars_read(expr->binary.right, lhs_ent);
1540 case EXPR_BINARY_ASSIGN:
1541 case EXPR_BINARY_MUL_ASSIGN:
1542 case EXPR_BINARY_DIV_ASSIGN:
1543 case EXPR_BINARY_MOD_ASSIGN:
1544 case EXPR_BINARY_ADD_ASSIGN:
1545 case EXPR_BINARY_SUB_ASSIGN:
1546 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1547 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1548 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1549 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1550 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1551 if (lhs_ent == ENT_ANY)
1553 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1554 mark_vars_read(expr->binary.right, lhs_ent);
1559 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1565 case EXPR_STRING_LITERAL:
1566 case EXPR_WIDE_STRING_LITERAL:
1567 case EXPR_COMPOUND_LITERAL: // TODO init?
1569 case EXPR_CLASSIFY_TYPE:
1572 case EXPR_BUILTIN_CONSTANT_P:
1573 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1575 case EXPR_STATEMENT: // TODO
1576 case EXPR_LABEL_ADDRESS:
1577 case EXPR_REFERENCE_ENUM_VALUE:
1581 panic("unhandled expression");
1584 static designator_t *parse_designation(void)
1586 designator_t *result = NULL;
1587 designator_t **anchor = &result;
1590 designator_t *designator;
1591 switch (token.type) {
1593 designator = allocate_ast_zero(sizeof(designator[0]));
1594 designator->source_position = token.source_position;
1596 add_anchor_token(']');
1597 designator->array_index = parse_constant_expression();
1598 rem_anchor_token(']');
1599 expect(']', end_error);
1602 designator = allocate_ast_zero(sizeof(designator[0]));
1603 designator->source_position = token.source_position;
1605 if (token.type != T_IDENTIFIER) {
1606 parse_error_expected("while parsing designator",
1607 T_IDENTIFIER, NULL);
1610 designator->symbol = token.symbol;
1614 expect('=', end_error);
1618 assert(designator != NULL);
1619 *anchor = designator;
1620 anchor = &designator->next;
1626 static initializer_t *initializer_from_string(array_type_t *const type,
1627 const string_t *const string)
1629 /* TODO: check len vs. size of array type */
1632 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1633 initializer->string.string = *string;
1638 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1639 const string_t *const string)
1641 /* TODO: check len vs. size of array type */
1644 initializer_t *const initializer =
1645 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1646 initializer->wide_string.string = *string;
1652 * Build an initializer from a given expression.
1654 static initializer_t *initializer_from_expression(type_t *orig_type,
1655 expression_t *expression)
1657 /* TODO check that expression is a constant expression */
1659 /* §6.7.8.14/15 char array may be initialized by string literals */
1660 type_t *type = skip_typeref(orig_type);
1661 type_t *expr_type_orig = expression->base.type;
1662 type_t *expr_type = skip_typeref(expr_type_orig);
1664 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1665 array_type_t *const array_type = &type->array;
1666 type_t *const element_type = skip_typeref(array_type->element_type);
1668 if (element_type->kind == TYPE_ATOMIC) {
1669 atomic_type_kind_t akind = element_type->atomic.akind;
1670 switch (expression->kind) {
1671 case EXPR_STRING_LITERAL:
1672 if (akind == ATOMIC_TYPE_CHAR
1673 || akind == ATOMIC_TYPE_SCHAR
1674 || akind == ATOMIC_TYPE_UCHAR) {
1675 return initializer_from_string(array_type,
1676 &expression->string_literal.value);
1680 case EXPR_WIDE_STRING_LITERAL: {
1681 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1682 if (get_unqualified_type(element_type) == bare_wchar_type) {
1683 return initializer_from_wide_string(array_type,
1684 &expression->string_literal.value);
1695 assign_error_t error = semantic_assign(type, expression);
1696 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1698 report_assign_error(error, type, expression, "initializer",
1699 &expression->base.source_position);
1701 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1702 result->value.value = create_implicit_cast(expression, type);
1708 * Checks if a given expression can be used as a constant initializer.
1710 static bool is_initializer_constant(const expression_t *expression)
1712 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1713 is_linker_constant(expression) != EXPR_CLASS_VARIABLE;
1717 * Parses an scalar initializer.
1719 * §6.7.8.11; eat {} without warning
1721 static initializer_t *parse_scalar_initializer(type_t *type,
1722 bool must_be_constant)
1724 /* there might be extra {} hierarchies */
1726 if (token.type == '{') {
1727 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1731 } while (token.type == '{');
1734 expression_t *expression = parse_assignment_expression();
1735 mark_vars_read(expression, NULL);
1736 if (must_be_constant && !is_initializer_constant(expression)) {
1737 errorf(&expression->base.source_position,
1738 "initialisation expression '%E' is not constant",
1742 initializer_t *initializer = initializer_from_expression(type, expression);
1744 if (initializer == NULL) {
1745 errorf(&expression->base.source_position,
1746 "expression '%E' (type '%T') doesn't match expected type '%T'",
1747 expression, expression->base.type, type);
1752 bool additional_warning_displayed = false;
1753 while (braces > 0) {
1755 if (token.type != '}') {
1756 if (!additional_warning_displayed) {
1757 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1758 additional_warning_displayed = true;
1769 * An entry in the type path.
1771 typedef struct type_path_entry_t type_path_entry_t;
1772 struct type_path_entry_t {
1773 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1775 size_t index; /**< For array types: the current index. */
1776 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1781 * A type path expression a position inside compound or array types.
1783 typedef struct type_path_t type_path_t;
1784 struct type_path_t {
1785 type_path_entry_t *path; /**< An flexible array containing the current path. */
1786 type_t *top_type; /**< type of the element the path points */
1787 size_t max_index; /**< largest index in outermost array */
1791 * Prints a type path for debugging.
1793 static __attribute__((unused)) void debug_print_type_path(
1794 const type_path_t *path)
1796 size_t len = ARR_LEN(path->path);
1798 for (size_t i = 0; i < len; ++i) {
1799 const type_path_entry_t *entry = & path->path[i];
1801 type_t *type = skip_typeref(entry->type);
1802 if (is_type_compound(type)) {
1803 /* in gcc mode structs can have no members */
1804 if (entry->v.compound_entry == NULL) {
1808 fprintf(stderr, ".%s",
1809 entry->v.compound_entry->base.symbol->string);
1810 } else if (is_type_array(type)) {
1811 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1813 fprintf(stderr, "-INVALID-");
1816 if (path->top_type != NULL) {
1817 fprintf(stderr, " (");
1818 print_type(path->top_type);
1819 fprintf(stderr, ")");
1824 * Return the top type path entry, ie. in a path
1825 * (type).a.b returns the b.
1827 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1829 size_t len = ARR_LEN(path->path);
1831 return &path->path[len-1];
1835 * Enlarge the type path by an (empty) element.
1837 static type_path_entry_t *append_to_type_path(type_path_t *path)
1839 size_t len = ARR_LEN(path->path);
1840 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1842 type_path_entry_t *result = & path->path[len];
1843 memset(result, 0, sizeof(result[0]));
1848 * Descending into a sub-type. Enter the scope of the current top_type.
1850 static void descend_into_subtype(type_path_t *path)
1852 type_t *orig_top_type = path->top_type;
1853 type_t *top_type = skip_typeref(orig_top_type);
1855 type_path_entry_t *top = append_to_type_path(path);
1856 top->type = top_type;
1858 if (is_type_compound(top_type)) {
1859 compound_t *compound = top_type->compound.compound;
1860 entity_t *entry = compound->members.entities;
1862 if (entry != NULL) {
1863 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1864 top->v.compound_entry = &entry->declaration;
1865 path->top_type = entry->declaration.type;
1867 path->top_type = NULL;
1869 } else if (is_type_array(top_type)) {
1871 path->top_type = top_type->array.element_type;
1873 assert(!is_type_valid(top_type));
1878 * Pop an entry from the given type path, ie. returning from
1879 * (type).a.b to (type).a
1881 static void ascend_from_subtype(type_path_t *path)
1883 type_path_entry_t *top = get_type_path_top(path);
1885 path->top_type = top->type;
1887 size_t len = ARR_LEN(path->path);
1888 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1892 * Pop entries from the given type path until the given
1893 * path level is reached.
1895 static void ascend_to(type_path_t *path, size_t top_path_level)
1897 size_t len = ARR_LEN(path->path);
1899 while (len > top_path_level) {
1900 ascend_from_subtype(path);
1901 len = ARR_LEN(path->path);
1905 static bool walk_designator(type_path_t *path, const designator_t *designator,
1906 bool used_in_offsetof)
1908 for (; designator != NULL; designator = designator->next) {
1909 type_path_entry_t *top = get_type_path_top(path);
1910 type_t *orig_type = top->type;
1912 type_t *type = skip_typeref(orig_type);
1914 if (designator->symbol != NULL) {
1915 symbol_t *symbol = designator->symbol;
1916 if (!is_type_compound(type)) {
1917 if (is_type_valid(type)) {
1918 errorf(&designator->source_position,
1919 "'.%Y' designator used for non-compound type '%T'",
1923 top->type = type_error_type;
1924 top->v.compound_entry = NULL;
1925 orig_type = type_error_type;
1927 compound_t *compound = type->compound.compound;
1928 entity_t *iter = compound->members.entities;
1929 for (; iter != NULL; iter = iter->base.next) {
1930 if (iter->base.symbol == symbol) {
1935 errorf(&designator->source_position,
1936 "'%T' has no member named '%Y'", orig_type, symbol);
1939 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1940 if (used_in_offsetof) {
1941 type_t *real_type = skip_typeref(iter->declaration.type);
1942 if (real_type->kind == TYPE_BITFIELD) {
1943 errorf(&designator->source_position,
1944 "offsetof designator '%Y' must not specify bitfield",
1950 top->type = orig_type;
1951 top->v.compound_entry = &iter->declaration;
1952 orig_type = iter->declaration.type;
1955 expression_t *array_index = designator->array_index;
1956 assert(designator->array_index != NULL);
1958 if (!is_type_array(type)) {
1959 if (is_type_valid(type)) {
1960 errorf(&designator->source_position,
1961 "[%E] designator used for non-array type '%T'",
1962 array_index, orig_type);
1967 long index = fold_constant_to_int(array_index);
1968 if (!used_in_offsetof) {
1970 errorf(&designator->source_position,
1971 "array index [%E] must be positive", array_index);
1972 } else if (type->array.size_constant) {
1973 long array_size = type->array.size;
1974 if (index >= array_size) {
1975 errorf(&designator->source_position,
1976 "designator [%E] (%d) exceeds array size %d",
1977 array_index, index, array_size);
1982 top->type = orig_type;
1983 top->v.index = (size_t) index;
1984 orig_type = type->array.element_type;
1986 path->top_type = orig_type;
1988 if (designator->next != NULL) {
1989 descend_into_subtype(path);
1995 static void advance_current_object(type_path_t *path, size_t top_path_level)
1997 type_path_entry_t *top = get_type_path_top(path);
1999 type_t *type = skip_typeref(top->type);
2000 if (is_type_union(type)) {
2001 /* in unions only the first element is initialized */
2002 top->v.compound_entry = NULL;
2003 } else if (is_type_struct(type)) {
2004 declaration_t *entry = top->v.compound_entry;
2006 entity_t *next_entity = entry->base.next;
2007 if (next_entity != NULL) {
2008 assert(is_declaration(next_entity));
2009 entry = &next_entity->declaration;
2014 top->v.compound_entry = entry;
2015 if (entry != NULL) {
2016 path->top_type = entry->type;
2019 } else if (is_type_array(type)) {
2020 assert(is_type_array(type));
2024 if (!type->array.size_constant || top->v.index < type->array.size) {
2028 assert(!is_type_valid(type));
2032 /* we're past the last member of the current sub-aggregate, try if we
2033 * can ascend in the type hierarchy and continue with another subobject */
2034 size_t len = ARR_LEN(path->path);
2036 if (len > top_path_level) {
2037 ascend_from_subtype(path);
2038 advance_current_object(path, top_path_level);
2040 path->top_type = NULL;
2045 * skip any {...} blocks until a closing bracket is reached.
2047 static void skip_initializers(void)
2051 while (token.type != '}') {
2052 if (token.type == T_EOF)
2054 if (token.type == '{') {
2062 static initializer_t *create_empty_initializer(void)
2064 static initializer_t empty_initializer
2065 = { .list = { { INITIALIZER_LIST }, 0 } };
2066 return &empty_initializer;
2070 * Parse a part of an initialiser for a struct or union,
2072 static initializer_t *parse_sub_initializer(type_path_t *path,
2073 type_t *outer_type, size_t top_path_level,
2074 parse_initializer_env_t *env)
2076 if (token.type == '}') {
2077 /* empty initializer */
2078 return create_empty_initializer();
2081 type_t *orig_type = path->top_type;
2082 type_t *type = NULL;
2084 if (orig_type == NULL) {
2085 /* We are initializing an empty compound. */
2087 type = skip_typeref(orig_type);
2090 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2093 designator_t *designator = NULL;
2094 if (token.type == '.' || token.type == '[') {
2095 designator = parse_designation();
2096 goto finish_designator;
2097 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2098 /* GNU-style designator ("identifier: value") */
2099 designator = allocate_ast_zero(sizeof(designator[0]));
2100 designator->source_position = token.source_position;
2101 designator->symbol = token.symbol;
2106 /* reset path to toplevel, evaluate designator from there */
2107 ascend_to(path, top_path_level);
2108 if (!walk_designator(path, designator, false)) {
2109 /* can't continue after designation error */
2113 initializer_t *designator_initializer
2114 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2115 designator_initializer->designator.designator = designator;
2116 ARR_APP1(initializer_t*, initializers, designator_initializer);
2118 orig_type = path->top_type;
2119 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2124 if (token.type == '{') {
2125 if (type != NULL && is_type_scalar(type)) {
2126 sub = parse_scalar_initializer(type, env->must_be_constant);
2129 if (env->entity != NULL) {
2131 "extra brace group at end of initializer for '%Y'",
2132 env->entity->base.symbol);
2134 errorf(HERE, "extra brace group at end of initializer");
2139 descend_into_subtype(path);
2142 add_anchor_token('}');
2143 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2145 rem_anchor_token('}');
2148 ascend_from_subtype(path);
2149 expect('}', end_error);
2151 expect('}', end_error);
2152 goto error_parse_next;
2156 /* must be an expression */
2157 expression_t *expression = parse_assignment_expression();
2158 mark_vars_read(expression, NULL);
2160 if (env->must_be_constant && !is_initializer_constant(expression)) {
2161 errorf(&expression->base.source_position,
2162 "Initialisation expression '%E' is not constant",
2167 /* we are already outside, ... */
2168 if (outer_type == NULL)
2169 goto error_parse_next;
2170 type_t *const outer_type_skip = skip_typeref(outer_type);
2171 if (is_type_compound(outer_type_skip) &&
2172 !outer_type_skip->compound.compound->complete) {
2173 goto error_parse_next;
2176 source_position_t const* const pos = &expression->base.source_position;
2177 if (env->entity != NULL) {
2178 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2180 warningf(WARN_OTHER, pos, "excess elements in initializer");
2182 goto error_parse_next;
2185 /* handle { "string" } special case */
2186 if ((expression->kind == EXPR_STRING_LITERAL
2187 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2188 && outer_type != NULL) {
2189 sub = initializer_from_expression(outer_type, expression);
2192 if (token.type != '}') {
2193 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2195 /* TODO: eat , ... */
2200 /* descend into subtypes until expression matches type */
2202 orig_type = path->top_type;
2203 type = skip_typeref(orig_type);
2205 sub = initializer_from_expression(orig_type, expression);
2209 if (!is_type_valid(type)) {
2212 if (is_type_scalar(type)) {
2213 errorf(&expression->base.source_position,
2214 "expression '%E' doesn't match expected type '%T'",
2215 expression, orig_type);
2219 descend_into_subtype(path);
2223 /* update largest index of top array */
2224 const type_path_entry_t *first = &path->path[0];
2225 type_t *first_type = first->type;
2226 first_type = skip_typeref(first_type);
2227 if (is_type_array(first_type)) {
2228 size_t index = first->v.index;
2229 if (index > path->max_index)
2230 path->max_index = index;
2233 /* append to initializers list */
2234 ARR_APP1(initializer_t*, initializers, sub);
2237 if (token.type == '}') {
2240 expect(',', end_error);
2241 if (token.type == '}') {
2246 /* advance to the next declaration if we are not at the end */
2247 advance_current_object(path, top_path_level);
2248 orig_type = path->top_type;
2249 if (orig_type != NULL)
2250 type = skip_typeref(orig_type);
2256 size_t len = ARR_LEN(initializers);
2257 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2258 initializer_t *result = allocate_ast_zero(size);
2259 result->kind = INITIALIZER_LIST;
2260 result->list.len = len;
2261 memcpy(&result->list.initializers, initializers,
2262 len * sizeof(initializers[0]));
2264 DEL_ARR_F(initializers);
2265 ascend_to(path, top_path_level+1);
2270 skip_initializers();
2271 DEL_ARR_F(initializers);
2272 ascend_to(path, top_path_level+1);
2276 static expression_t *make_size_literal(size_t value)
2278 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2279 literal->base.type = type_size_t;
2282 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2283 literal->literal.value = make_string(buf);
2289 * Parses an initializer. Parsers either a compound literal
2290 * (env->declaration == NULL) or an initializer of a declaration.
2292 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2294 type_t *type = skip_typeref(env->type);
2295 size_t max_index = 0;
2296 initializer_t *result;
2298 if (is_type_scalar(type)) {
2299 result = parse_scalar_initializer(type, env->must_be_constant);
2300 } else if (token.type == '{') {
2304 memset(&path, 0, sizeof(path));
2305 path.top_type = env->type;
2306 path.path = NEW_ARR_F(type_path_entry_t, 0);
2308 descend_into_subtype(&path);
2310 add_anchor_token('}');
2311 result = parse_sub_initializer(&path, env->type, 1, env);
2312 rem_anchor_token('}');
2314 max_index = path.max_index;
2315 DEL_ARR_F(path.path);
2317 expect('}', end_error);
2320 /* parse_scalar_initializer() also works in this case: we simply
2321 * have an expression without {} around it */
2322 result = parse_scalar_initializer(type, env->must_be_constant);
2325 /* §6.7.8:22 array initializers for arrays with unknown size determine
2326 * the array type size */
2327 if (is_type_array(type) && type->array.size_expression == NULL
2328 && result != NULL) {
2330 switch (result->kind) {
2331 case INITIALIZER_LIST:
2332 assert(max_index != 0xdeadbeaf);
2333 size = max_index + 1;
2336 case INITIALIZER_STRING:
2337 size = result->string.string.size;
2340 case INITIALIZER_WIDE_STRING:
2341 size = result->wide_string.string.size;
2344 case INITIALIZER_DESIGNATOR:
2345 case INITIALIZER_VALUE:
2346 /* can happen for parse errors */
2351 internal_errorf(HERE, "invalid initializer type");
2354 type_t *new_type = duplicate_type(type);
2356 new_type->array.size_expression = make_size_literal(size);
2357 new_type->array.size_constant = true;
2358 new_type->array.has_implicit_size = true;
2359 new_type->array.size = size;
2360 env->type = new_type;
2366 static void append_entity(scope_t *scope, entity_t *entity)
2368 if (scope->last_entity != NULL) {
2369 scope->last_entity->base.next = entity;
2371 scope->entities = entity;
2373 entity->base.parent_entity = current_entity;
2374 scope->last_entity = entity;
2378 static compound_t *parse_compound_type_specifier(bool is_struct)
2380 source_position_t const pos = *HERE;
2381 eat(is_struct ? T_struct : T_union);
2383 symbol_t *symbol = NULL;
2384 entity_t *entity = NULL;
2385 attribute_t *attributes = NULL;
2387 if (token.type == T___attribute__) {
2388 attributes = parse_attributes(NULL);
2391 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2392 if (token.type == T_IDENTIFIER) {
2393 /* the compound has a name, check if we have seen it already */
2394 symbol = token.symbol;
2395 entity = get_tag(symbol, kind);
2398 if (entity != NULL) {
2399 if (entity->base.parent_scope != current_scope &&
2400 (token.type == '{' || token.type == ';')) {
2401 /* we're in an inner scope and have a definition. Shadow
2402 * existing definition in outer scope */
2404 } else if (entity->compound.complete && token.type == '{') {
2405 source_position_t const *const ppos = &entity->base.source_position;
2406 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2407 /* clear members in the hope to avoid further errors */
2408 entity->compound.members.entities = NULL;
2411 } else if (token.type != '{') {
2412 char const *const msg =
2413 is_struct ? "while parsing struct type specifier" :
2414 "while parsing union type specifier";
2415 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2420 if (entity == NULL) {
2421 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2422 entity->compound.alignment = 1;
2423 entity->base.source_position = pos;
2424 entity->base.parent_scope = current_scope;
2425 if (symbol != NULL) {
2426 environment_push(entity);
2428 append_entity(current_scope, entity);
2431 if (token.type == '{') {
2432 parse_compound_type_entries(&entity->compound);
2434 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2435 if (symbol == NULL) {
2436 assert(anonymous_entity == NULL);
2437 anonymous_entity = entity;
2441 if (attributes != NULL) {
2442 handle_entity_attributes(attributes, entity);
2445 return &entity->compound;
2448 static void parse_enum_entries(type_t *const enum_type)
2452 if (token.type == '}') {
2453 errorf(HERE, "empty enum not allowed");
2458 add_anchor_token('}');
2460 if (token.type != T_IDENTIFIER) {
2461 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2463 rem_anchor_token('}');
2467 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, token.symbol);
2468 entity->enum_value.enum_type = enum_type;
2469 entity->base.source_position = token.source_position;
2473 expression_t *value = parse_constant_expression();
2475 value = create_implicit_cast(value, enum_type);
2476 entity->enum_value.value = value;
2481 record_entity(entity, false);
2482 } while (next_if(',') && token.type != '}');
2483 rem_anchor_token('}');
2485 expect('}', end_error);
2491 static type_t *parse_enum_specifier(void)
2493 source_position_t const pos = *HERE;
2498 switch (token.type) {
2500 symbol = token.symbol;
2501 entity = get_tag(symbol, ENTITY_ENUM);
2504 if (entity != NULL) {
2505 if (entity->base.parent_scope != current_scope &&
2506 (token.type == '{' || token.type == ';')) {
2507 /* we're in an inner scope and have a definition. Shadow
2508 * existing definition in outer scope */
2510 } else if (entity->enume.complete && token.type == '{') {
2511 source_position_t const *const ppos = &entity->base.source_position;
2512 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2523 parse_error_expected("while parsing enum type specifier",
2524 T_IDENTIFIER, '{', NULL);
2528 if (entity == NULL) {
2529 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2530 entity->base.source_position = pos;
2531 entity->base.parent_scope = current_scope;
2534 type_t *const type = allocate_type_zero(TYPE_ENUM);
2535 type->enumt.enume = &entity->enume;
2536 type->enumt.akind = ATOMIC_TYPE_INT;
2538 if (token.type == '{') {
2539 if (symbol != NULL) {
2540 environment_push(entity);
2542 append_entity(current_scope, entity);
2543 entity->enume.complete = true;
2545 parse_enum_entries(type);
2546 parse_attributes(NULL);
2548 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2549 if (symbol == NULL) {
2550 assert(anonymous_entity == NULL);
2551 anonymous_entity = entity;
2553 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2554 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2561 * if a symbol is a typedef to another type, return true
2563 static bool is_typedef_symbol(symbol_t *symbol)
2565 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2566 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2569 static type_t *parse_typeof(void)
2575 expect('(', end_error);
2576 add_anchor_token(')');
2578 expression_t *expression = NULL;
2580 bool old_type_prop = in_type_prop;
2581 bool old_gcc_extension = in_gcc_extension;
2582 in_type_prop = true;
2584 while (next_if(T___extension__)) {
2585 /* This can be a prefix to a typename or an expression. */
2586 in_gcc_extension = true;
2588 switch (token.type) {
2590 if (is_typedef_symbol(token.symbol)) {
2592 type = parse_typename();
2595 expression = parse_expression();
2596 type = revert_automatic_type_conversion(expression);
2600 in_type_prop = old_type_prop;
2601 in_gcc_extension = old_gcc_extension;
2603 rem_anchor_token(')');
2604 expect(')', end_error);
2606 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2607 typeof_type->typeoft.expression = expression;
2608 typeof_type->typeoft.typeof_type = type;
2615 typedef enum specifiers_t {
2616 SPECIFIER_SIGNED = 1 << 0,
2617 SPECIFIER_UNSIGNED = 1 << 1,
2618 SPECIFIER_LONG = 1 << 2,
2619 SPECIFIER_INT = 1 << 3,
2620 SPECIFIER_DOUBLE = 1 << 4,
2621 SPECIFIER_CHAR = 1 << 5,
2622 SPECIFIER_WCHAR_T = 1 << 6,
2623 SPECIFIER_SHORT = 1 << 7,
2624 SPECIFIER_LONG_LONG = 1 << 8,
2625 SPECIFIER_FLOAT = 1 << 9,
2626 SPECIFIER_BOOL = 1 << 10,
2627 SPECIFIER_VOID = 1 << 11,
2628 SPECIFIER_INT8 = 1 << 12,
2629 SPECIFIER_INT16 = 1 << 13,
2630 SPECIFIER_INT32 = 1 << 14,
2631 SPECIFIER_INT64 = 1 << 15,
2632 SPECIFIER_INT128 = 1 << 16,
2633 SPECIFIER_COMPLEX = 1 << 17,
2634 SPECIFIER_IMAGINARY = 1 << 18,
2637 static type_t *get_typedef_type(symbol_t *symbol)
2639 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2640 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2643 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2644 type->typedeft.typedefe = &entity->typedefe;
2649 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2651 expect('(', end_error);
2653 attribute_property_argument_t *property
2654 = allocate_ast_zero(sizeof(*property));
2657 if (token.type != T_IDENTIFIER) {
2658 parse_error_expected("while parsing property declspec",
2659 T_IDENTIFIER, NULL);
2664 symbol_t *symbol = token.symbol;
2665 if (strcmp(symbol->string, "put") == 0) {
2666 prop = &property->put_symbol;
2667 } else if (strcmp(symbol->string, "get") == 0) {
2668 prop = &property->get_symbol;
2670 errorf(HERE, "expected put or get in property declspec");
2674 expect('=', end_error);
2675 if (token.type != T_IDENTIFIER) {
2676 parse_error_expected("while parsing property declspec",
2677 T_IDENTIFIER, NULL);
2681 *prop = token.symbol;
2683 } while (next_if(','));
2685 attribute->a.property = property;
2687 expect(')', end_error);
2693 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2695 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2696 if (next_if(T_restrict)) {
2697 kind = ATTRIBUTE_MS_RESTRICT;
2698 } else if (token.type == T_IDENTIFIER) {
2699 const char *name = token.symbol->string;
2700 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2702 const char *attribute_name = get_attribute_name(k);
2703 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2709 if (kind == ATTRIBUTE_UNKNOWN) {
2710 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2714 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2718 attribute_t *attribute = allocate_attribute_zero(kind);
2720 if (kind == ATTRIBUTE_MS_PROPERTY) {
2721 return parse_attribute_ms_property(attribute);
2724 /* parse arguments */
2726 attribute->a.arguments = parse_attribute_arguments();
2731 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2735 expect('(', end_error);
2740 add_anchor_token(')');
2742 attribute_t **anchor = &first;
2744 while (*anchor != NULL)
2745 anchor = &(*anchor)->next;
2747 attribute_t *attribute
2748 = parse_microsoft_extended_decl_modifier_single();
2749 if (attribute == NULL)
2752 *anchor = attribute;
2753 anchor = &attribute->next;
2754 } while (next_if(','));
2756 rem_anchor_token(')');
2757 expect(')', end_error);
2761 rem_anchor_token(')');
2765 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2767 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2768 entity->base.source_position = *HERE;
2769 if (is_declaration(entity)) {
2770 entity->declaration.type = type_error_type;
2771 entity->declaration.implicit = true;
2772 } else if (kind == ENTITY_TYPEDEF) {
2773 entity->typedefe.type = type_error_type;
2774 entity->typedefe.builtin = true;
2776 if (kind != ENTITY_COMPOUND_MEMBER)
2777 record_entity(entity, false);
2781 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2783 type_t *type = NULL;
2784 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2785 unsigned type_specifiers = 0;
2786 bool newtype = false;
2787 bool saw_error = false;
2788 bool old_gcc_extension = in_gcc_extension;
2790 memset(specifiers, 0, sizeof(*specifiers));
2791 specifiers->source_position = token.source_position;
2794 specifiers->attributes = parse_attributes(specifiers->attributes);
2796 switch (token.type) {
2798 #define MATCH_STORAGE_CLASS(token, class) \
2800 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2801 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2803 specifiers->storage_class = class; \
2804 if (specifiers->thread_local) \
2805 goto check_thread_storage_class; \
2809 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2810 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2811 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2812 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2813 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2816 specifiers->attributes
2817 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2821 if (specifiers->thread_local) {
2822 errorf(HERE, "duplicate '__thread'");
2824 specifiers->thread_local = true;
2825 check_thread_storage_class:
2826 switch (specifiers->storage_class) {
2827 case STORAGE_CLASS_EXTERN:
2828 case STORAGE_CLASS_NONE:
2829 case STORAGE_CLASS_STATIC:
2833 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2834 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2835 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2836 wrong_thread_storage_class:
2837 errorf(HERE, "'__thread' used with '%s'", wrong);
2844 /* type qualifiers */
2845 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2847 qualifiers |= qualifier; \
2851 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2852 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2853 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2854 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2855 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2856 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2857 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2858 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2860 case T___extension__:
2862 in_gcc_extension = true;
2865 /* type specifiers */
2866 #define MATCH_SPECIFIER(token, specifier, name) \
2868 if (type_specifiers & specifier) { \
2869 errorf(HERE, "multiple " name " type specifiers given"); \
2871 type_specifiers |= specifier; \
2876 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2877 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2878 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2879 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2880 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2881 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2882 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2883 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2884 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2885 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2886 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2887 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2888 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2889 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2890 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2891 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2892 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2893 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2897 specifiers->is_inline = true;
2901 case T__forceinline:
2903 specifiers->modifiers |= DM_FORCEINLINE;
2908 if (type_specifiers & SPECIFIER_LONG_LONG) {
2909 errorf(HERE, "too many long type specifiers given");
2910 } else if (type_specifiers & SPECIFIER_LONG) {
2911 type_specifiers |= SPECIFIER_LONG_LONG;
2913 type_specifiers |= SPECIFIER_LONG;
2918 #define CHECK_DOUBLE_TYPE() \
2919 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2922 CHECK_DOUBLE_TYPE();
2923 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2925 type->compound.compound = parse_compound_type_specifier(true);
2928 CHECK_DOUBLE_TYPE();
2929 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2930 type->compound.compound = parse_compound_type_specifier(false);
2933 CHECK_DOUBLE_TYPE();
2934 type = parse_enum_specifier();
2937 CHECK_DOUBLE_TYPE();
2938 type = parse_typeof();
2940 case T___builtin_va_list:
2941 CHECK_DOUBLE_TYPE();
2942 type = duplicate_type(type_valist);
2946 case T_IDENTIFIER: {
2947 /* only parse identifier if we haven't found a type yet */
2948 if (type != NULL || type_specifiers != 0) {
2949 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2950 * declaration, so it doesn't generate errors about expecting '(' or
2952 switch (look_ahead(1)->type) {
2959 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2963 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2968 goto finish_specifiers;
2972 type_t *const typedef_type = get_typedef_type(token.symbol);
2973 if (typedef_type == NULL) {
2974 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2975 * declaration, so it doesn't generate 'implicit int' followed by more
2976 * errors later on. */
2977 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
2983 errorf(HERE, "%K does not name a type", &token);
2986 create_error_entity(token.symbol, ENTITY_TYPEDEF);
2988 type = allocate_type_zero(TYPE_TYPEDEF);
2989 type->typedeft.typedefe = &entity->typedefe;
2997 goto finish_specifiers;
3002 type = typedef_type;
3006 /* function specifier */
3008 goto finish_specifiers;
3013 specifiers->attributes = parse_attributes(specifiers->attributes);
3015 in_gcc_extension = old_gcc_extension;
3017 if (type == NULL || (saw_error && type_specifiers != 0)) {
3018 atomic_type_kind_t atomic_type;
3020 /* match valid basic types */
3021 switch (type_specifiers) {
3022 case SPECIFIER_VOID:
3023 atomic_type = ATOMIC_TYPE_VOID;
3025 case SPECIFIER_WCHAR_T:
3026 atomic_type = ATOMIC_TYPE_WCHAR_T;
3028 case SPECIFIER_CHAR:
3029 atomic_type = ATOMIC_TYPE_CHAR;
3031 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3032 atomic_type = ATOMIC_TYPE_SCHAR;
3034 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3035 atomic_type = ATOMIC_TYPE_UCHAR;
3037 case SPECIFIER_SHORT:
3038 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3039 case SPECIFIER_SHORT | SPECIFIER_INT:
3040 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3041 atomic_type = ATOMIC_TYPE_SHORT;
3043 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3044 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3045 atomic_type = ATOMIC_TYPE_USHORT;
3048 case SPECIFIER_SIGNED:
3049 case SPECIFIER_SIGNED | SPECIFIER_INT:
3050 atomic_type = ATOMIC_TYPE_INT;
3052 case SPECIFIER_UNSIGNED:
3053 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3054 atomic_type = ATOMIC_TYPE_UINT;
3056 case SPECIFIER_LONG:
3057 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3058 case SPECIFIER_LONG | SPECIFIER_INT:
3059 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3060 atomic_type = ATOMIC_TYPE_LONG;
3062 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3063 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3064 atomic_type = ATOMIC_TYPE_ULONG;
3067 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3068 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3069 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3070 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3072 atomic_type = ATOMIC_TYPE_LONGLONG;
3073 goto warn_about_long_long;
3075 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3076 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3078 atomic_type = ATOMIC_TYPE_ULONGLONG;
3079 warn_about_long_long:
3080 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3083 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3084 atomic_type = unsigned_int8_type_kind;
3087 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3088 atomic_type = unsigned_int16_type_kind;
3091 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3092 atomic_type = unsigned_int32_type_kind;
3095 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3096 atomic_type = unsigned_int64_type_kind;
3099 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3100 atomic_type = unsigned_int128_type_kind;
3103 case SPECIFIER_INT8:
3104 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3105 atomic_type = int8_type_kind;
3108 case SPECIFIER_INT16:
3109 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3110 atomic_type = int16_type_kind;
3113 case SPECIFIER_INT32:
3114 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3115 atomic_type = int32_type_kind;
3118 case SPECIFIER_INT64:
3119 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3120 atomic_type = int64_type_kind;
3123 case SPECIFIER_INT128:
3124 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3125 atomic_type = int128_type_kind;
3128 case SPECIFIER_FLOAT:
3129 atomic_type = ATOMIC_TYPE_FLOAT;
3131 case SPECIFIER_DOUBLE:
3132 atomic_type = ATOMIC_TYPE_DOUBLE;
3134 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3135 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3137 case SPECIFIER_BOOL:
3138 atomic_type = ATOMIC_TYPE_BOOL;
3140 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3141 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3142 atomic_type = ATOMIC_TYPE_FLOAT;
3144 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3145 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3146 atomic_type = ATOMIC_TYPE_DOUBLE;
3148 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3149 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3150 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3153 /* invalid specifier combination, give an error message */
3154 source_position_t const* const pos = &specifiers->source_position;
3155 if (type_specifiers == 0) {
3157 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3158 if (!(c_mode & _CXX) && !strict_mode) {
3159 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3160 atomic_type = ATOMIC_TYPE_INT;
3163 errorf(pos, "no type specifiers given in declaration");
3166 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3167 (type_specifiers & SPECIFIER_UNSIGNED)) {
3168 errorf(pos, "signed and unsigned specifiers given");
3169 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3170 errorf(pos, "only integer types can be signed or unsigned");
3172 errorf(pos, "multiple datatypes in declaration");
3178 if (type_specifiers & SPECIFIER_COMPLEX) {
3179 type = allocate_type_zero(TYPE_COMPLEX);
3180 type->complex.akind = atomic_type;
3181 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3182 type = allocate_type_zero(TYPE_IMAGINARY);
3183 type->imaginary.akind = atomic_type;
3185 type = allocate_type_zero(TYPE_ATOMIC);
3186 type->atomic.akind = atomic_type;
3189 } else if (type_specifiers != 0) {
3190 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3193 /* FIXME: check type qualifiers here */
3194 type->base.qualifiers = qualifiers;
3197 type = identify_new_type(type);
3199 type = typehash_insert(type);
3202 if (specifiers->attributes != NULL)
3203 type = handle_type_attributes(specifiers->attributes, type);
3204 specifiers->type = type;
3208 specifiers->type = type_error_type;
3211 static type_qualifiers_t parse_type_qualifiers(void)
3213 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3216 switch (token.type) {
3217 /* type qualifiers */
3218 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3219 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3220 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3221 /* microsoft extended type modifiers */
3222 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3223 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3224 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3225 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3226 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3235 * Parses an K&R identifier list
3237 static void parse_identifier_list(scope_t *scope)
3240 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.symbol);
3241 entity->base.source_position = token.source_position;
3242 /* a K&R parameter has no type, yet */
3246 append_entity(scope, entity);
3247 } while (next_if(',') && token.type == T_IDENTIFIER);
3250 static entity_t *parse_parameter(void)
3252 declaration_specifiers_t specifiers;
3253 parse_declaration_specifiers(&specifiers);
3255 entity_t *entity = parse_declarator(&specifiers,
3256 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3257 anonymous_entity = NULL;
3261 static void semantic_parameter_incomplete(const entity_t *entity)
3263 assert(entity->kind == ENTITY_PARAMETER);
3265 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3266 * list in a function declarator that is part of a
3267 * definition of that function shall not have
3268 * incomplete type. */
3269 type_t *type = skip_typeref(entity->declaration.type);
3270 if (is_type_incomplete(type)) {
3271 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3275 static bool has_parameters(void)
3277 /* func(void) is not a parameter */
3278 if (token.type == T_IDENTIFIER) {
3279 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3282 if (entity->kind != ENTITY_TYPEDEF)
3284 if (skip_typeref(entity->typedefe.type) != type_void)
3286 } else if (token.type != T_void) {
3289 if (look_ahead(1)->type != ')')
3296 * Parses function type parameters (and optionally creates variable_t entities
3297 * for them in a scope)
3299 static void parse_parameters(function_type_t *type, scope_t *scope)
3302 add_anchor_token(')');
3303 int saved_comma_state = save_and_reset_anchor_state(',');
3305 if (token.type == T_IDENTIFIER &&
3306 !is_typedef_symbol(token.symbol)) {
3307 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3308 if (la1_type == ',' || la1_type == ')') {
3309 type->kr_style_parameters = true;
3310 parse_identifier_list(scope);
3311 goto parameters_finished;
3315 if (token.type == ')') {
3316 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3317 if (!(c_mode & _CXX))
3318 type->unspecified_parameters = true;
3319 } else if (has_parameters()) {
3320 function_parameter_t **anchor = &type->parameters;
3322 switch (token.type) {
3325 type->variadic = true;
3326 goto parameters_finished;
3329 case T___extension__:
3332 entity_t *entity = parse_parameter();
3333 if (entity->kind == ENTITY_TYPEDEF) {
3334 errorf(&entity->base.source_position,
3335 "typedef not allowed as function parameter");
3338 assert(is_declaration(entity));
3340 semantic_parameter_incomplete(entity);
3342 function_parameter_t *const parameter =
3343 allocate_parameter(entity->declaration.type);
3345 if (scope != NULL) {
3346 append_entity(scope, entity);
3349 *anchor = parameter;
3350 anchor = ¶meter->next;
3355 goto parameters_finished;
3357 } while (next_if(','));
3360 parameters_finished:
3361 rem_anchor_token(')');
3362 expect(')', end_error);
3365 restore_anchor_state(',', saved_comma_state);
3368 typedef enum construct_type_kind_t {
3371 CONSTRUCT_REFERENCE,
3374 } construct_type_kind_t;
3376 typedef union construct_type_t construct_type_t;
3378 typedef struct construct_type_base_t {
3379 construct_type_kind_t kind;
3380 source_position_t pos;
3381 construct_type_t *next;
3382 } construct_type_base_t;
3384 typedef struct parsed_pointer_t {
3385 construct_type_base_t base;
3386 type_qualifiers_t type_qualifiers;
3387 variable_t *base_variable; /**< MS __based extension. */
3390 typedef struct parsed_reference_t {
3391 construct_type_base_t base;
3392 } parsed_reference_t;
3394 typedef struct construct_function_type_t {
3395 construct_type_base_t base;
3396 type_t *function_type;
3397 } construct_function_type_t;
3399 typedef struct parsed_array_t {
3400 construct_type_base_t base;
3401 type_qualifiers_t type_qualifiers;
3407 union construct_type_t {
3408 construct_type_kind_t kind;
3409 construct_type_base_t base;
3410 parsed_pointer_t pointer;
3411 parsed_reference_t reference;
3412 construct_function_type_t function;
3413 parsed_array_t array;
3416 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3418 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3419 memset(cons, 0, size);
3421 cons->base.pos = *HERE;
3426 static construct_type_t *parse_pointer_declarator(void)
3428 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3430 cons->pointer.type_qualifiers = parse_type_qualifiers();
3431 //cons->pointer.base_variable = base_variable;
3436 /* ISO/IEC 14882:1998(E) §8.3.2 */
3437 static construct_type_t *parse_reference_declarator(void)
3439 if (!(c_mode & _CXX))
3440 errorf(HERE, "references are only available for C++");
3442 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3449 static construct_type_t *parse_array_declarator(void)
3451 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3452 parsed_array_t *const array = &cons->array;
3455 add_anchor_token(']');
3457 bool is_static = next_if(T_static);
3459 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3462 is_static = next_if(T_static);
3464 array->type_qualifiers = type_qualifiers;
3465 array->is_static = is_static;
3467 expression_t *size = NULL;
3468 if (token.type == '*' && look_ahead(1)->type == ']') {
3469 array->is_variable = true;
3471 } else if (token.type != ']') {
3472 size = parse_assignment_expression();
3474 /* §6.7.5.2:1 Array size must have integer type */
3475 type_t *const orig_type = size->base.type;
3476 type_t *const type = skip_typeref(orig_type);
3477 if (!is_type_integer(type) && is_type_valid(type)) {
3478 errorf(&size->base.source_position,
3479 "array size '%E' must have integer type but has type '%T'",
3484 mark_vars_read(size, NULL);
3487 if (is_static && size == NULL)
3488 errorf(&array->base.pos, "static array parameters require a size");
3490 rem_anchor_token(']');
3491 expect(']', end_error);
3498 static construct_type_t *parse_function_declarator(scope_t *scope)
3500 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3502 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3503 function_type_t *ftype = &type->function;
3505 ftype->linkage = current_linkage;
3506 ftype->calling_convention = CC_DEFAULT;
3508 parse_parameters(ftype, scope);
3510 cons->function.function_type = type;
3515 typedef struct parse_declarator_env_t {
3516 bool may_be_abstract : 1;
3517 bool must_be_abstract : 1;
3518 decl_modifiers_t modifiers;
3520 source_position_t source_position;
3522 attribute_t *attributes;
3523 } parse_declarator_env_t;
3526 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3528 /* construct a single linked list of construct_type_t's which describe
3529 * how to construct the final declarator type */
3530 construct_type_t *first = NULL;
3531 construct_type_t **anchor = &first;
3533 env->attributes = parse_attributes(env->attributes);
3536 construct_type_t *type;
3537 //variable_t *based = NULL; /* MS __based extension */
3538 switch (token.type) {
3540 type = parse_reference_declarator();
3544 panic("based not supported anymore");
3549 type = parse_pointer_declarator();
3553 goto ptr_operator_end;
3557 anchor = &type->base.next;
3559 /* TODO: find out if this is correct */
3560 env->attributes = parse_attributes(env->attributes);
3564 construct_type_t *inner_types = NULL;
3566 switch (token.type) {
3568 if (env->must_be_abstract) {
3569 errorf(HERE, "no identifier expected in typename");
3571 env->symbol = token.symbol;
3572 env->source_position = token.source_position;
3578 /* Parenthesized declarator or function declarator? */
3579 token_t const *const la1 = look_ahead(1);
3580 switch (la1->type) {
3582 if (is_typedef_symbol(la1->symbol)) {
3584 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3585 * interpreted as ``function with no parameter specification'', rather
3586 * than redundant parentheses around the omitted identifier. */
3588 /* Function declarator. */
3589 if (!env->may_be_abstract) {
3590 errorf(HERE, "function declarator must have a name");
3597 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3598 /* Paranthesized declarator. */
3600 add_anchor_token(')');
3601 inner_types = parse_inner_declarator(env);
3602 if (inner_types != NULL) {
3603 /* All later declarators only modify the return type */
3604 env->must_be_abstract = true;
3606 rem_anchor_token(')');
3607 expect(')', end_error);
3615 if (env->may_be_abstract)
3617 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3622 construct_type_t **const p = anchor;
3625 construct_type_t *type;
3626 switch (token.type) {
3628 scope_t *scope = NULL;
3629 if (!env->must_be_abstract) {
3630 scope = &env->parameters;
3633 type = parse_function_declarator(scope);
3637 type = parse_array_declarator();
3640 goto declarator_finished;
3643 /* insert in the middle of the list (at p) */
3644 type->base.next = *p;
3647 anchor = &type->base.next;
3650 declarator_finished:
3651 /* append inner_types at the end of the list, we don't to set anchor anymore
3652 * as it's not needed anymore */
3653 *anchor = inner_types;
3660 static type_t *construct_declarator_type(construct_type_t *construct_list,
3663 construct_type_t *iter = construct_list;
3664 for (; iter != NULL; iter = iter->base.next) {
3665 source_position_t const* const pos = &iter->base.pos;
3666 switch (iter->kind) {
3667 case CONSTRUCT_INVALID:
3669 case CONSTRUCT_FUNCTION: {
3670 construct_function_type_t *function = &iter->function;
3671 type_t *function_type = function->function_type;
3673 function_type->function.return_type = type;
3675 type_t *skipped_return_type = skip_typeref(type);
3677 if (is_type_function(skipped_return_type)) {
3678 errorf(pos, "function returning function is not allowed");
3679 } else if (is_type_array(skipped_return_type)) {
3680 errorf(pos, "function returning array is not allowed");
3682 if (skipped_return_type->base.qualifiers != 0) {
3683 warningf(WARN_OTHER, pos, "type qualifiers in return type of function type are meaningless");
3687 /* The function type was constructed earlier. Freeing it here will
3688 * destroy other types. */
3689 type = typehash_insert(function_type);
3693 case CONSTRUCT_POINTER: {
3694 if (is_type_reference(skip_typeref(type)))
3695 errorf(pos, "cannot declare a pointer to reference");
3697 parsed_pointer_t *pointer = &iter->pointer;
3698 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3702 case CONSTRUCT_REFERENCE:
3703 if (is_type_reference(skip_typeref(type)))
3704 errorf(pos, "cannot declare a reference to reference");
3706 type = make_reference_type(type);
3709 case CONSTRUCT_ARRAY: {
3710 if (is_type_reference(skip_typeref(type)))
3711 errorf(pos, "cannot declare an array of references");
3713 parsed_array_t *array = &iter->array;
3714 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3716 expression_t *size_expression = array->size;
3717 if (size_expression != NULL) {
3719 = create_implicit_cast(size_expression, type_size_t);
3722 array_type->base.qualifiers = array->type_qualifiers;
3723 array_type->array.element_type = type;
3724 array_type->array.is_static = array->is_static;
3725 array_type->array.is_variable = array->is_variable;
3726 array_type->array.size_expression = size_expression;
3728 if (size_expression != NULL) {
3729 switch (is_constant_expression(size_expression)) {
3730 case EXPR_CLASS_CONSTANT: {
3731 long const size = fold_constant_to_int(size_expression);
3732 array_type->array.size = size;
3733 array_type->array.size_constant = true;
3734 /* §6.7.5.2:1 If the expression is a constant expression,
3735 * it shall have a value greater than zero. */
3737 errorf(&size_expression->base.source_position,
3738 "size of array must be greater than zero");
3739 } else if (size == 0 && !GNU_MODE) {
3740 errorf(&size_expression->base.source_position,
3741 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3746 case EXPR_CLASS_VARIABLE:
3747 array_type->array.is_vla = true;
3750 case EXPR_CLASS_ERROR:
3755 type_t *skipped_type = skip_typeref(type);
3757 if (is_type_incomplete(skipped_type)) {
3758 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3759 } else if (is_type_function(skipped_type)) {
3760 errorf(pos, "array of functions is not allowed");
3762 type = identify_new_type(array_type);
3766 internal_errorf(pos, "invalid type construction found");
3772 static type_t *automatic_type_conversion(type_t *orig_type);
3774 static type_t *semantic_parameter(const source_position_t *pos,
3776 const declaration_specifiers_t *specifiers,
3777 entity_t const *const param)
3779 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3780 * shall be adjusted to ``qualified pointer to type'',
3782 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3783 * type'' shall be adjusted to ``pointer to function
3784 * returning type'', as in 6.3.2.1. */
3785 type = automatic_type_conversion(type);
3787 if (specifiers->is_inline && is_type_valid(type)) {
3788 errorf(pos, "'%N' declared 'inline'", param);
3791 /* §6.9.1:6 The declarations in the declaration list shall contain
3792 * no storage-class specifier other than register and no
3793 * initializations. */
3794 if (specifiers->thread_local || (
3795 specifiers->storage_class != STORAGE_CLASS_NONE &&
3796 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3798 errorf(pos, "invalid storage class for '%N'", param);
3801 /* delay test for incomplete type, because we might have (void)
3802 * which is legal but incomplete... */
3807 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3808 declarator_flags_t flags)
3810 parse_declarator_env_t env;
3811 memset(&env, 0, sizeof(env));
3812 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3814 construct_type_t *construct_type = parse_inner_declarator(&env);
3816 construct_declarator_type(construct_type, specifiers->type);
3817 type_t *type = skip_typeref(orig_type);
3819 if (construct_type != NULL) {
3820 obstack_free(&temp_obst, construct_type);
3823 attribute_t *attributes = parse_attributes(env.attributes);
3824 /* append (shared) specifier attribute behind attributes of this
3826 attribute_t **anchor = &attributes;
3827 while (*anchor != NULL)
3828 anchor = &(*anchor)->next;
3829 *anchor = specifiers->attributes;
3832 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3833 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3834 entity->base.source_position = env.source_position;
3835 entity->typedefe.type = orig_type;
3837 if (anonymous_entity != NULL) {
3838 if (is_type_compound(type)) {
3839 assert(anonymous_entity->compound.alias == NULL);
3840 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3841 anonymous_entity->kind == ENTITY_UNION);
3842 anonymous_entity->compound.alias = entity;
3843 anonymous_entity = NULL;
3844 } else if (is_type_enum(type)) {
3845 assert(anonymous_entity->enume.alias == NULL);
3846 assert(anonymous_entity->kind == ENTITY_ENUM);
3847 anonymous_entity->enume.alias = entity;
3848 anonymous_entity = NULL;
3852 /* create a declaration type entity */
3853 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3854 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3856 if (env.symbol != NULL) {
3857 if (specifiers->is_inline && is_type_valid(type)) {
3858 errorf(&env.source_position,
3859 "compound member '%Y' declared 'inline'", env.symbol);
3862 if (specifiers->thread_local ||
3863 specifiers->storage_class != STORAGE_CLASS_NONE) {
3864 errorf(&env.source_position,
3865 "compound member '%Y' must have no storage class",
3869 } else if (flags & DECL_IS_PARAMETER) {
3870 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3871 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3872 } else if (is_type_function(type)) {
3873 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3874 entity->function.is_inline = specifiers->is_inline;
3875 entity->function.elf_visibility = default_visibility;
3876 entity->function.parameters = env.parameters;
3878 if (env.symbol != NULL) {
3879 /* this needs fixes for C++ */
3880 bool in_function_scope = current_function != NULL;
3882 if (specifiers->thread_local || (
3883 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3884 specifiers->storage_class != STORAGE_CLASS_NONE &&
3885 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3887 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3891 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3892 entity->variable.elf_visibility = default_visibility;
3893 entity->variable.thread_local = specifiers->thread_local;
3895 if (env.symbol != NULL) {
3896 if (specifiers->is_inline && is_type_valid(type)) {
3897 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3900 bool invalid_storage_class = false;
3901 if (current_scope == file_scope) {
3902 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3903 specifiers->storage_class != STORAGE_CLASS_NONE &&
3904 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3905 invalid_storage_class = true;
3908 if (specifiers->thread_local &&
3909 specifiers->storage_class == STORAGE_CLASS_NONE) {
3910 invalid_storage_class = true;
3913 if (invalid_storage_class) {
3914 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3919 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3920 entity->declaration.type = orig_type;
3921 entity->declaration.alignment = get_type_alignment(orig_type);
3922 entity->declaration.modifiers = env.modifiers;
3923 entity->declaration.attributes = attributes;
3925 storage_class_t storage_class = specifiers->storage_class;
3926 entity->declaration.declared_storage_class = storage_class;
3928 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3929 storage_class = STORAGE_CLASS_AUTO;
3930 entity->declaration.storage_class = storage_class;
3933 if (attributes != NULL) {
3934 handle_entity_attributes(attributes, entity);
3940 static type_t *parse_abstract_declarator(type_t *base_type)
3942 parse_declarator_env_t env;
3943 memset(&env, 0, sizeof(env));
3944 env.may_be_abstract = true;
3945 env.must_be_abstract = true;
3947 construct_type_t *construct_type = parse_inner_declarator(&env);
3949 type_t *result = construct_declarator_type(construct_type, base_type);
3950 if (construct_type != NULL) {
3951 obstack_free(&temp_obst, construct_type);
3953 result = handle_type_attributes(env.attributes, result);
3959 * Check if the declaration of main is suspicious. main should be a
3960 * function with external linkage, returning int, taking either zero
3961 * arguments, two, or three arguments of appropriate types, ie.
3963 * int main([ int argc, char **argv [, char **env ] ]).
3965 * @param decl the declaration to check
3966 * @param type the function type of the declaration
3968 static void check_main(const entity_t *entity)
3970 const source_position_t *pos = &entity->base.source_position;
3971 if (entity->kind != ENTITY_FUNCTION) {
3972 warningf(WARN_MAIN, pos, "'main' is not a function");
3976 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3977 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3980 type_t *type = skip_typeref(entity->declaration.type);
3981 assert(is_type_function(type));
3983 function_type_t const *const func_type = &type->function;
3984 type_t *const ret_type = func_type->return_type;
3985 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3986 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3988 const function_parameter_t *parm = func_type->parameters;
3990 type_t *const first_type = skip_typeref(parm->type);
3991 type_t *const first_type_unqual = get_unqualified_type(first_type);
3992 if (!types_compatible(first_type_unqual, type_int)) {
3993 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3997 type_t *const second_type = skip_typeref(parm->type);
3998 type_t *const second_type_unqual
3999 = get_unqualified_type(second_type);
4000 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4001 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
4005 type_t *const third_type = skip_typeref(parm->type);
4006 type_t *const third_type_unqual
4007 = get_unqualified_type(third_type);
4008 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4009 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
4013 goto warn_arg_count;
4017 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
4023 * Check if a symbol is the equal to "main".
4025 static bool is_sym_main(const symbol_t *const sym)
4027 return strcmp(sym->string, "main") == 0;
4030 static void error_redefined_as_different_kind(const source_position_t *pos,
4031 const entity_t *old, entity_kind_t new_kind)
4033 char const *const what = get_entity_kind_name(new_kind);
4034 source_position_t const *const ppos = &old->base.source_position;
4035 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4038 static bool is_entity_valid(entity_t *const ent)
4040 if (is_declaration(ent)) {
4041 return is_type_valid(skip_typeref(ent->declaration.type));
4042 } else if (ent->kind == ENTITY_TYPEDEF) {
4043 return is_type_valid(skip_typeref(ent->typedefe.type));
4048 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4050 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4051 if (attributes_equal(tattr, attr))
4058 * test wether new_list contains any attributes not included in old_list
4060 static bool has_new_attributes(const attribute_t *old_list,
4061 const attribute_t *new_list)
4063 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4064 if (!contains_attribute(old_list, attr))
4071 * Merge in attributes from an attribute list (probably from a previous
4072 * declaration with the same name). Warning: destroys the old structure
4073 * of the attribute list - don't reuse attributes after this call.
4075 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4078 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4080 if (contains_attribute(decl->attributes, attr))
4083 /* move attribute to new declarations attributes list */
4084 attr->next = decl->attributes;
4085 decl->attributes = attr;
4090 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4091 * for various problems that occur for multiple definitions
4093 entity_t *record_entity(entity_t *entity, const bool is_definition)
4095 const symbol_t *const symbol = entity->base.symbol;
4096 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4097 const source_position_t *pos = &entity->base.source_position;
4099 /* can happen in error cases */
4103 entity_t *const previous_entity = get_entity(symbol, namespc);
4104 /* pushing the same entity twice will break the stack structure */
4105 assert(previous_entity != entity);
4107 if (entity->kind == ENTITY_FUNCTION) {
4108 type_t *const orig_type = entity->declaration.type;
4109 type_t *const type = skip_typeref(orig_type);
4111 assert(is_type_function(type));
4112 if (type->function.unspecified_parameters &&
4113 previous_entity == NULL &&
4114 !entity->declaration.implicit) {
4115 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4118 if (current_scope == file_scope && is_sym_main(symbol)) {
4123 if (is_declaration(entity) &&
4124 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4125 current_scope != file_scope &&
4126 !entity->declaration.implicit) {
4127 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4130 if (previous_entity != NULL) {
4131 source_position_t const *const ppos = &previous_entity->base.source_position;
4133 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4134 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4135 assert(previous_entity->kind == ENTITY_PARAMETER);
4136 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4140 if (previous_entity->base.parent_scope == current_scope) {
4141 if (previous_entity->kind != entity->kind) {
4142 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4143 error_redefined_as_different_kind(pos, previous_entity,
4148 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4149 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4152 if (previous_entity->kind == ENTITY_TYPEDEF) {
4153 /* TODO: C++ allows this for exactly the same type */
4154 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4158 /* at this point we should have only VARIABLES or FUNCTIONS */
4159 assert(is_declaration(previous_entity) && is_declaration(entity));
4161 declaration_t *const prev_decl = &previous_entity->declaration;
4162 declaration_t *const decl = &entity->declaration;
4164 /* can happen for K&R style declarations */
4165 if (prev_decl->type == NULL &&
4166 previous_entity->kind == ENTITY_PARAMETER &&
4167 entity->kind == ENTITY_PARAMETER) {
4168 prev_decl->type = decl->type;
4169 prev_decl->storage_class = decl->storage_class;
4170 prev_decl->declared_storage_class = decl->declared_storage_class;
4171 prev_decl->modifiers = decl->modifiers;
4172 return previous_entity;
4175 type_t *const type = skip_typeref(decl->type);
4176 type_t *const prev_type = skip_typeref(prev_decl->type);
4178 if (!types_compatible(type, prev_type)) {
4179 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4181 unsigned old_storage_class = prev_decl->storage_class;
4183 if (is_definition &&
4185 !(prev_decl->modifiers & DM_USED) &&
4186 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4187 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4190 storage_class_t new_storage_class = decl->storage_class;
4192 /* pretend no storage class means extern for function
4193 * declarations (except if the previous declaration is neither
4194 * none nor extern) */
4195 if (entity->kind == ENTITY_FUNCTION) {
4196 /* the previous declaration could have unspecified parameters or
4197 * be a typedef, so use the new type */
4198 if (prev_type->function.unspecified_parameters || is_definition)
4199 prev_decl->type = type;
4201 switch (old_storage_class) {
4202 case STORAGE_CLASS_NONE:
4203 old_storage_class = STORAGE_CLASS_EXTERN;
4206 case STORAGE_CLASS_EXTERN:
4207 if (is_definition) {
4208 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4209 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4211 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4212 new_storage_class = STORAGE_CLASS_EXTERN;
4219 } else if (is_type_incomplete(prev_type)) {
4220 prev_decl->type = type;
4223 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4224 new_storage_class == STORAGE_CLASS_EXTERN) {
4226 warn_redundant_declaration: ;
4228 = has_new_attributes(prev_decl->attributes,
4230 if (has_new_attrs) {
4231 merge_in_attributes(decl, prev_decl->attributes);
4232 } else if (!is_definition &&
4233 is_type_valid(prev_type) &&
4234 strcmp(ppos->input_name, "<builtin>") != 0) {
4235 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4237 } else if (current_function == NULL) {
4238 if (old_storage_class != STORAGE_CLASS_STATIC &&
4239 new_storage_class == STORAGE_CLASS_STATIC) {
4240 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4241 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4242 prev_decl->storage_class = STORAGE_CLASS_NONE;
4243 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4245 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4247 goto error_redeclaration;
4248 goto warn_redundant_declaration;
4250 } else if (is_type_valid(prev_type)) {
4251 if (old_storage_class == new_storage_class) {
4252 error_redeclaration:
4253 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4255 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4260 prev_decl->modifiers |= decl->modifiers;
4261 if (entity->kind == ENTITY_FUNCTION) {
4262 previous_entity->function.is_inline |= entity->function.is_inline;
4264 return previous_entity;
4268 if (is_warn_on(why = WARN_SHADOW) ||
4269 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4270 char const *const what = get_entity_kind_name(previous_entity->kind);
4271 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4275 if (entity->kind == ENTITY_FUNCTION) {
4276 if (is_definition &&
4277 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4278 !is_sym_main(symbol)) {
4279 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4280 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4282 goto warn_missing_declaration;
4285 } else if (entity->kind == ENTITY_VARIABLE) {
4286 if (current_scope == file_scope &&
4287 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4288 !entity->declaration.implicit) {
4289 warn_missing_declaration:
4290 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4295 assert(entity->base.parent_scope == NULL);
4296 assert(current_scope != NULL);
4298 entity->base.parent_scope = current_scope;
4299 environment_push(entity);
4300 append_entity(current_scope, entity);
4305 static void parser_error_multiple_definition(entity_t *entity,
4306 const source_position_t *source_position)
4308 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4309 entity->base.symbol, &entity->base.source_position);
4312 static bool is_declaration_specifier(const token_t *token)
4314 switch (token->type) {
4318 return is_typedef_symbol(token->symbol);
4325 static void parse_init_declarator_rest(entity_t *entity)
4327 type_t *orig_type = type_error_type;
4329 if (entity->base.kind == ENTITY_TYPEDEF) {
4330 source_position_t const *const pos = &entity->base.source_position;
4331 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4333 assert(is_declaration(entity));
4334 orig_type = entity->declaration.type;
4337 type_t *type = skip_typeref(orig_type);
4339 if (entity->kind == ENTITY_VARIABLE
4340 && entity->variable.initializer != NULL) {
4341 parser_error_multiple_definition(entity, HERE);
4345 declaration_t *const declaration = &entity->declaration;
4346 bool must_be_constant = false;
4347 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4348 entity->base.parent_scope == file_scope) {
4349 must_be_constant = true;
4352 if (is_type_function(type)) {
4353 source_position_t const *const pos = &entity->base.source_position;
4354 errorf(pos, "'%N' is initialized like a variable", entity);
4355 orig_type = type_error_type;
4358 parse_initializer_env_t env;
4359 env.type = orig_type;
4360 env.must_be_constant = must_be_constant;
4361 env.entity = entity;
4362 current_init_decl = entity;
4364 initializer_t *initializer = parse_initializer(&env);
4365 current_init_decl = NULL;
4367 if (entity->kind == ENTITY_VARIABLE) {
4368 /* §6.7.5:22 array initializers for arrays with unknown size
4369 * determine the array type size */
4370 declaration->type = env.type;
4371 entity->variable.initializer = initializer;
4375 /* parse rest of a declaration without any declarator */
4376 static void parse_anonymous_declaration_rest(
4377 const declaration_specifiers_t *specifiers)
4380 anonymous_entity = NULL;
4382 source_position_t const *const pos = &specifiers->source_position;
4383 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4384 specifiers->thread_local) {
4385 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4388 type_t *type = specifiers->type;
4389 switch (type->kind) {
4390 case TYPE_COMPOUND_STRUCT:
4391 case TYPE_COMPOUND_UNION: {
4392 if (type->compound.compound->base.symbol == NULL) {
4393 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4402 warningf(WARN_OTHER, pos, "empty declaration");
4407 static void check_variable_type_complete(entity_t *ent)
4409 if (ent->kind != ENTITY_VARIABLE)
4412 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4413 * type for the object shall be complete [...] */
4414 declaration_t *decl = &ent->declaration;
4415 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4416 decl->storage_class == STORAGE_CLASS_STATIC)
4419 type_t *const type = skip_typeref(decl->type);
4420 if (!is_type_incomplete(type))
4423 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4424 * are given length one. */
4425 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4426 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4430 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4434 static void parse_declaration_rest(entity_t *ndeclaration,
4435 const declaration_specifiers_t *specifiers,
4436 parsed_declaration_func finished_declaration,
4437 declarator_flags_t flags)
4439 add_anchor_token(';');
4440 add_anchor_token(',');
4442 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4444 if (token.type == '=') {
4445 parse_init_declarator_rest(entity);
4446 } else if (entity->kind == ENTITY_VARIABLE) {
4447 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4448 * [...] where the extern specifier is explicitly used. */
4449 declaration_t *decl = &entity->declaration;
4450 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4451 type_t *type = decl->type;
4452 if (is_type_reference(skip_typeref(type))) {
4453 source_position_t const *const pos = &entity->base.source_position;
4454 errorf(pos, "reference '%#N' must be initialized", entity);
4459 check_variable_type_complete(entity);
4464 add_anchor_token('=');
4465 ndeclaration = parse_declarator(specifiers, flags);
4466 rem_anchor_token('=');
4468 expect(';', end_error);
4471 anonymous_entity = NULL;
4472 rem_anchor_token(';');
4473 rem_anchor_token(',');
4476 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4478 symbol_t *symbol = entity->base.symbol;
4482 assert(entity->base.namespc == NAMESPACE_NORMAL);
4483 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4484 if (previous_entity == NULL
4485 || previous_entity->base.parent_scope != current_scope) {
4486 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4491 if (is_definition) {
4492 errorf(HERE, "'%N' is initialised", entity);
4495 return record_entity(entity, false);
4498 static void parse_declaration(parsed_declaration_func finished_declaration,
4499 declarator_flags_t flags)
4501 add_anchor_token(';');
4502 declaration_specifiers_t specifiers;
4503 parse_declaration_specifiers(&specifiers);
4504 rem_anchor_token(';');
4506 if (token.type == ';') {
4507 parse_anonymous_declaration_rest(&specifiers);
4509 entity_t *entity = parse_declarator(&specifiers, flags);
4510 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4515 static type_t *get_default_promoted_type(type_t *orig_type)
4517 type_t *result = orig_type;
4519 type_t *type = skip_typeref(orig_type);
4520 if (is_type_integer(type)) {
4521 result = promote_integer(type);
4522 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4523 result = type_double;
4529 static void parse_kr_declaration_list(entity_t *entity)
4531 if (entity->kind != ENTITY_FUNCTION)
4534 type_t *type = skip_typeref(entity->declaration.type);
4535 assert(is_type_function(type));
4536 if (!type->function.kr_style_parameters)
4539 add_anchor_token('{');
4541 /* push function parameters */
4542 size_t const top = environment_top();
4543 scope_t *old_scope = scope_push(&entity->function.parameters);
4545 entity_t *parameter = entity->function.parameters.entities;
4546 for ( ; parameter != NULL; parameter = parameter->base.next) {
4547 assert(parameter->base.parent_scope == NULL);
4548 parameter->base.parent_scope = current_scope;
4549 environment_push(parameter);
4552 /* parse declaration list */
4554 switch (token.type) {
4556 case T___extension__:
4557 /* This covers symbols, which are no type, too, and results in
4558 * better error messages. The typical cases are misspelled type
4559 * names and missing includes. */
4561 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4569 /* pop function parameters */
4570 assert(current_scope == &entity->function.parameters);
4571 scope_pop(old_scope);
4572 environment_pop_to(top);
4574 /* update function type */
4575 type_t *new_type = duplicate_type(type);
4577 function_parameter_t *parameters = NULL;
4578 function_parameter_t **anchor = ¶meters;
4580 /* did we have an earlier prototype? */
4581 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4582 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4585 function_parameter_t *proto_parameter = NULL;
4586 if (proto_type != NULL) {
4587 type_t *proto_type_type = proto_type->declaration.type;
4588 proto_parameter = proto_type_type->function.parameters;
4589 /* If a K&R function definition has a variadic prototype earlier, then
4590 * make the function definition variadic, too. This should conform to
4591 * §6.7.5.3:15 and §6.9.1:8. */
4592 new_type->function.variadic = proto_type_type->function.variadic;
4594 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4596 new_type->function.unspecified_parameters = true;
4599 bool need_incompatible_warning = false;
4600 parameter = entity->function.parameters.entities;
4601 for (; parameter != NULL; parameter = parameter->base.next,
4603 proto_parameter == NULL ? NULL : proto_parameter->next) {
4604 if (parameter->kind != ENTITY_PARAMETER)
4607 type_t *parameter_type = parameter->declaration.type;
4608 if (parameter_type == NULL) {
4609 source_position_t const* const pos = ¶meter->base.source_position;
4611 errorf(pos, "no type specified for function '%N'", parameter);
4612 parameter_type = type_error_type;
4614 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4615 parameter_type = type_int;
4617 parameter->declaration.type = parameter_type;
4620 semantic_parameter_incomplete(parameter);
4622 /* we need the default promoted types for the function type */
4623 type_t *not_promoted = parameter_type;
4624 parameter_type = get_default_promoted_type(parameter_type);
4626 /* gcc special: if the type of the prototype matches the unpromoted
4627 * type don't promote */
4628 if (!strict_mode && proto_parameter != NULL) {
4629 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4630 type_t *promo_skip = skip_typeref(parameter_type);
4631 type_t *param_skip = skip_typeref(not_promoted);
4632 if (!types_compatible(proto_p_type, promo_skip)
4633 && types_compatible(proto_p_type, param_skip)) {
4635 need_incompatible_warning = true;
4636 parameter_type = not_promoted;
4639 function_parameter_t *const function_parameter
4640 = allocate_parameter(parameter_type);
4642 *anchor = function_parameter;
4643 anchor = &function_parameter->next;
4646 new_type->function.parameters = parameters;
4647 new_type = identify_new_type(new_type);
4649 if (need_incompatible_warning) {
4650 symbol_t const *const sym = entity->base.symbol;
4651 source_position_t const *const pos = &entity->base.source_position;
4652 source_position_t const *const ppos = &proto_type->base.source_position;
4653 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4655 entity->declaration.type = new_type;
4657 rem_anchor_token('{');
4660 static bool first_err = true;
4663 * When called with first_err set, prints the name of the current function,
4666 static void print_in_function(void)
4670 char const *const file = current_function->base.base.source_position.input_name;
4671 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4676 * Check if all labels are defined in the current function.
4677 * Check if all labels are used in the current function.
4679 static void check_labels(void)
4681 for (const goto_statement_t *goto_statement = goto_first;
4682 goto_statement != NULL;
4683 goto_statement = goto_statement->next) {
4684 /* skip computed gotos */
4685 if (goto_statement->expression != NULL)
4688 label_t *label = goto_statement->label;
4689 if (label->base.source_position.input_name == NULL) {
4690 print_in_function();
4691 source_position_t const *const pos = &goto_statement->base.source_position;
4692 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4696 if (is_warn_on(WARN_UNUSED_LABEL)) {
4697 for (const label_statement_t *label_statement = label_first;
4698 label_statement != NULL;
4699 label_statement = label_statement->next) {
4700 label_t *label = label_statement->label;
4702 if (! label->used) {
4703 print_in_function();
4704 source_position_t const *const pos = &label_statement->base.source_position;
4705 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4711 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4713 entity_t const *const end = last != NULL ? last->base.next : NULL;
4714 for (; entity != end; entity = entity->base.next) {
4715 if (!is_declaration(entity))
4718 declaration_t *declaration = &entity->declaration;
4719 if (declaration->implicit)
4722 if (!declaration->used) {
4723 print_in_function();
4724 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4725 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4726 print_in_function();
4727 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4732 static void check_unused_variables(statement_t *const stmt, void *const env)
4736 switch (stmt->kind) {
4737 case STATEMENT_DECLARATION: {
4738 declaration_statement_t const *const decls = &stmt->declaration;
4739 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4744 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4753 * Check declarations of current_function for unused entities.
4755 static void check_declarations(void)
4757 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4758 const scope_t *scope = ¤t_function->parameters;
4760 /* do not issue unused warnings for main */
4761 if (!is_sym_main(current_function->base.base.symbol)) {
4762 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4765 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4766 walk_statements(current_function->statement, check_unused_variables,
4771 static int determine_truth(expression_t const* const cond)
4774 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4775 fold_constant_to_bool(cond) ? 1 :
4779 static void check_reachable(statement_t *);
4780 static bool reaches_end;
4782 static bool expression_returns(expression_t const *const expr)
4784 switch (expr->kind) {
4786 expression_t const *const func = expr->call.function;
4787 if (func->kind == EXPR_REFERENCE) {
4788 entity_t *entity = func->reference.entity;
4789 if (entity->kind == ENTITY_FUNCTION
4790 && entity->declaration.modifiers & DM_NORETURN)
4794 if (!expression_returns(func))
4797 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4798 if (!expression_returns(arg->expression))
4805 case EXPR_REFERENCE:
4806 case EXPR_REFERENCE_ENUM_VALUE:
4808 case EXPR_STRING_LITERAL:
4809 case EXPR_WIDE_STRING_LITERAL:
4810 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4811 case EXPR_LABEL_ADDRESS:
4812 case EXPR_CLASSIFY_TYPE:
4813 case EXPR_SIZEOF: // TODO handle obscure VLA case
4816 case EXPR_BUILTIN_CONSTANT_P:
4817 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4822 case EXPR_STATEMENT: {
4823 bool old_reaches_end = reaches_end;
4824 reaches_end = false;
4825 check_reachable(expr->statement.statement);
4826 bool returns = reaches_end;
4827 reaches_end = old_reaches_end;
4831 case EXPR_CONDITIONAL:
4832 // TODO handle constant expression
4834 if (!expression_returns(expr->conditional.condition))
4837 if (expr->conditional.true_expression != NULL
4838 && expression_returns(expr->conditional.true_expression))
4841 return expression_returns(expr->conditional.false_expression);
4844 return expression_returns(expr->select.compound);
4846 case EXPR_ARRAY_ACCESS:
4848 expression_returns(expr->array_access.array_ref) &&
4849 expression_returns(expr->array_access.index);
4852 return expression_returns(expr->va_starte.ap);
4855 return expression_returns(expr->va_arge.ap);
4858 return expression_returns(expr->va_copye.src);
4860 EXPR_UNARY_CASES_MANDATORY
4861 return expression_returns(expr->unary.value);
4863 case EXPR_UNARY_THROW:
4867 // TODO handle constant lhs of && and ||
4869 expression_returns(expr->binary.left) &&
4870 expression_returns(expr->binary.right);
4876 panic("unhandled expression");
4879 static bool initializer_returns(initializer_t const *const init)
4881 switch (init->kind) {
4882 case INITIALIZER_VALUE:
4883 return expression_returns(init->value.value);
4885 case INITIALIZER_LIST: {
4886 initializer_t * const* i = init->list.initializers;
4887 initializer_t * const* const end = i + init->list.len;
4888 bool returns = true;
4889 for (; i != end; ++i) {
4890 if (!initializer_returns(*i))
4896 case INITIALIZER_STRING:
4897 case INITIALIZER_WIDE_STRING:
4898 case INITIALIZER_DESIGNATOR: // designators have no payload
4901 panic("unhandled initializer");
4904 static bool noreturn_candidate;
4906 static void check_reachable(statement_t *const stmt)
4908 if (stmt->base.reachable)
4910 if (stmt->kind != STATEMENT_DO_WHILE)
4911 stmt->base.reachable = true;
4913 statement_t *last = stmt;
4915 switch (stmt->kind) {
4916 case STATEMENT_INVALID:
4917 case STATEMENT_EMPTY:
4919 next = stmt->base.next;
4922 case STATEMENT_DECLARATION: {
4923 declaration_statement_t const *const decl = &stmt->declaration;
4924 entity_t const * ent = decl->declarations_begin;
4925 entity_t const *const last_decl = decl->declarations_end;
4927 for (;; ent = ent->base.next) {
4928 if (ent->kind == ENTITY_VARIABLE &&
4929 ent->variable.initializer != NULL &&
4930 !initializer_returns(ent->variable.initializer)) {
4933 if (ent == last_decl)
4937 next = stmt->base.next;
4941 case STATEMENT_COMPOUND:
4942 next = stmt->compound.statements;
4944 next = stmt->base.next;
4947 case STATEMENT_RETURN: {
4948 expression_t const *const val = stmt->returns.value;
4949 if (val == NULL || expression_returns(val))
4950 noreturn_candidate = false;
4954 case STATEMENT_IF: {
4955 if_statement_t const *const ifs = &stmt->ifs;
4956 expression_t const *const cond = ifs->condition;
4958 if (!expression_returns(cond))
4961 int const val = determine_truth(cond);
4964 check_reachable(ifs->true_statement);
4969 if (ifs->false_statement != NULL) {
4970 check_reachable(ifs->false_statement);
4974 next = stmt->base.next;
4978 case STATEMENT_SWITCH: {
4979 switch_statement_t const *const switchs = &stmt->switchs;
4980 expression_t const *const expr = switchs->expression;
4982 if (!expression_returns(expr))
4985 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4986 long const val = fold_constant_to_int(expr);
4987 case_label_statement_t * defaults = NULL;
4988 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4989 if (i->expression == NULL) {
4994 if (i->first_case <= val && val <= i->last_case) {
4995 check_reachable((statement_t*)i);
5000 if (defaults != NULL) {
5001 check_reachable((statement_t*)defaults);
5005 bool has_default = false;
5006 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5007 if (i->expression == NULL)
5010 check_reachable((statement_t*)i);
5017 next = stmt->base.next;
5021 case STATEMENT_EXPRESSION: {
5022 /* Check for noreturn function call */
5023 expression_t const *const expr = stmt->expression.expression;
5024 if (!expression_returns(expr))
5027 next = stmt->base.next;
5031 case STATEMENT_CONTINUE:
5032 for (statement_t *parent = stmt;;) {
5033 parent = parent->base.parent;
5034 if (parent == NULL) /* continue not within loop */
5038 switch (parent->kind) {
5039 case STATEMENT_WHILE: goto continue_while;
5040 case STATEMENT_DO_WHILE: goto continue_do_while;
5041 case STATEMENT_FOR: goto continue_for;
5047 case STATEMENT_BREAK:
5048 for (statement_t *parent = stmt;;) {
5049 parent = parent->base.parent;
5050 if (parent == NULL) /* break not within loop/switch */
5053 switch (parent->kind) {
5054 case STATEMENT_SWITCH:
5055 case STATEMENT_WHILE:
5056 case STATEMENT_DO_WHILE:
5059 next = parent->base.next;
5060 goto found_break_parent;
5068 case STATEMENT_GOTO:
5069 if (stmt->gotos.expression) {
5070 if (!expression_returns(stmt->gotos.expression))
5073 statement_t *parent = stmt->base.parent;
5074 if (parent == NULL) /* top level goto */
5078 next = stmt->gotos.label->statement;
5079 if (next == NULL) /* missing label */
5084 case STATEMENT_LABEL:
5085 next = stmt->label.statement;
5088 case STATEMENT_CASE_LABEL:
5089 next = stmt->case_label.statement;
5092 case STATEMENT_WHILE: {
5093 while_statement_t const *const whiles = &stmt->whiles;
5094 expression_t const *const cond = whiles->condition;
5096 if (!expression_returns(cond))
5099 int const val = determine_truth(cond);
5102 check_reachable(whiles->body);
5107 next = stmt->base.next;
5111 case STATEMENT_DO_WHILE:
5112 next = stmt->do_while.body;
5115 case STATEMENT_FOR: {
5116 for_statement_t *const fors = &stmt->fors;
5118 if (fors->condition_reachable)
5120 fors->condition_reachable = true;
5122 expression_t const *const cond = fors->condition;
5127 } else if (expression_returns(cond)) {
5128 val = determine_truth(cond);
5134 check_reachable(fors->body);
5139 next = stmt->base.next;
5143 case STATEMENT_MS_TRY: {
5144 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5145 check_reachable(ms_try->try_statement);
5146 next = ms_try->final_statement;
5150 case STATEMENT_LEAVE: {
5151 statement_t *parent = stmt;
5153 parent = parent->base.parent;
5154 if (parent == NULL) /* __leave not within __try */
5157 if (parent->kind == STATEMENT_MS_TRY) {
5159 next = parent->ms_try.final_statement;
5167 panic("invalid statement kind");
5170 while (next == NULL) {
5171 next = last->base.parent;
5173 noreturn_candidate = false;
5175 type_t *const type = skip_typeref(current_function->base.type);
5176 assert(is_type_function(type));
5177 type_t *const ret = skip_typeref(type->function.return_type);
5178 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5179 is_type_valid(ret) &&
5180 !is_sym_main(current_function->base.base.symbol)) {
5181 source_position_t const *const pos = &stmt->base.source_position;
5182 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5187 switch (next->kind) {
5188 case STATEMENT_INVALID:
5189 case STATEMENT_EMPTY:
5190 case STATEMENT_DECLARATION:
5191 case STATEMENT_EXPRESSION:
5193 case STATEMENT_RETURN:
5194 case STATEMENT_CONTINUE:
5195 case STATEMENT_BREAK:
5196 case STATEMENT_GOTO:
5197 case STATEMENT_LEAVE:
5198 panic("invalid control flow in function");
5200 case STATEMENT_COMPOUND:
5201 if (next->compound.stmt_expr) {
5207 case STATEMENT_SWITCH:
5208 case STATEMENT_LABEL:
5209 case STATEMENT_CASE_LABEL:
5211 next = next->base.next;
5214 case STATEMENT_WHILE: {
5216 if (next->base.reachable)
5218 next->base.reachable = true;
5220 while_statement_t const *const whiles = &next->whiles;
5221 expression_t const *const cond = whiles->condition;
5223 if (!expression_returns(cond))
5226 int const val = determine_truth(cond);
5229 check_reachable(whiles->body);
5235 next = next->base.next;
5239 case STATEMENT_DO_WHILE: {
5241 if (next->base.reachable)
5243 next->base.reachable = true;
5245 do_while_statement_t const *const dw = &next->do_while;
5246 expression_t const *const cond = dw->condition;
5248 if (!expression_returns(cond))
5251 int const val = determine_truth(cond);
5254 check_reachable(dw->body);
5260 next = next->base.next;
5264 case STATEMENT_FOR: {
5266 for_statement_t *const fors = &next->fors;
5268 fors->step_reachable = true;
5270 if (fors->condition_reachable)
5272 fors->condition_reachable = true;
5274 expression_t const *const cond = fors->condition;
5279 } else if (expression_returns(cond)) {
5280 val = determine_truth(cond);
5286 check_reachable(fors->body);
5292 next = next->base.next;
5296 case STATEMENT_MS_TRY:
5298 next = next->ms_try.final_statement;
5303 check_reachable(next);
5306 static void check_unreachable(statement_t* const stmt, void *const env)
5310 switch (stmt->kind) {
5311 case STATEMENT_DO_WHILE:
5312 if (!stmt->base.reachable) {
5313 expression_t const *const cond = stmt->do_while.condition;
5314 if (determine_truth(cond) >= 0) {
5315 source_position_t const *const pos = &cond->base.source_position;
5316 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5321 case STATEMENT_FOR: {
5322 for_statement_t const* const fors = &stmt->fors;
5324 // if init and step are unreachable, cond is unreachable, too
5325 if (!stmt->base.reachable && !fors->step_reachable) {
5326 goto warn_unreachable;
5328 if (!stmt->base.reachable && fors->initialisation != NULL) {
5329 source_position_t const *const pos = &fors->initialisation->base.source_position;
5330 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5333 if (!fors->condition_reachable && fors->condition != NULL) {
5334 source_position_t const *const pos = &fors->condition->base.source_position;
5335 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5338 if (!fors->step_reachable && fors->step != NULL) {
5339 source_position_t const *const pos = &fors->step->base.source_position;
5340 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5346 case STATEMENT_COMPOUND:
5347 if (stmt->compound.statements != NULL)
5349 goto warn_unreachable;
5351 case STATEMENT_DECLARATION: {
5352 /* Only warn if there is at least one declarator with an initializer.
5353 * This typically occurs in switch statements. */
5354 declaration_statement_t const *const decl = &stmt->declaration;
5355 entity_t const * ent = decl->declarations_begin;
5356 entity_t const *const last = decl->declarations_end;
5358 for (;; ent = ent->base.next) {
5359 if (ent->kind == ENTITY_VARIABLE &&
5360 ent->variable.initializer != NULL) {
5361 goto warn_unreachable;
5371 if (!stmt->base.reachable) {
5372 source_position_t const *const pos = &stmt->base.source_position;
5373 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5379 static void parse_external_declaration(void)
5381 /* function-definitions and declarations both start with declaration
5383 add_anchor_token(';');
5384 declaration_specifiers_t specifiers;
5385 parse_declaration_specifiers(&specifiers);
5386 rem_anchor_token(';');
5388 /* must be a declaration */
5389 if (token.type == ';') {
5390 parse_anonymous_declaration_rest(&specifiers);
5394 add_anchor_token(',');
5395 add_anchor_token('=');
5396 add_anchor_token(';');
5397 add_anchor_token('{');
5399 /* declarator is common to both function-definitions and declarations */
5400 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5402 rem_anchor_token('{');
5403 rem_anchor_token(';');
5404 rem_anchor_token('=');
5405 rem_anchor_token(',');
5407 /* must be a declaration */
5408 switch (token.type) {
5412 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5417 /* must be a function definition */
5418 parse_kr_declaration_list(ndeclaration);
5420 if (token.type != '{') {
5421 parse_error_expected("while parsing function definition", '{', NULL);
5422 eat_until_matching_token(';');
5426 assert(is_declaration(ndeclaration));
5427 type_t *const orig_type = ndeclaration->declaration.type;
5428 type_t * type = skip_typeref(orig_type);
5430 if (!is_type_function(type)) {
5431 if (is_type_valid(type)) {
5432 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5438 source_position_t const *const pos = &ndeclaration->base.source_position;
5439 if (is_typeref(orig_type)) {
5441 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5444 if (is_type_compound(skip_typeref(type->function.return_type))) {
5445 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5447 if (type->function.unspecified_parameters) {
5448 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5450 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5453 /* §6.7.5.3:14 a function definition with () means no
5454 * parameters (and not unspecified parameters) */
5455 if (type->function.unspecified_parameters &&
5456 type->function.parameters == NULL) {
5457 type_t *copy = duplicate_type(type);
5458 copy->function.unspecified_parameters = false;
5459 type = identify_new_type(copy);
5461 ndeclaration->declaration.type = type;
5464 entity_t *const entity = record_entity(ndeclaration, true);
5465 assert(entity->kind == ENTITY_FUNCTION);
5466 assert(ndeclaration->kind == ENTITY_FUNCTION);
5468 function_t *const function = &entity->function;
5469 if (ndeclaration != entity) {
5470 function->parameters = ndeclaration->function.parameters;
5472 assert(is_declaration(entity));
5473 type = skip_typeref(entity->declaration.type);
5475 /* push function parameters and switch scope */
5476 size_t const top = environment_top();
5477 scope_t *old_scope = scope_push(&function->parameters);
5479 entity_t *parameter = function->parameters.entities;
5480 for (; parameter != NULL; parameter = parameter->base.next) {
5481 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5482 parameter->base.parent_scope = current_scope;
5484 assert(parameter->base.parent_scope == NULL
5485 || parameter->base.parent_scope == current_scope);
5486 parameter->base.parent_scope = current_scope;
5487 if (parameter->base.symbol == NULL) {
5488 errorf(¶meter->base.source_position, "parameter name omitted");
5491 environment_push(parameter);
5494 if (function->statement != NULL) {
5495 parser_error_multiple_definition(entity, HERE);
5498 /* parse function body */
5499 int label_stack_top = label_top();
5500 function_t *old_current_function = current_function;
5501 entity_t *old_current_entity = current_entity;
5502 current_function = function;
5503 current_entity = entity;
5504 current_parent = NULL;
5507 goto_anchor = &goto_first;
5509 label_anchor = &label_first;
5511 statement_t *const body = parse_compound_statement(false);
5512 function->statement = body;
5515 check_declarations();
5516 if (is_warn_on(WARN_RETURN_TYPE) ||
5517 is_warn_on(WARN_UNREACHABLE_CODE) ||
5518 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5519 noreturn_candidate = true;
5520 check_reachable(body);
5521 if (is_warn_on(WARN_UNREACHABLE_CODE))
5522 walk_statements(body, check_unreachable, NULL);
5523 if (noreturn_candidate &&
5524 !(function->base.modifiers & DM_NORETURN)) {
5525 source_position_t const *const pos = &body->base.source_position;
5526 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5530 assert(current_parent == NULL);
5531 assert(current_function == function);
5532 assert(current_entity == entity);
5533 current_entity = old_current_entity;
5534 current_function = old_current_function;
5535 label_pop_to(label_stack_top);
5538 assert(current_scope == &function->parameters);
5539 scope_pop(old_scope);
5540 environment_pop_to(top);
5543 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5544 source_position_t *source_position,
5545 const symbol_t *symbol)
5547 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5549 type->bitfield.base_type = base_type;
5550 type->bitfield.size_expression = size;
5553 type_t *skipped_type = skip_typeref(base_type);
5554 if (!is_type_integer(skipped_type)) {
5555 errorf(source_position, "bitfield base type '%T' is not an integer type", base_type);
5558 bit_size = get_type_size(base_type) * 8;
5561 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5562 long v = fold_constant_to_int(size);
5563 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5566 errorf(source_position, "negative width in bit-field '%Y'",
5568 } else if (v == 0 && symbol != NULL) {
5569 errorf(source_position, "zero width for bit-field '%Y'",
5571 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5572 errorf(source_position, "width of '%Y' exceeds its type",
5575 type->bitfield.bit_size = v;
5582 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5584 entity_t *iter = compound->members.entities;
5585 for (; iter != NULL; iter = iter->base.next) {
5586 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5589 if (iter->base.symbol == symbol) {
5591 } else if (iter->base.symbol == NULL) {
5592 /* search in anonymous structs and unions */
5593 type_t *type = skip_typeref(iter->declaration.type);
5594 if (is_type_compound(type)) {
5595 if (find_compound_entry(type->compound.compound, symbol)
5606 static void check_deprecated(const source_position_t *source_position,
5607 const entity_t *entity)
5609 if (!is_declaration(entity))
5611 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5614 source_position_t const *const epos = &entity->base.source_position;
5615 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5617 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5619 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5624 static expression_t *create_select(const source_position_t *pos,
5626 type_qualifiers_t qualifiers,
5629 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5631 check_deprecated(pos, entry);
5633 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5634 select->select.compound = addr;
5635 select->select.compound_entry = entry;
5637 type_t *entry_type = entry->declaration.type;
5638 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5640 /* we always do the auto-type conversions; the & and sizeof parser contains
5641 * code to revert this! */
5642 select->base.type = automatic_type_conversion(res_type);
5643 if (res_type->kind == TYPE_BITFIELD) {
5644 select->base.type = res_type->bitfield.base_type;
5651 * Find entry with symbol in compound. Search anonymous structs and unions and
5652 * creates implicit select expressions for them.
5653 * Returns the adress for the innermost compound.
5655 static expression_t *find_create_select(const source_position_t *pos,
5657 type_qualifiers_t qualifiers,
5658 compound_t *compound, symbol_t *symbol)
5660 entity_t *iter = compound->members.entities;
5661 for (; iter != NULL; iter = iter->base.next) {
5662 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5665 symbol_t *iter_symbol = iter->base.symbol;
5666 if (iter_symbol == NULL) {
5667 type_t *type = iter->declaration.type;
5668 if (type->kind != TYPE_COMPOUND_STRUCT
5669 && type->kind != TYPE_COMPOUND_UNION)
5672 compound_t *sub_compound = type->compound.compound;
5674 if (find_compound_entry(sub_compound, symbol) == NULL)
5677 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5678 sub_addr->base.source_position = *pos;
5679 sub_addr->select.implicit = true;
5680 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5684 if (iter_symbol == symbol) {
5685 return create_select(pos, addr, qualifiers, iter);
5692 static void parse_compound_declarators(compound_t *compound,
5693 const declaration_specifiers_t *specifiers)
5698 if (token.type == ':') {
5699 source_position_t source_position = *HERE;
5702 type_t *base_type = specifiers->type;
5703 expression_t *size = parse_constant_expression();
5705 type_t *type = make_bitfield_type(base_type, size,
5706 &source_position, NULL);
5708 attribute_t *attributes = parse_attributes(NULL);
5709 attribute_t **anchor = &attributes;
5710 while (*anchor != NULL)
5711 anchor = &(*anchor)->next;
5712 *anchor = specifiers->attributes;
5714 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL);
5715 entity->base.source_position = source_position;
5716 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5717 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5718 entity->declaration.type = type;
5719 entity->declaration.attributes = attributes;
5721 if (attributes != NULL) {
5722 handle_entity_attributes(attributes, entity);
5724 append_entity(&compound->members, entity);
5726 entity = parse_declarator(specifiers,
5727 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5728 source_position_t const *const pos = &entity->base.source_position;
5729 if (entity->kind == ENTITY_TYPEDEF) {
5730 errorf(pos, "typedef not allowed as compound member");
5732 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5734 /* make sure we don't define a symbol multiple times */
5735 symbol_t *symbol = entity->base.symbol;
5736 if (symbol != NULL) {
5737 entity_t *prev = find_compound_entry(compound, symbol);
5739 source_position_t const *const ppos = &prev->base.source_position;
5740 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5744 if (token.type == ':') {
5745 source_position_t source_position = *HERE;
5747 expression_t *size = parse_constant_expression();
5749 type_t *type = entity->declaration.type;
5750 type_t *bitfield_type = make_bitfield_type(type, size,
5751 &source_position, entity->base.symbol);
5753 attribute_t *attributes = parse_attributes(NULL);
5754 entity->declaration.type = bitfield_type;
5755 handle_entity_attributes(attributes, entity);
5757 type_t *orig_type = entity->declaration.type;
5758 type_t *type = skip_typeref(orig_type);
5759 if (is_type_function(type)) {
5760 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5761 } else if (is_type_incomplete(type)) {
5762 /* §6.7.2.1:16 flexible array member */
5763 if (!is_type_array(type) ||
5764 token.type != ';' ||
5765 look_ahead(1)->type != '}') {
5766 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5771 append_entity(&compound->members, entity);
5774 } while (next_if(','));
5775 expect(';', end_error);
5778 anonymous_entity = NULL;
5781 static void parse_compound_type_entries(compound_t *compound)
5784 add_anchor_token('}');
5786 while (token.type != '}') {
5787 if (token.type == T_EOF) {
5788 errorf(HERE, "EOF while parsing struct");
5791 declaration_specifiers_t specifiers;
5792 parse_declaration_specifiers(&specifiers);
5793 parse_compound_declarators(compound, &specifiers);
5795 rem_anchor_token('}');
5799 compound->complete = true;
5802 static type_t *parse_typename(void)
5804 declaration_specifiers_t specifiers;
5805 parse_declaration_specifiers(&specifiers);
5806 if (specifiers.storage_class != STORAGE_CLASS_NONE
5807 || specifiers.thread_local) {
5808 /* TODO: improve error message, user does probably not know what a
5809 * storage class is...
5811 errorf(&specifiers.source_position, "typename must not have a storage class");
5814 type_t *result = parse_abstract_declarator(specifiers.type);
5822 typedef expression_t* (*parse_expression_function)(void);
5823 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5825 typedef struct expression_parser_function_t expression_parser_function_t;
5826 struct expression_parser_function_t {
5827 parse_expression_function parser;
5828 precedence_t infix_precedence;
5829 parse_expression_infix_function infix_parser;
5832 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5835 * Prints an error message if an expression was expected but not read
5837 static expression_t *expected_expression_error(void)
5839 /* skip the error message if the error token was read */
5840 if (token.type != T_ERROR) {
5841 errorf(HERE, "expected expression, got token %K", &token);
5845 return create_invalid_expression();
5848 static type_t *get_string_type(void)
5850 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5853 static type_t *get_wide_string_type(void)
5855 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5859 * Parse a string constant.
5861 static expression_t *parse_string_literal(void)
5863 source_position_t begin = token.source_position;
5864 string_t res = token.literal;
5865 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5868 while (token.type == T_STRING_LITERAL
5869 || token.type == T_WIDE_STRING_LITERAL) {
5870 warn_string_concat(&token.source_position);
5871 res = concat_strings(&res, &token.literal);
5873 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5876 expression_t *literal;
5878 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5879 literal->base.type = get_wide_string_type();
5881 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5882 literal->base.type = get_string_type();
5884 literal->base.source_position = begin;
5885 literal->literal.value = res;
5891 * Parse a boolean constant.
5893 static expression_t *parse_boolean_literal(bool value)
5895 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5896 literal->base.source_position = token.source_position;
5897 literal->base.type = type_bool;
5898 literal->literal.value.begin = value ? "true" : "false";
5899 literal->literal.value.size = value ? 4 : 5;
5905 static void warn_traditional_suffix(void)
5907 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%Y' suffix", token.symbol);
5910 static void check_integer_suffix(void)
5912 symbol_t *suffix = token.symbol;
5916 bool not_traditional = false;
5917 const char *c = suffix->string;
5918 if (*c == 'l' || *c == 'L') {
5921 not_traditional = true;
5923 if (*c == 'u' || *c == 'U') {
5926 } else if (*c == 'u' || *c == 'U') {
5927 not_traditional = true;
5930 } else if (*c == 'u' || *c == 'U') {
5931 not_traditional = true;
5933 if (*c == 'l' || *c == 'L') {
5941 errorf(&token.source_position,
5942 "invalid suffix '%s' on integer constant", suffix->string);
5943 } else if (not_traditional) {
5944 warn_traditional_suffix();
5948 static type_t *check_floatingpoint_suffix(void)
5950 symbol_t *suffix = token.symbol;
5951 type_t *type = type_double;
5955 bool not_traditional = false;
5956 const char *c = suffix->string;
5957 if (*c == 'f' || *c == 'F') {
5960 } else if (*c == 'l' || *c == 'L') {
5962 type = type_long_double;
5965 errorf(&token.source_position,
5966 "invalid suffix '%s' on floatingpoint constant", suffix->string);
5967 } else if (not_traditional) {
5968 warn_traditional_suffix();
5975 * Parse an integer constant.
5977 static expression_t *parse_number_literal(void)
5979 expression_kind_t kind;
5982 switch (token.type) {
5984 kind = EXPR_LITERAL_INTEGER;
5985 check_integer_suffix();
5988 case T_INTEGER_OCTAL:
5989 kind = EXPR_LITERAL_INTEGER_OCTAL;
5990 check_integer_suffix();
5993 case T_INTEGER_HEXADECIMAL:
5994 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5995 check_integer_suffix();
5998 case T_FLOATINGPOINT:
5999 kind = EXPR_LITERAL_FLOATINGPOINT;
6000 type = check_floatingpoint_suffix();
6002 case T_FLOATINGPOINT_HEXADECIMAL:
6003 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6004 type = check_floatingpoint_suffix();
6007 panic("unexpected token type in parse_number_literal");
6010 expression_t *literal = allocate_expression_zero(kind);
6011 literal->base.source_position = token.source_position;
6012 literal->base.type = type;
6013 literal->literal.value = token.literal;
6014 literal->literal.suffix = token.symbol;
6017 /* integer type depends on the size of the number and the size
6018 * representable by the types. The backend/codegeneration has to determine
6021 determine_literal_type(&literal->literal);
6026 * Parse a character constant.
6028 static expression_t *parse_character_constant(void)
6030 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6031 literal->base.source_position = token.source_position;
6032 literal->base.type = c_mode & _CXX ? type_char : type_int;
6033 literal->literal.value = token.literal;
6035 size_t len = literal->literal.value.size;
6037 if (!GNU_MODE && !(c_mode & _C99)) {
6038 errorf(HERE, "more than 1 character in character constant");
6040 literal->base.type = type_int;
6041 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6050 * Parse a wide character constant.
6052 static expression_t *parse_wide_character_constant(void)
6054 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6055 literal->base.source_position = token.source_position;
6056 literal->base.type = type_int;
6057 literal->literal.value = token.literal;
6059 size_t len = wstrlen(&literal->literal.value);
6061 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6068 static entity_t *create_implicit_function(symbol_t *symbol,
6069 const source_position_t *source_position)
6071 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6072 ntype->function.return_type = type_int;
6073 ntype->function.unspecified_parameters = true;
6074 ntype->function.linkage = LINKAGE_C;
6075 type_t *type = identify_new_type(ntype);
6077 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6078 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6079 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6080 entity->declaration.type = type;
6081 entity->declaration.implicit = true;
6082 entity->base.source_position = *source_position;
6084 if (current_scope != NULL)
6085 record_entity(entity, false);
6091 * Performs automatic type cast as described in §6.3.2.1.
6093 * @param orig_type the original type
6095 static type_t *automatic_type_conversion(type_t *orig_type)
6097 type_t *type = skip_typeref(orig_type);
6098 if (is_type_array(type)) {
6099 array_type_t *array_type = &type->array;
6100 type_t *element_type = array_type->element_type;
6101 unsigned qualifiers = array_type->base.qualifiers;
6103 return make_pointer_type(element_type, qualifiers);
6106 if (is_type_function(type)) {
6107 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6114 * reverts the automatic casts of array to pointer types and function
6115 * to function-pointer types as defined §6.3.2.1
6117 type_t *revert_automatic_type_conversion(const expression_t *expression)
6119 switch (expression->kind) {
6120 case EXPR_REFERENCE: {
6121 entity_t *entity = expression->reference.entity;
6122 if (is_declaration(entity)) {
6123 return entity->declaration.type;
6124 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6125 return entity->enum_value.enum_type;
6127 panic("no declaration or enum in reference");
6132 entity_t *entity = expression->select.compound_entry;
6133 assert(is_declaration(entity));
6134 type_t *type = entity->declaration.type;
6135 return get_qualified_type(type,
6136 expression->base.type->base.qualifiers);
6139 case EXPR_UNARY_DEREFERENCE: {
6140 const expression_t *const value = expression->unary.value;
6141 type_t *const type = skip_typeref(value->base.type);
6142 if (!is_type_pointer(type))
6143 return type_error_type;
6144 return type->pointer.points_to;
6147 case EXPR_ARRAY_ACCESS: {
6148 const expression_t *array_ref = expression->array_access.array_ref;
6149 type_t *type_left = skip_typeref(array_ref->base.type);
6150 if (!is_type_pointer(type_left))
6151 return type_error_type;
6152 return type_left->pointer.points_to;
6155 case EXPR_STRING_LITERAL: {
6156 size_t size = expression->string_literal.value.size;
6157 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6160 case EXPR_WIDE_STRING_LITERAL: {
6161 size_t size = wstrlen(&expression->string_literal.value);
6162 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6165 case EXPR_COMPOUND_LITERAL:
6166 return expression->compound_literal.type;
6171 return expression->base.type;
6175 * Find an entity matching a symbol in a scope.
6176 * Uses current scope if scope is NULL
6178 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6179 namespace_tag_t namespc)
6181 if (scope == NULL) {
6182 return get_entity(symbol, namespc);
6185 /* we should optimize here, if scope grows above a certain size we should
6186 construct a hashmap here... */
6187 entity_t *entity = scope->entities;
6188 for ( ; entity != NULL; entity = entity->base.next) {
6189 if (entity->base.symbol == symbol
6190 && (namespace_tag_t)entity->base.namespc == namespc)
6197 static entity_t *parse_qualified_identifier(void)
6199 /* namespace containing the symbol */
6201 source_position_t pos;
6202 const scope_t *lookup_scope = NULL;
6204 if (next_if(T_COLONCOLON))
6205 lookup_scope = &unit->scope;
6209 if (token.type != T_IDENTIFIER) {
6210 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6211 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6213 symbol = token.symbol;
6218 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6220 if (!next_if(T_COLONCOLON))
6223 switch (entity->kind) {
6224 case ENTITY_NAMESPACE:
6225 lookup_scope = &entity->namespacee.members;
6230 lookup_scope = &entity->compound.members;
6233 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6234 symbol, get_entity_kind_name(entity->kind));
6236 /* skip further qualifications */
6237 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6239 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6243 if (entity == NULL) {
6244 if (!strict_mode && token.type == '(') {
6245 /* an implicitly declared function */
6246 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6247 entity = create_implicit_function(symbol, &pos);
6249 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6250 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6257 static expression_t *parse_reference(void)
6259 source_position_t const pos = token.source_position;
6260 entity_t *const entity = parse_qualified_identifier();
6263 if (is_declaration(entity)) {
6264 orig_type = entity->declaration.type;
6265 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6266 orig_type = entity->enum_value.enum_type;
6268 panic("expected declaration or enum value in reference");
6271 /* we always do the auto-type conversions; the & and sizeof parser contains
6272 * code to revert this! */
6273 type_t *type = automatic_type_conversion(orig_type);
6275 expression_kind_t kind = EXPR_REFERENCE;
6276 if (entity->kind == ENTITY_ENUM_VALUE)
6277 kind = EXPR_REFERENCE_ENUM_VALUE;
6279 expression_t *expression = allocate_expression_zero(kind);
6280 expression->base.source_position = pos;
6281 expression->base.type = type;
6282 expression->reference.entity = entity;
6284 /* this declaration is used */
6285 if (is_declaration(entity)) {
6286 entity->declaration.used = true;
6289 if (entity->base.parent_scope != file_scope
6290 && (current_function != NULL
6291 && entity->base.parent_scope->depth < current_function->parameters.depth)
6292 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6293 if (entity->kind == ENTITY_VARIABLE) {
6294 /* access of a variable from an outer function */
6295 entity->variable.address_taken = true;
6296 } else if (entity->kind == ENTITY_PARAMETER) {
6297 entity->parameter.address_taken = true;
6299 current_function->need_closure = true;
6302 check_deprecated(&pos, entity);
6304 if (entity == current_init_decl && !in_type_prop && entity->kind == ENTITY_VARIABLE) {
6305 current_init_decl = NULL;
6306 warningf(WARN_INIT_SELF, &pos, "variable '%#N' is initialized by itself", entity);
6312 static bool semantic_cast(expression_t *cast)
6314 expression_t *expression = cast->unary.value;
6315 type_t *orig_dest_type = cast->base.type;
6316 type_t *orig_type_right = expression->base.type;
6317 type_t const *dst_type = skip_typeref(orig_dest_type);
6318 type_t const *src_type = skip_typeref(orig_type_right);
6319 source_position_t const *pos = &cast->base.source_position;
6321 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6322 if (dst_type == type_void)
6325 /* only integer and pointer can be casted to pointer */
6326 if (is_type_pointer(dst_type) &&
6327 !is_type_pointer(src_type) &&
6328 !is_type_integer(src_type) &&
6329 is_type_valid(src_type)) {
6330 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6334 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6335 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6339 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6340 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6344 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6345 type_t *src = skip_typeref(src_type->pointer.points_to);
6346 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6347 unsigned missing_qualifiers =
6348 src->base.qualifiers & ~dst->base.qualifiers;
6349 if (missing_qualifiers != 0) {
6350 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6356 static expression_t *parse_compound_literal(type_t *type)
6358 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6360 parse_initializer_env_t env;
6363 env.must_be_constant = false;
6364 initializer_t *initializer = parse_initializer(&env);
6367 expression->compound_literal.initializer = initializer;
6368 expression->compound_literal.type = type;
6369 expression->base.type = automatic_type_conversion(type);
6375 * Parse a cast expression.
6377 static expression_t *parse_cast(void)
6379 source_position_t source_position = token.source_position;
6382 add_anchor_token(')');
6384 type_t *type = parse_typename();
6386 rem_anchor_token(')');
6387 expect(')', end_error);
6389 if (token.type == '{') {
6390 return parse_compound_literal(type);
6393 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6394 cast->base.source_position = source_position;
6396 expression_t *value = parse_subexpression(PREC_CAST);
6397 cast->base.type = type;
6398 cast->unary.value = value;
6400 if (! semantic_cast(cast)) {
6401 /* TODO: record the error in the AST. else it is impossible to detect it */
6406 return create_invalid_expression();
6410 * Parse a statement expression.
6412 static expression_t *parse_statement_expression(void)
6414 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6417 add_anchor_token(')');
6419 statement_t *statement = parse_compound_statement(true);
6420 statement->compound.stmt_expr = true;
6421 expression->statement.statement = statement;
6423 /* find last statement and use its type */
6424 type_t *type = type_void;
6425 const statement_t *stmt = statement->compound.statements;
6427 while (stmt->base.next != NULL)
6428 stmt = stmt->base.next;
6430 if (stmt->kind == STATEMENT_EXPRESSION) {
6431 type = stmt->expression.expression->base.type;
6434 source_position_t const *const pos = &expression->base.source_position;
6435 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6437 expression->base.type = type;
6439 rem_anchor_token(')');
6440 expect(')', end_error);
6447 * Parse a parenthesized expression.
6449 static expression_t *parse_parenthesized_expression(void)
6451 token_t const* const la1 = look_ahead(1);
6452 switch (la1->type) {
6454 /* gcc extension: a statement expression */
6455 return parse_statement_expression();
6458 if (is_typedef_symbol(la1->symbol)) {
6460 return parse_cast();
6465 add_anchor_token(')');
6466 expression_t *result = parse_expression();
6467 result->base.parenthesized = true;
6468 rem_anchor_token(')');
6469 expect(')', end_error);
6475 static expression_t *parse_function_keyword(void)
6479 if (current_function == NULL) {
6480 errorf(HERE, "'__func__' used outside of a function");
6483 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6484 expression->base.type = type_char_ptr;
6485 expression->funcname.kind = FUNCNAME_FUNCTION;
6492 static expression_t *parse_pretty_function_keyword(void)
6494 if (current_function == NULL) {
6495 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6498 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6499 expression->base.type = type_char_ptr;
6500 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6502 eat(T___PRETTY_FUNCTION__);
6507 static expression_t *parse_funcsig_keyword(void)
6509 if (current_function == NULL) {
6510 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6513 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6514 expression->base.type = type_char_ptr;
6515 expression->funcname.kind = FUNCNAME_FUNCSIG;
6522 static expression_t *parse_funcdname_keyword(void)
6524 if (current_function == NULL) {
6525 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6528 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6529 expression->base.type = type_char_ptr;
6530 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6532 eat(T___FUNCDNAME__);
6537 static designator_t *parse_designator(void)
6539 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6540 result->source_position = *HERE;
6542 if (token.type != T_IDENTIFIER) {
6543 parse_error_expected("while parsing member designator",
6544 T_IDENTIFIER, NULL);
6547 result->symbol = token.symbol;
6550 designator_t *last_designator = result;
6553 if (token.type != T_IDENTIFIER) {
6554 parse_error_expected("while parsing member designator",
6555 T_IDENTIFIER, NULL);
6558 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6559 designator->source_position = *HERE;
6560 designator->symbol = token.symbol;
6563 last_designator->next = designator;
6564 last_designator = designator;
6568 add_anchor_token(']');
6569 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6570 designator->source_position = *HERE;
6571 designator->array_index = parse_expression();
6572 rem_anchor_token(']');
6573 expect(']', end_error);
6574 if (designator->array_index == NULL) {
6578 last_designator->next = designator;
6579 last_designator = designator;
6591 * Parse the __builtin_offsetof() expression.
6593 static expression_t *parse_offsetof(void)
6595 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6596 expression->base.type = type_size_t;
6598 eat(T___builtin_offsetof);
6600 expect('(', end_error);
6601 add_anchor_token(',');
6602 type_t *type = parse_typename();
6603 rem_anchor_token(',');
6604 expect(',', end_error);
6605 add_anchor_token(')');
6606 designator_t *designator = parse_designator();
6607 rem_anchor_token(')');
6608 expect(')', end_error);
6610 expression->offsetofe.type = type;
6611 expression->offsetofe.designator = designator;
6614 memset(&path, 0, sizeof(path));
6615 path.top_type = type;
6616 path.path = NEW_ARR_F(type_path_entry_t, 0);
6618 descend_into_subtype(&path);
6620 if (!walk_designator(&path, designator, true)) {
6621 return create_invalid_expression();
6624 DEL_ARR_F(path.path);
6628 return create_invalid_expression();
6632 * Parses a _builtin_va_start() expression.
6634 static expression_t *parse_va_start(void)
6636 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6638 eat(T___builtin_va_start);
6640 expect('(', end_error);
6641 add_anchor_token(',');
6642 expression->va_starte.ap = parse_assignment_expression();
6643 rem_anchor_token(',');
6644 expect(',', end_error);
6645 expression_t *const expr = parse_assignment_expression();
6646 if (expr->kind == EXPR_REFERENCE) {
6647 entity_t *const entity = expr->reference.entity;
6648 if (!current_function->base.type->function.variadic) {
6649 errorf(&expr->base.source_position,
6650 "'va_start' used in non-variadic function");
6651 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6652 entity->base.next != NULL ||
6653 entity->kind != ENTITY_PARAMETER) {
6654 errorf(&expr->base.source_position,
6655 "second argument of 'va_start' must be last parameter of the current function");
6657 expression->va_starte.parameter = &entity->variable;
6659 expect(')', end_error);
6662 expect(')', end_error);
6664 return create_invalid_expression();
6668 * Parses a __builtin_va_arg() expression.
6670 static expression_t *parse_va_arg(void)
6672 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6674 eat(T___builtin_va_arg);
6676 expect('(', end_error);
6678 ap.expression = parse_assignment_expression();
6679 expression->va_arge.ap = ap.expression;
6680 check_call_argument(type_valist, &ap, 1);
6682 expect(',', end_error);
6683 expression->base.type = parse_typename();
6684 expect(')', end_error);
6688 return create_invalid_expression();
6692 * Parses a __builtin_va_copy() expression.
6694 static expression_t *parse_va_copy(void)
6696 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6698 eat(T___builtin_va_copy);
6700 expect('(', end_error);
6701 expression_t *dst = parse_assignment_expression();
6702 assign_error_t error = semantic_assign(type_valist, dst);
6703 report_assign_error(error, type_valist, dst, "call argument 1",
6704 &dst->base.source_position);
6705 expression->va_copye.dst = dst;
6707 expect(',', end_error);
6709 call_argument_t src;
6710 src.expression = parse_assignment_expression();
6711 check_call_argument(type_valist, &src, 2);
6712 expression->va_copye.src = src.expression;
6713 expect(')', end_error);
6717 return create_invalid_expression();
6721 * Parses a __builtin_constant_p() expression.
6723 static expression_t *parse_builtin_constant(void)
6725 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6727 eat(T___builtin_constant_p);
6729 expect('(', end_error);
6730 add_anchor_token(')');
6731 expression->builtin_constant.value = parse_assignment_expression();
6732 rem_anchor_token(')');
6733 expect(')', end_error);
6734 expression->base.type = type_int;
6738 return create_invalid_expression();
6742 * Parses a __builtin_types_compatible_p() expression.
6744 static expression_t *parse_builtin_types_compatible(void)
6746 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6748 eat(T___builtin_types_compatible_p);
6750 expect('(', end_error);
6751 add_anchor_token(')');
6752 add_anchor_token(',');
6753 expression->builtin_types_compatible.left = parse_typename();
6754 rem_anchor_token(',');
6755 expect(',', end_error);
6756 expression->builtin_types_compatible.right = parse_typename();
6757 rem_anchor_token(')');
6758 expect(')', end_error);
6759 expression->base.type = type_int;
6763 return create_invalid_expression();
6767 * Parses a __builtin_is_*() compare expression.
6769 static expression_t *parse_compare_builtin(void)
6771 expression_t *expression;
6773 switch (token.type) {
6774 case T___builtin_isgreater:
6775 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6777 case T___builtin_isgreaterequal:
6778 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6780 case T___builtin_isless:
6781 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6783 case T___builtin_islessequal:
6784 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6786 case T___builtin_islessgreater:
6787 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6789 case T___builtin_isunordered:
6790 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6793 internal_errorf(HERE, "invalid compare builtin found");
6795 expression->base.source_position = *HERE;
6798 expect('(', end_error);
6799 expression->binary.left = parse_assignment_expression();
6800 expect(',', end_error);
6801 expression->binary.right = parse_assignment_expression();
6802 expect(')', end_error);
6804 type_t *const orig_type_left = expression->binary.left->base.type;
6805 type_t *const orig_type_right = expression->binary.right->base.type;
6807 type_t *const type_left = skip_typeref(orig_type_left);
6808 type_t *const type_right = skip_typeref(orig_type_right);
6809 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6810 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6811 type_error_incompatible("invalid operands in comparison",
6812 &expression->base.source_position, orig_type_left, orig_type_right);
6815 semantic_comparison(&expression->binary);
6820 return create_invalid_expression();
6824 * Parses a MS assume() expression.
6826 static expression_t *parse_assume(void)
6828 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6832 expect('(', end_error);
6833 add_anchor_token(')');
6834 expression->unary.value = parse_assignment_expression();
6835 rem_anchor_token(')');
6836 expect(')', end_error);
6838 expression->base.type = type_void;
6841 return create_invalid_expression();
6845 * Return the label for the current symbol or create a new one.
6847 static label_t *get_label(void)
6849 assert(token.type == T_IDENTIFIER);
6850 assert(current_function != NULL);
6852 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6853 /* If we find a local label, we already created the declaration. */
6854 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6855 if (label->base.parent_scope != current_scope) {
6856 assert(label->base.parent_scope->depth < current_scope->depth);
6857 current_function->goto_to_outer = true;
6859 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6860 /* There is no matching label in the same function, so create a new one. */
6861 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6866 return &label->label;
6870 * Parses a GNU && label address expression.
6872 static expression_t *parse_label_address(void)
6874 source_position_t source_position = token.source_position;
6876 if (token.type != T_IDENTIFIER) {
6877 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6878 return create_invalid_expression();
6881 label_t *const label = get_label();
6883 label->address_taken = true;
6885 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6886 expression->base.source_position = source_position;
6888 /* label address is treated as a void pointer */
6889 expression->base.type = type_void_ptr;
6890 expression->label_address.label = label;
6895 * Parse a microsoft __noop expression.
6897 static expression_t *parse_noop_expression(void)
6899 /* the result is a (int)0 */
6900 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6901 literal->base.type = type_int;
6902 literal->base.source_position = token.source_position;
6903 literal->literal.value.begin = "__noop";
6904 literal->literal.value.size = 6;
6908 if (token.type == '(') {
6909 /* parse arguments */
6911 add_anchor_token(')');
6912 add_anchor_token(',');
6914 if (token.type != ')') do {
6915 (void)parse_assignment_expression();
6916 } while (next_if(','));
6918 rem_anchor_token(',');
6919 rem_anchor_token(')');
6920 expect(')', end_error);
6927 * Parses a primary expression.
6929 static expression_t *parse_primary_expression(void)
6931 switch (token.type) {
6932 case T_false: return parse_boolean_literal(false);
6933 case T_true: return parse_boolean_literal(true);
6935 case T_INTEGER_OCTAL:
6936 case T_INTEGER_HEXADECIMAL:
6937 case T_FLOATINGPOINT:
6938 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6939 case T_CHARACTER_CONSTANT: return parse_character_constant();
6940 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6941 case T_STRING_LITERAL:
6942 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6943 case T___FUNCTION__:
6944 case T___func__: return parse_function_keyword();
6945 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6946 case T___FUNCSIG__: return parse_funcsig_keyword();
6947 case T___FUNCDNAME__: return parse_funcdname_keyword();
6948 case T___builtin_offsetof: return parse_offsetof();
6949 case T___builtin_va_start: return parse_va_start();
6950 case T___builtin_va_arg: return parse_va_arg();
6951 case T___builtin_va_copy: return parse_va_copy();
6952 case T___builtin_isgreater:
6953 case T___builtin_isgreaterequal:
6954 case T___builtin_isless:
6955 case T___builtin_islessequal:
6956 case T___builtin_islessgreater:
6957 case T___builtin_isunordered: return parse_compare_builtin();
6958 case T___builtin_constant_p: return parse_builtin_constant();
6959 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6960 case T__assume: return parse_assume();
6963 return parse_label_address();
6966 case '(': return parse_parenthesized_expression();
6967 case T___noop: return parse_noop_expression();
6969 /* Gracefully handle type names while parsing expressions. */
6971 return parse_reference();
6973 if (!is_typedef_symbol(token.symbol)) {
6974 return parse_reference();
6978 source_position_t const pos = *HERE;
6979 declaration_specifiers_t specifiers;
6980 parse_declaration_specifiers(&specifiers);
6981 type_t const *const type = parse_abstract_declarator(specifiers.type);
6982 errorf(&pos, "encountered type '%T' while parsing expression", type);
6983 return create_invalid_expression();
6987 errorf(HERE, "unexpected token %K, expected an expression", &token);
6989 return create_invalid_expression();
6992 static expression_t *parse_array_expression(expression_t *left)
6994 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6995 array_access_expression_t *const arr = &expr->array_access;
6998 add_anchor_token(']');
7000 expression_t *const inside = parse_expression();
7002 type_t *const orig_type_left = left->base.type;
7003 type_t *const orig_type_inside = inside->base.type;
7005 type_t *const type_left = skip_typeref(orig_type_left);
7006 type_t *const type_inside = skip_typeref(orig_type_inside);
7012 if (is_type_pointer(type_left)) {
7015 idx_type = type_inside;
7016 res_type = type_left->pointer.points_to;
7018 } else if (is_type_pointer(type_inside)) {
7019 arr->flipped = true;
7022 idx_type = type_left;
7023 res_type = type_inside->pointer.points_to;
7025 res_type = automatic_type_conversion(res_type);
7026 if (!is_type_integer(idx_type)) {
7027 errorf(&idx->base.source_position, "array subscript must have integer type");
7028 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
7029 source_position_t const *const pos = &idx->base.source_position;
7030 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
7033 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7034 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7036 res_type = type_error_type;
7041 arr->array_ref = ref;
7043 arr->base.type = res_type;
7045 rem_anchor_token(']');
7046 expect(']', end_error);
7051 static expression_t *parse_typeprop(expression_kind_t const kind)
7053 expression_t *tp_expression = allocate_expression_zero(kind);
7054 tp_expression->base.type = type_size_t;
7056 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7058 /* we only refer to a type property, mark this case */
7059 bool old = in_type_prop;
7060 in_type_prop = true;
7063 expression_t *expression;
7064 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7066 add_anchor_token(')');
7067 orig_type = parse_typename();
7068 rem_anchor_token(')');
7069 expect(')', end_error);
7071 if (token.type == '{') {
7072 /* It was not sizeof(type) after all. It is sizeof of an expression
7073 * starting with a compound literal */
7074 expression = parse_compound_literal(orig_type);
7075 goto typeprop_expression;
7078 expression = parse_subexpression(PREC_UNARY);
7080 typeprop_expression:
7081 tp_expression->typeprop.tp_expression = expression;
7083 orig_type = revert_automatic_type_conversion(expression);
7084 expression->base.type = orig_type;
7087 tp_expression->typeprop.type = orig_type;
7088 type_t const* const type = skip_typeref(orig_type);
7089 char const* wrong_type = NULL;
7090 if (is_type_incomplete(type)) {
7091 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7092 wrong_type = "incomplete";
7093 } else if (type->kind == TYPE_FUNCTION) {
7095 /* function types are allowed (and return 1) */
7096 source_position_t const *const pos = &tp_expression->base.source_position;
7097 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7098 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7100 wrong_type = "function";
7103 if (is_type_incomplete(type))
7104 wrong_type = "incomplete";
7106 if (type->kind == TYPE_BITFIELD)
7107 wrong_type = "bitfield";
7109 if (wrong_type != NULL) {
7110 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7111 errorf(&tp_expression->base.source_position,
7112 "operand of %s expression must not be of %s type '%T'",
7113 what, wrong_type, orig_type);
7118 return tp_expression;
7121 static expression_t *parse_sizeof(void)
7123 return parse_typeprop(EXPR_SIZEOF);
7126 static expression_t *parse_alignof(void)
7128 return parse_typeprop(EXPR_ALIGNOF);
7131 static expression_t *parse_select_expression(expression_t *addr)
7133 assert(token.type == '.' || token.type == T_MINUSGREATER);
7134 bool select_left_arrow = (token.type == T_MINUSGREATER);
7135 source_position_t const pos = *HERE;
7138 if (token.type != T_IDENTIFIER) {
7139 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7140 return create_invalid_expression();
7142 symbol_t *symbol = token.symbol;
7145 type_t *const orig_type = addr->base.type;
7146 type_t *const type = skip_typeref(orig_type);
7149 bool saw_error = false;
7150 if (is_type_pointer(type)) {
7151 if (!select_left_arrow) {
7153 "request for member '%Y' in something not a struct or union, but '%T'",
7157 type_left = skip_typeref(type->pointer.points_to);
7159 if (select_left_arrow && is_type_valid(type)) {
7160 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7166 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7167 type_left->kind != TYPE_COMPOUND_UNION) {
7169 if (is_type_valid(type_left) && !saw_error) {
7171 "request for member '%Y' in something not a struct or union, but '%T'",
7174 return create_invalid_expression();
7177 compound_t *compound = type_left->compound.compound;
7178 if (!compound->complete) {
7179 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7181 return create_invalid_expression();
7184 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7185 expression_t *result =
7186 find_create_select(&pos, addr, qualifiers, compound, symbol);
7188 if (result == NULL) {
7189 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7190 return create_invalid_expression();
7196 static void check_call_argument(type_t *expected_type,
7197 call_argument_t *argument, unsigned pos)
7199 type_t *expected_type_skip = skip_typeref(expected_type);
7200 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7201 expression_t *arg_expr = argument->expression;
7202 type_t *arg_type = skip_typeref(arg_expr->base.type);
7204 /* handle transparent union gnu extension */
7205 if (is_type_union(expected_type_skip)
7206 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7207 compound_t *union_decl = expected_type_skip->compound.compound;
7208 type_t *best_type = NULL;
7209 entity_t *entry = union_decl->members.entities;
7210 for ( ; entry != NULL; entry = entry->base.next) {
7211 assert(is_declaration(entry));
7212 type_t *decl_type = entry->declaration.type;
7213 error = semantic_assign(decl_type, arg_expr);
7214 if (error == ASSIGN_ERROR_INCOMPATIBLE
7215 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7218 if (error == ASSIGN_SUCCESS) {
7219 best_type = decl_type;
7220 } else if (best_type == NULL) {
7221 best_type = decl_type;
7225 if (best_type != NULL) {
7226 expected_type = best_type;
7230 error = semantic_assign(expected_type, arg_expr);
7231 argument->expression = create_implicit_cast(arg_expr, expected_type);
7233 if (error != ASSIGN_SUCCESS) {
7234 /* report exact scope in error messages (like "in argument 3") */
7236 snprintf(buf, sizeof(buf), "call argument %u", pos);
7237 report_assign_error(error, expected_type, arg_expr, buf,
7238 &arg_expr->base.source_position);
7240 type_t *const promoted_type = get_default_promoted_type(arg_type);
7241 if (!types_compatible(expected_type_skip, promoted_type) &&
7242 !types_compatible(expected_type_skip, type_void_ptr) &&
7243 !types_compatible(type_void_ptr, promoted_type)) {
7244 /* Deliberately show the skipped types in this warning */
7245 source_position_t const *const apos = &arg_expr->base.source_position;
7246 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7252 * Handle the semantic restrictions of builtin calls
7254 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7255 switch (call->function->reference.entity->function.btk) {
7256 case bk_gnu_builtin_return_address:
7257 case bk_gnu_builtin_frame_address: {
7258 /* argument must be constant */
7259 call_argument_t *argument = call->arguments;
7261 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7262 errorf(&call->base.source_position,
7263 "argument of '%Y' must be a constant expression",
7264 call->function->reference.entity->base.symbol);
7268 case bk_gnu_builtin_object_size:
7269 if (call->arguments == NULL)
7272 call_argument_t *arg = call->arguments->next;
7273 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7274 errorf(&call->base.source_position,
7275 "second argument of '%Y' must be a constant expression",
7276 call->function->reference.entity->base.symbol);
7279 case bk_gnu_builtin_prefetch:
7280 /* second and third argument must be constant if existent */
7281 if (call->arguments == NULL)
7283 call_argument_t *rw = call->arguments->next;
7284 call_argument_t *locality = NULL;
7287 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7288 errorf(&call->base.source_position,
7289 "second argument of '%Y' must be a constant expression",
7290 call->function->reference.entity->base.symbol);
7292 locality = rw->next;
7294 if (locality != NULL) {
7295 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7296 errorf(&call->base.source_position,
7297 "third argument of '%Y' must be a constant expression",
7298 call->function->reference.entity->base.symbol);
7300 locality = rw->next;
7309 * Parse a call expression, ie. expression '( ... )'.
7311 * @param expression the function address
7313 static expression_t *parse_call_expression(expression_t *expression)
7315 expression_t *result = allocate_expression_zero(EXPR_CALL);
7316 call_expression_t *call = &result->call;
7317 call->function = expression;
7319 type_t *const orig_type = expression->base.type;
7320 type_t *const type = skip_typeref(orig_type);
7322 function_type_t *function_type = NULL;
7323 if (is_type_pointer(type)) {
7324 type_t *const to_type = skip_typeref(type->pointer.points_to);
7326 if (is_type_function(to_type)) {
7327 function_type = &to_type->function;
7328 call->base.type = function_type->return_type;
7332 if (function_type == NULL && is_type_valid(type)) {
7334 "called object '%E' (type '%T') is not a pointer to a function",
7335 expression, orig_type);
7338 /* parse arguments */
7340 add_anchor_token(')');
7341 add_anchor_token(',');
7343 if (token.type != ')') {
7344 call_argument_t **anchor = &call->arguments;
7346 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7347 argument->expression = parse_assignment_expression();
7350 anchor = &argument->next;
7351 } while (next_if(','));
7353 rem_anchor_token(',');
7354 rem_anchor_token(')');
7355 expect(')', end_error);
7357 if (function_type == NULL)
7360 /* check type and count of call arguments */
7361 function_parameter_t *parameter = function_type->parameters;
7362 call_argument_t *argument = call->arguments;
7363 if (!function_type->unspecified_parameters) {
7364 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7365 parameter = parameter->next, argument = argument->next) {
7366 check_call_argument(parameter->type, argument, ++pos);
7369 if (parameter != NULL) {
7370 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7371 } else if (argument != NULL && !function_type->variadic) {
7372 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7376 /* do default promotion for other arguments */
7377 for (; argument != NULL; argument = argument->next) {
7378 type_t *argument_type = argument->expression->base.type;
7379 if (!is_type_object(skip_typeref(argument_type))) {
7380 errorf(&argument->expression->base.source_position,
7381 "call argument '%E' must not be void", argument->expression);
7384 argument_type = get_default_promoted_type(argument_type);
7386 argument->expression
7387 = create_implicit_cast(argument->expression, argument_type);
7392 if (is_type_compound(skip_typeref(function_type->return_type))) {
7393 source_position_t const *const pos = &expression->base.source_position;
7394 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7397 if (expression->kind == EXPR_REFERENCE) {
7398 reference_expression_t *reference = &expression->reference;
7399 if (reference->entity->kind == ENTITY_FUNCTION &&
7400 reference->entity->function.btk != bk_none)
7401 handle_builtin_argument_restrictions(call);
7408 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7410 static bool same_compound_type(const type_t *type1, const type_t *type2)
7413 is_type_compound(type1) &&
7414 type1->kind == type2->kind &&
7415 type1->compound.compound == type2->compound.compound;
7418 static expression_t const *get_reference_address(expression_t const *expr)
7420 bool regular_take_address = true;
7422 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7423 expr = expr->unary.value;
7425 regular_take_address = false;
7428 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7431 expr = expr->unary.value;
7434 if (expr->kind != EXPR_REFERENCE)
7437 /* special case for functions which are automatically converted to a
7438 * pointer to function without an extra TAKE_ADDRESS operation */
7439 if (!regular_take_address &&
7440 expr->reference.entity->kind != ENTITY_FUNCTION) {
7447 static void warn_reference_address_as_bool(expression_t const* expr)
7449 expr = get_reference_address(expr);
7451 source_position_t const *const pos = &expr->base.source_position;
7452 entity_t const *const ent = expr->reference.entity;
7453 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7457 static void warn_assignment_in_condition(const expression_t *const expr)
7459 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7461 if (expr->base.parenthesized)
7463 source_position_t const *const pos = &expr->base.source_position;
7464 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7467 static void semantic_condition(expression_t const *const expr,
7468 char const *const context)
7470 type_t *const type = skip_typeref(expr->base.type);
7471 if (is_type_scalar(type)) {
7472 warn_reference_address_as_bool(expr);
7473 warn_assignment_in_condition(expr);
7474 } else if (is_type_valid(type)) {
7475 errorf(&expr->base.source_position,
7476 "%s must have scalar type", context);
7481 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7483 * @param expression the conditional expression
7485 static expression_t *parse_conditional_expression(expression_t *expression)
7487 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7489 conditional_expression_t *conditional = &result->conditional;
7490 conditional->condition = expression;
7493 add_anchor_token(':');
7495 /* §6.5.15:2 The first operand shall have scalar type. */
7496 semantic_condition(expression, "condition of conditional operator");
7498 expression_t *true_expression = expression;
7499 bool gnu_cond = false;
7500 if (GNU_MODE && token.type == ':') {
7503 true_expression = parse_expression();
7505 rem_anchor_token(':');
7506 expect(':', end_error);
7508 expression_t *false_expression =
7509 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7511 type_t *const orig_true_type = true_expression->base.type;
7512 type_t *const orig_false_type = false_expression->base.type;
7513 type_t *const true_type = skip_typeref(orig_true_type);
7514 type_t *const false_type = skip_typeref(orig_false_type);
7517 source_position_t const *const pos = &conditional->base.source_position;
7518 type_t *result_type;
7519 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7520 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7521 /* ISO/IEC 14882:1998(E) §5.16:2 */
7522 if (true_expression->kind == EXPR_UNARY_THROW) {
7523 result_type = false_type;
7524 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7525 result_type = true_type;
7527 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7528 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7529 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7531 result_type = type_void;
7533 } else if (is_type_arithmetic(true_type)
7534 && is_type_arithmetic(false_type)) {
7535 result_type = semantic_arithmetic(true_type, false_type);
7536 } else if (same_compound_type(true_type, false_type)) {
7537 /* just take 1 of the 2 types */
7538 result_type = true_type;
7539 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7540 type_t *pointer_type;
7542 expression_t *other_expression;
7543 if (is_type_pointer(true_type) &&
7544 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7545 pointer_type = true_type;
7546 other_type = false_type;
7547 other_expression = false_expression;
7549 pointer_type = false_type;
7550 other_type = true_type;
7551 other_expression = true_expression;
7554 if (is_null_pointer_constant(other_expression)) {
7555 result_type = pointer_type;
7556 } else if (is_type_pointer(other_type)) {
7557 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7558 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7561 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7562 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7564 } else if (types_compatible(get_unqualified_type(to1),
7565 get_unqualified_type(to2))) {
7568 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7572 type_t *const type =
7573 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7574 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7575 } else if (is_type_integer(other_type)) {
7576 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7577 result_type = pointer_type;
7579 goto types_incompatible;
7583 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7584 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7586 result_type = type_error_type;
7589 conditional->true_expression
7590 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7591 conditional->false_expression
7592 = create_implicit_cast(false_expression, result_type);
7593 conditional->base.type = result_type;
7598 * Parse an extension expression.
7600 static expression_t *parse_extension(void)
7602 eat(T___extension__);
7604 bool old_gcc_extension = in_gcc_extension;
7605 in_gcc_extension = true;
7606 expression_t *expression = parse_subexpression(PREC_UNARY);
7607 in_gcc_extension = old_gcc_extension;
7612 * Parse a __builtin_classify_type() expression.
7614 static expression_t *parse_builtin_classify_type(void)
7616 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7617 result->base.type = type_int;
7619 eat(T___builtin_classify_type);
7621 expect('(', end_error);
7622 add_anchor_token(')');
7623 expression_t *expression = parse_expression();
7624 rem_anchor_token(')');
7625 expect(')', end_error);
7626 result->classify_type.type_expression = expression;
7630 return create_invalid_expression();
7634 * Parse a delete expression
7635 * ISO/IEC 14882:1998(E) §5.3.5
7637 static expression_t *parse_delete(void)
7639 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7640 result->base.type = type_void;
7645 result->kind = EXPR_UNARY_DELETE_ARRAY;
7646 expect(']', end_error);
7650 expression_t *const value = parse_subexpression(PREC_CAST);
7651 result->unary.value = value;
7653 type_t *const type = skip_typeref(value->base.type);
7654 if (!is_type_pointer(type)) {
7655 if (is_type_valid(type)) {
7656 errorf(&value->base.source_position,
7657 "operand of delete must have pointer type");
7659 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7660 source_position_t const *const pos = &value->base.source_position;
7661 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7668 * Parse a throw expression
7669 * ISO/IEC 14882:1998(E) §15:1
7671 static expression_t *parse_throw(void)
7673 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7674 result->base.type = type_void;
7678 expression_t *value = NULL;
7679 switch (token.type) {
7681 value = parse_assignment_expression();
7682 /* ISO/IEC 14882:1998(E) §15.1:3 */
7683 type_t *const orig_type = value->base.type;
7684 type_t *const type = skip_typeref(orig_type);
7685 if (is_type_incomplete(type)) {
7686 errorf(&value->base.source_position,
7687 "cannot throw object of incomplete type '%T'", orig_type);
7688 } else if (is_type_pointer(type)) {
7689 type_t *const points_to = skip_typeref(type->pointer.points_to);
7690 if (is_type_incomplete(points_to) &&
7691 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7692 errorf(&value->base.source_position,
7693 "cannot throw pointer to incomplete type '%T'", orig_type);
7701 result->unary.value = value;
7706 static bool check_pointer_arithmetic(const source_position_t *source_position,
7707 type_t *pointer_type,
7708 type_t *orig_pointer_type)
7710 type_t *points_to = pointer_type->pointer.points_to;
7711 points_to = skip_typeref(points_to);
7713 if (is_type_incomplete(points_to)) {
7714 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7715 errorf(source_position,
7716 "arithmetic with pointer to incomplete type '%T' not allowed",
7720 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7722 } else if (is_type_function(points_to)) {
7724 errorf(source_position,
7725 "arithmetic with pointer to function type '%T' not allowed",
7729 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7735 static bool is_lvalue(const expression_t *expression)
7737 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7738 switch (expression->kind) {
7739 case EXPR_ARRAY_ACCESS:
7740 case EXPR_COMPOUND_LITERAL:
7741 case EXPR_REFERENCE:
7743 case EXPR_UNARY_DEREFERENCE:
7747 type_t *type = skip_typeref(expression->base.type);
7749 /* ISO/IEC 14882:1998(E) §3.10:3 */
7750 is_type_reference(type) ||
7751 /* Claim it is an lvalue, if the type is invalid. There was a parse
7752 * error before, which maybe prevented properly recognizing it as
7754 !is_type_valid(type);
7759 static void semantic_incdec(unary_expression_t *expression)
7761 type_t *const orig_type = expression->value->base.type;
7762 type_t *const type = skip_typeref(orig_type);
7763 if (is_type_pointer(type)) {
7764 if (!check_pointer_arithmetic(&expression->base.source_position,
7768 } else if (!is_type_real(type) && is_type_valid(type)) {
7769 /* TODO: improve error message */
7770 errorf(&expression->base.source_position,
7771 "operation needs an arithmetic or pointer type");
7774 if (!is_lvalue(expression->value)) {
7775 /* TODO: improve error message */
7776 errorf(&expression->base.source_position, "lvalue required as operand");
7778 expression->base.type = orig_type;
7781 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7783 type_t *const orig_type = expression->value->base.type;
7784 type_t *const type = skip_typeref(orig_type);
7785 if (!is_type_arithmetic(type)) {
7786 if (is_type_valid(type)) {
7787 /* TODO: improve error message */
7788 errorf(&expression->base.source_position,
7789 "operation needs an arithmetic type");
7794 expression->base.type = orig_type;
7797 static void semantic_unexpr_plus(unary_expression_t *expression)
7799 semantic_unexpr_arithmetic(expression);
7800 source_position_t const *const pos = &expression->base.source_position;
7801 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7804 static void semantic_not(unary_expression_t *expression)
7806 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7807 semantic_condition(expression->value, "operand of !");
7808 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7811 static void semantic_unexpr_integer(unary_expression_t *expression)
7813 type_t *const orig_type = expression->value->base.type;
7814 type_t *const type = skip_typeref(orig_type);
7815 if (!is_type_integer(type)) {
7816 if (is_type_valid(type)) {
7817 errorf(&expression->base.source_position,
7818 "operand of ~ must be of integer type");
7823 expression->base.type = orig_type;
7826 static void semantic_dereference(unary_expression_t *expression)
7828 type_t *const orig_type = expression->value->base.type;
7829 type_t *const type = skip_typeref(orig_type);
7830 if (!is_type_pointer(type)) {
7831 if (is_type_valid(type)) {
7832 errorf(&expression->base.source_position,
7833 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7838 type_t *result_type = type->pointer.points_to;
7839 result_type = automatic_type_conversion(result_type);
7840 expression->base.type = result_type;
7844 * Record that an address is taken (expression represents an lvalue).
7846 * @param expression the expression
7847 * @param may_be_register if true, the expression might be an register
7849 static void set_address_taken(expression_t *expression, bool may_be_register)
7851 if (expression->kind != EXPR_REFERENCE)
7854 entity_t *const entity = expression->reference.entity;
7856 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7859 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7860 && !may_be_register) {
7861 source_position_t const *const pos = &expression->base.source_position;
7862 errorf(pos, "address of register '%N' requested", entity);
7865 if (entity->kind == ENTITY_VARIABLE) {
7866 entity->variable.address_taken = true;
7868 assert(entity->kind == ENTITY_PARAMETER);
7869 entity->parameter.address_taken = true;
7874 * Check the semantic of the address taken expression.
7876 static void semantic_take_addr(unary_expression_t *expression)
7878 expression_t *value = expression->value;
7879 value->base.type = revert_automatic_type_conversion(value);
7881 type_t *orig_type = value->base.type;
7882 type_t *type = skip_typeref(orig_type);
7883 if (!is_type_valid(type))
7887 if (!is_lvalue(value)) {
7888 errorf(&expression->base.source_position, "'&' requires an lvalue");
7890 if (type->kind == TYPE_BITFIELD) {
7891 errorf(&expression->base.source_position,
7892 "'&' not allowed on object with bitfield type '%T'",
7896 set_address_taken(value, false);
7898 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7901 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7902 static expression_t *parse_##unexpression_type(void) \
7904 expression_t *unary_expression \
7905 = allocate_expression_zero(unexpression_type); \
7907 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7909 sfunc(&unary_expression->unary); \
7911 return unary_expression; \
7914 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7915 semantic_unexpr_arithmetic)
7916 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7917 semantic_unexpr_plus)
7918 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7920 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7921 semantic_dereference)
7922 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7924 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7925 semantic_unexpr_integer)
7926 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7928 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7931 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7933 static expression_t *parse_##unexpression_type(expression_t *left) \
7935 expression_t *unary_expression \
7936 = allocate_expression_zero(unexpression_type); \
7938 unary_expression->unary.value = left; \
7940 sfunc(&unary_expression->unary); \
7942 return unary_expression; \
7945 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7946 EXPR_UNARY_POSTFIX_INCREMENT,
7948 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7949 EXPR_UNARY_POSTFIX_DECREMENT,
7952 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7954 /* TODO: handle complex + imaginary types */
7956 type_left = get_unqualified_type(type_left);
7957 type_right = get_unqualified_type(type_right);
7959 /* §6.3.1.8 Usual arithmetic conversions */
7960 if (type_left == type_long_double || type_right == type_long_double) {
7961 return type_long_double;
7962 } else if (type_left == type_double || type_right == type_double) {
7964 } else if (type_left == type_float || type_right == type_float) {
7968 type_left = promote_integer(type_left);
7969 type_right = promote_integer(type_right);
7971 if (type_left == type_right)
7974 bool const signed_left = is_type_signed(type_left);
7975 bool const signed_right = is_type_signed(type_right);
7976 int const rank_left = get_rank(type_left);
7977 int const rank_right = get_rank(type_right);
7979 if (signed_left == signed_right)
7980 return rank_left >= rank_right ? type_left : type_right;
7989 u_rank = rank_right;
7990 u_type = type_right;
7992 s_rank = rank_right;
7993 s_type = type_right;
7998 if (u_rank >= s_rank)
8001 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8003 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8004 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8008 case ATOMIC_TYPE_INT: return type_unsigned_int;
8009 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8010 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8012 default: panic("invalid atomic type");
8017 * Check the semantic restrictions for a binary expression.
8019 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8021 expression_t *const left = expression->left;
8022 expression_t *const right = expression->right;
8023 type_t *const orig_type_left = left->base.type;
8024 type_t *const orig_type_right = right->base.type;
8025 type_t *const type_left = skip_typeref(orig_type_left);
8026 type_t *const type_right = skip_typeref(orig_type_right);
8028 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8029 /* TODO: improve error message */
8030 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8031 errorf(&expression->base.source_position,
8032 "operation needs arithmetic types");
8037 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8038 expression->left = create_implicit_cast(left, arithmetic_type);
8039 expression->right = create_implicit_cast(right, arithmetic_type);
8040 expression->base.type = arithmetic_type;
8043 static void semantic_binexpr_integer(binary_expression_t *const expression)
8045 expression_t *const left = expression->left;
8046 expression_t *const right = expression->right;
8047 type_t *const orig_type_left = left->base.type;
8048 type_t *const orig_type_right = right->base.type;
8049 type_t *const type_left = skip_typeref(orig_type_left);
8050 type_t *const type_right = skip_typeref(orig_type_right);
8052 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8053 /* TODO: improve error message */
8054 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8055 errorf(&expression->base.source_position,
8056 "operation needs integer types");
8061 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8062 expression->left = create_implicit_cast(left, result_type);
8063 expression->right = create_implicit_cast(right, result_type);
8064 expression->base.type = result_type;
8067 static void warn_div_by_zero(binary_expression_t const *const expression)
8069 if (!is_type_integer(expression->base.type))
8072 expression_t const *const right = expression->right;
8073 /* The type of the right operand can be different for /= */
8074 if (is_type_integer(right->base.type) &&
8075 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8076 !fold_constant_to_bool(right)) {
8077 source_position_t const *const pos = &expression->base.source_position;
8078 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8083 * Check the semantic restrictions for a div/mod expression.
8085 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8087 semantic_binexpr_arithmetic(expression);
8088 warn_div_by_zero(expression);
8091 static void warn_addsub_in_shift(const expression_t *const expr)
8093 if (expr->base.parenthesized)
8097 switch (expr->kind) {
8098 case EXPR_BINARY_ADD: op = '+'; break;
8099 case EXPR_BINARY_SUB: op = '-'; break;
8103 source_position_t const *const pos = &expr->base.source_position;
8104 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8107 static bool semantic_shift(binary_expression_t *expression)
8109 expression_t *const left = expression->left;
8110 expression_t *const right = expression->right;
8111 type_t *const orig_type_left = left->base.type;
8112 type_t *const orig_type_right = right->base.type;
8113 type_t * type_left = skip_typeref(orig_type_left);
8114 type_t * type_right = skip_typeref(orig_type_right);
8116 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8117 /* TODO: improve error message */
8118 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8119 errorf(&expression->base.source_position,
8120 "operands of shift operation must have integer types");
8125 type_left = promote_integer(type_left);
8127 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8128 source_position_t const *const pos = &right->base.source_position;
8129 long const count = fold_constant_to_int(right);
8131 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8132 } else if ((unsigned long)count >=
8133 get_atomic_type_size(type_left->atomic.akind) * 8) {
8134 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8138 type_right = promote_integer(type_right);
8139 expression->right = create_implicit_cast(right, type_right);
8144 static void semantic_shift_op(binary_expression_t *expression)
8146 expression_t *const left = expression->left;
8147 expression_t *const right = expression->right;
8149 if (!semantic_shift(expression))
8152 warn_addsub_in_shift(left);
8153 warn_addsub_in_shift(right);
8155 type_t *const orig_type_left = left->base.type;
8156 type_t * type_left = skip_typeref(orig_type_left);
8158 type_left = promote_integer(type_left);
8159 expression->left = create_implicit_cast(left, type_left);
8160 expression->base.type = type_left;
8163 static void semantic_add(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);
8173 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8174 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8175 expression->left = create_implicit_cast(left, arithmetic_type);
8176 expression->right = create_implicit_cast(right, arithmetic_type);
8177 expression->base.type = arithmetic_type;
8178 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8179 check_pointer_arithmetic(&expression->base.source_position,
8180 type_left, orig_type_left);
8181 expression->base.type = type_left;
8182 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8183 check_pointer_arithmetic(&expression->base.source_position,
8184 type_right, orig_type_right);
8185 expression->base.type = type_right;
8186 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8187 errorf(&expression->base.source_position,
8188 "invalid operands to binary + ('%T', '%T')",
8189 orig_type_left, orig_type_right);
8193 static void semantic_sub(binary_expression_t *expression)
8195 expression_t *const left = expression->left;
8196 expression_t *const right = expression->right;
8197 type_t *const orig_type_left = left->base.type;
8198 type_t *const orig_type_right = right->base.type;
8199 type_t *const type_left = skip_typeref(orig_type_left);
8200 type_t *const type_right = skip_typeref(orig_type_right);
8201 source_position_t const *const pos = &expression->base.source_position;
8204 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8205 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8206 expression->left = create_implicit_cast(left, arithmetic_type);
8207 expression->right = create_implicit_cast(right, arithmetic_type);
8208 expression->base.type = arithmetic_type;
8209 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8210 check_pointer_arithmetic(&expression->base.source_position,
8211 type_left, orig_type_left);
8212 expression->base.type = type_left;
8213 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8214 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8215 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8216 if (!types_compatible(unqual_left, unqual_right)) {
8218 "subtracting pointers to incompatible types '%T' and '%T'",
8219 orig_type_left, orig_type_right);
8220 } else if (!is_type_object(unqual_left)) {
8221 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8222 errorf(pos, "subtracting pointers to non-object types '%T'",
8225 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8228 expression->base.type = type_ptrdiff_t;
8229 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8230 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8231 orig_type_left, orig_type_right);
8235 static void warn_string_literal_address(expression_t const* expr)
8237 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8238 expr = expr->unary.value;
8239 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8241 expr = expr->unary.value;
8244 if (expr->kind == EXPR_STRING_LITERAL
8245 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8246 source_position_t const *const pos = &expr->base.source_position;
8247 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8251 static bool maybe_negative(expression_t const *const expr)
8253 switch (is_constant_expression(expr)) {
8254 case EXPR_CLASS_ERROR: return false;
8255 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8256 default: return true;
8260 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8262 warn_string_literal_address(expr);
8264 expression_t const* const ref = get_reference_address(expr);
8265 if (ref != NULL && is_null_pointer_constant(other)) {
8266 entity_t const *const ent = ref->reference.entity;
8267 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8270 if (!expr->base.parenthesized) {
8271 switch (expr->base.kind) {
8272 case EXPR_BINARY_LESS:
8273 case EXPR_BINARY_GREATER:
8274 case EXPR_BINARY_LESSEQUAL:
8275 case EXPR_BINARY_GREATEREQUAL:
8276 case EXPR_BINARY_NOTEQUAL:
8277 case EXPR_BINARY_EQUAL:
8278 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8287 * Check the semantics of comparison expressions.
8289 * @param expression The expression to check.
8291 static void semantic_comparison(binary_expression_t *expression)
8293 source_position_t const *const pos = &expression->base.source_position;
8294 expression_t *const left = expression->left;
8295 expression_t *const right = expression->right;
8297 warn_comparison(pos, left, right);
8298 warn_comparison(pos, right, left);
8300 type_t *orig_type_left = left->base.type;
8301 type_t *orig_type_right = right->base.type;
8302 type_t *type_left = skip_typeref(orig_type_left);
8303 type_t *type_right = skip_typeref(orig_type_right);
8305 /* TODO non-arithmetic types */
8306 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8307 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8309 /* test for signed vs unsigned compares */
8310 if (is_type_integer(arithmetic_type)) {
8311 bool const signed_left = is_type_signed(type_left);
8312 bool const signed_right = is_type_signed(type_right);
8313 if (signed_left != signed_right) {
8314 /* FIXME long long needs better const folding magic */
8315 /* TODO check whether constant value can be represented by other type */
8316 if ((signed_left && maybe_negative(left)) ||
8317 (signed_right && maybe_negative(right))) {
8318 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8323 expression->left = create_implicit_cast(left, arithmetic_type);
8324 expression->right = create_implicit_cast(right, arithmetic_type);
8325 expression->base.type = arithmetic_type;
8326 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8327 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8328 is_type_float(arithmetic_type)) {
8329 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8331 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8332 /* TODO check compatibility */
8333 } else if (is_type_pointer(type_left)) {
8334 expression->right = create_implicit_cast(right, type_left);
8335 } else if (is_type_pointer(type_right)) {
8336 expression->left = create_implicit_cast(left, type_right);
8337 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8338 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8340 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8344 * Checks if a compound type has constant fields.
8346 static bool has_const_fields(const compound_type_t *type)
8348 compound_t *compound = type->compound;
8349 entity_t *entry = compound->members.entities;
8351 for (; entry != NULL; entry = entry->base.next) {
8352 if (!is_declaration(entry))
8355 const type_t *decl_type = skip_typeref(entry->declaration.type);
8356 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8363 static bool is_valid_assignment_lhs(expression_t const* const left)
8365 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8366 type_t *const type_left = skip_typeref(orig_type_left);
8368 if (!is_lvalue(left)) {
8369 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8374 if (left->kind == EXPR_REFERENCE
8375 && left->reference.entity->kind == ENTITY_FUNCTION) {
8376 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8380 if (is_type_array(type_left)) {
8381 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8384 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8385 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8389 if (is_type_incomplete(type_left)) {
8390 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8391 left, orig_type_left);
8394 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8395 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8396 left, orig_type_left);
8403 static void semantic_arithmetic_assign(binary_expression_t *expression)
8405 expression_t *left = expression->left;
8406 expression_t *right = expression->right;
8407 type_t *orig_type_left = left->base.type;
8408 type_t *orig_type_right = right->base.type;
8410 if (!is_valid_assignment_lhs(left))
8413 type_t *type_left = skip_typeref(orig_type_left);
8414 type_t *type_right = skip_typeref(orig_type_right);
8416 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8417 /* TODO: improve error message */
8418 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8419 errorf(&expression->base.source_position,
8420 "operation needs arithmetic types");
8425 /* combined instructions are tricky. We can't create an implicit cast on
8426 * the left side, because we need the uncasted form for the store.
8427 * The ast2firm pass has to know that left_type must be right_type
8428 * for the arithmetic operation and create a cast by itself */
8429 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8430 expression->right = create_implicit_cast(right, arithmetic_type);
8431 expression->base.type = type_left;
8434 static void semantic_divmod_assign(binary_expression_t *expression)
8436 semantic_arithmetic_assign(expression);
8437 warn_div_by_zero(expression);
8440 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8442 expression_t *const left = expression->left;
8443 expression_t *const right = expression->right;
8444 type_t *const orig_type_left = left->base.type;
8445 type_t *const orig_type_right = right->base.type;
8446 type_t *const type_left = skip_typeref(orig_type_left);
8447 type_t *const type_right = skip_typeref(orig_type_right);
8449 if (!is_valid_assignment_lhs(left))
8452 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8453 /* combined instructions are tricky. We can't create an implicit cast on
8454 * the left side, because we need the uncasted form for the store.
8455 * The ast2firm pass has to know that left_type must be right_type
8456 * for the arithmetic operation and create a cast by itself */
8457 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8458 expression->right = create_implicit_cast(right, arithmetic_type);
8459 expression->base.type = type_left;
8460 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8461 check_pointer_arithmetic(&expression->base.source_position,
8462 type_left, orig_type_left);
8463 expression->base.type = type_left;
8464 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8465 errorf(&expression->base.source_position,
8466 "incompatible types '%T' and '%T' in assignment",
8467 orig_type_left, orig_type_right);
8471 static void semantic_integer_assign(binary_expression_t *expression)
8473 expression_t *left = expression->left;
8474 expression_t *right = expression->right;
8475 type_t *orig_type_left = left->base.type;
8476 type_t *orig_type_right = right->base.type;
8478 if (!is_valid_assignment_lhs(left))
8481 type_t *type_left = skip_typeref(orig_type_left);
8482 type_t *type_right = skip_typeref(orig_type_right);
8484 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8485 /* TODO: improve error message */
8486 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8487 errorf(&expression->base.source_position,
8488 "operation needs integer types");
8493 /* combined instructions are tricky. We can't create an implicit cast on
8494 * the left side, because we need the uncasted form for the store.
8495 * The ast2firm pass has to know that left_type must be right_type
8496 * for the arithmetic operation and create a cast by itself */
8497 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8498 expression->right = create_implicit_cast(right, arithmetic_type);
8499 expression->base.type = type_left;
8502 static void semantic_shift_assign(binary_expression_t *expression)
8504 expression_t *left = expression->left;
8506 if (!is_valid_assignment_lhs(left))
8509 if (!semantic_shift(expression))
8512 expression->base.type = skip_typeref(left->base.type);
8515 static void warn_logical_and_within_or(const expression_t *const expr)
8517 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8519 if (expr->base.parenthesized)
8521 source_position_t const *const pos = &expr->base.source_position;
8522 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8526 * Check the semantic restrictions of a logical expression.
8528 static void semantic_logical_op(binary_expression_t *expression)
8530 /* §6.5.13:2 Each of the operands shall have scalar type.
8531 * §6.5.14:2 Each of the operands shall have scalar type. */
8532 semantic_condition(expression->left, "left operand of logical operator");
8533 semantic_condition(expression->right, "right operand of logical operator");
8534 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8535 warn_logical_and_within_or(expression->left);
8536 warn_logical_and_within_or(expression->right);
8538 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8542 * Check the semantic restrictions of a binary assign expression.
8544 static void semantic_binexpr_assign(binary_expression_t *expression)
8546 expression_t *left = expression->left;
8547 type_t *orig_type_left = left->base.type;
8549 if (!is_valid_assignment_lhs(left))
8552 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8553 report_assign_error(error, orig_type_left, expression->right,
8554 "assignment", &left->base.source_position);
8555 expression->right = create_implicit_cast(expression->right, orig_type_left);
8556 expression->base.type = orig_type_left;
8560 * Determine if the outermost operation (or parts thereof) of the given
8561 * expression has no effect in order to generate a warning about this fact.
8562 * Therefore in some cases this only examines some of the operands of the
8563 * expression (see comments in the function and examples below).
8565 * f() + 23; // warning, because + has no effect
8566 * x || f(); // no warning, because x controls execution of f()
8567 * x ? y : f(); // warning, because y has no effect
8568 * (void)x; // no warning to be able to suppress the warning
8569 * This function can NOT be used for an "expression has definitely no effect"-
8571 static bool expression_has_effect(const expression_t *const expr)
8573 switch (expr->kind) {
8574 case EXPR_UNKNOWN: break;
8575 case EXPR_INVALID: return true; /* do NOT warn */
8576 case EXPR_REFERENCE: return false;
8577 case EXPR_REFERENCE_ENUM_VALUE: return false;
8578 case EXPR_LABEL_ADDRESS: return false;
8580 /* suppress the warning for microsoft __noop operations */
8581 case EXPR_LITERAL_MS_NOOP: return true;
8582 case EXPR_LITERAL_BOOLEAN:
8583 case EXPR_LITERAL_CHARACTER:
8584 case EXPR_LITERAL_WIDE_CHARACTER:
8585 case EXPR_LITERAL_INTEGER:
8586 case EXPR_LITERAL_INTEGER_OCTAL:
8587 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8588 case EXPR_LITERAL_FLOATINGPOINT:
8589 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8590 case EXPR_STRING_LITERAL: return false;
8591 case EXPR_WIDE_STRING_LITERAL: return false;
8594 const call_expression_t *const call = &expr->call;
8595 if (call->function->kind != EXPR_REFERENCE)
8598 switch (call->function->reference.entity->function.btk) {
8599 /* FIXME: which builtins have no effect? */
8600 default: return true;
8604 /* Generate the warning if either the left or right hand side of a
8605 * conditional expression has no effect */
8606 case EXPR_CONDITIONAL: {
8607 conditional_expression_t const *const cond = &expr->conditional;
8608 expression_t const *const t = cond->true_expression;
8610 (t == NULL || expression_has_effect(t)) &&
8611 expression_has_effect(cond->false_expression);
8614 case EXPR_SELECT: return false;
8615 case EXPR_ARRAY_ACCESS: return false;
8616 case EXPR_SIZEOF: return false;
8617 case EXPR_CLASSIFY_TYPE: return false;
8618 case EXPR_ALIGNOF: return false;
8620 case EXPR_FUNCNAME: return false;
8621 case EXPR_BUILTIN_CONSTANT_P: return false;
8622 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8623 case EXPR_OFFSETOF: return false;
8624 case EXPR_VA_START: return true;
8625 case EXPR_VA_ARG: return true;
8626 case EXPR_VA_COPY: return true;
8627 case EXPR_STATEMENT: return true; // TODO
8628 case EXPR_COMPOUND_LITERAL: return false;
8630 case EXPR_UNARY_NEGATE: return false;
8631 case EXPR_UNARY_PLUS: return false;
8632 case EXPR_UNARY_BITWISE_NEGATE: return false;
8633 case EXPR_UNARY_NOT: return false;
8634 case EXPR_UNARY_DEREFERENCE: return false;
8635 case EXPR_UNARY_TAKE_ADDRESS: return false;
8636 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8637 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8638 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8639 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8641 /* Treat void casts as if they have an effect in order to being able to
8642 * suppress the warning */
8643 case EXPR_UNARY_CAST: {
8644 type_t *const type = skip_typeref(expr->base.type);
8645 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8648 case EXPR_UNARY_CAST_IMPLICIT: return true;
8649 case EXPR_UNARY_ASSUME: return true;
8650 case EXPR_UNARY_DELETE: return true;
8651 case EXPR_UNARY_DELETE_ARRAY: return true;
8652 case EXPR_UNARY_THROW: return true;
8654 case EXPR_BINARY_ADD: return false;
8655 case EXPR_BINARY_SUB: return false;
8656 case EXPR_BINARY_MUL: return false;
8657 case EXPR_BINARY_DIV: return false;
8658 case EXPR_BINARY_MOD: return false;
8659 case EXPR_BINARY_EQUAL: return false;
8660 case EXPR_BINARY_NOTEQUAL: return false;
8661 case EXPR_BINARY_LESS: return false;
8662 case EXPR_BINARY_LESSEQUAL: return false;
8663 case EXPR_BINARY_GREATER: return false;
8664 case EXPR_BINARY_GREATEREQUAL: return false;
8665 case EXPR_BINARY_BITWISE_AND: return false;
8666 case EXPR_BINARY_BITWISE_OR: return false;
8667 case EXPR_BINARY_BITWISE_XOR: return false;
8668 case EXPR_BINARY_SHIFTLEFT: return false;
8669 case EXPR_BINARY_SHIFTRIGHT: return false;
8670 case EXPR_BINARY_ASSIGN: return true;
8671 case EXPR_BINARY_MUL_ASSIGN: return true;
8672 case EXPR_BINARY_DIV_ASSIGN: return true;
8673 case EXPR_BINARY_MOD_ASSIGN: return true;
8674 case EXPR_BINARY_ADD_ASSIGN: return true;
8675 case EXPR_BINARY_SUB_ASSIGN: return true;
8676 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8677 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8678 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8679 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8680 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8682 /* Only examine the right hand side of && and ||, because the left hand
8683 * side already has the effect of controlling the execution of the right
8685 case EXPR_BINARY_LOGICAL_AND:
8686 case EXPR_BINARY_LOGICAL_OR:
8687 /* Only examine the right hand side of a comma expression, because the left
8688 * hand side has a separate warning */
8689 case EXPR_BINARY_COMMA:
8690 return expression_has_effect(expr->binary.right);
8692 case EXPR_BINARY_ISGREATER: return false;
8693 case EXPR_BINARY_ISGREATEREQUAL: return false;
8694 case EXPR_BINARY_ISLESS: return false;
8695 case EXPR_BINARY_ISLESSEQUAL: return false;
8696 case EXPR_BINARY_ISLESSGREATER: return false;
8697 case EXPR_BINARY_ISUNORDERED: return false;
8700 internal_errorf(HERE, "unexpected expression");
8703 static void semantic_comma(binary_expression_t *expression)
8705 const expression_t *const left = expression->left;
8706 if (!expression_has_effect(left)) {
8707 source_position_t const *const pos = &left->base.source_position;
8708 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8710 expression->base.type = expression->right->base.type;
8714 * @param prec_r precedence of the right operand
8716 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8717 static expression_t *parse_##binexpression_type(expression_t *left) \
8719 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8720 binexpr->binary.left = left; \
8723 expression_t *right = parse_subexpression(prec_r); \
8725 binexpr->binary.right = right; \
8726 sfunc(&binexpr->binary); \
8731 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8732 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8733 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8734 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8735 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8736 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8737 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8738 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8739 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8740 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8741 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8742 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8743 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8744 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8745 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8746 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8747 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8748 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8749 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8750 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8751 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8752 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8753 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8754 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8755 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8756 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8757 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8758 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8759 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8760 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8763 static expression_t *parse_subexpression(precedence_t precedence)
8765 if (token.type < 0) {
8766 return expected_expression_error();
8769 expression_parser_function_t *parser
8770 = &expression_parsers[token.type];
8771 source_position_t source_position = token.source_position;
8774 if (parser->parser != NULL) {
8775 left = parser->parser();
8777 left = parse_primary_expression();
8779 assert(left != NULL);
8780 left->base.source_position = source_position;
8783 if (token.type < 0) {
8784 return expected_expression_error();
8787 parser = &expression_parsers[token.type];
8788 if (parser->infix_parser == NULL)
8790 if (parser->infix_precedence < precedence)
8793 left = parser->infix_parser(left);
8795 assert(left != NULL);
8796 assert(left->kind != EXPR_UNKNOWN);
8797 left->base.source_position = source_position;
8804 * Parse an expression.
8806 static expression_t *parse_expression(void)
8808 return parse_subexpression(PREC_EXPRESSION);
8812 * Register a parser for a prefix-like operator.
8814 * @param parser the parser function
8815 * @param token_type the token type of the prefix token
8817 static void register_expression_parser(parse_expression_function parser,
8820 expression_parser_function_t *entry = &expression_parsers[token_type];
8822 if (entry->parser != NULL) {
8823 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8824 panic("trying to register multiple expression parsers for a token");
8826 entry->parser = parser;
8830 * Register a parser for an infix operator with given precedence.
8832 * @param parser the parser function
8833 * @param token_type the token type of the infix operator
8834 * @param precedence the precedence of the operator
8836 static void register_infix_parser(parse_expression_infix_function parser,
8837 int token_type, precedence_t precedence)
8839 expression_parser_function_t *entry = &expression_parsers[token_type];
8841 if (entry->infix_parser != NULL) {
8842 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8843 panic("trying to register multiple infix expression parsers for a "
8846 entry->infix_parser = parser;
8847 entry->infix_precedence = precedence;
8851 * Initialize the expression parsers.
8853 static void init_expression_parsers(void)
8855 memset(&expression_parsers, 0, sizeof(expression_parsers));
8857 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8858 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8859 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8860 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8861 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8862 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8863 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8864 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8865 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8866 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8867 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8868 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8869 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8870 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8871 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8872 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8873 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8874 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8875 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8876 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8877 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8878 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8879 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8880 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8881 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8882 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8883 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8884 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8885 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8886 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8887 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8888 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8889 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8890 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8891 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8892 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8893 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8895 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8896 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8897 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8898 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8899 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8900 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8901 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8902 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8903 register_expression_parser(parse_sizeof, T_sizeof);
8904 register_expression_parser(parse_alignof, T___alignof__);
8905 register_expression_parser(parse_extension, T___extension__);
8906 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8907 register_expression_parser(parse_delete, T_delete);
8908 register_expression_parser(parse_throw, T_throw);
8912 * Parse a asm statement arguments specification.
8914 static asm_argument_t *parse_asm_arguments(bool is_out)
8916 asm_argument_t *result = NULL;
8917 asm_argument_t **anchor = &result;
8919 while (token.type == T_STRING_LITERAL || token.type == '[') {
8920 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8921 memset(argument, 0, sizeof(argument[0]));
8924 if (token.type != T_IDENTIFIER) {
8925 parse_error_expected("while parsing asm argument",
8926 T_IDENTIFIER, NULL);
8929 argument->symbol = token.symbol;
8931 expect(']', end_error);
8934 argument->constraints = parse_string_literals();
8935 expect('(', end_error);
8936 add_anchor_token(')');
8937 expression_t *expression = parse_expression();
8938 rem_anchor_token(')');
8940 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8941 * change size or type representation (e.g. int -> long is ok, but
8942 * int -> float is not) */
8943 if (expression->kind == EXPR_UNARY_CAST) {
8944 type_t *const type = expression->base.type;
8945 type_kind_t const kind = type->kind;
8946 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8949 if (kind == TYPE_ATOMIC) {
8950 atomic_type_kind_t const akind = type->atomic.akind;
8951 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8952 size = get_atomic_type_size(akind);
8954 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8955 size = get_atomic_type_size(get_intptr_kind());
8959 expression_t *const value = expression->unary.value;
8960 type_t *const value_type = value->base.type;
8961 type_kind_t const value_kind = value_type->kind;
8963 unsigned value_flags;
8964 unsigned value_size;
8965 if (value_kind == TYPE_ATOMIC) {
8966 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8967 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8968 value_size = get_atomic_type_size(value_akind);
8969 } else if (value_kind == TYPE_POINTER) {
8970 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8971 value_size = get_atomic_type_size(get_intptr_kind());
8976 if (value_flags != flags || value_size != size)
8980 } while (expression->kind == EXPR_UNARY_CAST);
8984 if (!is_lvalue(expression)) {
8985 errorf(&expression->base.source_position,
8986 "asm output argument is not an lvalue");
8989 if (argument->constraints.begin[0] == '=')
8990 determine_lhs_ent(expression, NULL);
8992 mark_vars_read(expression, NULL);
8994 mark_vars_read(expression, NULL);
8996 argument->expression = expression;
8997 expect(')', end_error);
8999 set_address_taken(expression, true);
9002 anchor = &argument->next;
9014 * Parse a asm statement clobber specification.
9016 static asm_clobber_t *parse_asm_clobbers(void)
9018 asm_clobber_t *result = NULL;
9019 asm_clobber_t **anchor = &result;
9021 while (token.type == T_STRING_LITERAL) {
9022 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9023 clobber->clobber = parse_string_literals();
9026 anchor = &clobber->next;
9036 * Parse an asm statement.
9038 static statement_t *parse_asm_statement(void)
9040 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9041 asm_statement_t *asm_statement = &statement->asms;
9045 if (next_if(T_volatile))
9046 asm_statement->is_volatile = true;
9048 expect('(', end_error);
9049 add_anchor_token(')');
9050 if (token.type != T_STRING_LITERAL) {
9051 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9054 asm_statement->asm_text = parse_string_literals();
9056 add_anchor_token(':');
9057 if (!next_if(':')) {
9058 rem_anchor_token(':');
9062 asm_statement->outputs = parse_asm_arguments(true);
9063 if (!next_if(':')) {
9064 rem_anchor_token(':');
9068 asm_statement->inputs = parse_asm_arguments(false);
9069 if (!next_if(':')) {
9070 rem_anchor_token(':');
9073 rem_anchor_token(':');
9075 asm_statement->clobbers = parse_asm_clobbers();
9078 rem_anchor_token(')');
9079 expect(')', end_error);
9080 expect(';', end_error);
9082 if (asm_statement->outputs == NULL) {
9083 /* GCC: An 'asm' instruction without any output operands will be treated
9084 * identically to a volatile 'asm' instruction. */
9085 asm_statement->is_volatile = true;
9090 return create_invalid_statement();
9093 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9095 statement_t *inner_stmt;
9096 switch (token.type) {
9098 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9099 inner_stmt = create_invalid_statement();
9103 if (label->kind == STATEMENT_LABEL) {
9104 /* Eat an empty statement here, to avoid the warning about an empty
9105 * statement after a label. label:; is commonly used to have a label
9106 * before a closing brace. */
9107 inner_stmt = create_empty_statement();
9114 inner_stmt = parse_statement();
9115 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9116 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9117 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9125 * Parse a case statement.
9127 static statement_t *parse_case_statement(void)
9129 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9130 source_position_t *const pos = &statement->base.source_position;
9134 expression_t *const expression = parse_expression();
9135 statement->case_label.expression = expression;
9136 expression_classification_t const expr_class = is_constant_expression(expression);
9137 if (expr_class != EXPR_CLASS_CONSTANT) {
9138 if (expr_class != EXPR_CLASS_ERROR) {
9139 errorf(pos, "case label does not reduce to an integer constant");
9141 statement->case_label.is_bad = true;
9143 long const val = fold_constant_to_int(expression);
9144 statement->case_label.first_case = val;
9145 statement->case_label.last_case = val;
9149 if (next_if(T_DOTDOTDOT)) {
9150 expression_t *const end_range = parse_expression();
9151 statement->case_label.end_range = end_range;
9152 expression_classification_t const end_class = is_constant_expression(end_range);
9153 if (end_class != EXPR_CLASS_CONSTANT) {
9154 if (end_class != EXPR_CLASS_ERROR) {
9155 errorf(pos, "case range does not reduce to an integer constant");
9157 statement->case_label.is_bad = true;
9159 long const val = fold_constant_to_int(end_range);
9160 statement->case_label.last_case = val;
9162 if (val < statement->case_label.first_case) {
9163 statement->case_label.is_empty_range = true;
9164 warningf(WARN_OTHER, pos, "empty range specified");
9170 PUSH_PARENT(statement);
9172 expect(':', end_error);
9175 if (current_switch != NULL) {
9176 if (! statement->case_label.is_bad) {
9177 /* Check for duplicate case values */
9178 case_label_statement_t *c = &statement->case_label;
9179 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9180 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9183 if (c->last_case < l->first_case || c->first_case > l->last_case)
9186 errorf(pos, "duplicate case value (previously used %P)",
9187 &l->base.source_position);
9191 /* link all cases into the switch statement */
9192 if (current_switch->last_case == NULL) {
9193 current_switch->first_case = &statement->case_label;
9195 current_switch->last_case->next = &statement->case_label;
9197 current_switch->last_case = &statement->case_label;
9199 errorf(pos, "case label not within a switch statement");
9202 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9209 * Parse a default statement.
9211 static statement_t *parse_default_statement(void)
9213 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9217 PUSH_PARENT(statement);
9219 expect(':', end_error);
9222 if (current_switch != NULL) {
9223 const case_label_statement_t *def_label = current_switch->default_label;
9224 if (def_label != NULL) {
9225 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9227 current_switch->default_label = &statement->case_label;
9229 /* link all cases into the switch statement */
9230 if (current_switch->last_case == NULL) {
9231 current_switch->first_case = &statement->case_label;
9233 current_switch->last_case->next = &statement->case_label;
9235 current_switch->last_case = &statement->case_label;
9238 errorf(&statement->base.source_position,
9239 "'default' label not within a switch statement");
9242 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9249 * Parse a label statement.
9251 static statement_t *parse_label_statement(void)
9253 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9254 label_t *const label = get_label();
9255 statement->label.label = label;
9257 PUSH_PARENT(statement);
9259 /* if statement is already set then the label is defined twice,
9260 * otherwise it was just mentioned in a goto/local label declaration so far
9262 source_position_t const* const pos = &statement->base.source_position;
9263 if (label->statement != NULL) {
9264 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9266 label->base.source_position = *pos;
9267 label->statement = statement;
9272 statement->label.statement = parse_label_inner_statement(statement, "label");
9274 /* remember the labels in a list for later checking */
9275 *label_anchor = &statement->label;
9276 label_anchor = &statement->label.next;
9283 * Parse an if statement.
9285 static statement_t *parse_if(void)
9287 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9291 PUSH_PARENT(statement);
9293 add_anchor_token('{');
9295 expect('(', end_error);
9296 add_anchor_token(')');
9297 expression_t *const expr = parse_expression();
9298 statement->ifs.condition = expr;
9299 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9301 semantic_condition(expr, "condition of 'if'-statment");
9302 mark_vars_read(expr, NULL);
9303 rem_anchor_token(')');
9304 expect(')', end_error);
9307 rem_anchor_token('{');
9309 add_anchor_token(T_else);
9310 statement_t *const true_stmt = parse_statement();
9311 statement->ifs.true_statement = true_stmt;
9312 rem_anchor_token(T_else);
9314 if (next_if(T_else)) {
9315 statement->ifs.false_statement = parse_statement();
9316 } else if (true_stmt->kind == STATEMENT_IF &&
9317 true_stmt->ifs.false_statement != NULL) {
9318 source_position_t const *const pos = &true_stmt->base.source_position;
9319 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9327 * Check that all enums are handled in a switch.
9329 * @param statement the switch statement to check
9331 static void check_enum_cases(const switch_statement_t *statement)
9333 if (!is_warn_on(WARN_SWITCH_ENUM))
9335 const type_t *type = skip_typeref(statement->expression->base.type);
9336 if (! is_type_enum(type))
9338 const enum_type_t *enumt = &type->enumt;
9340 /* if we have a default, no warnings */
9341 if (statement->default_label != NULL)
9344 /* FIXME: calculation of value should be done while parsing */
9345 /* TODO: quadratic algorithm here. Change to an n log n one */
9346 long last_value = -1;
9347 const entity_t *entry = enumt->enume->base.next;
9348 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9349 entry = entry->base.next) {
9350 const expression_t *expression = entry->enum_value.value;
9351 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9353 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9354 if (l->expression == NULL)
9356 if (l->first_case <= value && value <= l->last_case) {
9362 source_position_t const *const pos = &statement->base.source_position;
9363 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9370 * Parse a switch statement.
9372 static statement_t *parse_switch(void)
9374 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9378 PUSH_PARENT(statement);
9380 expect('(', end_error);
9381 add_anchor_token(')');
9382 expression_t *const expr = parse_expression();
9383 mark_vars_read(expr, NULL);
9384 type_t * type = skip_typeref(expr->base.type);
9385 if (is_type_integer(type)) {
9386 type = promote_integer(type);
9387 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9388 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9390 } else if (is_type_valid(type)) {
9391 errorf(&expr->base.source_position,
9392 "switch quantity is not an integer, but '%T'", type);
9393 type = type_error_type;
9395 statement->switchs.expression = create_implicit_cast(expr, type);
9396 expect(')', end_error);
9397 rem_anchor_token(')');
9399 switch_statement_t *rem = current_switch;
9400 current_switch = &statement->switchs;
9401 statement->switchs.body = parse_statement();
9402 current_switch = rem;
9404 if (statement->switchs.default_label == NULL) {
9405 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9407 check_enum_cases(&statement->switchs);
9413 return create_invalid_statement();
9416 static statement_t *parse_loop_body(statement_t *const loop)
9418 statement_t *const rem = current_loop;
9419 current_loop = loop;
9421 statement_t *const body = parse_statement();
9428 * Parse a while statement.
9430 static statement_t *parse_while(void)
9432 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9436 PUSH_PARENT(statement);
9438 expect('(', end_error);
9439 add_anchor_token(')');
9440 expression_t *const cond = parse_expression();
9441 statement->whiles.condition = cond;
9442 /* §6.8.5:2 The controlling expression of an iteration statement shall
9443 * have scalar type. */
9444 semantic_condition(cond, "condition of 'while'-statement");
9445 mark_vars_read(cond, NULL);
9446 rem_anchor_token(')');
9447 expect(')', end_error);
9449 statement->whiles.body = parse_loop_body(statement);
9455 return create_invalid_statement();
9459 * Parse a do statement.
9461 static statement_t *parse_do(void)
9463 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9467 PUSH_PARENT(statement);
9469 add_anchor_token(T_while);
9470 statement->do_while.body = parse_loop_body(statement);
9471 rem_anchor_token(T_while);
9473 expect(T_while, end_error);
9474 expect('(', end_error);
9475 add_anchor_token(')');
9476 expression_t *const cond = parse_expression();
9477 statement->do_while.condition = cond;
9478 /* §6.8.5:2 The controlling expression of an iteration statement shall
9479 * have scalar type. */
9480 semantic_condition(cond, "condition of 'do-while'-statement");
9481 mark_vars_read(cond, NULL);
9482 rem_anchor_token(')');
9483 expect(')', end_error);
9484 expect(';', end_error);
9490 return create_invalid_statement();
9494 * Parse a for statement.
9496 static statement_t *parse_for(void)
9498 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9502 expect('(', end_error1);
9503 add_anchor_token(')');
9505 PUSH_PARENT(statement);
9507 size_t const top = environment_top();
9508 scope_t *old_scope = scope_push(&statement->fors.scope);
9510 bool old_gcc_extension = in_gcc_extension;
9511 while (next_if(T___extension__)) {
9512 in_gcc_extension = true;
9516 } else if (is_declaration_specifier(&token)) {
9517 parse_declaration(record_entity, DECL_FLAGS_NONE);
9519 add_anchor_token(';');
9520 expression_t *const init = parse_expression();
9521 statement->fors.initialisation = init;
9522 mark_vars_read(init, ENT_ANY);
9523 if (!expression_has_effect(init)) {
9524 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9526 rem_anchor_token(';');
9527 expect(';', end_error2);
9529 in_gcc_extension = old_gcc_extension;
9531 if (token.type != ';') {
9532 add_anchor_token(';');
9533 expression_t *const cond = parse_expression();
9534 statement->fors.condition = cond;
9535 /* §6.8.5:2 The controlling expression of an iteration statement
9536 * shall have scalar type. */
9537 semantic_condition(cond, "condition of 'for'-statement");
9538 mark_vars_read(cond, NULL);
9539 rem_anchor_token(';');
9541 expect(';', end_error2);
9542 if (token.type != ')') {
9543 expression_t *const step = parse_expression();
9544 statement->fors.step = step;
9545 mark_vars_read(step, ENT_ANY);
9546 if (!expression_has_effect(step)) {
9547 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9550 expect(')', end_error2);
9551 rem_anchor_token(')');
9552 statement->fors.body = parse_loop_body(statement);
9554 assert(current_scope == &statement->fors.scope);
9555 scope_pop(old_scope);
9556 environment_pop_to(top);
9563 rem_anchor_token(')');
9564 assert(current_scope == &statement->fors.scope);
9565 scope_pop(old_scope);
9566 environment_pop_to(top);
9570 return create_invalid_statement();
9574 * Parse a goto statement.
9576 static statement_t *parse_goto(void)
9578 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9581 if (GNU_MODE && next_if('*')) {
9582 expression_t *expression = parse_expression();
9583 mark_vars_read(expression, NULL);
9585 /* Argh: although documentation says the expression must be of type void*,
9586 * gcc accepts anything that can be casted into void* without error */
9587 type_t *type = expression->base.type;
9589 if (type != type_error_type) {
9590 if (!is_type_pointer(type) && !is_type_integer(type)) {
9591 errorf(&expression->base.source_position,
9592 "cannot convert to a pointer type");
9593 } else if (type != type_void_ptr) {
9594 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9596 expression = create_implicit_cast(expression, type_void_ptr);
9599 statement->gotos.expression = expression;
9600 } else if (token.type == T_IDENTIFIER) {
9601 label_t *const label = get_label();
9603 statement->gotos.label = label;
9606 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9608 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9610 return create_invalid_statement();
9613 /* remember the goto's in a list for later checking */
9614 *goto_anchor = &statement->gotos;
9615 goto_anchor = &statement->gotos.next;
9617 expect(';', end_error);
9624 * Parse a continue statement.
9626 static statement_t *parse_continue(void)
9628 if (current_loop == NULL) {
9629 errorf(HERE, "continue statement not within loop");
9632 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9635 expect(';', end_error);
9642 * Parse a break statement.
9644 static statement_t *parse_break(void)
9646 if (current_switch == NULL && current_loop == NULL) {
9647 errorf(HERE, "break statement not within loop or switch");
9650 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9653 expect(';', end_error);
9660 * Parse a __leave statement.
9662 static statement_t *parse_leave_statement(void)
9664 if (current_try == NULL) {
9665 errorf(HERE, "__leave statement not within __try");
9668 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9671 expect(';', end_error);
9678 * Check if a given entity represents a local variable.
9680 static bool is_local_variable(const entity_t *entity)
9682 if (entity->kind != ENTITY_VARIABLE)
9685 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9686 case STORAGE_CLASS_AUTO:
9687 case STORAGE_CLASS_REGISTER: {
9688 const type_t *type = skip_typeref(entity->declaration.type);
9689 if (is_type_function(type)) {
9701 * Check if a given expression represents a local variable.
9703 static bool expression_is_local_variable(const expression_t *expression)
9705 if (expression->base.kind != EXPR_REFERENCE) {
9708 const entity_t *entity = expression->reference.entity;
9709 return is_local_variable(entity);
9713 * Check if a given expression represents a local variable and
9714 * return its declaration then, else return NULL.
9716 entity_t *expression_is_variable(const expression_t *expression)
9718 if (expression->base.kind != EXPR_REFERENCE) {
9721 entity_t *entity = expression->reference.entity;
9722 if (entity->kind != ENTITY_VARIABLE)
9729 * Parse a return statement.
9731 static statement_t *parse_return(void)
9735 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9737 expression_t *return_value = NULL;
9738 if (token.type != ';') {
9739 return_value = parse_expression();
9740 mark_vars_read(return_value, NULL);
9743 const type_t *const func_type = skip_typeref(current_function->base.type);
9744 assert(is_type_function(func_type));
9745 type_t *const return_type = skip_typeref(func_type->function.return_type);
9747 source_position_t const *const pos = &statement->base.source_position;
9748 if (return_value != NULL) {
9749 type_t *return_value_type = skip_typeref(return_value->base.type);
9751 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9752 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9753 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9754 /* Only warn in C mode, because GCC does the same */
9755 if (c_mode & _CXX || strict_mode) {
9757 "'return' with a value, in function returning 'void'");
9759 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9761 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9762 /* Only warn in C mode, because GCC does the same */
9765 "'return' with expression in function returning 'void'");
9767 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9771 assign_error_t error = semantic_assign(return_type, return_value);
9772 report_assign_error(error, return_type, return_value, "'return'",
9775 return_value = create_implicit_cast(return_value, return_type);
9776 /* check for returning address of a local var */
9777 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9778 const expression_t *expression = return_value->unary.value;
9779 if (expression_is_local_variable(expression)) {
9780 warningf(WARN_OTHER, pos, "function returns address of local variable");
9783 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9784 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9785 if (c_mode & _CXX || strict_mode) {
9787 "'return' without value, in function returning non-void");
9789 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9792 statement->returns.value = return_value;
9794 expect(';', end_error);
9801 * Parse a declaration statement.
9803 static statement_t *parse_declaration_statement(void)
9805 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9807 entity_t *before = current_scope->last_entity;
9809 parse_external_declaration();
9811 parse_declaration(record_entity, DECL_FLAGS_NONE);
9814 declaration_statement_t *const decl = &statement->declaration;
9815 entity_t *const begin =
9816 before != NULL ? before->base.next : current_scope->entities;
9817 decl->declarations_begin = begin;
9818 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9824 * Parse an expression statement, ie. expr ';'.
9826 static statement_t *parse_expression_statement(void)
9828 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9830 expression_t *const expr = parse_expression();
9831 statement->expression.expression = expr;
9832 mark_vars_read(expr, ENT_ANY);
9834 expect(';', end_error);
9841 * Parse a microsoft __try { } __finally { } or
9842 * __try{ } __except() { }
9844 static statement_t *parse_ms_try_statment(void)
9846 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9849 PUSH_PARENT(statement);
9851 ms_try_statement_t *rem = current_try;
9852 current_try = &statement->ms_try;
9853 statement->ms_try.try_statement = parse_compound_statement(false);
9858 if (next_if(T___except)) {
9859 expect('(', end_error);
9860 add_anchor_token(')');
9861 expression_t *const expr = parse_expression();
9862 mark_vars_read(expr, NULL);
9863 type_t * type = skip_typeref(expr->base.type);
9864 if (is_type_integer(type)) {
9865 type = promote_integer(type);
9866 } else if (is_type_valid(type)) {
9867 errorf(&expr->base.source_position,
9868 "__expect expression is not an integer, but '%T'", type);
9869 type = type_error_type;
9871 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9872 rem_anchor_token(')');
9873 expect(')', end_error);
9874 statement->ms_try.final_statement = parse_compound_statement(false);
9875 } else if (next_if(T__finally)) {
9876 statement->ms_try.final_statement = parse_compound_statement(false);
9878 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9879 return create_invalid_statement();
9883 return create_invalid_statement();
9886 static statement_t *parse_empty_statement(void)
9888 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9889 statement_t *const statement = create_empty_statement();
9894 static statement_t *parse_local_label_declaration(void)
9896 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9900 entity_t *begin = NULL;
9901 entity_t *end = NULL;
9902 entity_t **anchor = &begin;
9904 if (token.type != T_IDENTIFIER) {
9905 parse_error_expected("while parsing local label declaration",
9906 T_IDENTIFIER, NULL);
9909 symbol_t *symbol = token.symbol;
9910 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9911 if (entity != NULL && entity->base.parent_scope == current_scope) {
9912 source_position_t const *const ppos = &entity->base.source_position;
9913 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9915 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9916 entity->base.parent_scope = current_scope;
9917 entity->base.source_position = token.source_position;
9920 anchor = &entity->base.next;
9923 environment_push(entity);
9926 } while (next_if(','));
9927 expect(';', end_error);
9929 statement->declaration.declarations_begin = begin;
9930 statement->declaration.declarations_end = end;
9934 static void parse_namespace_definition(void)
9938 entity_t *entity = NULL;
9939 symbol_t *symbol = NULL;
9941 if (token.type == T_IDENTIFIER) {
9942 symbol = token.symbol;
9945 entity = get_entity(symbol, NAMESPACE_NORMAL);
9947 && entity->kind != ENTITY_NAMESPACE
9948 && entity->base.parent_scope == current_scope) {
9949 if (is_entity_valid(entity)) {
9950 error_redefined_as_different_kind(&token.source_position,
9951 entity, ENTITY_NAMESPACE);
9957 if (entity == NULL) {
9958 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9959 entity->base.source_position = token.source_position;
9960 entity->base.parent_scope = current_scope;
9963 if (token.type == '=') {
9964 /* TODO: parse namespace alias */
9965 panic("namespace alias definition not supported yet");
9968 environment_push(entity);
9969 append_entity(current_scope, entity);
9971 size_t const top = environment_top();
9972 scope_t *old_scope = scope_push(&entity->namespacee.members);
9974 entity_t *old_current_entity = current_entity;
9975 current_entity = entity;
9977 expect('{', end_error);
9979 expect('}', end_error);
9982 assert(current_scope == &entity->namespacee.members);
9983 assert(current_entity == entity);
9984 current_entity = old_current_entity;
9985 scope_pop(old_scope);
9986 environment_pop_to(top);
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.type) {
10001 case T_IDENTIFIER: {
10002 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10003 if (la1_type == ':') {
10004 statement = parse_label_statement();
10005 } else if (is_typedef_symbol(token.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.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. */
10032 while (next_if(T___extension__)) {}
10033 bool old_gcc_extension = in_gcc_extension;
10034 in_gcc_extension = true;
10035 statement = intern_parse_statement();
10036 in_gcc_extension = old_gcc_extension;
10040 statement = parse_declaration_statement();
10044 statement = parse_local_label_declaration();
10047 case ';': statement = parse_empty_statement(); break;
10048 case '{': statement = parse_compound_statement(false); break;
10049 case T___leave: statement = parse_leave_statement(); break;
10050 case T___try: statement = parse_ms_try_statment(); break;
10051 case T_asm: statement = parse_asm_statement(); break;
10052 case T_break: statement = parse_break(); break;
10053 case T_case: statement = parse_case_statement(); break;
10054 case T_continue: statement = parse_continue(); break;
10055 case T_default: statement = parse_default_statement(); break;
10056 case T_do: statement = parse_do(); break;
10057 case T_for: statement = parse_for(); break;
10058 case T_goto: statement = parse_goto(); break;
10059 case T_if: statement = parse_if(); break;
10060 case T_return: statement = parse_return(); break;
10061 case T_switch: statement = parse_switch(); break;
10062 case T_while: statement = parse_while(); break;
10065 statement = parse_expression_statement();
10069 errorf(HERE, "unexpected token %K while parsing statement", &token);
10070 statement = create_invalid_statement();
10075 rem_anchor_token(';');
10077 assert(statement != NULL
10078 && statement->base.source_position.input_name != NULL);
10084 * parse a statement and emits "statement has no effect" warning if needed
10085 * (This is really a wrapper around intern_parse_statement with check for 1
10086 * single warning. It is needed, because for statement expressions we have
10087 * to avoid the warning on the last statement)
10089 static statement_t *parse_statement(void)
10091 statement_t *statement = intern_parse_statement();
10093 if (statement->kind == STATEMENT_EXPRESSION) {
10094 expression_t *expression = statement->expression.expression;
10095 if (!expression_has_effect(expression)) {
10096 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10104 * Parse a compound statement.
10106 static statement_t *parse_compound_statement(bool inside_expression_statement)
10108 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10110 PUSH_PARENT(statement);
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 size_t const top = environment_top();
10204 scope_t *old_scope = scope_push(&statement->compound.scope);
10206 statement_t **anchor = &statement->compound.statements;
10207 bool only_decls_so_far = true;
10208 while (token.type != '}') {
10209 if (token.type == T_EOF) {
10210 errorf(&statement->base.source_position,
10211 "EOF while parsing compound statement");
10214 statement_t *sub_statement = intern_parse_statement();
10215 if (is_invalid_statement(sub_statement)) {
10216 /* an error occurred. if we are at an anchor, return */
10222 if (sub_statement->kind != STATEMENT_DECLARATION) {
10223 only_decls_so_far = false;
10224 } else if (!only_decls_so_far) {
10225 source_position_t const *const pos = &sub_statement->base.source_position;
10226 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10229 *anchor = sub_statement;
10231 while (sub_statement->base.next != NULL)
10232 sub_statement = sub_statement->base.next;
10234 anchor = &sub_statement->base.next;
10238 /* look over all statements again to produce no effect warnings */
10239 if (is_warn_on(WARN_UNUSED_VALUE)) {
10240 statement_t *sub_statement = statement->compound.statements;
10241 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10242 if (sub_statement->kind != STATEMENT_EXPRESSION)
10244 /* don't emit a warning for the last expression in an expression
10245 * statement as it has always an effect */
10246 if (inside_expression_statement && sub_statement->base.next == NULL)
10249 expression_t *expression = sub_statement->expression.expression;
10250 if (!expression_has_effect(expression)) {
10251 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10257 rem_anchor_token(T_while);
10258 rem_anchor_token(T_wchar_t);
10259 rem_anchor_token(T_volatile);
10260 rem_anchor_token(T_void);
10261 rem_anchor_token(T_using);
10262 rem_anchor_token(T_unsigned);
10263 rem_anchor_token(T_union);
10264 rem_anchor_token(T_typeof);
10265 rem_anchor_token(T_typename);
10266 rem_anchor_token(T_typeid);
10267 rem_anchor_token(T_typedef);
10268 rem_anchor_token(T_try);
10269 rem_anchor_token(T_true);
10270 rem_anchor_token(T_throw);
10271 rem_anchor_token(T_this);
10272 rem_anchor_token(T_template);
10273 rem_anchor_token(T_switch);
10274 rem_anchor_token(T_struct);
10275 rem_anchor_token(T_static_cast);
10276 rem_anchor_token(T_static);
10277 rem_anchor_token(T_sizeof);
10278 rem_anchor_token(T_signed);
10279 rem_anchor_token(T_short);
10280 rem_anchor_token(T_return);
10281 rem_anchor_token(T_restrict);
10282 rem_anchor_token(T_reinterpret_cast);
10283 rem_anchor_token(T_register);
10284 rem_anchor_token(T_operator);
10285 rem_anchor_token(T_new);
10286 rem_anchor_token(T_long);
10287 rem_anchor_token(T_int);
10288 rem_anchor_token(T_inline);
10289 rem_anchor_token(T_if);
10290 rem_anchor_token(T_goto);
10291 rem_anchor_token(T_for);
10292 rem_anchor_token(T_float);
10293 rem_anchor_token(T_false);
10294 rem_anchor_token(T_extern);
10295 rem_anchor_token(T_enum);
10296 rem_anchor_token(T_dynamic_cast);
10297 rem_anchor_token(T_do);
10298 rem_anchor_token(T_double);
10299 rem_anchor_token(T_delete);
10300 rem_anchor_token(T_default);
10301 rem_anchor_token(T_continue);
10302 rem_anchor_token(T_const_cast);
10303 rem_anchor_token(T_const);
10304 rem_anchor_token(T_class);
10305 rem_anchor_token(T_char);
10306 rem_anchor_token(T_case);
10307 rem_anchor_token(T_break);
10308 rem_anchor_token(T_bool);
10309 rem_anchor_token(T_auto);
10310 rem_anchor_token(T_asm);
10311 rem_anchor_token(T___thread);
10312 rem_anchor_token(T___real__);
10313 rem_anchor_token(T___label__);
10314 rem_anchor_token(T___imag__);
10315 rem_anchor_token(T___func__);
10316 rem_anchor_token(T___extension__);
10317 rem_anchor_token(T___builtin_va_start);
10318 rem_anchor_token(T___attribute__);
10319 rem_anchor_token(T___alignof__);
10320 rem_anchor_token(T___PRETTY_FUNCTION__);
10321 rem_anchor_token(T___FUNCTION__);
10322 rem_anchor_token(T__Imaginary);
10323 rem_anchor_token(T__Complex);
10324 rem_anchor_token(T__Bool);
10325 rem_anchor_token(T_WIDE_STRING_LITERAL);
10326 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10327 rem_anchor_token(T_STRING_LITERAL);
10328 rem_anchor_token(T_PLUSPLUS);
10329 rem_anchor_token(T_MINUSMINUS);
10330 rem_anchor_token(T_INTEGER);
10331 rem_anchor_token(T_IDENTIFIER);
10332 rem_anchor_token(T_FLOATINGPOINT);
10333 rem_anchor_token(T_COLONCOLON);
10334 rem_anchor_token(T_CHARACTER_CONSTANT);
10335 rem_anchor_token('~');
10336 rem_anchor_token('{');
10337 rem_anchor_token('-');
10338 rem_anchor_token('+');
10339 rem_anchor_token('*');
10340 rem_anchor_token('(');
10341 rem_anchor_token('&');
10342 rem_anchor_token('!');
10343 rem_anchor_token('}');
10344 assert(current_scope == &statement->compound.scope);
10345 scope_pop(old_scope);
10346 environment_pop_to(top);
10353 * Check for unused global static functions and variables
10355 static void check_unused_globals(void)
10357 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10360 for (const entity_t *entity = file_scope->entities; entity != NULL;
10361 entity = entity->base.next) {
10362 if (!is_declaration(entity))
10365 const declaration_t *declaration = &entity->declaration;
10366 if (declaration->used ||
10367 declaration->modifiers & DM_UNUSED ||
10368 declaration->modifiers & DM_USED ||
10369 declaration->storage_class != STORAGE_CLASS_STATIC)
10374 if (entity->kind == ENTITY_FUNCTION) {
10375 /* inhibit warning for static inline functions */
10376 if (entity->function.is_inline)
10379 why = WARN_UNUSED_FUNCTION;
10380 s = entity->function.statement != NULL ? "defined" : "declared";
10382 why = WARN_UNUSED_VARIABLE;
10386 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10390 static void parse_global_asm(void)
10392 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10395 expect('(', end_error);
10397 statement->asms.asm_text = parse_string_literals();
10398 statement->base.next = unit->global_asm;
10399 unit->global_asm = statement;
10401 expect(')', end_error);
10402 expect(';', end_error);
10407 static void parse_linkage_specification(void)
10411 source_position_t const pos = *HERE;
10412 char const *const linkage = parse_string_literals().begin;
10414 linkage_kind_t old_linkage = current_linkage;
10415 linkage_kind_t new_linkage;
10416 if (strcmp(linkage, "C") == 0) {
10417 new_linkage = LINKAGE_C;
10418 } else if (strcmp(linkage, "C++") == 0) {
10419 new_linkage = LINKAGE_CXX;
10421 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10422 new_linkage = LINKAGE_INVALID;
10424 current_linkage = new_linkage;
10426 if (next_if('{')) {
10428 expect('}', end_error);
10434 assert(current_linkage == new_linkage);
10435 current_linkage = old_linkage;
10438 static void parse_external(void)
10440 switch (token.type) {
10441 DECLARATION_START_NO_EXTERN
10443 case T___extension__:
10444 /* tokens below are for implicit int */
10445 case '&': /* & x; -> int& x; (and error later, because C++ has no
10447 case '*': /* * x; -> int* x; */
10448 case '(': /* (x); -> int (x); */
10449 parse_external_declaration();
10453 if (look_ahead(1)->type == T_STRING_LITERAL) {
10454 parse_linkage_specification();
10456 parse_external_declaration();
10461 parse_global_asm();
10465 parse_namespace_definition();
10469 if (!strict_mode) {
10470 warningf(WARN_OTHER, HERE, "stray ';' outside of function");
10477 errorf(HERE, "stray %K outside of function", &token);
10478 if (token.type == '(' || token.type == '{' || token.type == '[')
10479 eat_until_matching_token(token.type);
10485 static void parse_externals(void)
10487 add_anchor_token('}');
10488 add_anchor_token(T_EOF);
10491 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10492 unsigned char token_anchor_copy[T_LAST_TOKEN];
10493 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10496 while (token.type != T_EOF && token.type != '}') {
10498 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10499 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10501 /* the anchor set and its copy differs */
10502 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10505 if (in_gcc_extension) {
10506 /* an gcc extension scope was not closed */
10507 internal_errorf(HERE, "Leaked __extension__");
10514 rem_anchor_token(T_EOF);
10515 rem_anchor_token('}');
10519 * Parse a translation unit.
10521 static void parse_translation_unit(void)
10523 add_anchor_token(T_EOF);
10528 if (token.type == T_EOF)
10531 errorf(HERE, "stray %K outside of function", &token);
10532 if (token.type == '(' || token.type == '{' || token.type == '[')
10533 eat_until_matching_token(token.type);
10538 void set_default_visibility(elf_visibility_tag_t visibility)
10540 default_visibility = visibility;
10546 * @return the translation unit or NULL if errors occurred.
10548 void start_parsing(void)
10550 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10551 label_stack = NEW_ARR_F(stack_entry_t, 0);
10552 diagnostic_count = 0;
10556 print_to_file(stderr);
10558 assert(unit == NULL);
10559 unit = allocate_ast_zero(sizeof(unit[0]));
10561 assert(file_scope == NULL);
10562 file_scope = &unit->scope;
10564 assert(current_scope == NULL);
10565 scope_push(&unit->scope);
10567 create_gnu_builtins();
10569 create_microsoft_intrinsics();
10572 translation_unit_t *finish_parsing(void)
10574 assert(current_scope == &unit->scope);
10577 assert(file_scope == &unit->scope);
10578 check_unused_globals();
10581 DEL_ARR_F(environment_stack);
10582 DEL_ARR_F(label_stack);
10584 translation_unit_t *result = unit;
10589 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10590 * are given length one. */
10591 static void complete_incomplete_arrays(void)
10593 size_t n = ARR_LEN(incomplete_arrays);
10594 for (size_t i = 0; i != n; ++i) {
10595 declaration_t *const decl = incomplete_arrays[i];
10596 type_t *const type = skip_typeref(decl->type);
10598 if (!is_type_incomplete(type))
10601 source_position_t const *const pos = &decl->base.source_position;
10602 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10604 type_t *const new_type = duplicate_type(type);
10605 new_type->array.size_constant = true;
10606 new_type->array.has_implicit_size = true;
10607 new_type->array.size = 1;
10609 type_t *const result = identify_new_type(new_type);
10611 decl->type = result;
10615 void prepare_main_collect2(entity_t *entity)
10617 // create call to __main
10618 symbol_t *symbol = symbol_table_insert("__main");
10619 entity_t *subsubmain_ent
10620 = create_implicit_function(symbol, &builtin_source_position);
10622 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10623 type_t *ftype = subsubmain_ent->declaration.type;
10624 ref->base.source_position = builtin_source_position;
10625 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10626 ref->reference.entity = subsubmain_ent;
10628 expression_t *call = allocate_expression_zero(EXPR_CALL);
10629 call->base.source_position = builtin_source_position;
10630 call->base.type = type_void;
10631 call->call.function = ref;
10633 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10634 expr_statement->base.source_position = builtin_source_position;
10635 expr_statement->expression.expression = call;
10637 statement_t *statement = entity->function.statement;
10638 assert(statement->kind == STATEMENT_COMPOUND);
10639 compound_statement_t *compounds = &statement->compound;
10641 expr_statement->base.next = compounds->statements;
10642 compounds->statements = expr_statement;
10647 lookahead_bufpos = 0;
10648 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10651 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10652 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10653 parse_translation_unit();
10654 complete_incomplete_arrays();
10655 DEL_ARR_F(incomplete_arrays);
10656 incomplete_arrays = NULL;
10660 * Initialize the parser.
10662 void init_parser(void)
10664 sym_anonymous = symbol_table_insert("<anonymous>");
10666 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10668 init_expression_parsers();
10669 obstack_init(&temp_obst);
10673 * Terminate the parser.
10675 void exit_parser(void)
10677 obstack_free(&temp_obst, NULL);