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() \
2920 if ( type != NULL) \
2921 errorf(HERE, "multiple data types in declaration specifiers"); \
2925 CHECK_DOUBLE_TYPE();
2926 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2928 type->compound.compound = parse_compound_type_specifier(true);
2931 CHECK_DOUBLE_TYPE();
2932 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2933 type->compound.compound = parse_compound_type_specifier(false);
2936 CHECK_DOUBLE_TYPE();
2937 type = parse_enum_specifier();
2940 CHECK_DOUBLE_TYPE();
2941 type = parse_typeof();
2943 case T___builtin_va_list:
2944 CHECK_DOUBLE_TYPE();
2945 type = duplicate_type(type_valist);
2949 case T_IDENTIFIER: {
2950 /* only parse identifier if we haven't found a type yet */
2951 if (type != NULL || type_specifiers != 0) {
2952 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2953 * declaration, so it doesn't generate errors about expecting '(' or
2955 switch (look_ahead(1)->type) {
2962 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2966 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2971 goto finish_specifiers;
2975 type_t *const typedef_type = get_typedef_type(token.symbol);
2976 if (typedef_type == NULL) {
2977 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2978 * declaration, so it doesn't generate 'implicit int' followed by more
2979 * errors later on. */
2980 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
2986 errorf(HERE, "%K does not name a type", &token);
2989 create_error_entity(token.symbol, ENTITY_TYPEDEF);
2991 type = allocate_type_zero(TYPE_TYPEDEF);
2992 type->typedeft.typedefe = &entity->typedefe;
3000 goto finish_specifiers;
3005 type = typedef_type;
3009 /* function specifier */
3011 goto finish_specifiers;
3016 specifiers->attributes = parse_attributes(specifiers->attributes);
3018 in_gcc_extension = old_gcc_extension;
3020 if (type == NULL || (saw_error && type_specifiers != 0)) {
3021 atomic_type_kind_t atomic_type;
3023 /* match valid basic types */
3024 switch (type_specifiers) {
3025 case SPECIFIER_VOID:
3026 atomic_type = ATOMIC_TYPE_VOID;
3028 case SPECIFIER_WCHAR_T:
3029 atomic_type = ATOMIC_TYPE_WCHAR_T;
3031 case SPECIFIER_CHAR:
3032 atomic_type = ATOMIC_TYPE_CHAR;
3034 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3035 atomic_type = ATOMIC_TYPE_SCHAR;
3037 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3038 atomic_type = ATOMIC_TYPE_UCHAR;
3040 case SPECIFIER_SHORT:
3041 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3042 case SPECIFIER_SHORT | SPECIFIER_INT:
3043 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3044 atomic_type = ATOMIC_TYPE_SHORT;
3046 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3047 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3048 atomic_type = ATOMIC_TYPE_USHORT;
3051 case SPECIFIER_SIGNED:
3052 case SPECIFIER_SIGNED | SPECIFIER_INT:
3053 atomic_type = ATOMIC_TYPE_INT;
3055 case SPECIFIER_UNSIGNED:
3056 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3057 atomic_type = ATOMIC_TYPE_UINT;
3059 case SPECIFIER_LONG:
3060 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3061 case SPECIFIER_LONG | SPECIFIER_INT:
3062 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3063 atomic_type = ATOMIC_TYPE_LONG;
3065 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3066 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3067 atomic_type = ATOMIC_TYPE_ULONG;
3070 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3071 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3072 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3073 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3075 atomic_type = ATOMIC_TYPE_LONGLONG;
3076 goto warn_about_long_long;
3078 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3079 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3081 atomic_type = ATOMIC_TYPE_ULONGLONG;
3082 warn_about_long_long:
3083 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3086 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3087 atomic_type = unsigned_int8_type_kind;
3090 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3091 atomic_type = unsigned_int16_type_kind;
3094 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3095 atomic_type = unsigned_int32_type_kind;
3098 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3099 atomic_type = unsigned_int64_type_kind;
3102 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3103 atomic_type = unsigned_int128_type_kind;
3106 case SPECIFIER_INT8:
3107 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3108 atomic_type = int8_type_kind;
3111 case SPECIFIER_INT16:
3112 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3113 atomic_type = int16_type_kind;
3116 case SPECIFIER_INT32:
3117 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3118 atomic_type = int32_type_kind;
3121 case SPECIFIER_INT64:
3122 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3123 atomic_type = int64_type_kind;
3126 case SPECIFIER_INT128:
3127 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3128 atomic_type = int128_type_kind;
3131 case SPECIFIER_FLOAT:
3132 atomic_type = ATOMIC_TYPE_FLOAT;
3134 case SPECIFIER_DOUBLE:
3135 atomic_type = ATOMIC_TYPE_DOUBLE;
3137 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3138 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3140 case SPECIFIER_BOOL:
3141 atomic_type = ATOMIC_TYPE_BOOL;
3143 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3144 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3145 atomic_type = ATOMIC_TYPE_FLOAT;
3147 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3148 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3149 atomic_type = ATOMIC_TYPE_DOUBLE;
3151 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3152 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3153 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3156 /* invalid specifier combination, give an error message */
3157 source_position_t const* const pos = &specifiers->source_position;
3158 if (type_specifiers == 0) {
3160 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3161 if (!(c_mode & _CXX) && !strict_mode) {
3162 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3163 atomic_type = ATOMIC_TYPE_INT;
3166 errorf(pos, "no type specifiers given in declaration");
3169 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3170 (type_specifiers & SPECIFIER_UNSIGNED)) {
3171 errorf(pos, "signed and unsigned specifiers given");
3172 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3173 errorf(pos, "only integer types can be signed or unsigned");
3175 errorf(pos, "multiple datatypes in declaration");
3181 if (type_specifiers & SPECIFIER_COMPLEX) {
3182 type = allocate_type_zero(TYPE_COMPLEX);
3183 type->complex.akind = atomic_type;
3184 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3185 type = allocate_type_zero(TYPE_IMAGINARY);
3186 type->imaginary.akind = atomic_type;
3188 type = allocate_type_zero(TYPE_ATOMIC);
3189 type->atomic.akind = atomic_type;
3192 } else if (type_specifiers != 0) {
3193 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3196 /* FIXME: check type qualifiers here */
3197 type->base.qualifiers = qualifiers;
3200 type = identify_new_type(type);
3202 type = typehash_insert(type);
3205 if (specifiers->attributes != NULL)
3206 type = handle_type_attributes(specifiers->attributes, type);
3207 specifiers->type = type;
3211 specifiers->type = type_error_type;
3214 static type_qualifiers_t parse_type_qualifiers(void)
3216 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3219 switch (token.type) {
3220 /* type qualifiers */
3221 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3222 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3223 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3224 /* microsoft extended type modifiers */
3225 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3226 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3227 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3228 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3229 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3238 * Parses an K&R identifier list
3240 static void parse_identifier_list(scope_t *scope)
3243 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.symbol);
3244 entity->base.source_position = token.source_position;
3245 /* a K&R parameter has no type, yet */
3249 append_entity(scope, entity);
3250 } while (next_if(',') && token.type == T_IDENTIFIER);
3253 static entity_t *parse_parameter(void)
3255 declaration_specifiers_t specifiers;
3256 parse_declaration_specifiers(&specifiers);
3258 entity_t *entity = parse_declarator(&specifiers,
3259 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3260 anonymous_entity = NULL;
3264 static void semantic_parameter_incomplete(const entity_t *entity)
3266 assert(entity->kind == ENTITY_PARAMETER);
3268 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3269 * list in a function declarator that is part of a
3270 * definition of that function shall not have
3271 * incomplete type. */
3272 type_t *type = skip_typeref(entity->declaration.type);
3273 if (is_type_incomplete(type)) {
3274 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3278 static bool has_parameters(void)
3280 /* func(void) is not a parameter */
3281 if (token.type == T_IDENTIFIER) {
3282 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3285 if (entity->kind != ENTITY_TYPEDEF)
3287 if (skip_typeref(entity->typedefe.type) != type_void)
3289 } else if (token.type != T_void) {
3292 if (look_ahead(1)->type != ')')
3299 * Parses function type parameters (and optionally creates variable_t entities
3300 * for them in a scope)
3302 static void parse_parameters(function_type_t *type, scope_t *scope)
3305 add_anchor_token(')');
3306 int saved_comma_state = save_and_reset_anchor_state(',');
3308 if (token.type == T_IDENTIFIER &&
3309 !is_typedef_symbol(token.symbol)) {
3310 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3311 if (la1_type == ',' || la1_type == ')') {
3312 type->kr_style_parameters = true;
3313 parse_identifier_list(scope);
3314 goto parameters_finished;
3318 if (token.type == ')') {
3319 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3320 if (!(c_mode & _CXX))
3321 type->unspecified_parameters = true;
3322 } else if (has_parameters()) {
3323 function_parameter_t **anchor = &type->parameters;
3325 switch (token.type) {
3328 type->variadic = true;
3329 goto parameters_finished;
3332 case T___extension__:
3335 entity_t *entity = parse_parameter();
3336 if (entity->kind == ENTITY_TYPEDEF) {
3337 errorf(&entity->base.source_position,
3338 "typedef not allowed as function parameter");
3341 assert(is_declaration(entity));
3343 semantic_parameter_incomplete(entity);
3345 function_parameter_t *const parameter =
3346 allocate_parameter(entity->declaration.type);
3348 if (scope != NULL) {
3349 append_entity(scope, entity);
3352 *anchor = parameter;
3353 anchor = ¶meter->next;
3358 goto parameters_finished;
3360 } while (next_if(','));
3363 parameters_finished:
3364 rem_anchor_token(')');
3365 expect(')', end_error);
3368 restore_anchor_state(',', saved_comma_state);
3371 typedef enum construct_type_kind_t {
3374 CONSTRUCT_REFERENCE,
3377 } construct_type_kind_t;
3379 typedef union construct_type_t construct_type_t;
3381 typedef struct construct_type_base_t {
3382 construct_type_kind_t kind;
3383 source_position_t pos;
3384 construct_type_t *next;
3385 } construct_type_base_t;
3387 typedef struct parsed_pointer_t {
3388 construct_type_base_t base;
3389 type_qualifiers_t type_qualifiers;
3390 variable_t *base_variable; /**< MS __based extension. */
3393 typedef struct parsed_reference_t {
3394 construct_type_base_t base;
3395 } parsed_reference_t;
3397 typedef struct construct_function_type_t {
3398 construct_type_base_t base;
3399 type_t *function_type;
3400 } construct_function_type_t;
3402 typedef struct parsed_array_t {
3403 construct_type_base_t base;
3404 type_qualifiers_t type_qualifiers;
3410 union construct_type_t {
3411 construct_type_kind_t kind;
3412 construct_type_base_t base;
3413 parsed_pointer_t pointer;
3414 parsed_reference_t reference;
3415 construct_function_type_t function;
3416 parsed_array_t array;
3419 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3421 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3422 memset(cons, 0, size);
3424 cons->base.pos = *HERE;
3429 static construct_type_t *parse_pointer_declarator(void)
3431 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3433 cons->pointer.type_qualifiers = parse_type_qualifiers();
3434 //cons->pointer.base_variable = base_variable;
3439 /* ISO/IEC 14882:1998(E) §8.3.2 */
3440 static construct_type_t *parse_reference_declarator(void)
3442 if (!(c_mode & _CXX))
3443 errorf(HERE, "references are only available for C++");
3445 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3452 static construct_type_t *parse_array_declarator(void)
3454 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3455 parsed_array_t *const array = &cons->array;
3458 add_anchor_token(']');
3460 bool is_static = next_if(T_static);
3462 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3465 is_static = next_if(T_static);
3467 array->type_qualifiers = type_qualifiers;
3468 array->is_static = is_static;
3470 expression_t *size = NULL;
3471 if (token.type == '*' && look_ahead(1)->type == ']') {
3472 array->is_variable = true;
3474 } else if (token.type != ']') {
3475 size = parse_assignment_expression();
3477 /* §6.7.5.2:1 Array size must have integer type */
3478 type_t *const orig_type = size->base.type;
3479 type_t *const type = skip_typeref(orig_type);
3480 if (!is_type_integer(type) && is_type_valid(type)) {
3481 errorf(&size->base.source_position,
3482 "array size '%E' must have integer type but has type '%T'",
3487 mark_vars_read(size, NULL);
3490 if (is_static && size == NULL)
3491 errorf(&array->base.pos, "static array parameters require a size");
3493 rem_anchor_token(']');
3494 expect(']', end_error);
3501 static construct_type_t *parse_function_declarator(scope_t *scope)
3503 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3505 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3506 function_type_t *ftype = &type->function;
3508 ftype->linkage = current_linkage;
3509 ftype->calling_convention = CC_DEFAULT;
3511 parse_parameters(ftype, scope);
3513 cons->function.function_type = type;
3518 typedef struct parse_declarator_env_t {
3519 bool may_be_abstract : 1;
3520 bool must_be_abstract : 1;
3521 decl_modifiers_t modifiers;
3523 source_position_t source_position;
3525 attribute_t *attributes;
3526 } parse_declarator_env_t;
3529 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3531 /* construct a single linked list of construct_type_t's which describe
3532 * how to construct the final declarator type */
3533 construct_type_t *first = NULL;
3534 construct_type_t **anchor = &first;
3536 env->attributes = parse_attributes(env->attributes);
3539 construct_type_t *type;
3540 //variable_t *based = NULL; /* MS __based extension */
3541 switch (token.type) {
3543 type = parse_reference_declarator();
3547 panic("based not supported anymore");
3552 type = parse_pointer_declarator();
3556 goto ptr_operator_end;
3560 anchor = &type->base.next;
3562 /* TODO: find out if this is correct */
3563 env->attributes = parse_attributes(env->attributes);
3567 construct_type_t *inner_types = NULL;
3569 switch (token.type) {
3571 if (env->must_be_abstract) {
3572 errorf(HERE, "no identifier expected in typename");
3574 env->symbol = token.symbol;
3575 env->source_position = token.source_position;
3581 /* Parenthesized declarator or function declarator? */
3582 token_t const *const la1 = look_ahead(1);
3583 switch (la1->type) {
3585 if (is_typedef_symbol(la1->symbol)) {
3587 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3588 * interpreted as ``function with no parameter specification'', rather
3589 * than redundant parentheses around the omitted identifier. */
3591 /* Function declarator. */
3592 if (!env->may_be_abstract) {
3593 errorf(HERE, "function declarator must have a name");
3600 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3601 /* Paranthesized declarator. */
3603 add_anchor_token(')');
3604 inner_types = parse_inner_declarator(env);
3605 if (inner_types != NULL) {
3606 /* All later declarators only modify the return type */
3607 env->must_be_abstract = true;
3609 rem_anchor_token(')');
3610 expect(')', end_error);
3618 if (env->may_be_abstract)
3620 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3625 construct_type_t **const p = anchor;
3628 construct_type_t *type;
3629 switch (token.type) {
3631 scope_t *scope = NULL;
3632 if (!env->must_be_abstract) {
3633 scope = &env->parameters;
3636 type = parse_function_declarator(scope);
3640 type = parse_array_declarator();
3643 goto declarator_finished;
3646 /* insert in the middle of the list (at p) */
3647 type->base.next = *p;
3650 anchor = &type->base.next;
3653 declarator_finished:
3654 /* append inner_types at the end of the list, we don't to set anchor anymore
3655 * as it's not needed anymore */
3656 *anchor = inner_types;
3663 static type_t *construct_declarator_type(construct_type_t *construct_list,
3666 construct_type_t *iter = construct_list;
3667 for (; iter != NULL; iter = iter->base.next) {
3668 source_position_t const* const pos = &iter->base.pos;
3669 switch (iter->kind) {
3670 case CONSTRUCT_INVALID:
3672 case CONSTRUCT_FUNCTION: {
3673 construct_function_type_t *function = &iter->function;
3674 type_t *function_type = function->function_type;
3676 function_type->function.return_type = type;
3678 type_t *skipped_return_type = skip_typeref(type);
3680 if (is_type_function(skipped_return_type)) {
3681 errorf(pos, "function returning function is not allowed");
3682 } else if (is_type_array(skipped_return_type)) {
3683 errorf(pos, "function returning array is not allowed");
3685 if (skipped_return_type->base.qualifiers != 0) {
3686 warningf(WARN_OTHER, pos, "type qualifiers in return type of function type are meaningless");
3690 /* The function type was constructed earlier. Freeing it here will
3691 * destroy other types. */
3692 type = typehash_insert(function_type);
3696 case CONSTRUCT_POINTER: {
3697 if (is_type_reference(skip_typeref(type)))
3698 errorf(pos, "cannot declare a pointer to reference");
3700 parsed_pointer_t *pointer = &iter->pointer;
3701 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3705 case CONSTRUCT_REFERENCE:
3706 if (is_type_reference(skip_typeref(type)))
3707 errorf(pos, "cannot declare a reference to reference");
3709 type = make_reference_type(type);
3712 case CONSTRUCT_ARRAY: {
3713 if (is_type_reference(skip_typeref(type)))
3714 errorf(pos, "cannot declare an array of references");
3716 parsed_array_t *array = &iter->array;
3717 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3719 expression_t *size_expression = array->size;
3720 if (size_expression != NULL) {
3722 = create_implicit_cast(size_expression, type_size_t);
3725 array_type->base.qualifiers = array->type_qualifiers;
3726 array_type->array.element_type = type;
3727 array_type->array.is_static = array->is_static;
3728 array_type->array.is_variable = array->is_variable;
3729 array_type->array.size_expression = size_expression;
3731 if (size_expression != NULL) {
3732 switch (is_constant_expression(size_expression)) {
3733 case EXPR_CLASS_CONSTANT: {
3734 long const size = fold_constant_to_int(size_expression);
3735 array_type->array.size = size;
3736 array_type->array.size_constant = true;
3737 /* §6.7.5.2:1 If the expression is a constant expression,
3738 * it shall have a value greater than zero. */
3740 errorf(&size_expression->base.source_position,
3741 "size of array must be greater than zero");
3742 } else if (size == 0 && !GNU_MODE) {
3743 errorf(&size_expression->base.source_position,
3744 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3749 case EXPR_CLASS_VARIABLE:
3750 array_type->array.is_vla = true;
3753 case EXPR_CLASS_ERROR:
3758 type_t *skipped_type = skip_typeref(type);
3760 if (is_type_incomplete(skipped_type)) {
3761 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3762 } else if (is_type_function(skipped_type)) {
3763 errorf(pos, "array of functions is not allowed");
3765 type = identify_new_type(array_type);
3769 internal_errorf(pos, "invalid type construction found");
3775 static type_t *automatic_type_conversion(type_t *orig_type);
3777 static type_t *semantic_parameter(const source_position_t *pos,
3779 const declaration_specifiers_t *specifiers,
3780 entity_t const *const param)
3782 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3783 * shall be adjusted to ``qualified pointer to type'',
3785 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3786 * type'' shall be adjusted to ``pointer to function
3787 * returning type'', as in 6.3.2.1. */
3788 type = automatic_type_conversion(type);
3790 if (specifiers->is_inline && is_type_valid(type)) {
3791 errorf(pos, "'%N' declared 'inline'", param);
3794 /* §6.9.1:6 The declarations in the declaration list shall contain
3795 * no storage-class specifier other than register and no
3796 * initializations. */
3797 if (specifiers->thread_local || (
3798 specifiers->storage_class != STORAGE_CLASS_NONE &&
3799 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3801 errorf(pos, "invalid storage class for '%N'", param);
3804 /* delay test for incomplete type, because we might have (void)
3805 * which is legal but incomplete... */
3810 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3811 declarator_flags_t flags)
3813 parse_declarator_env_t env;
3814 memset(&env, 0, sizeof(env));
3815 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3817 construct_type_t *construct_type = parse_inner_declarator(&env);
3819 construct_declarator_type(construct_type, specifiers->type);
3820 type_t *type = skip_typeref(orig_type);
3822 if (construct_type != NULL) {
3823 obstack_free(&temp_obst, construct_type);
3826 attribute_t *attributes = parse_attributes(env.attributes);
3827 /* append (shared) specifier attribute behind attributes of this
3829 attribute_t **anchor = &attributes;
3830 while (*anchor != NULL)
3831 anchor = &(*anchor)->next;
3832 *anchor = specifiers->attributes;
3835 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3836 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3837 entity->base.source_position = env.source_position;
3838 entity->typedefe.type = orig_type;
3840 if (anonymous_entity != NULL) {
3841 if (is_type_compound(type)) {
3842 assert(anonymous_entity->compound.alias == NULL);
3843 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3844 anonymous_entity->kind == ENTITY_UNION);
3845 anonymous_entity->compound.alias = entity;
3846 anonymous_entity = NULL;
3847 } else if (is_type_enum(type)) {
3848 assert(anonymous_entity->enume.alias == NULL);
3849 assert(anonymous_entity->kind == ENTITY_ENUM);
3850 anonymous_entity->enume.alias = entity;
3851 anonymous_entity = NULL;
3855 /* create a declaration type entity */
3856 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3857 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3859 if (env.symbol != NULL) {
3860 if (specifiers->is_inline && is_type_valid(type)) {
3861 errorf(&env.source_position,
3862 "compound member '%Y' declared 'inline'", env.symbol);
3865 if (specifiers->thread_local ||
3866 specifiers->storage_class != STORAGE_CLASS_NONE) {
3867 errorf(&env.source_position,
3868 "compound member '%Y' must have no storage class",
3872 } else if (flags & DECL_IS_PARAMETER) {
3873 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3874 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3875 } else if (is_type_function(type)) {
3876 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3877 entity->function.is_inline = specifiers->is_inline;
3878 entity->function.elf_visibility = default_visibility;
3879 entity->function.parameters = env.parameters;
3881 if (env.symbol != NULL) {
3882 /* this needs fixes for C++ */
3883 bool in_function_scope = current_function != NULL;
3885 if (specifiers->thread_local || (
3886 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3887 specifiers->storage_class != STORAGE_CLASS_NONE &&
3888 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3890 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3894 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3895 entity->variable.elf_visibility = default_visibility;
3896 entity->variable.thread_local = specifiers->thread_local;
3898 if (env.symbol != NULL) {
3899 if (specifiers->is_inline && is_type_valid(type)) {
3900 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3903 bool invalid_storage_class = false;
3904 if (current_scope == file_scope) {
3905 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3906 specifiers->storage_class != STORAGE_CLASS_NONE &&
3907 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3908 invalid_storage_class = true;
3911 if (specifiers->thread_local &&
3912 specifiers->storage_class == STORAGE_CLASS_NONE) {
3913 invalid_storage_class = true;
3916 if (invalid_storage_class) {
3917 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3922 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3923 entity->declaration.type = orig_type;
3924 entity->declaration.alignment = get_type_alignment(orig_type);
3925 entity->declaration.modifiers = env.modifiers;
3926 entity->declaration.attributes = attributes;
3928 storage_class_t storage_class = specifiers->storage_class;
3929 entity->declaration.declared_storage_class = storage_class;
3931 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3932 storage_class = STORAGE_CLASS_AUTO;
3933 entity->declaration.storage_class = storage_class;
3936 if (attributes != NULL) {
3937 handle_entity_attributes(attributes, entity);
3943 static type_t *parse_abstract_declarator(type_t *base_type)
3945 parse_declarator_env_t env;
3946 memset(&env, 0, sizeof(env));
3947 env.may_be_abstract = true;
3948 env.must_be_abstract = true;
3950 construct_type_t *construct_type = parse_inner_declarator(&env);
3952 type_t *result = construct_declarator_type(construct_type, base_type);
3953 if (construct_type != NULL) {
3954 obstack_free(&temp_obst, construct_type);
3956 result = handle_type_attributes(env.attributes, result);
3962 * Check if the declaration of main is suspicious. main should be a
3963 * function with external linkage, returning int, taking either zero
3964 * arguments, two, or three arguments of appropriate types, ie.
3966 * int main([ int argc, char **argv [, char **env ] ]).
3968 * @param decl the declaration to check
3969 * @param type the function type of the declaration
3971 static void check_main(const entity_t *entity)
3973 const source_position_t *pos = &entity->base.source_position;
3974 if (entity->kind != ENTITY_FUNCTION) {
3975 warningf(WARN_MAIN, pos, "'main' is not a function");
3979 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3980 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3983 type_t *type = skip_typeref(entity->declaration.type);
3984 assert(is_type_function(type));
3986 function_type_t const *const func_type = &type->function;
3987 type_t *const ret_type = func_type->return_type;
3988 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3989 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3991 const function_parameter_t *parm = func_type->parameters;
3993 type_t *const first_type = skip_typeref(parm->type);
3994 type_t *const first_type_unqual = get_unqualified_type(first_type);
3995 if (!types_compatible(first_type_unqual, type_int)) {
3996 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
4000 type_t *const second_type = skip_typeref(parm->type);
4001 type_t *const second_type_unqual
4002 = get_unqualified_type(second_type);
4003 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4004 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
4008 type_t *const third_type = skip_typeref(parm->type);
4009 type_t *const third_type_unqual
4010 = get_unqualified_type(third_type);
4011 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4012 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
4016 goto warn_arg_count;
4020 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
4026 * Check if a symbol is the equal to "main".
4028 static bool is_sym_main(const symbol_t *const sym)
4030 return strcmp(sym->string, "main") == 0;
4033 static void error_redefined_as_different_kind(const source_position_t *pos,
4034 const entity_t *old, entity_kind_t new_kind)
4036 char const *const what = get_entity_kind_name(new_kind);
4037 source_position_t const *const ppos = &old->base.source_position;
4038 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4041 static bool is_entity_valid(entity_t *const ent)
4043 if (is_declaration(ent)) {
4044 return is_type_valid(skip_typeref(ent->declaration.type));
4045 } else if (ent->kind == ENTITY_TYPEDEF) {
4046 return is_type_valid(skip_typeref(ent->typedefe.type));
4051 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4053 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4054 if (attributes_equal(tattr, attr))
4061 * test wether new_list contains any attributes not included in old_list
4063 static bool has_new_attributes(const attribute_t *old_list,
4064 const attribute_t *new_list)
4066 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4067 if (!contains_attribute(old_list, attr))
4074 * Merge in attributes from an attribute list (probably from a previous
4075 * declaration with the same name). Warning: destroys the old structure
4076 * of the attribute list - don't reuse attributes after this call.
4078 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4081 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4083 if (contains_attribute(decl->attributes, attr))
4086 /* move attribute to new declarations attributes list */
4087 attr->next = decl->attributes;
4088 decl->attributes = attr;
4093 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4094 * for various problems that occur for multiple definitions
4096 entity_t *record_entity(entity_t *entity, const bool is_definition)
4098 const symbol_t *const symbol = entity->base.symbol;
4099 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4100 const source_position_t *pos = &entity->base.source_position;
4102 /* can happen in error cases */
4106 entity_t *const previous_entity = get_entity(symbol, namespc);
4107 /* pushing the same entity twice will break the stack structure */
4108 assert(previous_entity != entity);
4110 if (entity->kind == ENTITY_FUNCTION) {
4111 type_t *const orig_type = entity->declaration.type;
4112 type_t *const type = skip_typeref(orig_type);
4114 assert(is_type_function(type));
4115 if (type->function.unspecified_parameters &&
4116 previous_entity == NULL &&
4117 !entity->declaration.implicit) {
4118 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4121 if (current_scope == file_scope && is_sym_main(symbol)) {
4126 if (is_declaration(entity) &&
4127 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4128 current_scope != file_scope &&
4129 !entity->declaration.implicit) {
4130 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4133 if (previous_entity != NULL) {
4134 source_position_t const *const ppos = &previous_entity->base.source_position;
4136 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4137 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4138 assert(previous_entity->kind == ENTITY_PARAMETER);
4139 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4143 if (previous_entity->base.parent_scope == current_scope) {
4144 if (previous_entity->kind != entity->kind) {
4145 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4146 error_redefined_as_different_kind(pos, previous_entity,
4151 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4152 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4155 if (previous_entity->kind == ENTITY_TYPEDEF) {
4156 /* TODO: C++ allows this for exactly the same type */
4157 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4161 /* at this point we should have only VARIABLES or FUNCTIONS */
4162 assert(is_declaration(previous_entity) && is_declaration(entity));
4164 declaration_t *const prev_decl = &previous_entity->declaration;
4165 declaration_t *const decl = &entity->declaration;
4167 /* can happen for K&R style declarations */
4168 if (prev_decl->type == NULL &&
4169 previous_entity->kind == ENTITY_PARAMETER &&
4170 entity->kind == ENTITY_PARAMETER) {
4171 prev_decl->type = decl->type;
4172 prev_decl->storage_class = decl->storage_class;
4173 prev_decl->declared_storage_class = decl->declared_storage_class;
4174 prev_decl->modifiers = decl->modifiers;
4175 return previous_entity;
4178 type_t *const type = skip_typeref(decl->type);
4179 type_t *const prev_type = skip_typeref(prev_decl->type);
4181 if (!types_compatible(type, prev_type)) {
4182 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4184 unsigned old_storage_class = prev_decl->storage_class;
4186 if (is_definition &&
4188 !(prev_decl->modifiers & DM_USED) &&
4189 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4190 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4193 storage_class_t new_storage_class = decl->storage_class;
4195 /* pretend no storage class means extern for function
4196 * declarations (except if the previous declaration is neither
4197 * none nor extern) */
4198 if (entity->kind == ENTITY_FUNCTION) {
4199 /* the previous declaration could have unspecified parameters or
4200 * be a typedef, so use the new type */
4201 if (prev_type->function.unspecified_parameters || is_definition)
4202 prev_decl->type = type;
4204 switch (old_storage_class) {
4205 case STORAGE_CLASS_NONE:
4206 old_storage_class = STORAGE_CLASS_EXTERN;
4209 case STORAGE_CLASS_EXTERN:
4210 if (is_definition) {
4211 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4212 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4214 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4215 new_storage_class = STORAGE_CLASS_EXTERN;
4222 } else if (is_type_incomplete(prev_type)) {
4223 prev_decl->type = type;
4226 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4227 new_storage_class == STORAGE_CLASS_EXTERN) {
4229 warn_redundant_declaration: ;
4231 = has_new_attributes(prev_decl->attributes,
4233 if (has_new_attrs) {
4234 merge_in_attributes(decl, prev_decl->attributes);
4235 } else if (!is_definition &&
4236 is_type_valid(prev_type) &&
4237 strcmp(ppos->input_name, "<builtin>") != 0) {
4238 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4240 } else if (current_function == NULL) {
4241 if (old_storage_class != STORAGE_CLASS_STATIC &&
4242 new_storage_class == STORAGE_CLASS_STATIC) {
4243 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4244 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4245 prev_decl->storage_class = STORAGE_CLASS_NONE;
4246 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4248 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4250 goto error_redeclaration;
4251 goto warn_redundant_declaration;
4253 } else if (is_type_valid(prev_type)) {
4254 if (old_storage_class == new_storage_class) {
4255 error_redeclaration:
4256 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4258 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4263 prev_decl->modifiers |= decl->modifiers;
4264 if (entity->kind == ENTITY_FUNCTION) {
4265 previous_entity->function.is_inline |= entity->function.is_inline;
4267 return previous_entity;
4271 if (is_warn_on(why = WARN_SHADOW) ||
4272 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4273 char const *const what = get_entity_kind_name(previous_entity->kind);
4274 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4278 if (entity->kind == ENTITY_FUNCTION) {
4279 if (is_definition &&
4280 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4281 !is_sym_main(symbol)) {
4282 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4283 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4285 goto warn_missing_declaration;
4288 } else if (entity->kind == ENTITY_VARIABLE) {
4289 if (current_scope == file_scope &&
4290 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4291 !entity->declaration.implicit) {
4292 warn_missing_declaration:
4293 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4298 assert(entity->base.parent_scope == NULL);
4299 assert(current_scope != NULL);
4301 entity->base.parent_scope = current_scope;
4302 environment_push(entity);
4303 append_entity(current_scope, entity);
4308 static void parser_error_multiple_definition(entity_t *entity,
4309 const source_position_t *source_position)
4311 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4312 entity->base.symbol, &entity->base.source_position);
4315 static bool is_declaration_specifier(const token_t *token)
4317 switch (token->type) {
4321 return is_typedef_symbol(token->symbol);
4328 static void parse_init_declarator_rest(entity_t *entity)
4330 type_t *orig_type = type_error_type;
4332 if (entity->base.kind == ENTITY_TYPEDEF) {
4333 source_position_t const *const pos = &entity->base.source_position;
4334 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4336 assert(is_declaration(entity));
4337 orig_type = entity->declaration.type;
4340 type_t *type = skip_typeref(orig_type);
4342 if (entity->kind == ENTITY_VARIABLE
4343 && entity->variable.initializer != NULL) {
4344 parser_error_multiple_definition(entity, HERE);
4348 declaration_t *const declaration = &entity->declaration;
4349 bool must_be_constant = false;
4350 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4351 entity->base.parent_scope == file_scope) {
4352 must_be_constant = true;
4355 if (is_type_function(type)) {
4356 source_position_t const *const pos = &entity->base.source_position;
4357 errorf(pos, "'%N' is initialized like a variable", entity);
4358 orig_type = type_error_type;
4361 parse_initializer_env_t env;
4362 env.type = orig_type;
4363 env.must_be_constant = must_be_constant;
4364 env.entity = entity;
4365 current_init_decl = entity;
4367 initializer_t *initializer = parse_initializer(&env);
4368 current_init_decl = NULL;
4370 if (entity->kind == ENTITY_VARIABLE) {
4371 /* §6.7.5:22 array initializers for arrays with unknown size
4372 * determine the array type size */
4373 declaration->type = env.type;
4374 entity->variable.initializer = initializer;
4378 /* parse rest of a declaration without any declarator */
4379 static void parse_anonymous_declaration_rest(
4380 const declaration_specifiers_t *specifiers)
4383 anonymous_entity = NULL;
4385 source_position_t const *const pos = &specifiers->source_position;
4386 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4387 specifiers->thread_local) {
4388 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4391 type_t *type = specifiers->type;
4392 switch (type->kind) {
4393 case TYPE_COMPOUND_STRUCT:
4394 case TYPE_COMPOUND_UNION: {
4395 if (type->compound.compound->base.symbol == NULL) {
4396 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4405 warningf(WARN_OTHER, pos, "empty declaration");
4410 static void check_variable_type_complete(entity_t *ent)
4412 if (ent->kind != ENTITY_VARIABLE)
4415 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4416 * type for the object shall be complete [...] */
4417 declaration_t *decl = &ent->declaration;
4418 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4419 decl->storage_class == STORAGE_CLASS_STATIC)
4422 type_t *const type = skip_typeref(decl->type);
4423 if (!is_type_incomplete(type))
4426 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4427 * are given length one. */
4428 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4429 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4433 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4437 static void parse_declaration_rest(entity_t *ndeclaration,
4438 const declaration_specifiers_t *specifiers,
4439 parsed_declaration_func finished_declaration,
4440 declarator_flags_t flags)
4442 add_anchor_token(';');
4443 add_anchor_token(',');
4445 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4447 if (token.type == '=') {
4448 parse_init_declarator_rest(entity);
4449 } else if (entity->kind == ENTITY_VARIABLE) {
4450 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4451 * [...] where the extern specifier is explicitly used. */
4452 declaration_t *decl = &entity->declaration;
4453 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4454 type_t *type = decl->type;
4455 if (is_type_reference(skip_typeref(type))) {
4456 source_position_t const *const pos = &entity->base.source_position;
4457 errorf(pos, "reference '%#N' must be initialized", entity);
4462 check_variable_type_complete(entity);
4467 add_anchor_token('=');
4468 ndeclaration = parse_declarator(specifiers, flags);
4469 rem_anchor_token('=');
4471 expect(';', end_error);
4474 anonymous_entity = NULL;
4475 rem_anchor_token(';');
4476 rem_anchor_token(',');
4479 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4481 symbol_t *symbol = entity->base.symbol;
4485 assert(entity->base.namespc == NAMESPACE_NORMAL);
4486 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4487 if (previous_entity == NULL
4488 || previous_entity->base.parent_scope != current_scope) {
4489 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4494 if (is_definition) {
4495 errorf(HERE, "'%N' is initialised", entity);
4498 return record_entity(entity, false);
4501 static void parse_declaration(parsed_declaration_func finished_declaration,
4502 declarator_flags_t flags)
4504 add_anchor_token(';');
4505 declaration_specifiers_t specifiers;
4506 parse_declaration_specifiers(&specifiers);
4507 rem_anchor_token(';');
4509 if (token.type == ';') {
4510 parse_anonymous_declaration_rest(&specifiers);
4512 entity_t *entity = parse_declarator(&specifiers, flags);
4513 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4518 static type_t *get_default_promoted_type(type_t *orig_type)
4520 type_t *result = orig_type;
4522 type_t *type = skip_typeref(orig_type);
4523 if (is_type_integer(type)) {
4524 result = promote_integer(type);
4525 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4526 result = type_double;
4532 static void parse_kr_declaration_list(entity_t *entity)
4534 if (entity->kind != ENTITY_FUNCTION)
4537 type_t *type = skip_typeref(entity->declaration.type);
4538 assert(is_type_function(type));
4539 if (!type->function.kr_style_parameters)
4542 add_anchor_token('{');
4544 /* push function parameters */
4545 size_t const top = environment_top();
4546 scope_t *old_scope = scope_push(&entity->function.parameters);
4548 entity_t *parameter = entity->function.parameters.entities;
4549 for ( ; parameter != NULL; parameter = parameter->base.next) {
4550 assert(parameter->base.parent_scope == NULL);
4551 parameter->base.parent_scope = current_scope;
4552 environment_push(parameter);
4555 /* parse declaration list */
4557 switch (token.type) {
4559 case T___extension__:
4560 /* This covers symbols, which are no type, too, and results in
4561 * better error messages. The typical cases are misspelled type
4562 * names and missing includes. */
4564 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4572 /* pop function parameters */
4573 assert(current_scope == &entity->function.parameters);
4574 scope_pop(old_scope);
4575 environment_pop_to(top);
4577 /* update function type */
4578 type_t *new_type = duplicate_type(type);
4580 function_parameter_t *parameters = NULL;
4581 function_parameter_t **anchor = ¶meters;
4583 /* did we have an earlier prototype? */
4584 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4585 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4588 function_parameter_t *proto_parameter = NULL;
4589 if (proto_type != NULL) {
4590 type_t *proto_type_type = proto_type->declaration.type;
4591 proto_parameter = proto_type_type->function.parameters;
4592 /* If a K&R function definition has a variadic prototype earlier, then
4593 * make the function definition variadic, too. This should conform to
4594 * §6.7.5.3:15 and §6.9.1:8. */
4595 new_type->function.variadic = proto_type_type->function.variadic;
4597 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4599 new_type->function.unspecified_parameters = true;
4602 bool need_incompatible_warning = false;
4603 parameter = entity->function.parameters.entities;
4604 for (; parameter != NULL; parameter = parameter->base.next,
4606 proto_parameter == NULL ? NULL : proto_parameter->next) {
4607 if (parameter->kind != ENTITY_PARAMETER)
4610 type_t *parameter_type = parameter->declaration.type;
4611 if (parameter_type == NULL) {
4612 source_position_t const* const pos = ¶meter->base.source_position;
4614 errorf(pos, "no type specified for function '%N'", parameter);
4615 parameter_type = type_error_type;
4617 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4618 parameter_type = type_int;
4620 parameter->declaration.type = parameter_type;
4623 semantic_parameter_incomplete(parameter);
4625 /* we need the default promoted types for the function type */
4626 type_t *not_promoted = parameter_type;
4627 parameter_type = get_default_promoted_type(parameter_type);
4629 /* gcc special: if the type of the prototype matches the unpromoted
4630 * type don't promote */
4631 if (!strict_mode && proto_parameter != NULL) {
4632 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4633 type_t *promo_skip = skip_typeref(parameter_type);
4634 type_t *param_skip = skip_typeref(not_promoted);
4635 if (!types_compatible(proto_p_type, promo_skip)
4636 && types_compatible(proto_p_type, param_skip)) {
4638 need_incompatible_warning = true;
4639 parameter_type = not_promoted;
4642 function_parameter_t *const function_parameter
4643 = allocate_parameter(parameter_type);
4645 *anchor = function_parameter;
4646 anchor = &function_parameter->next;
4649 new_type->function.parameters = parameters;
4650 new_type = identify_new_type(new_type);
4652 if (need_incompatible_warning) {
4653 symbol_t const *const sym = entity->base.symbol;
4654 source_position_t const *const pos = &entity->base.source_position;
4655 source_position_t const *const ppos = &proto_type->base.source_position;
4656 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4658 entity->declaration.type = new_type;
4660 rem_anchor_token('{');
4663 static bool first_err = true;
4666 * When called with first_err set, prints the name of the current function,
4669 static void print_in_function(void)
4673 char const *const file = current_function->base.base.source_position.input_name;
4674 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4679 * Check if all labels are defined in the current function.
4680 * Check if all labels are used in the current function.
4682 static void check_labels(void)
4684 for (const goto_statement_t *goto_statement = goto_first;
4685 goto_statement != NULL;
4686 goto_statement = goto_statement->next) {
4687 /* skip computed gotos */
4688 if (goto_statement->expression != NULL)
4691 label_t *label = goto_statement->label;
4692 if (label->base.source_position.input_name == NULL) {
4693 print_in_function();
4694 source_position_t const *const pos = &goto_statement->base.source_position;
4695 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4699 if (is_warn_on(WARN_UNUSED_LABEL)) {
4700 for (const label_statement_t *label_statement = label_first;
4701 label_statement != NULL;
4702 label_statement = label_statement->next) {
4703 label_t *label = label_statement->label;
4705 if (! label->used) {
4706 print_in_function();
4707 source_position_t const *const pos = &label_statement->base.source_position;
4708 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4714 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4716 entity_t const *const end = last != NULL ? last->base.next : NULL;
4717 for (; entity != end; entity = entity->base.next) {
4718 if (!is_declaration(entity))
4721 declaration_t *declaration = &entity->declaration;
4722 if (declaration->implicit)
4725 if (!declaration->used) {
4726 print_in_function();
4727 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4728 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4729 print_in_function();
4730 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4735 static void check_unused_variables(statement_t *const stmt, void *const env)
4739 switch (stmt->kind) {
4740 case STATEMENT_DECLARATION: {
4741 declaration_statement_t const *const decls = &stmt->declaration;
4742 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4747 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4756 * Check declarations of current_function for unused entities.
4758 static void check_declarations(void)
4760 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4761 const scope_t *scope = ¤t_function->parameters;
4763 /* do not issue unused warnings for main */
4764 if (!is_sym_main(current_function->base.base.symbol)) {
4765 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4768 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4769 walk_statements(current_function->statement, check_unused_variables,
4774 static int determine_truth(expression_t const* const cond)
4777 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4778 fold_constant_to_bool(cond) ? 1 :
4782 static void check_reachable(statement_t *);
4783 static bool reaches_end;
4785 static bool expression_returns(expression_t const *const expr)
4787 switch (expr->kind) {
4789 expression_t const *const func = expr->call.function;
4790 if (func->kind == EXPR_REFERENCE) {
4791 entity_t *entity = func->reference.entity;
4792 if (entity->kind == ENTITY_FUNCTION
4793 && entity->declaration.modifiers & DM_NORETURN)
4797 if (!expression_returns(func))
4800 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4801 if (!expression_returns(arg->expression))
4808 case EXPR_REFERENCE:
4809 case EXPR_REFERENCE_ENUM_VALUE:
4811 case EXPR_STRING_LITERAL:
4812 case EXPR_WIDE_STRING_LITERAL:
4813 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4814 case EXPR_LABEL_ADDRESS:
4815 case EXPR_CLASSIFY_TYPE:
4816 case EXPR_SIZEOF: // TODO handle obscure VLA case
4819 case EXPR_BUILTIN_CONSTANT_P:
4820 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4825 case EXPR_STATEMENT: {
4826 bool old_reaches_end = reaches_end;
4827 reaches_end = false;
4828 check_reachable(expr->statement.statement);
4829 bool returns = reaches_end;
4830 reaches_end = old_reaches_end;
4834 case EXPR_CONDITIONAL:
4835 // TODO handle constant expression
4837 if (!expression_returns(expr->conditional.condition))
4840 if (expr->conditional.true_expression != NULL
4841 && expression_returns(expr->conditional.true_expression))
4844 return expression_returns(expr->conditional.false_expression);
4847 return expression_returns(expr->select.compound);
4849 case EXPR_ARRAY_ACCESS:
4851 expression_returns(expr->array_access.array_ref) &&
4852 expression_returns(expr->array_access.index);
4855 return expression_returns(expr->va_starte.ap);
4858 return expression_returns(expr->va_arge.ap);
4861 return expression_returns(expr->va_copye.src);
4863 EXPR_UNARY_CASES_MANDATORY
4864 return expression_returns(expr->unary.value);
4866 case EXPR_UNARY_THROW:
4870 // TODO handle constant lhs of && and ||
4872 expression_returns(expr->binary.left) &&
4873 expression_returns(expr->binary.right);
4879 panic("unhandled expression");
4882 static bool initializer_returns(initializer_t const *const init)
4884 switch (init->kind) {
4885 case INITIALIZER_VALUE:
4886 return expression_returns(init->value.value);
4888 case INITIALIZER_LIST: {
4889 initializer_t * const* i = init->list.initializers;
4890 initializer_t * const* const end = i + init->list.len;
4891 bool returns = true;
4892 for (; i != end; ++i) {
4893 if (!initializer_returns(*i))
4899 case INITIALIZER_STRING:
4900 case INITIALIZER_WIDE_STRING:
4901 case INITIALIZER_DESIGNATOR: // designators have no payload
4904 panic("unhandled initializer");
4907 static bool noreturn_candidate;
4909 static void check_reachable(statement_t *const stmt)
4911 if (stmt->base.reachable)
4913 if (stmt->kind != STATEMENT_DO_WHILE)
4914 stmt->base.reachable = true;
4916 statement_t *last = stmt;
4918 switch (stmt->kind) {
4919 case STATEMENT_INVALID:
4920 case STATEMENT_EMPTY:
4922 next = stmt->base.next;
4925 case STATEMENT_DECLARATION: {
4926 declaration_statement_t const *const decl = &stmt->declaration;
4927 entity_t const * ent = decl->declarations_begin;
4928 entity_t const *const last_decl = decl->declarations_end;
4930 for (;; ent = ent->base.next) {
4931 if (ent->kind == ENTITY_VARIABLE &&
4932 ent->variable.initializer != NULL &&
4933 !initializer_returns(ent->variable.initializer)) {
4936 if (ent == last_decl)
4940 next = stmt->base.next;
4944 case STATEMENT_COMPOUND:
4945 next = stmt->compound.statements;
4947 next = stmt->base.next;
4950 case STATEMENT_RETURN: {
4951 expression_t const *const val = stmt->returns.value;
4952 if (val == NULL || expression_returns(val))
4953 noreturn_candidate = false;
4957 case STATEMENT_IF: {
4958 if_statement_t const *const ifs = &stmt->ifs;
4959 expression_t const *const cond = ifs->condition;
4961 if (!expression_returns(cond))
4964 int const val = determine_truth(cond);
4967 check_reachable(ifs->true_statement);
4972 if (ifs->false_statement != NULL) {
4973 check_reachable(ifs->false_statement);
4977 next = stmt->base.next;
4981 case STATEMENT_SWITCH: {
4982 switch_statement_t const *const switchs = &stmt->switchs;
4983 expression_t const *const expr = switchs->expression;
4985 if (!expression_returns(expr))
4988 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4989 long const val = fold_constant_to_int(expr);
4990 case_label_statement_t * defaults = NULL;
4991 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4992 if (i->expression == NULL) {
4997 if (i->first_case <= val && val <= i->last_case) {
4998 check_reachable((statement_t*)i);
5003 if (defaults != NULL) {
5004 check_reachable((statement_t*)defaults);
5008 bool has_default = false;
5009 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5010 if (i->expression == NULL)
5013 check_reachable((statement_t*)i);
5020 next = stmt->base.next;
5024 case STATEMENT_EXPRESSION: {
5025 /* Check for noreturn function call */
5026 expression_t const *const expr = stmt->expression.expression;
5027 if (!expression_returns(expr))
5030 next = stmt->base.next;
5034 case STATEMENT_CONTINUE:
5035 for (statement_t *parent = stmt;;) {
5036 parent = parent->base.parent;
5037 if (parent == NULL) /* continue not within loop */
5041 switch (parent->kind) {
5042 case STATEMENT_WHILE: goto continue_while;
5043 case STATEMENT_DO_WHILE: goto continue_do_while;
5044 case STATEMENT_FOR: goto continue_for;
5050 case STATEMENT_BREAK:
5051 for (statement_t *parent = stmt;;) {
5052 parent = parent->base.parent;
5053 if (parent == NULL) /* break not within loop/switch */
5056 switch (parent->kind) {
5057 case STATEMENT_SWITCH:
5058 case STATEMENT_WHILE:
5059 case STATEMENT_DO_WHILE:
5062 next = parent->base.next;
5063 goto found_break_parent;
5071 case STATEMENT_GOTO:
5072 if (stmt->gotos.expression) {
5073 if (!expression_returns(stmt->gotos.expression))
5076 statement_t *parent = stmt->base.parent;
5077 if (parent == NULL) /* top level goto */
5081 next = stmt->gotos.label->statement;
5082 if (next == NULL) /* missing label */
5087 case STATEMENT_LABEL:
5088 next = stmt->label.statement;
5091 case STATEMENT_CASE_LABEL:
5092 next = stmt->case_label.statement;
5095 case STATEMENT_WHILE: {
5096 while_statement_t const *const whiles = &stmt->whiles;
5097 expression_t const *const cond = whiles->condition;
5099 if (!expression_returns(cond))
5102 int const val = determine_truth(cond);
5105 check_reachable(whiles->body);
5110 next = stmt->base.next;
5114 case STATEMENT_DO_WHILE:
5115 next = stmt->do_while.body;
5118 case STATEMENT_FOR: {
5119 for_statement_t *const fors = &stmt->fors;
5121 if (fors->condition_reachable)
5123 fors->condition_reachable = true;
5125 expression_t const *const cond = fors->condition;
5130 } else if (expression_returns(cond)) {
5131 val = determine_truth(cond);
5137 check_reachable(fors->body);
5142 next = stmt->base.next;
5146 case STATEMENT_MS_TRY: {
5147 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5148 check_reachable(ms_try->try_statement);
5149 next = ms_try->final_statement;
5153 case STATEMENT_LEAVE: {
5154 statement_t *parent = stmt;
5156 parent = parent->base.parent;
5157 if (parent == NULL) /* __leave not within __try */
5160 if (parent->kind == STATEMENT_MS_TRY) {
5162 next = parent->ms_try.final_statement;
5170 panic("invalid statement kind");
5173 while (next == NULL) {
5174 next = last->base.parent;
5176 noreturn_candidate = false;
5178 type_t *const type = skip_typeref(current_function->base.type);
5179 assert(is_type_function(type));
5180 type_t *const ret = skip_typeref(type->function.return_type);
5181 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5182 is_type_valid(ret) &&
5183 !is_sym_main(current_function->base.base.symbol)) {
5184 source_position_t const *const pos = &stmt->base.source_position;
5185 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5190 switch (next->kind) {
5191 case STATEMENT_INVALID:
5192 case STATEMENT_EMPTY:
5193 case STATEMENT_DECLARATION:
5194 case STATEMENT_EXPRESSION:
5196 case STATEMENT_RETURN:
5197 case STATEMENT_CONTINUE:
5198 case STATEMENT_BREAK:
5199 case STATEMENT_GOTO:
5200 case STATEMENT_LEAVE:
5201 panic("invalid control flow in function");
5203 case STATEMENT_COMPOUND:
5204 if (next->compound.stmt_expr) {
5210 case STATEMENT_SWITCH:
5211 case STATEMENT_LABEL:
5212 case STATEMENT_CASE_LABEL:
5214 next = next->base.next;
5217 case STATEMENT_WHILE: {
5219 if (next->base.reachable)
5221 next->base.reachable = true;
5223 while_statement_t const *const whiles = &next->whiles;
5224 expression_t const *const cond = whiles->condition;
5226 if (!expression_returns(cond))
5229 int const val = determine_truth(cond);
5232 check_reachable(whiles->body);
5238 next = next->base.next;
5242 case STATEMENT_DO_WHILE: {
5244 if (next->base.reachable)
5246 next->base.reachable = true;
5248 do_while_statement_t const *const dw = &next->do_while;
5249 expression_t const *const cond = dw->condition;
5251 if (!expression_returns(cond))
5254 int const val = determine_truth(cond);
5257 check_reachable(dw->body);
5263 next = next->base.next;
5267 case STATEMENT_FOR: {
5269 for_statement_t *const fors = &next->fors;
5271 fors->step_reachable = true;
5273 if (fors->condition_reachable)
5275 fors->condition_reachable = true;
5277 expression_t const *const cond = fors->condition;
5282 } else if (expression_returns(cond)) {
5283 val = determine_truth(cond);
5289 check_reachable(fors->body);
5295 next = next->base.next;
5299 case STATEMENT_MS_TRY:
5301 next = next->ms_try.final_statement;
5306 check_reachable(next);
5309 static void check_unreachable(statement_t* const stmt, void *const env)
5313 switch (stmt->kind) {
5314 case STATEMENT_DO_WHILE:
5315 if (!stmt->base.reachable) {
5316 expression_t const *const cond = stmt->do_while.condition;
5317 if (determine_truth(cond) >= 0) {
5318 source_position_t const *const pos = &cond->base.source_position;
5319 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5324 case STATEMENT_FOR: {
5325 for_statement_t const* const fors = &stmt->fors;
5327 // if init and step are unreachable, cond is unreachable, too
5328 if (!stmt->base.reachable && !fors->step_reachable) {
5329 goto warn_unreachable;
5331 if (!stmt->base.reachable && fors->initialisation != NULL) {
5332 source_position_t const *const pos = &fors->initialisation->base.source_position;
5333 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5336 if (!fors->condition_reachable && fors->condition != NULL) {
5337 source_position_t const *const pos = &fors->condition->base.source_position;
5338 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5341 if (!fors->step_reachable && fors->step != NULL) {
5342 source_position_t const *const pos = &fors->step->base.source_position;
5343 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5349 case STATEMENT_COMPOUND:
5350 if (stmt->compound.statements != NULL)
5352 goto warn_unreachable;
5354 case STATEMENT_DECLARATION: {
5355 /* Only warn if there is at least one declarator with an initializer.
5356 * This typically occurs in switch statements. */
5357 declaration_statement_t const *const decl = &stmt->declaration;
5358 entity_t const * ent = decl->declarations_begin;
5359 entity_t const *const last = decl->declarations_end;
5361 for (;; ent = ent->base.next) {
5362 if (ent->kind == ENTITY_VARIABLE &&
5363 ent->variable.initializer != NULL) {
5364 goto warn_unreachable;
5374 if (!stmt->base.reachable) {
5375 source_position_t const *const pos = &stmt->base.source_position;
5376 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5382 static void parse_external_declaration(void)
5384 /* function-definitions and declarations both start with declaration
5386 add_anchor_token(';');
5387 declaration_specifiers_t specifiers;
5388 parse_declaration_specifiers(&specifiers);
5389 rem_anchor_token(';');
5391 /* must be a declaration */
5392 if (token.type == ';') {
5393 parse_anonymous_declaration_rest(&specifiers);
5397 add_anchor_token(',');
5398 add_anchor_token('=');
5399 add_anchor_token(';');
5400 add_anchor_token('{');
5402 /* declarator is common to both function-definitions and declarations */
5403 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5405 rem_anchor_token('{');
5406 rem_anchor_token(';');
5407 rem_anchor_token('=');
5408 rem_anchor_token(',');
5410 /* must be a declaration */
5411 switch (token.type) {
5415 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5420 /* must be a function definition */
5421 parse_kr_declaration_list(ndeclaration);
5423 if (token.type != '{') {
5424 parse_error_expected("while parsing function definition", '{', NULL);
5425 eat_until_matching_token(';');
5429 assert(is_declaration(ndeclaration));
5430 type_t *const orig_type = ndeclaration->declaration.type;
5431 type_t * type = skip_typeref(orig_type);
5433 if (!is_type_function(type)) {
5434 if (is_type_valid(type)) {
5435 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5441 source_position_t const *const pos = &ndeclaration->base.source_position;
5442 if (is_typeref(orig_type)) {
5444 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5447 if (is_type_compound(skip_typeref(type->function.return_type))) {
5448 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5450 if (type->function.unspecified_parameters) {
5451 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5453 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5456 /* §6.7.5.3:14 a function definition with () means no
5457 * parameters (and not unspecified parameters) */
5458 if (type->function.unspecified_parameters &&
5459 type->function.parameters == NULL) {
5460 type_t *copy = duplicate_type(type);
5461 copy->function.unspecified_parameters = false;
5462 type = identify_new_type(copy);
5464 ndeclaration->declaration.type = type;
5467 entity_t *const entity = record_entity(ndeclaration, true);
5468 assert(entity->kind == ENTITY_FUNCTION);
5469 assert(ndeclaration->kind == ENTITY_FUNCTION);
5471 function_t *const function = &entity->function;
5472 if (ndeclaration != entity) {
5473 function->parameters = ndeclaration->function.parameters;
5475 assert(is_declaration(entity));
5476 type = skip_typeref(entity->declaration.type);
5478 /* push function parameters and switch scope */
5479 size_t const top = environment_top();
5480 scope_t *old_scope = scope_push(&function->parameters);
5482 entity_t *parameter = function->parameters.entities;
5483 for (; parameter != NULL; parameter = parameter->base.next) {
5484 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5485 parameter->base.parent_scope = current_scope;
5487 assert(parameter->base.parent_scope == NULL
5488 || parameter->base.parent_scope == current_scope);
5489 parameter->base.parent_scope = current_scope;
5490 if (parameter->base.symbol == NULL) {
5491 errorf(¶meter->base.source_position, "parameter name omitted");
5494 environment_push(parameter);
5497 if (function->statement != NULL) {
5498 parser_error_multiple_definition(entity, HERE);
5501 /* parse function body */
5502 int label_stack_top = label_top();
5503 function_t *old_current_function = current_function;
5504 entity_t *old_current_entity = current_entity;
5505 current_function = function;
5506 current_entity = entity;
5507 current_parent = NULL;
5510 goto_anchor = &goto_first;
5512 label_anchor = &label_first;
5514 statement_t *const body = parse_compound_statement(false);
5515 function->statement = body;
5518 check_declarations();
5519 if (is_warn_on(WARN_RETURN_TYPE) ||
5520 is_warn_on(WARN_UNREACHABLE_CODE) ||
5521 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5522 noreturn_candidate = true;
5523 check_reachable(body);
5524 if (is_warn_on(WARN_UNREACHABLE_CODE))
5525 walk_statements(body, check_unreachable, NULL);
5526 if (noreturn_candidate &&
5527 !(function->base.modifiers & DM_NORETURN)) {
5528 source_position_t const *const pos = &body->base.source_position;
5529 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5533 assert(current_parent == NULL);
5534 assert(current_function == function);
5535 assert(current_entity == entity);
5536 current_entity = old_current_entity;
5537 current_function = old_current_function;
5538 label_pop_to(label_stack_top);
5541 assert(current_scope == &function->parameters);
5542 scope_pop(old_scope);
5543 environment_pop_to(top);
5546 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5547 source_position_t *source_position,
5548 const symbol_t *symbol)
5550 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5552 type->bitfield.base_type = base_type;
5553 type->bitfield.size_expression = size;
5556 type_t *skipped_type = skip_typeref(base_type);
5557 if (!is_type_integer(skipped_type)) {
5558 errorf(source_position, "bitfield base type '%T' is not an integer type", base_type);
5561 bit_size = get_type_size(base_type) * 8;
5564 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5565 long v = fold_constant_to_int(size);
5566 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5569 errorf(source_position, "negative width in bit-field '%Y'",
5571 } else if (v == 0 && symbol != NULL) {
5572 errorf(source_position, "zero width for bit-field '%Y'",
5574 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5575 errorf(source_position, "width of '%Y' exceeds its type",
5578 type->bitfield.bit_size = v;
5585 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5587 entity_t *iter = compound->members.entities;
5588 for (; iter != NULL; iter = iter->base.next) {
5589 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5592 if (iter->base.symbol == symbol) {
5594 } else if (iter->base.symbol == NULL) {
5595 /* search in anonymous structs and unions */
5596 type_t *type = skip_typeref(iter->declaration.type);
5597 if (is_type_compound(type)) {
5598 if (find_compound_entry(type->compound.compound, symbol)
5609 static void check_deprecated(const source_position_t *source_position,
5610 const entity_t *entity)
5612 if (!is_declaration(entity))
5614 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5617 source_position_t const *const epos = &entity->base.source_position;
5618 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5620 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5622 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5627 static expression_t *create_select(const source_position_t *pos,
5629 type_qualifiers_t qualifiers,
5632 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5634 check_deprecated(pos, entry);
5636 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5637 select->select.compound = addr;
5638 select->select.compound_entry = entry;
5640 type_t *entry_type = entry->declaration.type;
5641 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5643 /* we always do the auto-type conversions; the & and sizeof parser contains
5644 * code to revert this! */
5645 select->base.type = automatic_type_conversion(res_type);
5646 if (res_type->kind == TYPE_BITFIELD) {
5647 select->base.type = res_type->bitfield.base_type;
5654 * Find entry with symbol in compound. Search anonymous structs and unions and
5655 * creates implicit select expressions for them.
5656 * Returns the adress for the innermost compound.
5658 static expression_t *find_create_select(const source_position_t *pos,
5660 type_qualifiers_t qualifiers,
5661 compound_t *compound, symbol_t *symbol)
5663 entity_t *iter = compound->members.entities;
5664 for (; iter != NULL; iter = iter->base.next) {
5665 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5668 symbol_t *iter_symbol = iter->base.symbol;
5669 if (iter_symbol == NULL) {
5670 type_t *type = iter->declaration.type;
5671 if (type->kind != TYPE_COMPOUND_STRUCT
5672 && type->kind != TYPE_COMPOUND_UNION)
5675 compound_t *sub_compound = type->compound.compound;
5677 if (find_compound_entry(sub_compound, symbol) == NULL)
5680 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5681 sub_addr->base.source_position = *pos;
5682 sub_addr->select.implicit = true;
5683 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5687 if (iter_symbol == symbol) {
5688 return create_select(pos, addr, qualifiers, iter);
5695 static void parse_compound_declarators(compound_t *compound,
5696 const declaration_specifiers_t *specifiers)
5701 if (token.type == ':') {
5702 source_position_t source_position = *HERE;
5705 type_t *base_type = specifiers->type;
5706 expression_t *size = parse_constant_expression();
5708 type_t *type = make_bitfield_type(base_type, size,
5709 &source_position, NULL);
5711 attribute_t *attributes = parse_attributes(NULL);
5712 attribute_t **anchor = &attributes;
5713 while (*anchor != NULL)
5714 anchor = &(*anchor)->next;
5715 *anchor = specifiers->attributes;
5717 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL);
5718 entity->base.source_position = source_position;
5719 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5720 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5721 entity->declaration.type = type;
5722 entity->declaration.attributes = attributes;
5724 if (attributes != NULL) {
5725 handle_entity_attributes(attributes, entity);
5727 append_entity(&compound->members, entity);
5729 entity = parse_declarator(specifiers,
5730 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5731 source_position_t const *const pos = &entity->base.source_position;
5732 if (entity->kind == ENTITY_TYPEDEF) {
5733 errorf(pos, "typedef not allowed as compound member");
5735 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5737 /* make sure we don't define a symbol multiple times */
5738 symbol_t *symbol = entity->base.symbol;
5739 if (symbol != NULL) {
5740 entity_t *prev = find_compound_entry(compound, symbol);
5742 source_position_t const *const ppos = &prev->base.source_position;
5743 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5747 if (token.type == ':') {
5748 source_position_t source_position = *HERE;
5750 expression_t *size = parse_constant_expression();
5752 type_t *type = entity->declaration.type;
5753 type_t *bitfield_type = make_bitfield_type(type, size,
5754 &source_position, entity->base.symbol);
5756 attribute_t *attributes = parse_attributes(NULL);
5757 entity->declaration.type = bitfield_type;
5758 handle_entity_attributes(attributes, entity);
5760 type_t *orig_type = entity->declaration.type;
5761 type_t *type = skip_typeref(orig_type);
5762 if (is_type_function(type)) {
5763 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5764 } else if (is_type_incomplete(type)) {
5765 /* §6.7.2.1:16 flexible array member */
5766 if (!is_type_array(type) ||
5767 token.type != ';' ||
5768 look_ahead(1)->type != '}') {
5769 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5774 append_entity(&compound->members, entity);
5777 } while (next_if(','));
5778 expect(';', end_error);
5781 anonymous_entity = NULL;
5784 static void parse_compound_type_entries(compound_t *compound)
5787 add_anchor_token('}');
5789 while (token.type != '}') {
5790 if (token.type == T_EOF) {
5791 errorf(HERE, "EOF while parsing struct");
5794 declaration_specifiers_t specifiers;
5795 parse_declaration_specifiers(&specifiers);
5796 parse_compound_declarators(compound, &specifiers);
5798 rem_anchor_token('}');
5802 compound->complete = true;
5805 static type_t *parse_typename(void)
5807 declaration_specifiers_t specifiers;
5808 parse_declaration_specifiers(&specifiers);
5809 if (specifiers.storage_class != STORAGE_CLASS_NONE
5810 || specifiers.thread_local) {
5811 /* TODO: improve error message, user does probably not know what a
5812 * storage class is...
5814 errorf(&specifiers.source_position, "typename must not have a storage class");
5817 type_t *result = parse_abstract_declarator(specifiers.type);
5825 typedef expression_t* (*parse_expression_function)(void);
5826 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5828 typedef struct expression_parser_function_t expression_parser_function_t;
5829 struct expression_parser_function_t {
5830 parse_expression_function parser;
5831 precedence_t infix_precedence;
5832 parse_expression_infix_function infix_parser;
5835 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5838 * Prints an error message if an expression was expected but not read
5840 static expression_t *expected_expression_error(void)
5842 /* skip the error message if the error token was read */
5843 if (token.type != T_ERROR) {
5844 errorf(HERE, "expected expression, got token %K", &token);
5848 return create_invalid_expression();
5851 static type_t *get_string_type(void)
5853 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5856 static type_t *get_wide_string_type(void)
5858 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5862 * Parse a string constant.
5864 static expression_t *parse_string_literal(void)
5866 source_position_t begin = token.source_position;
5867 string_t res = token.literal;
5868 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5871 while (token.type == T_STRING_LITERAL
5872 || token.type == T_WIDE_STRING_LITERAL) {
5873 warn_string_concat(&token.source_position);
5874 res = concat_strings(&res, &token.literal);
5876 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5879 expression_t *literal;
5881 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5882 literal->base.type = get_wide_string_type();
5884 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5885 literal->base.type = get_string_type();
5887 literal->base.source_position = begin;
5888 literal->literal.value = res;
5894 * Parse a boolean constant.
5896 static expression_t *parse_boolean_literal(bool value)
5898 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5899 literal->base.source_position = token.source_position;
5900 literal->base.type = type_bool;
5901 literal->literal.value.begin = value ? "true" : "false";
5902 literal->literal.value.size = value ? 4 : 5;
5908 static void warn_traditional_suffix(void)
5910 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%Y' suffix", token.symbol);
5913 static void check_integer_suffix(void)
5915 symbol_t *suffix = token.symbol;
5919 bool not_traditional = false;
5920 const char *c = suffix->string;
5921 if (*c == 'l' || *c == 'L') {
5924 not_traditional = true;
5926 if (*c == 'u' || *c == 'U') {
5929 } else if (*c == 'u' || *c == 'U') {
5930 not_traditional = true;
5933 } else if (*c == 'u' || *c == 'U') {
5934 not_traditional = true;
5936 if (*c == 'l' || *c == 'L') {
5944 errorf(&token.source_position,
5945 "invalid suffix '%s' on integer constant", suffix->string);
5946 } else if (not_traditional) {
5947 warn_traditional_suffix();
5951 static type_t *check_floatingpoint_suffix(void)
5953 symbol_t *suffix = token.symbol;
5954 type_t *type = type_double;
5958 bool not_traditional = false;
5959 const char *c = suffix->string;
5960 if (*c == 'f' || *c == 'F') {
5963 } else if (*c == 'l' || *c == 'L') {
5965 type = type_long_double;
5968 errorf(&token.source_position,
5969 "invalid suffix '%s' on floatingpoint constant", suffix->string);
5970 } else if (not_traditional) {
5971 warn_traditional_suffix();
5978 * Parse an integer constant.
5980 static expression_t *parse_number_literal(void)
5982 expression_kind_t kind;
5985 switch (token.type) {
5987 kind = EXPR_LITERAL_INTEGER;
5988 check_integer_suffix();
5991 case T_INTEGER_OCTAL:
5992 kind = EXPR_LITERAL_INTEGER_OCTAL;
5993 check_integer_suffix();
5996 case T_INTEGER_HEXADECIMAL:
5997 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5998 check_integer_suffix();
6001 case T_FLOATINGPOINT:
6002 kind = EXPR_LITERAL_FLOATINGPOINT;
6003 type = check_floatingpoint_suffix();
6005 case T_FLOATINGPOINT_HEXADECIMAL:
6006 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6007 type = check_floatingpoint_suffix();
6010 panic("unexpected token type in parse_number_literal");
6013 expression_t *literal = allocate_expression_zero(kind);
6014 literal->base.source_position = token.source_position;
6015 literal->base.type = type;
6016 literal->literal.value = token.literal;
6017 literal->literal.suffix = token.symbol;
6020 /* integer type depends on the size of the number and the size
6021 * representable by the types. The backend/codegeneration has to determine
6024 determine_literal_type(&literal->literal);
6029 * Parse a character constant.
6031 static expression_t *parse_character_constant(void)
6033 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6034 literal->base.source_position = token.source_position;
6035 literal->base.type = c_mode & _CXX ? type_char : type_int;
6036 literal->literal.value = token.literal;
6038 size_t len = literal->literal.value.size;
6040 if (!GNU_MODE && !(c_mode & _C99)) {
6041 errorf(HERE, "more than 1 character in character constant");
6043 literal->base.type = type_int;
6044 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6053 * Parse a wide character constant.
6055 static expression_t *parse_wide_character_constant(void)
6057 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6058 literal->base.source_position = token.source_position;
6059 literal->base.type = type_int;
6060 literal->literal.value = token.literal;
6062 size_t len = wstrlen(&literal->literal.value);
6064 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6071 static entity_t *create_implicit_function(symbol_t *symbol,
6072 const source_position_t *source_position)
6074 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6075 ntype->function.return_type = type_int;
6076 ntype->function.unspecified_parameters = true;
6077 ntype->function.linkage = LINKAGE_C;
6078 type_t *type = identify_new_type(ntype);
6080 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6081 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6082 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6083 entity->declaration.type = type;
6084 entity->declaration.implicit = true;
6085 entity->base.source_position = *source_position;
6087 if (current_scope != NULL)
6088 record_entity(entity, false);
6094 * Performs automatic type cast as described in §6.3.2.1.
6096 * @param orig_type the original type
6098 static type_t *automatic_type_conversion(type_t *orig_type)
6100 type_t *type = skip_typeref(orig_type);
6101 if (is_type_array(type)) {
6102 array_type_t *array_type = &type->array;
6103 type_t *element_type = array_type->element_type;
6104 unsigned qualifiers = array_type->base.qualifiers;
6106 return make_pointer_type(element_type, qualifiers);
6109 if (is_type_function(type)) {
6110 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6117 * reverts the automatic casts of array to pointer types and function
6118 * to function-pointer types as defined §6.3.2.1
6120 type_t *revert_automatic_type_conversion(const expression_t *expression)
6122 switch (expression->kind) {
6123 case EXPR_REFERENCE: {
6124 entity_t *entity = expression->reference.entity;
6125 if (is_declaration(entity)) {
6126 return entity->declaration.type;
6127 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6128 return entity->enum_value.enum_type;
6130 panic("no declaration or enum in reference");
6135 entity_t *entity = expression->select.compound_entry;
6136 assert(is_declaration(entity));
6137 type_t *type = entity->declaration.type;
6138 return get_qualified_type(type,
6139 expression->base.type->base.qualifiers);
6142 case EXPR_UNARY_DEREFERENCE: {
6143 const expression_t *const value = expression->unary.value;
6144 type_t *const type = skip_typeref(value->base.type);
6145 if (!is_type_pointer(type))
6146 return type_error_type;
6147 return type->pointer.points_to;
6150 case EXPR_ARRAY_ACCESS: {
6151 const expression_t *array_ref = expression->array_access.array_ref;
6152 type_t *type_left = skip_typeref(array_ref->base.type);
6153 if (!is_type_pointer(type_left))
6154 return type_error_type;
6155 return type_left->pointer.points_to;
6158 case EXPR_STRING_LITERAL: {
6159 size_t size = expression->string_literal.value.size;
6160 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6163 case EXPR_WIDE_STRING_LITERAL: {
6164 size_t size = wstrlen(&expression->string_literal.value);
6165 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6168 case EXPR_COMPOUND_LITERAL:
6169 return expression->compound_literal.type;
6174 return expression->base.type;
6178 * Find an entity matching a symbol in a scope.
6179 * Uses current scope if scope is NULL
6181 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6182 namespace_tag_t namespc)
6184 if (scope == NULL) {
6185 return get_entity(symbol, namespc);
6188 /* we should optimize here, if scope grows above a certain size we should
6189 construct a hashmap here... */
6190 entity_t *entity = scope->entities;
6191 for ( ; entity != NULL; entity = entity->base.next) {
6192 if (entity->base.symbol == symbol
6193 && (namespace_tag_t)entity->base.namespc == namespc)
6200 static entity_t *parse_qualified_identifier(void)
6202 /* namespace containing the symbol */
6204 source_position_t pos;
6205 const scope_t *lookup_scope = NULL;
6207 if (next_if(T_COLONCOLON))
6208 lookup_scope = &unit->scope;
6212 if (token.type != T_IDENTIFIER) {
6213 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6214 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6216 symbol = token.symbol;
6221 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6223 if (!next_if(T_COLONCOLON))
6226 switch (entity->kind) {
6227 case ENTITY_NAMESPACE:
6228 lookup_scope = &entity->namespacee.members;
6233 lookup_scope = &entity->compound.members;
6236 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6237 symbol, get_entity_kind_name(entity->kind));
6239 /* skip further qualifications */
6240 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6242 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6246 if (entity == NULL) {
6247 if (!strict_mode && token.type == '(') {
6248 /* an implicitly declared function */
6249 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6250 entity = create_implicit_function(symbol, &pos);
6252 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6253 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6260 static expression_t *parse_reference(void)
6262 source_position_t const pos = token.source_position;
6263 entity_t *const entity = parse_qualified_identifier();
6266 if (is_declaration(entity)) {
6267 orig_type = entity->declaration.type;
6268 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6269 orig_type = entity->enum_value.enum_type;
6271 panic("expected declaration or enum value in reference");
6274 /* we always do the auto-type conversions; the & and sizeof parser contains
6275 * code to revert this! */
6276 type_t *type = automatic_type_conversion(orig_type);
6278 expression_kind_t kind = EXPR_REFERENCE;
6279 if (entity->kind == ENTITY_ENUM_VALUE)
6280 kind = EXPR_REFERENCE_ENUM_VALUE;
6282 expression_t *expression = allocate_expression_zero(kind);
6283 expression->base.source_position = pos;
6284 expression->base.type = type;
6285 expression->reference.entity = entity;
6287 /* this declaration is used */
6288 if (is_declaration(entity)) {
6289 entity->declaration.used = true;
6292 if (entity->base.parent_scope != file_scope
6293 && (current_function != NULL
6294 && entity->base.parent_scope->depth < current_function->parameters.depth)
6295 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6296 if (entity->kind == ENTITY_VARIABLE) {
6297 /* access of a variable from an outer function */
6298 entity->variable.address_taken = true;
6299 } else if (entity->kind == ENTITY_PARAMETER) {
6300 entity->parameter.address_taken = true;
6302 current_function->need_closure = true;
6305 check_deprecated(&pos, entity);
6307 if (entity == current_init_decl && !in_type_prop && entity->kind == ENTITY_VARIABLE) {
6308 current_init_decl = NULL;
6309 warningf(WARN_INIT_SELF, &pos, "variable '%#N' is initialized by itself", entity);
6315 static bool semantic_cast(expression_t *cast)
6317 expression_t *expression = cast->unary.value;
6318 type_t *orig_dest_type = cast->base.type;
6319 type_t *orig_type_right = expression->base.type;
6320 type_t const *dst_type = skip_typeref(orig_dest_type);
6321 type_t const *src_type = skip_typeref(orig_type_right);
6322 source_position_t const *pos = &cast->base.source_position;
6324 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6325 if (dst_type == type_void)
6328 /* only integer and pointer can be casted to pointer */
6329 if (is_type_pointer(dst_type) &&
6330 !is_type_pointer(src_type) &&
6331 !is_type_integer(src_type) &&
6332 is_type_valid(src_type)) {
6333 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6337 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6338 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6342 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6343 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6347 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6348 type_t *src = skip_typeref(src_type->pointer.points_to);
6349 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6350 unsigned missing_qualifiers =
6351 src->base.qualifiers & ~dst->base.qualifiers;
6352 if (missing_qualifiers != 0) {
6353 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6359 static expression_t *parse_compound_literal(type_t *type)
6361 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6363 parse_initializer_env_t env;
6366 env.must_be_constant = false;
6367 initializer_t *initializer = parse_initializer(&env);
6370 expression->compound_literal.initializer = initializer;
6371 expression->compound_literal.type = type;
6372 expression->base.type = automatic_type_conversion(type);
6378 * Parse a cast expression.
6380 static expression_t *parse_cast(void)
6382 source_position_t source_position = token.source_position;
6385 add_anchor_token(')');
6387 type_t *type = parse_typename();
6389 rem_anchor_token(')');
6390 expect(')', end_error);
6392 if (token.type == '{') {
6393 return parse_compound_literal(type);
6396 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6397 cast->base.source_position = source_position;
6399 expression_t *value = parse_subexpression(PREC_CAST);
6400 cast->base.type = type;
6401 cast->unary.value = value;
6403 if (! semantic_cast(cast)) {
6404 /* TODO: record the error in the AST. else it is impossible to detect it */
6409 return create_invalid_expression();
6413 * Parse a statement expression.
6415 static expression_t *parse_statement_expression(void)
6417 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6420 add_anchor_token(')');
6422 statement_t *statement = parse_compound_statement(true);
6423 statement->compound.stmt_expr = true;
6424 expression->statement.statement = statement;
6426 /* find last statement and use its type */
6427 type_t *type = type_void;
6428 const statement_t *stmt = statement->compound.statements;
6430 while (stmt->base.next != NULL)
6431 stmt = stmt->base.next;
6433 if (stmt->kind == STATEMENT_EXPRESSION) {
6434 type = stmt->expression.expression->base.type;
6437 source_position_t const *const pos = &expression->base.source_position;
6438 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6440 expression->base.type = type;
6442 rem_anchor_token(')');
6443 expect(')', end_error);
6450 * Parse a parenthesized expression.
6452 static expression_t *parse_parenthesized_expression(void)
6454 token_t const* const la1 = look_ahead(1);
6455 switch (la1->type) {
6457 /* gcc extension: a statement expression */
6458 return parse_statement_expression();
6461 if (is_typedef_symbol(la1->symbol)) {
6463 return parse_cast();
6468 add_anchor_token(')');
6469 expression_t *result = parse_expression();
6470 result->base.parenthesized = true;
6471 rem_anchor_token(')');
6472 expect(')', end_error);
6478 static expression_t *parse_function_keyword(void)
6482 if (current_function == NULL) {
6483 errorf(HERE, "'__func__' used outside of a function");
6486 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6487 expression->base.type = type_char_ptr;
6488 expression->funcname.kind = FUNCNAME_FUNCTION;
6495 static expression_t *parse_pretty_function_keyword(void)
6497 if (current_function == NULL) {
6498 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6501 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6502 expression->base.type = type_char_ptr;
6503 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6505 eat(T___PRETTY_FUNCTION__);
6510 static expression_t *parse_funcsig_keyword(void)
6512 if (current_function == NULL) {
6513 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6516 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6517 expression->base.type = type_char_ptr;
6518 expression->funcname.kind = FUNCNAME_FUNCSIG;
6525 static expression_t *parse_funcdname_keyword(void)
6527 if (current_function == NULL) {
6528 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6531 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6532 expression->base.type = type_char_ptr;
6533 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6535 eat(T___FUNCDNAME__);
6540 static designator_t *parse_designator(void)
6542 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6543 result->source_position = *HERE;
6545 if (token.type != T_IDENTIFIER) {
6546 parse_error_expected("while parsing member designator",
6547 T_IDENTIFIER, NULL);
6550 result->symbol = token.symbol;
6553 designator_t *last_designator = result;
6556 if (token.type != T_IDENTIFIER) {
6557 parse_error_expected("while parsing member designator",
6558 T_IDENTIFIER, NULL);
6561 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6562 designator->source_position = *HERE;
6563 designator->symbol = token.symbol;
6566 last_designator->next = designator;
6567 last_designator = designator;
6571 add_anchor_token(']');
6572 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6573 designator->source_position = *HERE;
6574 designator->array_index = parse_expression();
6575 rem_anchor_token(']');
6576 expect(']', end_error);
6577 if (designator->array_index == NULL) {
6581 last_designator->next = designator;
6582 last_designator = designator;
6594 * Parse the __builtin_offsetof() expression.
6596 static expression_t *parse_offsetof(void)
6598 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6599 expression->base.type = type_size_t;
6601 eat(T___builtin_offsetof);
6603 expect('(', end_error);
6604 add_anchor_token(',');
6605 type_t *type = parse_typename();
6606 rem_anchor_token(',');
6607 expect(',', end_error);
6608 add_anchor_token(')');
6609 designator_t *designator = parse_designator();
6610 rem_anchor_token(')');
6611 expect(')', end_error);
6613 expression->offsetofe.type = type;
6614 expression->offsetofe.designator = designator;
6617 memset(&path, 0, sizeof(path));
6618 path.top_type = type;
6619 path.path = NEW_ARR_F(type_path_entry_t, 0);
6621 descend_into_subtype(&path);
6623 if (!walk_designator(&path, designator, true)) {
6624 return create_invalid_expression();
6627 DEL_ARR_F(path.path);
6631 return create_invalid_expression();
6635 * Parses a _builtin_va_start() expression.
6637 static expression_t *parse_va_start(void)
6639 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6641 eat(T___builtin_va_start);
6643 expect('(', end_error);
6644 add_anchor_token(',');
6645 expression->va_starte.ap = parse_assignment_expression();
6646 rem_anchor_token(',');
6647 expect(',', end_error);
6648 expression_t *const expr = parse_assignment_expression();
6649 if (expr->kind == EXPR_REFERENCE) {
6650 entity_t *const entity = expr->reference.entity;
6651 if (!current_function->base.type->function.variadic) {
6652 errorf(&expr->base.source_position,
6653 "'va_start' used in non-variadic function");
6654 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6655 entity->base.next != NULL ||
6656 entity->kind != ENTITY_PARAMETER) {
6657 errorf(&expr->base.source_position,
6658 "second argument of 'va_start' must be last parameter of the current function");
6660 expression->va_starte.parameter = &entity->variable;
6662 expect(')', end_error);
6665 expect(')', end_error);
6667 return create_invalid_expression();
6671 * Parses a __builtin_va_arg() expression.
6673 static expression_t *parse_va_arg(void)
6675 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6677 eat(T___builtin_va_arg);
6679 expect('(', end_error);
6681 ap.expression = parse_assignment_expression();
6682 expression->va_arge.ap = ap.expression;
6683 check_call_argument(type_valist, &ap, 1);
6685 expect(',', end_error);
6686 expression->base.type = parse_typename();
6687 expect(')', end_error);
6691 return create_invalid_expression();
6695 * Parses a __builtin_va_copy() expression.
6697 static expression_t *parse_va_copy(void)
6699 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6701 eat(T___builtin_va_copy);
6703 expect('(', end_error);
6704 expression_t *dst = parse_assignment_expression();
6705 assign_error_t error = semantic_assign(type_valist, dst);
6706 report_assign_error(error, type_valist, dst, "call argument 1",
6707 &dst->base.source_position);
6708 expression->va_copye.dst = dst;
6710 expect(',', end_error);
6712 call_argument_t src;
6713 src.expression = parse_assignment_expression();
6714 check_call_argument(type_valist, &src, 2);
6715 expression->va_copye.src = src.expression;
6716 expect(')', end_error);
6720 return create_invalid_expression();
6724 * Parses a __builtin_constant_p() expression.
6726 static expression_t *parse_builtin_constant(void)
6728 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6730 eat(T___builtin_constant_p);
6732 expect('(', end_error);
6733 add_anchor_token(')');
6734 expression->builtin_constant.value = parse_assignment_expression();
6735 rem_anchor_token(')');
6736 expect(')', end_error);
6737 expression->base.type = type_int;
6741 return create_invalid_expression();
6745 * Parses a __builtin_types_compatible_p() expression.
6747 static expression_t *parse_builtin_types_compatible(void)
6749 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6751 eat(T___builtin_types_compatible_p);
6753 expect('(', end_error);
6754 add_anchor_token(')');
6755 add_anchor_token(',');
6756 expression->builtin_types_compatible.left = parse_typename();
6757 rem_anchor_token(',');
6758 expect(',', end_error);
6759 expression->builtin_types_compatible.right = parse_typename();
6760 rem_anchor_token(')');
6761 expect(')', end_error);
6762 expression->base.type = type_int;
6766 return create_invalid_expression();
6770 * Parses a __builtin_is_*() compare expression.
6772 static expression_t *parse_compare_builtin(void)
6774 expression_t *expression;
6776 switch (token.type) {
6777 case T___builtin_isgreater:
6778 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6780 case T___builtin_isgreaterequal:
6781 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6783 case T___builtin_isless:
6784 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6786 case T___builtin_islessequal:
6787 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6789 case T___builtin_islessgreater:
6790 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6792 case T___builtin_isunordered:
6793 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6796 internal_errorf(HERE, "invalid compare builtin found");
6798 expression->base.source_position = *HERE;
6801 expect('(', end_error);
6802 expression->binary.left = parse_assignment_expression();
6803 expect(',', end_error);
6804 expression->binary.right = parse_assignment_expression();
6805 expect(')', end_error);
6807 type_t *const orig_type_left = expression->binary.left->base.type;
6808 type_t *const orig_type_right = expression->binary.right->base.type;
6810 type_t *const type_left = skip_typeref(orig_type_left);
6811 type_t *const type_right = skip_typeref(orig_type_right);
6812 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6813 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6814 type_error_incompatible("invalid operands in comparison",
6815 &expression->base.source_position, orig_type_left, orig_type_right);
6818 semantic_comparison(&expression->binary);
6823 return create_invalid_expression();
6827 * Parses a MS assume() expression.
6829 static expression_t *parse_assume(void)
6831 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6835 expect('(', end_error);
6836 add_anchor_token(')');
6837 expression->unary.value = parse_assignment_expression();
6838 rem_anchor_token(')');
6839 expect(')', end_error);
6841 expression->base.type = type_void;
6844 return create_invalid_expression();
6848 * Return the label for the current symbol or create a new one.
6850 static label_t *get_label(void)
6852 assert(token.type == T_IDENTIFIER);
6853 assert(current_function != NULL);
6855 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6856 /* If we find a local label, we already created the declaration. */
6857 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6858 if (label->base.parent_scope != current_scope) {
6859 assert(label->base.parent_scope->depth < current_scope->depth);
6860 current_function->goto_to_outer = true;
6862 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6863 /* There is no matching label in the same function, so create a new one. */
6864 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6869 return &label->label;
6873 * Parses a GNU && label address expression.
6875 static expression_t *parse_label_address(void)
6877 source_position_t source_position = token.source_position;
6879 if (token.type != T_IDENTIFIER) {
6880 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6881 return create_invalid_expression();
6884 label_t *const label = get_label();
6886 label->address_taken = true;
6888 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6889 expression->base.source_position = source_position;
6891 /* label address is treated as a void pointer */
6892 expression->base.type = type_void_ptr;
6893 expression->label_address.label = label;
6898 * Parse a microsoft __noop expression.
6900 static expression_t *parse_noop_expression(void)
6902 /* the result is a (int)0 */
6903 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6904 literal->base.type = type_int;
6905 literal->base.source_position = token.source_position;
6906 literal->literal.value.begin = "__noop";
6907 literal->literal.value.size = 6;
6911 if (token.type == '(') {
6912 /* parse arguments */
6914 add_anchor_token(')');
6915 add_anchor_token(',');
6917 if (token.type != ')') do {
6918 (void)parse_assignment_expression();
6919 } while (next_if(','));
6921 rem_anchor_token(',');
6922 rem_anchor_token(')');
6923 expect(')', end_error);
6930 * Parses a primary expression.
6932 static expression_t *parse_primary_expression(void)
6934 switch (token.type) {
6935 case T_false: return parse_boolean_literal(false);
6936 case T_true: return parse_boolean_literal(true);
6938 case T_INTEGER_OCTAL:
6939 case T_INTEGER_HEXADECIMAL:
6940 case T_FLOATINGPOINT:
6941 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6942 case T_CHARACTER_CONSTANT: return parse_character_constant();
6943 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6944 case T_STRING_LITERAL:
6945 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6946 case T___FUNCTION__:
6947 case T___func__: return parse_function_keyword();
6948 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6949 case T___FUNCSIG__: return parse_funcsig_keyword();
6950 case T___FUNCDNAME__: return parse_funcdname_keyword();
6951 case T___builtin_offsetof: return parse_offsetof();
6952 case T___builtin_va_start: return parse_va_start();
6953 case T___builtin_va_arg: return parse_va_arg();
6954 case T___builtin_va_copy: return parse_va_copy();
6955 case T___builtin_isgreater:
6956 case T___builtin_isgreaterequal:
6957 case T___builtin_isless:
6958 case T___builtin_islessequal:
6959 case T___builtin_islessgreater:
6960 case T___builtin_isunordered: return parse_compare_builtin();
6961 case T___builtin_constant_p: return parse_builtin_constant();
6962 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6963 case T__assume: return parse_assume();
6966 return parse_label_address();
6969 case '(': return parse_parenthesized_expression();
6970 case T___noop: return parse_noop_expression();
6972 /* Gracefully handle type names while parsing expressions. */
6974 return parse_reference();
6976 if (!is_typedef_symbol(token.symbol)) {
6977 return parse_reference();
6981 source_position_t const pos = *HERE;
6982 declaration_specifiers_t specifiers;
6983 parse_declaration_specifiers(&specifiers);
6984 type_t const *const type = parse_abstract_declarator(specifiers.type);
6985 errorf(&pos, "encountered type '%T' while parsing expression", type);
6986 return create_invalid_expression();
6990 errorf(HERE, "unexpected token %K, expected an expression", &token);
6992 return create_invalid_expression();
6995 static expression_t *parse_array_expression(expression_t *left)
6997 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6998 array_access_expression_t *const arr = &expr->array_access;
7001 add_anchor_token(']');
7003 expression_t *const inside = parse_expression();
7005 type_t *const orig_type_left = left->base.type;
7006 type_t *const orig_type_inside = inside->base.type;
7008 type_t *const type_left = skip_typeref(orig_type_left);
7009 type_t *const type_inside = skip_typeref(orig_type_inside);
7015 if (is_type_pointer(type_left)) {
7018 idx_type = type_inside;
7019 res_type = type_left->pointer.points_to;
7021 } else if (is_type_pointer(type_inside)) {
7022 arr->flipped = true;
7025 idx_type = type_left;
7026 res_type = type_inside->pointer.points_to;
7028 res_type = automatic_type_conversion(res_type);
7029 if (!is_type_integer(idx_type)) {
7030 errorf(&idx->base.source_position, "array subscript must have integer type");
7031 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
7032 source_position_t const *const pos = &idx->base.source_position;
7033 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
7036 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7037 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7039 res_type = type_error_type;
7044 arr->array_ref = ref;
7046 arr->base.type = res_type;
7048 rem_anchor_token(']');
7049 expect(']', end_error);
7054 static expression_t *parse_typeprop(expression_kind_t const kind)
7056 expression_t *tp_expression = allocate_expression_zero(kind);
7057 tp_expression->base.type = type_size_t;
7059 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7061 /* we only refer to a type property, mark this case */
7062 bool old = in_type_prop;
7063 in_type_prop = true;
7066 expression_t *expression;
7067 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7069 add_anchor_token(')');
7070 orig_type = parse_typename();
7071 rem_anchor_token(')');
7072 expect(')', end_error);
7074 if (token.type == '{') {
7075 /* It was not sizeof(type) after all. It is sizeof of an expression
7076 * starting with a compound literal */
7077 expression = parse_compound_literal(orig_type);
7078 goto typeprop_expression;
7081 expression = parse_subexpression(PREC_UNARY);
7083 typeprop_expression:
7084 tp_expression->typeprop.tp_expression = expression;
7086 orig_type = revert_automatic_type_conversion(expression);
7087 expression->base.type = orig_type;
7090 tp_expression->typeprop.type = orig_type;
7091 type_t const* const type = skip_typeref(orig_type);
7092 char const* wrong_type = NULL;
7093 if (is_type_incomplete(type)) {
7094 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7095 wrong_type = "incomplete";
7096 } else if (type->kind == TYPE_FUNCTION) {
7098 /* function types are allowed (and return 1) */
7099 source_position_t const *const pos = &tp_expression->base.source_position;
7100 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7101 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7103 wrong_type = "function";
7106 if (is_type_incomplete(type))
7107 wrong_type = "incomplete";
7109 if (type->kind == TYPE_BITFIELD)
7110 wrong_type = "bitfield";
7112 if (wrong_type != NULL) {
7113 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7114 errorf(&tp_expression->base.source_position,
7115 "operand of %s expression must not be of %s type '%T'",
7116 what, wrong_type, orig_type);
7121 return tp_expression;
7124 static expression_t *parse_sizeof(void)
7126 return parse_typeprop(EXPR_SIZEOF);
7129 static expression_t *parse_alignof(void)
7131 return parse_typeprop(EXPR_ALIGNOF);
7134 static expression_t *parse_select_expression(expression_t *addr)
7136 assert(token.type == '.' || token.type == T_MINUSGREATER);
7137 bool select_left_arrow = (token.type == T_MINUSGREATER);
7138 source_position_t const pos = *HERE;
7141 if (token.type != T_IDENTIFIER) {
7142 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7143 return create_invalid_expression();
7145 symbol_t *symbol = token.symbol;
7148 type_t *const orig_type = addr->base.type;
7149 type_t *const type = skip_typeref(orig_type);
7152 bool saw_error = false;
7153 if (is_type_pointer(type)) {
7154 if (!select_left_arrow) {
7156 "request for member '%Y' in something not a struct or union, but '%T'",
7160 type_left = skip_typeref(type->pointer.points_to);
7162 if (select_left_arrow && is_type_valid(type)) {
7163 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7169 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7170 type_left->kind != TYPE_COMPOUND_UNION) {
7172 if (is_type_valid(type_left) && !saw_error) {
7174 "request for member '%Y' in something not a struct or union, but '%T'",
7177 return create_invalid_expression();
7180 compound_t *compound = type_left->compound.compound;
7181 if (!compound->complete) {
7182 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7184 return create_invalid_expression();
7187 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7188 expression_t *result =
7189 find_create_select(&pos, addr, qualifiers, compound, symbol);
7191 if (result == NULL) {
7192 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7193 return create_invalid_expression();
7199 static void check_call_argument(type_t *expected_type,
7200 call_argument_t *argument, unsigned pos)
7202 type_t *expected_type_skip = skip_typeref(expected_type);
7203 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7204 expression_t *arg_expr = argument->expression;
7205 type_t *arg_type = skip_typeref(arg_expr->base.type);
7207 /* handle transparent union gnu extension */
7208 if (is_type_union(expected_type_skip)
7209 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7210 compound_t *union_decl = expected_type_skip->compound.compound;
7211 type_t *best_type = NULL;
7212 entity_t *entry = union_decl->members.entities;
7213 for ( ; entry != NULL; entry = entry->base.next) {
7214 assert(is_declaration(entry));
7215 type_t *decl_type = entry->declaration.type;
7216 error = semantic_assign(decl_type, arg_expr);
7217 if (error == ASSIGN_ERROR_INCOMPATIBLE
7218 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7221 if (error == ASSIGN_SUCCESS) {
7222 best_type = decl_type;
7223 } else if (best_type == NULL) {
7224 best_type = decl_type;
7228 if (best_type != NULL) {
7229 expected_type = best_type;
7233 error = semantic_assign(expected_type, arg_expr);
7234 argument->expression = create_implicit_cast(arg_expr, expected_type);
7236 if (error != ASSIGN_SUCCESS) {
7237 /* report exact scope in error messages (like "in argument 3") */
7239 snprintf(buf, sizeof(buf), "call argument %u", pos);
7240 report_assign_error(error, expected_type, arg_expr, buf,
7241 &arg_expr->base.source_position);
7243 type_t *const promoted_type = get_default_promoted_type(arg_type);
7244 if (!types_compatible(expected_type_skip, promoted_type) &&
7245 !types_compatible(expected_type_skip, type_void_ptr) &&
7246 !types_compatible(type_void_ptr, promoted_type)) {
7247 /* Deliberately show the skipped types in this warning */
7248 source_position_t const *const apos = &arg_expr->base.source_position;
7249 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7255 * Handle the semantic restrictions of builtin calls
7257 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7258 switch (call->function->reference.entity->function.btk) {
7259 case bk_gnu_builtin_return_address:
7260 case bk_gnu_builtin_frame_address: {
7261 /* argument must be constant */
7262 call_argument_t *argument = call->arguments;
7264 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7265 errorf(&call->base.source_position,
7266 "argument of '%Y' must be a constant expression",
7267 call->function->reference.entity->base.symbol);
7271 case bk_gnu_builtin_object_size:
7272 if (call->arguments == NULL)
7275 call_argument_t *arg = call->arguments->next;
7276 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7277 errorf(&call->base.source_position,
7278 "second argument of '%Y' must be a constant expression",
7279 call->function->reference.entity->base.symbol);
7282 case bk_gnu_builtin_prefetch:
7283 /* second and third argument must be constant if existent */
7284 if (call->arguments == NULL)
7286 call_argument_t *rw = call->arguments->next;
7287 call_argument_t *locality = NULL;
7290 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7291 errorf(&call->base.source_position,
7292 "second argument of '%Y' must be a constant expression",
7293 call->function->reference.entity->base.symbol);
7295 locality = rw->next;
7297 if (locality != NULL) {
7298 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7299 errorf(&call->base.source_position,
7300 "third argument of '%Y' must be a constant expression",
7301 call->function->reference.entity->base.symbol);
7303 locality = rw->next;
7312 * Parse a call expression, ie. expression '( ... )'.
7314 * @param expression the function address
7316 static expression_t *parse_call_expression(expression_t *expression)
7318 expression_t *result = allocate_expression_zero(EXPR_CALL);
7319 call_expression_t *call = &result->call;
7320 call->function = expression;
7322 type_t *const orig_type = expression->base.type;
7323 type_t *const type = skip_typeref(orig_type);
7325 function_type_t *function_type = NULL;
7326 if (is_type_pointer(type)) {
7327 type_t *const to_type = skip_typeref(type->pointer.points_to);
7329 if (is_type_function(to_type)) {
7330 function_type = &to_type->function;
7331 call->base.type = function_type->return_type;
7335 if (function_type == NULL && is_type_valid(type)) {
7337 "called object '%E' (type '%T') is not a pointer to a function",
7338 expression, orig_type);
7341 /* parse arguments */
7343 add_anchor_token(')');
7344 add_anchor_token(',');
7346 if (token.type != ')') {
7347 call_argument_t **anchor = &call->arguments;
7349 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7350 argument->expression = parse_assignment_expression();
7353 anchor = &argument->next;
7354 } while (next_if(','));
7356 rem_anchor_token(',');
7357 rem_anchor_token(')');
7358 expect(')', end_error);
7360 if (function_type == NULL)
7363 /* check type and count of call arguments */
7364 function_parameter_t *parameter = function_type->parameters;
7365 call_argument_t *argument = call->arguments;
7366 if (!function_type->unspecified_parameters) {
7367 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7368 parameter = parameter->next, argument = argument->next) {
7369 check_call_argument(parameter->type, argument, ++pos);
7372 if (parameter != NULL) {
7373 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7374 } else if (argument != NULL && !function_type->variadic) {
7375 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7379 /* do default promotion for other arguments */
7380 for (; argument != NULL; argument = argument->next) {
7381 type_t *argument_type = argument->expression->base.type;
7382 if (!is_type_object(skip_typeref(argument_type))) {
7383 errorf(&argument->expression->base.source_position,
7384 "call argument '%E' must not be void", argument->expression);
7387 argument_type = get_default_promoted_type(argument_type);
7389 argument->expression
7390 = create_implicit_cast(argument->expression, argument_type);
7395 if (is_type_compound(skip_typeref(function_type->return_type))) {
7396 source_position_t const *const pos = &expression->base.source_position;
7397 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7400 if (expression->kind == EXPR_REFERENCE) {
7401 reference_expression_t *reference = &expression->reference;
7402 if (reference->entity->kind == ENTITY_FUNCTION &&
7403 reference->entity->function.btk != bk_none)
7404 handle_builtin_argument_restrictions(call);
7411 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7413 static bool same_compound_type(const type_t *type1, const type_t *type2)
7416 is_type_compound(type1) &&
7417 type1->kind == type2->kind &&
7418 type1->compound.compound == type2->compound.compound;
7421 static expression_t const *get_reference_address(expression_t const *expr)
7423 bool regular_take_address = true;
7425 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7426 expr = expr->unary.value;
7428 regular_take_address = false;
7431 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7434 expr = expr->unary.value;
7437 if (expr->kind != EXPR_REFERENCE)
7440 /* special case for functions which are automatically converted to a
7441 * pointer to function without an extra TAKE_ADDRESS operation */
7442 if (!regular_take_address &&
7443 expr->reference.entity->kind != ENTITY_FUNCTION) {
7450 static void warn_reference_address_as_bool(expression_t const* expr)
7452 expr = get_reference_address(expr);
7454 source_position_t const *const pos = &expr->base.source_position;
7455 entity_t const *const ent = expr->reference.entity;
7456 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7460 static void warn_assignment_in_condition(const expression_t *const expr)
7462 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7464 if (expr->base.parenthesized)
7466 source_position_t const *const pos = &expr->base.source_position;
7467 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7470 static void semantic_condition(expression_t const *const expr,
7471 char const *const context)
7473 type_t *const type = skip_typeref(expr->base.type);
7474 if (is_type_scalar(type)) {
7475 warn_reference_address_as_bool(expr);
7476 warn_assignment_in_condition(expr);
7477 } else if (is_type_valid(type)) {
7478 errorf(&expr->base.source_position,
7479 "%s must have scalar type", context);
7484 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7486 * @param expression the conditional expression
7488 static expression_t *parse_conditional_expression(expression_t *expression)
7490 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7492 conditional_expression_t *conditional = &result->conditional;
7493 conditional->condition = expression;
7496 add_anchor_token(':');
7498 /* §6.5.15:2 The first operand shall have scalar type. */
7499 semantic_condition(expression, "condition of conditional operator");
7501 expression_t *true_expression = expression;
7502 bool gnu_cond = false;
7503 if (GNU_MODE && token.type == ':') {
7506 true_expression = parse_expression();
7508 rem_anchor_token(':');
7509 expect(':', end_error);
7511 expression_t *false_expression =
7512 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7514 type_t *const orig_true_type = true_expression->base.type;
7515 type_t *const orig_false_type = false_expression->base.type;
7516 type_t *const true_type = skip_typeref(orig_true_type);
7517 type_t *const false_type = skip_typeref(orig_false_type);
7520 source_position_t const *const pos = &conditional->base.source_position;
7521 type_t *result_type;
7522 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7523 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7524 /* ISO/IEC 14882:1998(E) §5.16:2 */
7525 if (true_expression->kind == EXPR_UNARY_THROW) {
7526 result_type = false_type;
7527 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7528 result_type = true_type;
7530 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7531 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7532 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7534 result_type = type_void;
7536 } else if (is_type_arithmetic(true_type)
7537 && is_type_arithmetic(false_type)) {
7538 result_type = semantic_arithmetic(true_type, false_type);
7539 } else if (same_compound_type(true_type, false_type)) {
7540 /* just take 1 of the 2 types */
7541 result_type = true_type;
7542 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7543 type_t *pointer_type;
7545 expression_t *other_expression;
7546 if (is_type_pointer(true_type) &&
7547 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7548 pointer_type = true_type;
7549 other_type = false_type;
7550 other_expression = false_expression;
7552 pointer_type = false_type;
7553 other_type = true_type;
7554 other_expression = true_expression;
7557 if (is_null_pointer_constant(other_expression)) {
7558 result_type = pointer_type;
7559 } else if (is_type_pointer(other_type)) {
7560 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7561 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7564 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7565 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7567 } else if (types_compatible(get_unqualified_type(to1),
7568 get_unqualified_type(to2))) {
7571 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7575 type_t *const type =
7576 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7577 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7578 } else if (is_type_integer(other_type)) {
7579 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7580 result_type = pointer_type;
7582 goto types_incompatible;
7586 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7587 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7589 result_type = type_error_type;
7592 conditional->true_expression
7593 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7594 conditional->false_expression
7595 = create_implicit_cast(false_expression, result_type);
7596 conditional->base.type = result_type;
7601 * Parse an extension expression.
7603 static expression_t *parse_extension(void)
7605 eat(T___extension__);
7607 bool old_gcc_extension = in_gcc_extension;
7608 in_gcc_extension = true;
7609 expression_t *expression = parse_subexpression(PREC_UNARY);
7610 in_gcc_extension = old_gcc_extension;
7615 * Parse a __builtin_classify_type() expression.
7617 static expression_t *parse_builtin_classify_type(void)
7619 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7620 result->base.type = type_int;
7622 eat(T___builtin_classify_type);
7624 expect('(', end_error);
7625 add_anchor_token(')');
7626 expression_t *expression = parse_expression();
7627 rem_anchor_token(')');
7628 expect(')', end_error);
7629 result->classify_type.type_expression = expression;
7633 return create_invalid_expression();
7637 * Parse a delete expression
7638 * ISO/IEC 14882:1998(E) §5.3.5
7640 static expression_t *parse_delete(void)
7642 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7643 result->base.type = type_void;
7648 result->kind = EXPR_UNARY_DELETE_ARRAY;
7649 expect(']', end_error);
7653 expression_t *const value = parse_subexpression(PREC_CAST);
7654 result->unary.value = value;
7656 type_t *const type = skip_typeref(value->base.type);
7657 if (!is_type_pointer(type)) {
7658 if (is_type_valid(type)) {
7659 errorf(&value->base.source_position,
7660 "operand of delete must have pointer type");
7662 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7663 source_position_t const *const pos = &value->base.source_position;
7664 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7671 * Parse a throw expression
7672 * ISO/IEC 14882:1998(E) §15:1
7674 static expression_t *parse_throw(void)
7676 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7677 result->base.type = type_void;
7681 expression_t *value = NULL;
7682 switch (token.type) {
7684 value = parse_assignment_expression();
7685 /* ISO/IEC 14882:1998(E) §15.1:3 */
7686 type_t *const orig_type = value->base.type;
7687 type_t *const type = skip_typeref(orig_type);
7688 if (is_type_incomplete(type)) {
7689 errorf(&value->base.source_position,
7690 "cannot throw object of incomplete type '%T'", orig_type);
7691 } else if (is_type_pointer(type)) {
7692 type_t *const points_to = skip_typeref(type->pointer.points_to);
7693 if (is_type_incomplete(points_to) &&
7694 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7695 errorf(&value->base.source_position,
7696 "cannot throw pointer to incomplete type '%T'", orig_type);
7704 result->unary.value = value;
7709 static bool check_pointer_arithmetic(const source_position_t *source_position,
7710 type_t *pointer_type,
7711 type_t *orig_pointer_type)
7713 type_t *points_to = pointer_type->pointer.points_to;
7714 points_to = skip_typeref(points_to);
7716 if (is_type_incomplete(points_to)) {
7717 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7718 errorf(source_position,
7719 "arithmetic with pointer to incomplete type '%T' not allowed",
7723 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7725 } else if (is_type_function(points_to)) {
7727 errorf(source_position,
7728 "arithmetic with pointer to function type '%T' not allowed",
7732 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7738 static bool is_lvalue(const expression_t *expression)
7740 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7741 switch (expression->kind) {
7742 case EXPR_ARRAY_ACCESS:
7743 case EXPR_COMPOUND_LITERAL:
7744 case EXPR_REFERENCE:
7746 case EXPR_UNARY_DEREFERENCE:
7750 type_t *type = skip_typeref(expression->base.type);
7752 /* ISO/IEC 14882:1998(E) §3.10:3 */
7753 is_type_reference(type) ||
7754 /* Claim it is an lvalue, if the type is invalid. There was a parse
7755 * error before, which maybe prevented properly recognizing it as
7757 !is_type_valid(type);
7762 static void semantic_incdec(unary_expression_t *expression)
7764 type_t *const orig_type = expression->value->base.type;
7765 type_t *const type = skip_typeref(orig_type);
7766 if (is_type_pointer(type)) {
7767 if (!check_pointer_arithmetic(&expression->base.source_position,
7771 } else if (!is_type_real(type) && is_type_valid(type)) {
7772 /* TODO: improve error message */
7773 errorf(&expression->base.source_position,
7774 "operation needs an arithmetic or pointer type");
7777 if (!is_lvalue(expression->value)) {
7778 /* TODO: improve error message */
7779 errorf(&expression->base.source_position, "lvalue required as operand");
7781 expression->base.type = orig_type;
7784 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7786 type_t *const orig_type = expression->value->base.type;
7787 type_t *const type = skip_typeref(orig_type);
7788 if (!is_type_arithmetic(type)) {
7789 if (is_type_valid(type)) {
7790 /* TODO: improve error message */
7791 errorf(&expression->base.source_position,
7792 "operation needs an arithmetic type");
7797 expression->base.type = orig_type;
7800 static void semantic_unexpr_plus(unary_expression_t *expression)
7802 semantic_unexpr_arithmetic(expression);
7803 source_position_t const *const pos = &expression->base.source_position;
7804 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7807 static void semantic_not(unary_expression_t *expression)
7809 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7810 semantic_condition(expression->value, "operand of !");
7811 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7814 static void semantic_unexpr_integer(unary_expression_t *expression)
7816 type_t *const orig_type = expression->value->base.type;
7817 type_t *const type = skip_typeref(orig_type);
7818 if (!is_type_integer(type)) {
7819 if (is_type_valid(type)) {
7820 errorf(&expression->base.source_position,
7821 "operand of ~ must be of integer type");
7826 expression->base.type = orig_type;
7829 static void semantic_dereference(unary_expression_t *expression)
7831 type_t *const orig_type = expression->value->base.type;
7832 type_t *const type = skip_typeref(orig_type);
7833 if (!is_type_pointer(type)) {
7834 if (is_type_valid(type)) {
7835 errorf(&expression->base.source_position,
7836 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7841 type_t *result_type = type->pointer.points_to;
7842 result_type = automatic_type_conversion(result_type);
7843 expression->base.type = result_type;
7847 * Record that an address is taken (expression represents an lvalue).
7849 * @param expression the expression
7850 * @param may_be_register if true, the expression might be an register
7852 static void set_address_taken(expression_t *expression, bool may_be_register)
7854 if (expression->kind != EXPR_REFERENCE)
7857 entity_t *const entity = expression->reference.entity;
7859 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7862 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7863 && !may_be_register) {
7864 source_position_t const *const pos = &expression->base.source_position;
7865 errorf(pos, "address of register '%N' requested", entity);
7868 if (entity->kind == ENTITY_VARIABLE) {
7869 entity->variable.address_taken = true;
7871 assert(entity->kind == ENTITY_PARAMETER);
7872 entity->parameter.address_taken = true;
7877 * Check the semantic of the address taken expression.
7879 static void semantic_take_addr(unary_expression_t *expression)
7881 expression_t *value = expression->value;
7882 value->base.type = revert_automatic_type_conversion(value);
7884 type_t *orig_type = value->base.type;
7885 type_t *type = skip_typeref(orig_type);
7886 if (!is_type_valid(type))
7890 if (!is_lvalue(value)) {
7891 errorf(&expression->base.source_position, "'&' requires an lvalue");
7893 if (type->kind == TYPE_BITFIELD) {
7894 errorf(&expression->base.source_position,
7895 "'&' not allowed on object with bitfield type '%T'",
7899 set_address_taken(value, false);
7901 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7904 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7905 static expression_t *parse_##unexpression_type(void) \
7907 expression_t *unary_expression \
7908 = allocate_expression_zero(unexpression_type); \
7910 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7912 sfunc(&unary_expression->unary); \
7914 return unary_expression; \
7917 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7918 semantic_unexpr_arithmetic)
7919 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7920 semantic_unexpr_plus)
7921 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7923 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7924 semantic_dereference)
7925 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7927 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7928 semantic_unexpr_integer)
7929 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7931 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7934 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7936 static expression_t *parse_##unexpression_type(expression_t *left) \
7938 expression_t *unary_expression \
7939 = allocate_expression_zero(unexpression_type); \
7941 unary_expression->unary.value = left; \
7943 sfunc(&unary_expression->unary); \
7945 return unary_expression; \
7948 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7949 EXPR_UNARY_POSTFIX_INCREMENT,
7951 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7952 EXPR_UNARY_POSTFIX_DECREMENT,
7955 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7957 /* TODO: handle complex + imaginary types */
7959 type_left = get_unqualified_type(type_left);
7960 type_right = get_unqualified_type(type_right);
7962 /* §6.3.1.8 Usual arithmetic conversions */
7963 if (type_left == type_long_double || type_right == type_long_double) {
7964 return type_long_double;
7965 } else if (type_left == type_double || type_right == type_double) {
7967 } else if (type_left == type_float || type_right == type_float) {
7971 type_left = promote_integer(type_left);
7972 type_right = promote_integer(type_right);
7974 if (type_left == type_right)
7977 bool const signed_left = is_type_signed(type_left);
7978 bool const signed_right = is_type_signed(type_right);
7979 int const rank_left = get_rank(type_left);
7980 int const rank_right = get_rank(type_right);
7982 if (signed_left == signed_right)
7983 return rank_left >= rank_right ? type_left : type_right;
7992 u_rank = rank_right;
7993 u_type = type_right;
7995 s_rank = rank_right;
7996 s_type = type_right;
8001 if (u_rank >= s_rank)
8004 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8006 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8007 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8011 case ATOMIC_TYPE_INT: return type_unsigned_int;
8012 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8013 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8015 default: panic("invalid atomic type");
8020 * Check the semantic restrictions for a binary expression.
8022 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8024 expression_t *const left = expression->left;
8025 expression_t *const right = expression->right;
8026 type_t *const orig_type_left = left->base.type;
8027 type_t *const orig_type_right = right->base.type;
8028 type_t *const type_left = skip_typeref(orig_type_left);
8029 type_t *const type_right = skip_typeref(orig_type_right);
8031 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8032 /* TODO: improve error message */
8033 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8034 errorf(&expression->base.source_position,
8035 "operation needs arithmetic types");
8040 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8041 expression->left = create_implicit_cast(left, arithmetic_type);
8042 expression->right = create_implicit_cast(right, arithmetic_type);
8043 expression->base.type = arithmetic_type;
8046 static void semantic_binexpr_integer(binary_expression_t *const expression)
8048 expression_t *const left = expression->left;
8049 expression_t *const right = expression->right;
8050 type_t *const orig_type_left = left->base.type;
8051 type_t *const orig_type_right = right->base.type;
8052 type_t *const type_left = skip_typeref(orig_type_left);
8053 type_t *const type_right = skip_typeref(orig_type_right);
8055 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8056 /* TODO: improve error message */
8057 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8058 errorf(&expression->base.source_position,
8059 "operation needs integer types");
8064 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8065 expression->left = create_implicit_cast(left, result_type);
8066 expression->right = create_implicit_cast(right, result_type);
8067 expression->base.type = result_type;
8070 static void warn_div_by_zero(binary_expression_t const *const expression)
8072 if (!is_type_integer(expression->base.type))
8075 expression_t const *const right = expression->right;
8076 /* The type of the right operand can be different for /= */
8077 if (is_type_integer(right->base.type) &&
8078 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8079 !fold_constant_to_bool(right)) {
8080 source_position_t const *const pos = &expression->base.source_position;
8081 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8086 * Check the semantic restrictions for a div/mod expression.
8088 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8090 semantic_binexpr_arithmetic(expression);
8091 warn_div_by_zero(expression);
8094 static void warn_addsub_in_shift(const expression_t *const expr)
8096 if (expr->base.parenthesized)
8100 switch (expr->kind) {
8101 case EXPR_BINARY_ADD: op = '+'; break;
8102 case EXPR_BINARY_SUB: op = '-'; break;
8106 source_position_t const *const pos = &expr->base.source_position;
8107 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8110 static bool semantic_shift(binary_expression_t *expression)
8112 expression_t *const left = expression->left;
8113 expression_t *const right = expression->right;
8114 type_t *const orig_type_left = left->base.type;
8115 type_t *const orig_type_right = right->base.type;
8116 type_t * type_left = skip_typeref(orig_type_left);
8117 type_t * type_right = skip_typeref(orig_type_right);
8119 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8120 /* TODO: improve error message */
8121 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8122 errorf(&expression->base.source_position,
8123 "operands of shift operation must have integer types");
8128 type_left = promote_integer(type_left);
8130 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8131 source_position_t const *const pos = &right->base.source_position;
8132 long const count = fold_constant_to_int(right);
8134 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8135 } else if ((unsigned long)count >=
8136 get_atomic_type_size(type_left->atomic.akind) * 8) {
8137 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8141 type_right = promote_integer(type_right);
8142 expression->right = create_implicit_cast(right, type_right);
8147 static void semantic_shift_op(binary_expression_t *expression)
8149 expression_t *const left = expression->left;
8150 expression_t *const right = expression->right;
8152 if (!semantic_shift(expression))
8155 warn_addsub_in_shift(left);
8156 warn_addsub_in_shift(right);
8158 type_t *const orig_type_left = left->base.type;
8159 type_t * type_left = skip_typeref(orig_type_left);
8161 type_left = promote_integer(type_left);
8162 expression->left = create_implicit_cast(left, type_left);
8163 expression->base.type = type_left;
8166 static void semantic_add(binary_expression_t *expression)
8168 expression_t *const left = expression->left;
8169 expression_t *const right = expression->right;
8170 type_t *const orig_type_left = left->base.type;
8171 type_t *const orig_type_right = right->base.type;
8172 type_t *const type_left = skip_typeref(orig_type_left);
8173 type_t *const type_right = skip_typeref(orig_type_right);
8176 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8177 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8178 expression->left = create_implicit_cast(left, arithmetic_type);
8179 expression->right = create_implicit_cast(right, arithmetic_type);
8180 expression->base.type = arithmetic_type;
8181 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8182 check_pointer_arithmetic(&expression->base.source_position,
8183 type_left, orig_type_left);
8184 expression->base.type = type_left;
8185 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8186 check_pointer_arithmetic(&expression->base.source_position,
8187 type_right, orig_type_right);
8188 expression->base.type = type_right;
8189 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8190 errorf(&expression->base.source_position,
8191 "invalid operands to binary + ('%T', '%T')",
8192 orig_type_left, orig_type_right);
8196 static void semantic_sub(binary_expression_t *expression)
8198 expression_t *const left = expression->left;
8199 expression_t *const right = expression->right;
8200 type_t *const orig_type_left = left->base.type;
8201 type_t *const orig_type_right = right->base.type;
8202 type_t *const type_left = skip_typeref(orig_type_left);
8203 type_t *const type_right = skip_typeref(orig_type_right);
8204 source_position_t const *const pos = &expression->base.source_position;
8207 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8208 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8209 expression->left = create_implicit_cast(left, arithmetic_type);
8210 expression->right = create_implicit_cast(right, arithmetic_type);
8211 expression->base.type = arithmetic_type;
8212 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8213 check_pointer_arithmetic(&expression->base.source_position,
8214 type_left, orig_type_left);
8215 expression->base.type = type_left;
8216 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8217 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8218 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8219 if (!types_compatible(unqual_left, unqual_right)) {
8221 "subtracting pointers to incompatible types '%T' and '%T'",
8222 orig_type_left, orig_type_right);
8223 } else if (!is_type_object(unqual_left)) {
8224 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8225 errorf(pos, "subtracting pointers to non-object types '%T'",
8228 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8231 expression->base.type = type_ptrdiff_t;
8232 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8233 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8234 orig_type_left, orig_type_right);
8238 static void warn_string_literal_address(expression_t const* expr)
8240 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8241 expr = expr->unary.value;
8242 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8244 expr = expr->unary.value;
8247 if (expr->kind == EXPR_STRING_LITERAL
8248 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8249 source_position_t const *const pos = &expr->base.source_position;
8250 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8254 static bool maybe_negative(expression_t const *const expr)
8256 switch (is_constant_expression(expr)) {
8257 case EXPR_CLASS_ERROR: return false;
8258 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8259 default: return true;
8263 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8265 warn_string_literal_address(expr);
8267 expression_t const* const ref = get_reference_address(expr);
8268 if (ref != NULL && is_null_pointer_constant(other)) {
8269 entity_t const *const ent = ref->reference.entity;
8270 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8273 if (!expr->base.parenthesized) {
8274 switch (expr->base.kind) {
8275 case EXPR_BINARY_LESS:
8276 case EXPR_BINARY_GREATER:
8277 case EXPR_BINARY_LESSEQUAL:
8278 case EXPR_BINARY_GREATEREQUAL:
8279 case EXPR_BINARY_NOTEQUAL:
8280 case EXPR_BINARY_EQUAL:
8281 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8290 * Check the semantics of comparison expressions.
8292 * @param expression The expression to check.
8294 static void semantic_comparison(binary_expression_t *expression)
8296 source_position_t const *const pos = &expression->base.source_position;
8297 expression_t *const left = expression->left;
8298 expression_t *const right = expression->right;
8300 warn_comparison(pos, left, right);
8301 warn_comparison(pos, right, left);
8303 type_t *orig_type_left = left->base.type;
8304 type_t *orig_type_right = right->base.type;
8305 type_t *type_left = skip_typeref(orig_type_left);
8306 type_t *type_right = skip_typeref(orig_type_right);
8308 /* TODO non-arithmetic types */
8309 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8310 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8312 /* test for signed vs unsigned compares */
8313 if (is_type_integer(arithmetic_type)) {
8314 bool const signed_left = is_type_signed(type_left);
8315 bool const signed_right = is_type_signed(type_right);
8316 if (signed_left != signed_right) {
8317 /* FIXME long long needs better const folding magic */
8318 /* TODO check whether constant value can be represented by other type */
8319 if ((signed_left && maybe_negative(left)) ||
8320 (signed_right && maybe_negative(right))) {
8321 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8326 expression->left = create_implicit_cast(left, arithmetic_type);
8327 expression->right = create_implicit_cast(right, arithmetic_type);
8328 expression->base.type = arithmetic_type;
8329 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8330 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8331 is_type_float(arithmetic_type)) {
8332 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8334 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8335 /* TODO check compatibility */
8336 } else if (is_type_pointer(type_left)) {
8337 expression->right = create_implicit_cast(right, type_left);
8338 } else if (is_type_pointer(type_right)) {
8339 expression->left = create_implicit_cast(left, type_right);
8340 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8341 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8343 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8347 * Checks if a compound type has constant fields.
8349 static bool has_const_fields(const compound_type_t *type)
8351 compound_t *compound = type->compound;
8352 entity_t *entry = compound->members.entities;
8354 for (; entry != NULL; entry = entry->base.next) {
8355 if (!is_declaration(entry))
8358 const type_t *decl_type = skip_typeref(entry->declaration.type);
8359 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8366 static bool is_valid_assignment_lhs(expression_t const* const left)
8368 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8369 type_t *const type_left = skip_typeref(orig_type_left);
8371 if (!is_lvalue(left)) {
8372 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8377 if (left->kind == EXPR_REFERENCE
8378 && left->reference.entity->kind == ENTITY_FUNCTION) {
8379 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8383 if (is_type_array(type_left)) {
8384 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8387 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8388 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8392 if (is_type_incomplete(type_left)) {
8393 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8394 left, orig_type_left);
8397 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8398 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8399 left, orig_type_left);
8406 static void semantic_arithmetic_assign(binary_expression_t *expression)
8408 expression_t *left = expression->left;
8409 expression_t *right = expression->right;
8410 type_t *orig_type_left = left->base.type;
8411 type_t *orig_type_right = right->base.type;
8413 if (!is_valid_assignment_lhs(left))
8416 type_t *type_left = skip_typeref(orig_type_left);
8417 type_t *type_right = skip_typeref(orig_type_right);
8419 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8420 /* TODO: improve error message */
8421 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8422 errorf(&expression->base.source_position,
8423 "operation needs arithmetic types");
8428 /* combined instructions are tricky. We can't create an implicit cast on
8429 * the left side, because we need the uncasted form for the store.
8430 * The ast2firm pass has to know that left_type must be right_type
8431 * for the arithmetic operation and create a cast by itself */
8432 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8433 expression->right = create_implicit_cast(right, arithmetic_type);
8434 expression->base.type = type_left;
8437 static void semantic_divmod_assign(binary_expression_t *expression)
8439 semantic_arithmetic_assign(expression);
8440 warn_div_by_zero(expression);
8443 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8445 expression_t *const left = expression->left;
8446 expression_t *const right = expression->right;
8447 type_t *const orig_type_left = left->base.type;
8448 type_t *const orig_type_right = right->base.type;
8449 type_t *const type_left = skip_typeref(orig_type_left);
8450 type_t *const type_right = skip_typeref(orig_type_right);
8452 if (!is_valid_assignment_lhs(left))
8455 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8456 /* combined instructions are tricky. We can't create an implicit cast on
8457 * the left side, because we need the uncasted form for the store.
8458 * The ast2firm pass has to know that left_type must be right_type
8459 * for the arithmetic operation and create a cast by itself */
8460 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8461 expression->right = create_implicit_cast(right, arithmetic_type);
8462 expression->base.type = type_left;
8463 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8464 check_pointer_arithmetic(&expression->base.source_position,
8465 type_left, orig_type_left);
8466 expression->base.type = type_left;
8467 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8468 errorf(&expression->base.source_position,
8469 "incompatible types '%T' and '%T' in assignment",
8470 orig_type_left, orig_type_right);
8474 static void semantic_integer_assign(binary_expression_t *expression)
8476 expression_t *left = expression->left;
8477 expression_t *right = expression->right;
8478 type_t *orig_type_left = left->base.type;
8479 type_t *orig_type_right = right->base.type;
8481 if (!is_valid_assignment_lhs(left))
8484 type_t *type_left = skip_typeref(orig_type_left);
8485 type_t *type_right = skip_typeref(orig_type_right);
8487 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8488 /* TODO: improve error message */
8489 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8490 errorf(&expression->base.source_position,
8491 "operation needs integer types");
8496 /* combined instructions are tricky. We can't create an implicit cast on
8497 * the left side, because we need the uncasted form for the store.
8498 * The ast2firm pass has to know that left_type must be right_type
8499 * for the arithmetic operation and create a cast by itself */
8500 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8501 expression->right = create_implicit_cast(right, arithmetic_type);
8502 expression->base.type = type_left;
8505 static void semantic_shift_assign(binary_expression_t *expression)
8507 expression_t *left = expression->left;
8509 if (!is_valid_assignment_lhs(left))
8512 if (!semantic_shift(expression))
8515 expression->base.type = skip_typeref(left->base.type);
8518 static void warn_logical_and_within_or(const expression_t *const expr)
8520 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8522 if (expr->base.parenthesized)
8524 source_position_t const *const pos = &expr->base.source_position;
8525 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8529 * Check the semantic restrictions of a logical expression.
8531 static void semantic_logical_op(binary_expression_t *expression)
8533 /* §6.5.13:2 Each of the operands shall have scalar type.
8534 * §6.5.14:2 Each of the operands shall have scalar type. */
8535 semantic_condition(expression->left, "left operand of logical operator");
8536 semantic_condition(expression->right, "right operand of logical operator");
8537 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8538 warn_logical_and_within_or(expression->left);
8539 warn_logical_and_within_or(expression->right);
8541 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8545 * Check the semantic restrictions of a binary assign expression.
8547 static void semantic_binexpr_assign(binary_expression_t *expression)
8549 expression_t *left = expression->left;
8550 type_t *orig_type_left = left->base.type;
8552 if (!is_valid_assignment_lhs(left))
8555 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8556 report_assign_error(error, orig_type_left, expression->right,
8557 "assignment", &left->base.source_position);
8558 expression->right = create_implicit_cast(expression->right, orig_type_left);
8559 expression->base.type = orig_type_left;
8563 * Determine if the outermost operation (or parts thereof) of the given
8564 * expression has no effect in order to generate a warning about this fact.
8565 * Therefore in some cases this only examines some of the operands of the
8566 * expression (see comments in the function and examples below).
8568 * f() + 23; // warning, because + has no effect
8569 * x || f(); // no warning, because x controls execution of f()
8570 * x ? y : f(); // warning, because y has no effect
8571 * (void)x; // no warning to be able to suppress the warning
8572 * This function can NOT be used for an "expression has definitely no effect"-
8574 static bool expression_has_effect(const expression_t *const expr)
8576 switch (expr->kind) {
8577 case EXPR_UNKNOWN: break;
8578 case EXPR_INVALID: return true; /* do NOT warn */
8579 case EXPR_REFERENCE: return false;
8580 case EXPR_REFERENCE_ENUM_VALUE: return false;
8581 case EXPR_LABEL_ADDRESS: return false;
8583 /* suppress the warning for microsoft __noop operations */
8584 case EXPR_LITERAL_MS_NOOP: return true;
8585 case EXPR_LITERAL_BOOLEAN:
8586 case EXPR_LITERAL_CHARACTER:
8587 case EXPR_LITERAL_WIDE_CHARACTER:
8588 case EXPR_LITERAL_INTEGER:
8589 case EXPR_LITERAL_INTEGER_OCTAL:
8590 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8591 case EXPR_LITERAL_FLOATINGPOINT:
8592 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8593 case EXPR_STRING_LITERAL: return false;
8594 case EXPR_WIDE_STRING_LITERAL: return false;
8597 const call_expression_t *const call = &expr->call;
8598 if (call->function->kind != EXPR_REFERENCE)
8601 switch (call->function->reference.entity->function.btk) {
8602 /* FIXME: which builtins have no effect? */
8603 default: return true;
8607 /* Generate the warning if either the left or right hand side of a
8608 * conditional expression has no effect */
8609 case EXPR_CONDITIONAL: {
8610 conditional_expression_t const *const cond = &expr->conditional;
8611 expression_t const *const t = cond->true_expression;
8613 (t == NULL || expression_has_effect(t)) &&
8614 expression_has_effect(cond->false_expression);
8617 case EXPR_SELECT: return false;
8618 case EXPR_ARRAY_ACCESS: return false;
8619 case EXPR_SIZEOF: return false;
8620 case EXPR_CLASSIFY_TYPE: return false;
8621 case EXPR_ALIGNOF: return false;
8623 case EXPR_FUNCNAME: return false;
8624 case EXPR_BUILTIN_CONSTANT_P: return false;
8625 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8626 case EXPR_OFFSETOF: return false;
8627 case EXPR_VA_START: return true;
8628 case EXPR_VA_ARG: return true;
8629 case EXPR_VA_COPY: return true;
8630 case EXPR_STATEMENT: return true; // TODO
8631 case EXPR_COMPOUND_LITERAL: return false;
8633 case EXPR_UNARY_NEGATE: return false;
8634 case EXPR_UNARY_PLUS: return false;
8635 case EXPR_UNARY_BITWISE_NEGATE: return false;
8636 case EXPR_UNARY_NOT: return false;
8637 case EXPR_UNARY_DEREFERENCE: return false;
8638 case EXPR_UNARY_TAKE_ADDRESS: return false;
8639 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8640 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8641 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8642 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8644 /* Treat void casts as if they have an effect in order to being able to
8645 * suppress the warning */
8646 case EXPR_UNARY_CAST: {
8647 type_t *const type = skip_typeref(expr->base.type);
8648 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8651 case EXPR_UNARY_CAST_IMPLICIT: return true;
8652 case EXPR_UNARY_ASSUME: return true;
8653 case EXPR_UNARY_DELETE: return true;
8654 case EXPR_UNARY_DELETE_ARRAY: return true;
8655 case EXPR_UNARY_THROW: return true;
8657 case EXPR_BINARY_ADD: return false;
8658 case EXPR_BINARY_SUB: return false;
8659 case EXPR_BINARY_MUL: return false;
8660 case EXPR_BINARY_DIV: return false;
8661 case EXPR_BINARY_MOD: return false;
8662 case EXPR_BINARY_EQUAL: return false;
8663 case EXPR_BINARY_NOTEQUAL: return false;
8664 case EXPR_BINARY_LESS: return false;
8665 case EXPR_BINARY_LESSEQUAL: return false;
8666 case EXPR_BINARY_GREATER: return false;
8667 case EXPR_BINARY_GREATEREQUAL: return false;
8668 case EXPR_BINARY_BITWISE_AND: return false;
8669 case EXPR_BINARY_BITWISE_OR: return false;
8670 case EXPR_BINARY_BITWISE_XOR: return false;
8671 case EXPR_BINARY_SHIFTLEFT: return false;
8672 case EXPR_BINARY_SHIFTRIGHT: return false;
8673 case EXPR_BINARY_ASSIGN: return true;
8674 case EXPR_BINARY_MUL_ASSIGN: return true;
8675 case EXPR_BINARY_DIV_ASSIGN: return true;
8676 case EXPR_BINARY_MOD_ASSIGN: return true;
8677 case EXPR_BINARY_ADD_ASSIGN: return true;
8678 case EXPR_BINARY_SUB_ASSIGN: return true;
8679 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8680 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8681 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8682 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8683 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8685 /* Only examine the right hand side of && and ||, because the left hand
8686 * side already has the effect of controlling the execution of the right
8688 case EXPR_BINARY_LOGICAL_AND:
8689 case EXPR_BINARY_LOGICAL_OR:
8690 /* Only examine the right hand side of a comma expression, because the left
8691 * hand side has a separate warning */
8692 case EXPR_BINARY_COMMA:
8693 return expression_has_effect(expr->binary.right);
8695 case EXPR_BINARY_ISGREATER: return false;
8696 case EXPR_BINARY_ISGREATEREQUAL: return false;
8697 case EXPR_BINARY_ISLESS: return false;
8698 case EXPR_BINARY_ISLESSEQUAL: return false;
8699 case EXPR_BINARY_ISLESSGREATER: return false;
8700 case EXPR_BINARY_ISUNORDERED: return false;
8703 internal_errorf(HERE, "unexpected expression");
8706 static void semantic_comma(binary_expression_t *expression)
8708 const expression_t *const left = expression->left;
8709 if (!expression_has_effect(left)) {
8710 source_position_t const *const pos = &left->base.source_position;
8711 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8713 expression->base.type = expression->right->base.type;
8717 * @param prec_r precedence of the right operand
8719 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8720 static expression_t *parse_##binexpression_type(expression_t *left) \
8722 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8723 binexpr->binary.left = left; \
8726 expression_t *right = parse_subexpression(prec_r); \
8728 binexpr->binary.right = right; \
8729 sfunc(&binexpr->binary); \
8734 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8735 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8736 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8737 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8738 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8739 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8740 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8741 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8742 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8743 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8744 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8745 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8746 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8747 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8748 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8749 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8750 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8751 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8752 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8753 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8754 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8755 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8756 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8757 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8758 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8759 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8760 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8761 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8762 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8763 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8766 static expression_t *parse_subexpression(precedence_t precedence)
8768 if (token.type < 0) {
8769 return expected_expression_error();
8772 expression_parser_function_t *parser
8773 = &expression_parsers[token.type];
8774 source_position_t source_position = token.source_position;
8777 if (parser->parser != NULL) {
8778 left = parser->parser();
8780 left = parse_primary_expression();
8782 assert(left != NULL);
8783 left->base.source_position = source_position;
8786 if (token.type < 0) {
8787 return expected_expression_error();
8790 parser = &expression_parsers[token.type];
8791 if (parser->infix_parser == NULL)
8793 if (parser->infix_precedence < precedence)
8796 left = parser->infix_parser(left);
8798 assert(left != NULL);
8799 assert(left->kind != EXPR_UNKNOWN);
8800 left->base.source_position = source_position;
8807 * Parse an expression.
8809 static expression_t *parse_expression(void)
8811 return parse_subexpression(PREC_EXPRESSION);
8815 * Register a parser for a prefix-like operator.
8817 * @param parser the parser function
8818 * @param token_type the token type of the prefix token
8820 static void register_expression_parser(parse_expression_function parser,
8823 expression_parser_function_t *entry = &expression_parsers[token_type];
8825 if (entry->parser != NULL) {
8826 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8827 panic("trying to register multiple expression parsers for a token");
8829 entry->parser = parser;
8833 * Register a parser for an infix operator with given precedence.
8835 * @param parser the parser function
8836 * @param token_type the token type of the infix operator
8837 * @param precedence the precedence of the operator
8839 static void register_infix_parser(parse_expression_infix_function parser,
8840 int token_type, precedence_t precedence)
8842 expression_parser_function_t *entry = &expression_parsers[token_type];
8844 if (entry->infix_parser != NULL) {
8845 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8846 panic("trying to register multiple infix expression parsers for a "
8849 entry->infix_parser = parser;
8850 entry->infix_precedence = precedence;
8854 * Initialize the expression parsers.
8856 static void init_expression_parsers(void)
8858 memset(&expression_parsers, 0, sizeof(expression_parsers));
8860 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8861 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8862 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8863 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8864 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8865 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8866 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8867 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8868 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8869 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8870 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8871 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8872 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8873 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8874 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8875 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8876 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8877 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8878 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8879 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8880 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8881 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8882 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8883 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8884 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8885 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8886 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8887 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8888 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8889 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8890 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8891 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8892 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8893 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8894 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8895 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8896 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8898 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8899 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8900 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8901 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8902 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8903 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8904 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8905 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8906 register_expression_parser(parse_sizeof, T_sizeof);
8907 register_expression_parser(parse_alignof, T___alignof__);
8908 register_expression_parser(parse_extension, T___extension__);
8909 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8910 register_expression_parser(parse_delete, T_delete);
8911 register_expression_parser(parse_throw, T_throw);
8915 * Parse a asm statement arguments specification.
8917 static asm_argument_t *parse_asm_arguments(bool is_out)
8919 asm_argument_t *result = NULL;
8920 asm_argument_t **anchor = &result;
8922 while (token.type == T_STRING_LITERAL || token.type == '[') {
8923 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8924 memset(argument, 0, sizeof(argument[0]));
8927 if (token.type != T_IDENTIFIER) {
8928 parse_error_expected("while parsing asm argument",
8929 T_IDENTIFIER, NULL);
8932 argument->symbol = token.symbol;
8934 expect(']', end_error);
8937 argument->constraints = parse_string_literals();
8938 expect('(', end_error);
8939 add_anchor_token(')');
8940 expression_t *expression = parse_expression();
8941 rem_anchor_token(')');
8943 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8944 * change size or type representation (e.g. int -> long is ok, but
8945 * int -> float is not) */
8946 if (expression->kind == EXPR_UNARY_CAST) {
8947 type_t *const type = expression->base.type;
8948 type_kind_t const kind = type->kind;
8949 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8952 if (kind == TYPE_ATOMIC) {
8953 atomic_type_kind_t const akind = type->atomic.akind;
8954 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8955 size = get_atomic_type_size(akind);
8957 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8958 size = get_atomic_type_size(get_intptr_kind());
8962 expression_t *const value = expression->unary.value;
8963 type_t *const value_type = value->base.type;
8964 type_kind_t const value_kind = value_type->kind;
8966 unsigned value_flags;
8967 unsigned value_size;
8968 if (value_kind == TYPE_ATOMIC) {
8969 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8970 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8971 value_size = get_atomic_type_size(value_akind);
8972 } else if (value_kind == TYPE_POINTER) {
8973 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8974 value_size = get_atomic_type_size(get_intptr_kind());
8979 if (value_flags != flags || value_size != size)
8983 } while (expression->kind == EXPR_UNARY_CAST);
8987 if (!is_lvalue(expression)) {
8988 errorf(&expression->base.source_position,
8989 "asm output argument is not an lvalue");
8992 if (argument->constraints.begin[0] == '=')
8993 determine_lhs_ent(expression, NULL);
8995 mark_vars_read(expression, NULL);
8997 mark_vars_read(expression, NULL);
8999 argument->expression = expression;
9000 expect(')', end_error);
9002 set_address_taken(expression, true);
9005 anchor = &argument->next;
9017 * Parse a asm statement clobber specification.
9019 static asm_clobber_t *parse_asm_clobbers(void)
9021 asm_clobber_t *result = NULL;
9022 asm_clobber_t **anchor = &result;
9024 while (token.type == T_STRING_LITERAL) {
9025 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9026 clobber->clobber = parse_string_literals();
9029 anchor = &clobber->next;
9039 * Parse an asm statement.
9041 static statement_t *parse_asm_statement(void)
9043 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9044 asm_statement_t *asm_statement = &statement->asms;
9048 if (next_if(T_volatile))
9049 asm_statement->is_volatile = true;
9051 expect('(', end_error);
9052 add_anchor_token(')');
9053 if (token.type != T_STRING_LITERAL) {
9054 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9057 asm_statement->asm_text = parse_string_literals();
9059 add_anchor_token(':');
9060 if (!next_if(':')) {
9061 rem_anchor_token(':');
9065 asm_statement->outputs = parse_asm_arguments(true);
9066 if (!next_if(':')) {
9067 rem_anchor_token(':');
9071 asm_statement->inputs = parse_asm_arguments(false);
9072 if (!next_if(':')) {
9073 rem_anchor_token(':');
9076 rem_anchor_token(':');
9078 asm_statement->clobbers = parse_asm_clobbers();
9081 rem_anchor_token(')');
9082 expect(')', end_error);
9083 expect(';', end_error);
9085 if (asm_statement->outputs == NULL) {
9086 /* GCC: An 'asm' instruction without any output operands will be treated
9087 * identically to a volatile 'asm' instruction. */
9088 asm_statement->is_volatile = true;
9093 return create_invalid_statement();
9096 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9098 statement_t *inner_stmt;
9099 switch (token.type) {
9101 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9102 inner_stmt = create_invalid_statement();
9106 if (label->kind == STATEMENT_LABEL) {
9107 /* Eat an empty statement here, to avoid the warning about an empty
9108 * statement after a label. label:; is commonly used to have a label
9109 * before a closing brace. */
9110 inner_stmt = create_empty_statement();
9117 inner_stmt = parse_statement();
9118 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9119 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9120 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9128 * Parse a case statement.
9130 static statement_t *parse_case_statement(void)
9132 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9133 source_position_t *const pos = &statement->base.source_position;
9137 expression_t *const expression = parse_expression();
9138 statement->case_label.expression = expression;
9139 expression_classification_t const expr_class = is_constant_expression(expression);
9140 if (expr_class != EXPR_CLASS_CONSTANT) {
9141 if (expr_class != EXPR_CLASS_ERROR) {
9142 errorf(pos, "case label does not reduce to an integer constant");
9144 statement->case_label.is_bad = true;
9146 long const val = fold_constant_to_int(expression);
9147 statement->case_label.first_case = val;
9148 statement->case_label.last_case = val;
9152 if (next_if(T_DOTDOTDOT)) {
9153 expression_t *const end_range = parse_expression();
9154 statement->case_label.end_range = end_range;
9155 expression_classification_t const end_class = is_constant_expression(end_range);
9156 if (end_class != EXPR_CLASS_CONSTANT) {
9157 if (end_class != EXPR_CLASS_ERROR) {
9158 errorf(pos, "case range does not reduce to an integer constant");
9160 statement->case_label.is_bad = true;
9162 long const val = fold_constant_to_int(end_range);
9163 statement->case_label.last_case = val;
9165 if (val < statement->case_label.first_case) {
9166 statement->case_label.is_empty_range = true;
9167 warningf(WARN_OTHER, pos, "empty range specified");
9173 PUSH_PARENT(statement);
9175 expect(':', end_error);
9178 if (current_switch != NULL) {
9179 if (! statement->case_label.is_bad) {
9180 /* Check for duplicate case values */
9181 case_label_statement_t *c = &statement->case_label;
9182 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9183 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9186 if (c->last_case < l->first_case || c->first_case > l->last_case)
9189 errorf(pos, "duplicate case value (previously used %P)",
9190 &l->base.source_position);
9194 /* link all cases into the switch statement */
9195 if (current_switch->last_case == NULL) {
9196 current_switch->first_case = &statement->case_label;
9198 current_switch->last_case->next = &statement->case_label;
9200 current_switch->last_case = &statement->case_label;
9202 errorf(pos, "case label not within a switch statement");
9205 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9212 * Parse a default statement.
9214 static statement_t *parse_default_statement(void)
9216 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9220 PUSH_PARENT(statement);
9222 expect(':', end_error);
9225 if (current_switch != NULL) {
9226 const case_label_statement_t *def_label = current_switch->default_label;
9227 if (def_label != NULL) {
9228 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9230 current_switch->default_label = &statement->case_label;
9232 /* link all cases into the switch statement */
9233 if (current_switch->last_case == NULL) {
9234 current_switch->first_case = &statement->case_label;
9236 current_switch->last_case->next = &statement->case_label;
9238 current_switch->last_case = &statement->case_label;
9241 errorf(&statement->base.source_position,
9242 "'default' label not within a switch statement");
9245 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9252 * Parse a label statement.
9254 static statement_t *parse_label_statement(void)
9256 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9257 label_t *const label = get_label();
9258 statement->label.label = label;
9260 PUSH_PARENT(statement);
9262 /* if statement is already set then the label is defined twice,
9263 * otherwise it was just mentioned in a goto/local label declaration so far
9265 source_position_t const* const pos = &statement->base.source_position;
9266 if (label->statement != NULL) {
9267 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9269 label->base.source_position = *pos;
9270 label->statement = statement;
9275 statement->label.statement = parse_label_inner_statement(statement, "label");
9277 /* remember the labels in a list for later checking */
9278 *label_anchor = &statement->label;
9279 label_anchor = &statement->label.next;
9286 * Parse an if statement.
9288 static statement_t *parse_if(void)
9290 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9294 PUSH_PARENT(statement);
9296 add_anchor_token('{');
9298 expect('(', end_error);
9299 add_anchor_token(')');
9300 expression_t *const expr = parse_expression();
9301 statement->ifs.condition = expr;
9302 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9304 semantic_condition(expr, "condition of 'if'-statment");
9305 mark_vars_read(expr, NULL);
9306 rem_anchor_token(')');
9307 expect(')', end_error);
9310 rem_anchor_token('{');
9312 add_anchor_token(T_else);
9313 statement_t *const true_stmt = parse_statement();
9314 statement->ifs.true_statement = true_stmt;
9315 rem_anchor_token(T_else);
9317 if (next_if(T_else)) {
9318 statement->ifs.false_statement = parse_statement();
9319 } else if (true_stmt->kind == STATEMENT_IF &&
9320 true_stmt->ifs.false_statement != NULL) {
9321 source_position_t const *const pos = &true_stmt->base.source_position;
9322 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9330 * Check that all enums are handled in a switch.
9332 * @param statement the switch statement to check
9334 static void check_enum_cases(const switch_statement_t *statement)
9336 if (!is_warn_on(WARN_SWITCH_ENUM))
9338 const type_t *type = skip_typeref(statement->expression->base.type);
9339 if (! is_type_enum(type))
9341 const enum_type_t *enumt = &type->enumt;
9343 /* if we have a default, no warnings */
9344 if (statement->default_label != NULL)
9347 /* FIXME: calculation of value should be done while parsing */
9348 /* TODO: quadratic algorithm here. Change to an n log n one */
9349 long last_value = -1;
9350 const entity_t *entry = enumt->enume->base.next;
9351 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9352 entry = entry->base.next) {
9353 const expression_t *expression = entry->enum_value.value;
9354 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9356 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9357 if (l->expression == NULL)
9359 if (l->first_case <= value && value <= l->last_case) {
9365 source_position_t const *const pos = &statement->base.source_position;
9366 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9373 * Parse a switch statement.
9375 static statement_t *parse_switch(void)
9377 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9381 PUSH_PARENT(statement);
9383 expect('(', end_error);
9384 add_anchor_token(')');
9385 expression_t *const expr = parse_expression();
9386 mark_vars_read(expr, NULL);
9387 type_t * type = skip_typeref(expr->base.type);
9388 if (is_type_integer(type)) {
9389 type = promote_integer(type);
9390 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9391 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9393 } else if (is_type_valid(type)) {
9394 errorf(&expr->base.source_position,
9395 "switch quantity is not an integer, but '%T'", type);
9396 type = type_error_type;
9398 statement->switchs.expression = create_implicit_cast(expr, type);
9399 expect(')', end_error);
9400 rem_anchor_token(')');
9402 switch_statement_t *rem = current_switch;
9403 current_switch = &statement->switchs;
9404 statement->switchs.body = parse_statement();
9405 current_switch = rem;
9407 if (statement->switchs.default_label == NULL) {
9408 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9410 check_enum_cases(&statement->switchs);
9416 return create_invalid_statement();
9419 static statement_t *parse_loop_body(statement_t *const loop)
9421 statement_t *const rem = current_loop;
9422 current_loop = loop;
9424 statement_t *const body = parse_statement();
9431 * Parse a while statement.
9433 static statement_t *parse_while(void)
9435 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9439 PUSH_PARENT(statement);
9441 expect('(', end_error);
9442 add_anchor_token(')');
9443 expression_t *const cond = parse_expression();
9444 statement->whiles.condition = cond;
9445 /* §6.8.5:2 The controlling expression of an iteration statement shall
9446 * have scalar type. */
9447 semantic_condition(cond, "condition of 'while'-statement");
9448 mark_vars_read(cond, NULL);
9449 rem_anchor_token(')');
9450 expect(')', end_error);
9452 statement->whiles.body = parse_loop_body(statement);
9458 return create_invalid_statement();
9462 * Parse a do statement.
9464 static statement_t *parse_do(void)
9466 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9470 PUSH_PARENT(statement);
9472 add_anchor_token(T_while);
9473 statement->do_while.body = parse_loop_body(statement);
9474 rem_anchor_token(T_while);
9476 expect(T_while, end_error);
9477 expect('(', end_error);
9478 add_anchor_token(')');
9479 expression_t *const cond = parse_expression();
9480 statement->do_while.condition = cond;
9481 /* §6.8.5:2 The controlling expression of an iteration statement shall
9482 * have scalar type. */
9483 semantic_condition(cond, "condition of 'do-while'-statement");
9484 mark_vars_read(cond, NULL);
9485 rem_anchor_token(')');
9486 expect(')', end_error);
9487 expect(';', end_error);
9493 return create_invalid_statement();
9497 * Parse a for statement.
9499 static statement_t *parse_for(void)
9501 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9505 expect('(', end_error1);
9506 add_anchor_token(')');
9508 PUSH_PARENT(statement);
9510 size_t const top = environment_top();
9511 scope_t *old_scope = scope_push(&statement->fors.scope);
9513 bool old_gcc_extension = in_gcc_extension;
9514 while (next_if(T___extension__)) {
9515 in_gcc_extension = true;
9519 } else if (is_declaration_specifier(&token)) {
9520 parse_declaration(record_entity, DECL_FLAGS_NONE);
9522 add_anchor_token(';');
9523 expression_t *const init = parse_expression();
9524 statement->fors.initialisation = init;
9525 mark_vars_read(init, ENT_ANY);
9526 if (!expression_has_effect(init)) {
9527 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9529 rem_anchor_token(';');
9530 expect(';', end_error2);
9532 in_gcc_extension = old_gcc_extension;
9534 if (token.type != ';') {
9535 add_anchor_token(';');
9536 expression_t *const cond = parse_expression();
9537 statement->fors.condition = cond;
9538 /* §6.8.5:2 The controlling expression of an iteration statement
9539 * shall have scalar type. */
9540 semantic_condition(cond, "condition of 'for'-statement");
9541 mark_vars_read(cond, NULL);
9542 rem_anchor_token(';');
9544 expect(';', end_error2);
9545 if (token.type != ')') {
9546 expression_t *const step = parse_expression();
9547 statement->fors.step = step;
9548 mark_vars_read(step, ENT_ANY);
9549 if (!expression_has_effect(step)) {
9550 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9553 expect(')', end_error2);
9554 rem_anchor_token(')');
9555 statement->fors.body = parse_loop_body(statement);
9557 assert(current_scope == &statement->fors.scope);
9558 scope_pop(old_scope);
9559 environment_pop_to(top);
9566 rem_anchor_token(')');
9567 assert(current_scope == &statement->fors.scope);
9568 scope_pop(old_scope);
9569 environment_pop_to(top);
9573 return create_invalid_statement();
9577 * Parse a goto statement.
9579 static statement_t *parse_goto(void)
9581 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9584 if (GNU_MODE && next_if('*')) {
9585 expression_t *expression = parse_expression();
9586 mark_vars_read(expression, NULL);
9588 /* Argh: although documentation says the expression must be of type void*,
9589 * gcc accepts anything that can be casted into void* without error */
9590 type_t *type = expression->base.type;
9592 if (type != type_error_type) {
9593 if (!is_type_pointer(type) && !is_type_integer(type)) {
9594 errorf(&expression->base.source_position,
9595 "cannot convert to a pointer type");
9596 } else if (type != type_void_ptr) {
9597 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9599 expression = create_implicit_cast(expression, type_void_ptr);
9602 statement->gotos.expression = expression;
9603 } else if (token.type == T_IDENTIFIER) {
9604 label_t *const label = get_label();
9606 statement->gotos.label = label;
9609 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9611 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9613 return create_invalid_statement();
9616 /* remember the goto's in a list for later checking */
9617 *goto_anchor = &statement->gotos;
9618 goto_anchor = &statement->gotos.next;
9620 expect(';', end_error);
9627 * Parse a continue statement.
9629 static statement_t *parse_continue(void)
9631 if (current_loop == NULL) {
9632 errorf(HERE, "continue statement not within loop");
9635 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9638 expect(';', end_error);
9645 * Parse a break statement.
9647 static statement_t *parse_break(void)
9649 if (current_switch == NULL && current_loop == NULL) {
9650 errorf(HERE, "break statement not within loop or switch");
9653 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9656 expect(';', end_error);
9663 * Parse a __leave statement.
9665 static statement_t *parse_leave_statement(void)
9667 if (current_try == NULL) {
9668 errorf(HERE, "__leave statement not within __try");
9671 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9674 expect(';', end_error);
9681 * Check if a given entity represents a local variable.
9683 static bool is_local_variable(const entity_t *entity)
9685 if (entity->kind != ENTITY_VARIABLE)
9688 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9689 case STORAGE_CLASS_AUTO:
9690 case STORAGE_CLASS_REGISTER: {
9691 const type_t *type = skip_typeref(entity->declaration.type);
9692 if (is_type_function(type)) {
9704 * Check if a given expression represents a local variable.
9706 static bool expression_is_local_variable(const expression_t *expression)
9708 if (expression->base.kind != EXPR_REFERENCE) {
9711 const entity_t *entity = expression->reference.entity;
9712 return is_local_variable(entity);
9716 * Check if a given expression represents a local variable and
9717 * return its declaration then, else return NULL.
9719 entity_t *expression_is_variable(const expression_t *expression)
9721 if (expression->base.kind != EXPR_REFERENCE) {
9724 entity_t *entity = expression->reference.entity;
9725 if (entity->kind != ENTITY_VARIABLE)
9732 * Parse a return statement.
9734 static statement_t *parse_return(void)
9738 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9740 expression_t *return_value = NULL;
9741 if (token.type != ';') {
9742 return_value = parse_expression();
9743 mark_vars_read(return_value, NULL);
9746 const type_t *const func_type = skip_typeref(current_function->base.type);
9747 assert(is_type_function(func_type));
9748 type_t *const return_type = skip_typeref(func_type->function.return_type);
9750 source_position_t const *const pos = &statement->base.source_position;
9751 if (return_value != NULL) {
9752 type_t *return_value_type = skip_typeref(return_value->base.type);
9754 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9755 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9756 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9757 /* Only warn in C mode, because GCC does the same */
9758 if (c_mode & _CXX || strict_mode) {
9760 "'return' with a value, in function returning 'void'");
9762 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9764 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9765 /* Only warn in C mode, because GCC does the same */
9768 "'return' with expression in function returning 'void'");
9770 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9774 assign_error_t error = semantic_assign(return_type, return_value);
9775 report_assign_error(error, return_type, return_value, "'return'",
9778 return_value = create_implicit_cast(return_value, return_type);
9779 /* check for returning address of a local var */
9780 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9781 const expression_t *expression = return_value->unary.value;
9782 if (expression_is_local_variable(expression)) {
9783 warningf(WARN_OTHER, pos, "function returns address of local variable");
9786 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9787 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9788 if (c_mode & _CXX || strict_mode) {
9790 "'return' without value, in function returning non-void");
9792 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9795 statement->returns.value = return_value;
9797 expect(';', end_error);
9804 * Parse a declaration statement.
9806 static statement_t *parse_declaration_statement(void)
9808 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9810 entity_t *before = current_scope->last_entity;
9812 parse_external_declaration();
9814 parse_declaration(record_entity, DECL_FLAGS_NONE);
9817 declaration_statement_t *const decl = &statement->declaration;
9818 entity_t *const begin =
9819 before != NULL ? before->base.next : current_scope->entities;
9820 decl->declarations_begin = begin;
9821 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9827 * Parse an expression statement, ie. expr ';'.
9829 static statement_t *parse_expression_statement(void)
9831 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9833 expression_t *const expr = parse_expression();
9834 statement->expression.expression = expr;
9835 mark_vars_read(expr, ENT_ANY);
9837 expect(';', end_error);
9844 * Parse a microsoft __try { } __finally { } or
9845 * __try{ } __except() { }
9847 static statement_t *parse_ms_try_statment(void)
9849 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9852 PUSH_PARENT(statement);
9854 ms_try_statement_t *rem = current_try;
9855 current_try = &statement->ms_try;
9856 statement->ms_try.try_statement = parse_compound_statement(false);
9861 if (next_if(T___except)) {
9862 expect('(', end_error);
9863 add_anchor_token(')');
9864 expression_t *const expr = parse_expression();
9865 mark_vars_read(expr, NULL);
9866 type_t * type = skip_typeref(expr->base.type);
9867 if (is_type_integer(type)) {
9868 type = promote_integer(type);
9869 } else if (is_type_valid(type)) {
9870 errorf(&expr->base.source_position,
9871 "__expect expression is not an integer, but '%T'", type);
9872 type = type_error_type;
9874 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9875 rem_anchor_token(')');
9876 expect(')', end_error);
9877 statement->ms_try.final_statement = parse_compound_statement(false);
9878 } else if (next_if(T__finally)) {
9879 statement->ms_try.final_statement = parse_compound_statement(false);
9881 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9882 return create_invalid_statement();
9886 return create_invalid_statement();
9889 static statement_t *parse_empty_statement(void)
9891 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9892 statement_t *const statement = create_empty_statement();
9897 static statement_t *parse_local_label_declaration(void)
9899 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9903 entity_t *begin = NULL;
9904 entity_t *end = NULL;
9905 entity_t **anchor = &begin;
9907 if (token.type != T_IDENTIFIER) {
9908 parse_error_expected("while parsing local label declaration",
9909 T_IDENTIFIER, NULL);
9912 symbol_t *symbol = token.symbol;
9913 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9914 if (entity != NULL && entity->base.parent_scope == current_scope) {
9915 source_position_t const *const ppos = &entity->base.source_position;
9916 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9918 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9919 entity->base.parent_scope = current_scope;
9920 entity->base.source_position = token.source_position;
9923 anchor = &entity->base.next;
9926 environment_push(entity);
9929 } while (next_if(','));
9930 expect(';', end_error);
9932 statement->declaration.declarations_begin = begin;
9933 statement->declaration.declarations_end = end;
9937 static void parse_namespace_definition(void)
9941 entity_t *entity = NULL;
9942 symbol_t *symbol = NULL;
9944 if (token.type == T_IDENTIFIER) {
9945 symbol = token.symbol;
9948 entity = get_entity(symbol, NAMESPACE_NORMAL);
9950 && entity->kind != ENTITY_NAMESPACE
9951 && entity->base.parent_scope == current_scope) {
9952 if (is_entity_valid(entity)) {
9953 error_redefined_as_different_kind(&token.source_position,
9954 entity, ENTITY_NAMESPACE);
9960 if (entity == NULL) {
9961 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9962 entity->base.source_position = token.source_position;
9963 entity->base.parent_scope = current_scope;
9966 if (token.type == '=') {
9967 /* TODO: parse namespace alias */
9968 panic("namespace alias definition not supported yet");
9971 environment_push(entity);
9972 append_entity(current_scope, entity);
9974 size_t const top = environment_top();
9975 scope_t *old_scope = scope_push(&entity->namespacee.members);
9977 entity_t *old_current_entity = current_entity;
9978 current_entity = entity;
9980 expect('{', end_error);
9982 expect('}', end_error);
9985 assert(current_scope == &entity->namespacee.members);
9986 assert(current_entity == entity);
9987 current_entity = old_current_entity;
9988 scope_pop(old_scope);
9989 environment_pop_to(top);
9993 * Parse a statement.
9994 * There's also parse_statement() which additionally checks for
9995 * "statement has no effect" warnings
9997 static statement_t *intern_parse_statement(void)
9999 statement_t *statement = NULL;
10001 /* declaration or statement */
10002 add_anchor_token(';');
10003 switch (token.type) {
10004 case T_IDENTIFIER: {
10005 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10006 if (la1_type == ':') {
10007 statement = parse_label_statement();
10008 } else if (is_typedef_symbol(token.symbol)) {
10009 statement = parse_declaration_statement();
10011 /* it's an identifier, the grammar says this must be an
10012 * expression statement. However it is common that users mistype
10013 * declaration types, so we guess a bit here to improve robustness
10014 * for incorrect programs */
10015 switch (la1_type) {
10018 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10020 statement = parse_expression_statement();
10024 statement = parse_declaration_statement();
10032 case T___extension__:
10033 /* This can be a prefix to a declaration or an expression statement.
10034 * We simply eat it now and parse the rest with tail recursion. */
10035 while (next_if(T___extension__)) {}
10036 bool old_gcc_extension = in_gcc_extension;
10037 in_gcc_extension = true;
10038 statement = intern_parse_statement();
10039 in_gcc_extension = old_gcc_extension;
10043 statement = parse_declaration_statement();
10047 statement = parse_local_label_declaration();
10050 case ';': statement = parse_empty_statement(); break;
10051 case '{': statement = parse_compound_statement(false); break;
10052 case T___leave: statement = parse_leave_statement(); break;
10053 case T___try: statement = parse_ms_try_statment(); break;
10054 case T_asm: statement = parse_asm_statement(); break;
10055 case T_break: statement = parse_break(); break;
10056 case T_case: statement = parse_case_statement(); break;
10057 case T_continue: statement = parse_continue(); break;
10058 case T_default: statement = parse_default_statement(); break;
10059 case T_do: statement = parse_do(); break;
10060 case T_for: statement = parse_for(); break;
10061 case T_goto: statement = parse_goto(); break;
10062 case T_if: statement = parse_if(); break;
10063 case T_return: statement = parse_return(); break;
10064 case T_switch: statement = parse_switch(); break;
10065 case T_while: statement = parse_while(); break;
10068 statement = parse_expression_statement();
10072 errorf(HERE, "unexpected token %K while parsing statement", &token);
10073 statement = create_invalid_statement();
10078 rem_anchor_token(';');
10080 assert(statement != NULL
10081 && statement->base.source_position.input_name != NULL);
10087 * parse a statement and emits "statement has no effect" warning if needed
10088 * (This is really a wrapper around intern_parse_statement with check for 1
10089 * single warning. It is needed, because for statement expressions we have
10090 * to avoid the warning on the last statement)
10092 static statement_t *parse_statement(void)
10094 statement_t *statement = intern_parse_statement();
10096 if (statement->kind == STATEMENT_EXPRESSION) {
10097 expression_t *expression = statement->expression.expression;
10098 if (!expression_has_effect(expression)) {
10099 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10107 * Parse a compound statement.
10109 static statement_t *parse_compound_statement(bool inside_expression_statement)
10111 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10113 PUSH_PARENT(statement);
10116 add_anchor_token('}');
10117 /* tokens, which can start a statement */
10118 /* TODO MS, __builtin_FOO */
10119 add_anchor_token('!');
10120 add_anchor_token('&');
10121 add_anchor_token('(');
10122 add_anchor_token('*');
10123 add_anchor_token('+');
10124 add_anchor_token('-');
10125 add_anchor_token('{');
10126 add_anchor_token('~');
10127 add_anchor_token(T_CHARACTER_CONSTANT);
10128 add_anchor_token(T_COLONCOLON);
10129 add_anchor_token(T_FLOATINGPOINT);
10130 add_anchor_token(T_IDENTIFIER);
10131 add_anchor_token(T_INTEGER);
10132 add_anchor_token(T_MINUSMINUS);
10133 add_anchor_token(T_PLUSPLUS);
10134 add_anchor_token(T_STRING_LITERAL);
10135 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10136 add_anchor_token(T_WIDE_STRING_LITERAL);
10137 add_anchor_token(T__Bool);
10138 add_anchor_token(T__Complex);
10139 add_anchor_token(T__Imaginary);
10140 add_anchor_token(T___FUNCTION__);
10141 add_anchor_token(T___PRETTY_FUNCTION__);
10142 add_anchor_token(T___alignof__);
10143 add_anchor_token(T___attribute__);
10144 add_anchor_token(T___builtin_va_start);
10145 add_anchor_token(T___extension__);
10146 add_anchor_token(T___func__);
10147 add_anchor_token(T___imag__);
10148 add_anchor_token(T___label__);
10149 add_anchor_token(T___real__);
10150 add_anchor_token(T___thread);
10151 add_anchor_token(T_asm);
10152 add_anchor_token(T_auto);
10153 add_anchor_token(T_bool);
10154 add_anchor_token(T_break);
10155 add_anchor_token(T_case);
10156 add_anchor_token(T_char);
10157 add_anchor_token(T_class);
10158 add_anchor_token(T_const);
10159 add_anchor_token(T_const_cast);
10160 add_anchor_token(T_continue);
10161 add_anchor_token(T_default);
10162 add_anchor_token(T_delete);
10163 add_anchor_token(T_double);
10164 add_anchor_token(T_do);
10165 add_anchor_token(T_dynamic_cast);
10166 add_anchor_token(T_enum);
10167 add_anchor_token(T_extern);
10168 add_anchor_token(T_false);
10169 add_anchor_token(T_float);
10170 add_anchor_token(T_for);
10171 add_anchor_token(T_goto);
10172 add_anchor_token(T_if);
10173 add_anchor_token(T_inline);
10174 add_anchor_token(T_int);
10175 add_anchor_token(T_long);
10176 add_anchor_token(T_new);
10177 add_anchor_token(T_operator);
10178 add_anchor_token(T_register);
10179 add_anchor_token(T_reinterpret_cast);
10180 add_anchor_token(T_restrict);
10181 add_anchor_token(T_return);
10182 add_anchor_token(T_short);
10183 add_anchor_token(T_signed);
10184 add_anchor_token(T_sizeof);
10185 add_anchor_token(T_static);
10186 add_anchor_token(T_static_cast);
10187 add_anchor_token(T_struct);
10188 add_anchor_token(T_switch);
10189 add_anchor_token(T_template);
10190 add_anchor_token(T_this);
10191 add_anchor_token(T_throw);
10192 add_anchor_token(T_true);
10193 add_anchor_token(T_try);
10194 add_anchor_token(T_typedef);
10195 add_anchor_token(T_typeid);
10196 add_anchor_token(T_typename);
10197 add_anchor_token(T_typeof);
10198 add_anchor_token(T_union);
10199 add_anchor_token(T_unsigned);
10200 add_anchor_token(T_using);
10201 add_anchor_token(T_void);
10202 add_anchor_token(T_volatile);
10203 add_anchor_token(T_wchar_t);
10204 add_anchor_token(T_while);
10206 size_t const top = environment_top();
10207 scope_t *old_scope = scope_push(&statement->compound.scope);
10209 statement_t **anchor = &statement->compound.statements;
10210 bool only_decls_so_far = true;
10211 while (token.type != '}') {
10212 if (token.type == T_EOF) {
10213 errorf(&statement->base.source_position,
10214 "EOF while parsing compound statement");
10217 statement_t *sub_statement = intern_parse_statement();
10218 if (is_invalid_statement(sub_statement)) {
10219 /* an error occurred. if we are at an anchor, return */
10225 if (sub_statement->kind != STATEMENT_DECLARATION) {
10226 only_decls_so_far = false;
10227 } else if (!only_decls_so_far) {
10228 source_position_t const *const pos = &sub_statement->base.source_position;
10229 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10232 *anchor = sub_statement;
10234 while (sub_statement->base.next != NULL)
10235 sub_statement = sub_statement->base.next;
10237 anchor = &sub_statement->base.next;
10241 /* look over all statements again to produce no effect warnings */
10242 if (is_warn_on(WARN_UNUSED_VALUE)) {
10243 statement_t *sub_statement = statement->compound.statements;
10244 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10245 if (sub_statement->kind != STATEMENT_EXPRESSION)
10247 /* don't emit a warning for the last expression in an expression
10248 * statement as it has always an effect */
10249 if (inside_expression_statement && sub_statement->base.next == NULL)
10252 expression_t *expression = sub_statement->expression.expression;
10253 if (!expression_has_effect(expression)) {
10254 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10260 rem_anchor_token(T_while);
10261 rem_anchor_token(T_wchar_t);
10262 rem_anchor_token(T_volatile);
10263 rem_anchor_token(T_void);
10264 rem_anchor_token(T_using);
10265 rem_anchor_token(T_unsigned);
10266 rem_anchor_token(T_union);
10267 rem_anchor_token(T_typeof);
10268 rem_anchor_token(T_typename);
10269 rem_anchor_token(T_typeid);
10270 rem_anchor_token(T_typedef);
10271 rem_anchor_token(T_try);
10272 rem_anchor_token(T_true);
10273 rem_anchor_token(T_throw);
10274 rem_anchor_token(T_this);
10275 rem_anchor_token(T_template);
10276 rem_anchor_token(T_switch);
10277 rem_anchor_token(T_struct);
10278 rem_anchor_token(T_static_cast);
10279 rem_anchor_token(T_static);
10280 rem_anchor_token(T_sizeof);
10281 rem_anchor_token(T_signed);
10282 rem_anchor_token(T_short);
10283 rem_anchor_token(T_return);
10284 rem_anchor_token(T_restrict);
10285 rem_anchor_token(T_reinterpret_cast);
10286 rem_anchor_token(T_register);
10287 rem_anchor_token(T_operator);
10288 rem_anchor_token(T_new);
10289 rem_anchor_token(T_long);
10290 rem_anchor_token(T_int);
10291 rem_anchor_token(T_inline);
10292 rem_anchor_token(T_if);
10293 rem_anchor_token(T_goto);
10294 rem_anchor_token(T_for);
10295 rem_anchor_token(T_float);
10296 rem_anchor_token(T_false);
10297 rem_anchor_token(T_extern);
10298 rem_anchor_token(T_enum);
10299 rem_anchor_token(T_dynamic_cast);
10300 rem_anchor_token(T_do);
10301 rem_anchor_token(T_double);
10302 rem_anchor_token(T_delete);
10303 rem_anchor_token(T_default);
10304 rem_anchor_token(T_continue);
10305 rem_anchor_token(T_const_cast);
10306 rem_anchor_token(T_const);
10307 rem_anchor_token(T_class);
10308 rem_anchor_token(T_char);
10309 rem_anchor_token(T_case);
10310 rem_anchor_token(T_break);
10311 rem_anchor_token(T_bool);
10312 rem_anchor_token(T_auto);
10313 rem_anchor_token(T_asm);
10314 rem_anchor_token(T___thread);
10315 rem_anchor_token(T___real__);
10316 rem_anchor_token(T___label__);
10317 rem_anchor_token(T___imag__);
10318 rem_anchor_token(T___func__);
10319 rem_anchor_token(T___extension__);
10320 rem_anchor_token(T___builtin_va_start);
10321 rem_anchor_token(T___attribute__);
10322 rem_anchor_token(T___alignof__);
10323 rem_anchor_token(T___PRETTY_FUNCTION__);
10324 rem_anchor_token(T___FUNCTION__);
10325 rem_anchor_token(T__Imaginary);
10326 rem_anchor_token(T__Complex);
10327 rem_anchor_token(T__Bool);
10328 rem_anchor_token(T_WIDE_STRING_LITERAL);
10329 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10330 rem_anchor_token(T_STRING_LITERAL);
10331 rem_anchor_token(T_PLUSPLUS);
10332 rem_anchor_token(T_MINUSMINUS);
10333 rem_anchor_token(T_INTEGER);
10334 rem_anchor_token(T_IDENTIFIER);
10335 rem_anchor_token(T_FLOATINGPOINT);
10336 rem_anchor_token(T_COLONCOLON);
10337 rem_anchor_token(T_CHARACTER_CONSTANT);
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 rem_anchor_token('&');
10345 rem_anchor_token('!');
10346 rem_anchor_token('}');
10347 assert(current_scope == &statement->compound.scope);
10348 scope_pop(old_scope);
10349 environment_pop_to(top);
10356 * Check for unused global static functions and variables
10358 static void check_unused_globals(void)
10360 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10363 for (const entity_t *entity = file_scope->entities; entity != NULL;
10364 entity = entity->base.next) {
10365 if (!is_declaration(entity))
10368 const declaration_t *declaration = &entity->declaration;
10369 if (declaration->used ||
10370 declaration->modifiers & DM_UNUSED ||
10371 declaration->modifiers & DM_USED ||
10372 declaration->storage_class != STORAGE_CLASS_STATIC)
10377 if (entity->kind == ENTITY_FUNCTION) {
10378 /* inhibit warning for static inline functions */
10379 if (entity->function.is_inline)
10382 why = WARN_UNUSED_FUNCTION;
10383 s = entity->function.statement != NULL ? "defined" : "declared";
10385 why = WARN_UNUSED_VARIABLE;
10389 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity);
10393 static void parse_global_asm(void)
10395 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10398 expect('(', end_error);
10400 statement->asms.asm_text = parse_string_literals();
10401 statement->base.next = unit->global_asm;
10402 unit->global_asm = statement;
10404 expect(')', end_error);
10405 expect(';', end_error);
10410 static void parse_linkage_specification(void)
10414 source_position_t const pos = *HERE;
10415 char const *const linkage = parse_string_literals().begin;
10417 linkage_kind_t old_linkage = current_linkage;
10418 linkage_kind_t new_linkage;
10419 if (strcmp(linkage, "C") == 0) {
10420 new_linkage = LINKAGE_C;
10421 } else if (strcmp(linkage, "C++") == 0) {
10422 new_linkage = LINKAGE_CXX;
10424 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10425 new_linkage = LINKAGE_INVALID;
10427 current_linkage = new_linkage;
10429 if (next_if('{')) {
10431 expect('}', end_error);
10437 assert(current_linkage == new_linkage);
10438 current_linkage = old_linkage;
10441 static void parse_external(void)
10443 switch (token.type) {
10444 DECLARATION_START_NO_EXTERN
10446 case T___extension__:
10447 /* tokens below are for implicit int */
10448 case '&': /* & x; -> int& x; (and error later, because C++ has no
10450 case '*': /* * x; -> int* x; */
10451 case '(': /* (x); -> int (x); */
10452 parse_external_declaration();
10456 if (look_ahead(1)->type == T_STRING_LITERAL) {
10457 parse_linkage_specification();
10459 parse_external_declaration();
10464 parse_global_asm();
10468 parse_namespace_definition();
10472 if (!strict_mode) {
10473 warningf(WARN_OTHER, HERE, "stray ';' outside of function");
10480 errorf(HERE, "stray %K outside of function", &token);
10481 if (token.type == '(' || token.type == '{' || token.type == '[')
10482 eat_until_matching_token(token.type);
10488 static void parse_externals(void)
10490 add_anchor_token('}');
10491 add_anchor_token(T_EOF);
10494 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10495 unsigned char token_anchor_copy[T_LAST_TOKEN];
10496 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10499 while (token.type != T_EOF && token.type != '}') {
10501 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10502 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10504 /* the anchor set and its copy differs */
10505 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10508 if (in_gcc_extension) {
10509 /* an gcc extension scope was not closed */
10510 internal_errorf(HERE, "Leaked __extension__");
10517 rem_anchor_token(T_EOF);
10518 rem_anchor_token('}');
10522 * Parse a translation unit.
10524 static void parse_translation_unit(void)
10526 add_anchor_token(T_EOF);
10531 if (token.type == T_EOF)
10534 errorf(HERE, "stray %K outside of function", &token);
10535 if (token.type == '(' || token.type == '{' || token.type == '[')
10536 eat_until_matching_token(token.type);
10541 void set_default_visibility(elf_visibility_tag_t visibility)
10543 default_visibility = visibility;
10549 * @return the translation unit or NULL if errors occurred.
10551 void start_parsing(void)
10553 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10554 label_stack = NEW_ARR_F(stack_entry_t, 0);
10555 diagnostic_count = 0;
10559 print_to_file(stderr);
10561 assert(unit == NULL);
10562 unit = allocate_ast_zero(sizeof(unit[0]));
10564 assert(file_scope == NULL);
10565 file_scope = &unit->scope;
10567 assert(current_scope == NULL);
10568 scope_push(&unit->scope);
10570 create_gnu_builtins();
10572 create_microsoft_intrinsics();
10575 translation_unit_t *finish_parsing(void)
10577 assert(current_scope == &unit->scope);
10580 assert(file_scope == &unit->scope);
10581 check_unused_globals();
10584 DEL_ARR_F(environment_stack);
10585 DEL_ARR_F(label_stack);
10587 translation_unit_t *result = unit;
10592 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10593 * are given length one. */
10594 static void complete_incomplete_arrays(void)
10596 size_t n = ARR_LEN(incomplete_arrays);
10597 for (size_t i = 0; i != n; ++i) {
10598 declaration_t *const decl = incomplete_arrays[i];
10599 type_t *const type = skip_typeref(decl->type);
10601 if (!is_type_incomplete(type))
10604 source_position_t const *const pos = &decl->base.source_position;
10605 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10607 type_t *const new_type = duplicate_type(type);
10608 new_type->array.size_constant = true;
10609 new_type->array.has_implicit_size = true;
10610 new_type->array.size = 1;
10612 type_t *const result = identify_new_type(new_type);
10614 decl->type = result;
10618 void prepare_main_collect2(entity_t *entity)
10620 // create call to __main
10621 symbol_t *symbol = symbol_table_insert("__main");
10622 entity_t *subsubmain_ent
10623 = create_implicit_function(symbol, &builtin_source_position);
10625 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10626 type_t *ftype = subsubmain_ent->declaration.type;
10627 ref->base.source_position = builtin_source_position;
10628 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10629 ref->reference.entity = subsubmain_ent;
10631 expression_t *call = allocate_expression_zero(EXPR_CALL);
10632 call->base.source_position = builtin_source_position;
10633 call->base.type = type_void;
10634 call->call.function = ref;
10636 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10637 expr_statement->base.source_position = builtin_source_position;
10638 expr_statement->expression.expression = call;
10640 statement_t *statement = entity->function.statement;
10641 assert(statement->kind == STATEMENT_COMPOUND);
10642 compound_statement_t *compounds = &statement->compound;
10644 expr_statement->base.next = compounds->statements;
10645 compounds->statements = expr_statement;
10650 lookahead_bufpos = 0;
10651 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10654 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10655 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10656 parse_translation_unit();
10657 complete_incomplete_arrays();
10658 DEL_ARR_F(incomplete_arrays);
10659 incomplete_arrays = NULL;
10663 * Initialize the parser.
10665 void init_parser(void)
10667 sym_anonymous = symbol_table_insert("<anonymous>");
10669 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10671 init_expression_parsers();
10672 obstack_init(&temp_obst);
10676 * Terminate the parser.
10678 void exit_parser(void)
10680 obstack_free(&temp_obst, NULL);