2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static switch_statement_t *current_switch = NULL;
93 static statement_t *current_loop = NULL;
94 static statement_t *current_parent = NULL;
95 static ms_try_statement_t *current_try = NULL;
96 static linkage_kind_t current_linkage;
97 static goto_statement_t *goto_first = NULL;
98 static goto_statement_t **goto_anchor = NULL;
99 static label_statement_t *label_first = NULL;
100 static label_statement_t **label_anchor = NULL;
101 /** current translation unit. */
102 static translation_unit_t *unit = NULL;
103 /** true if we are in an __extension__ context. */
104 static bool in_gcc_extension = false;
105 static struct obstack temp_obst;
106 static entity_t *anonymous_entity;
107 static declaration_t **incomplete_arrays;
108 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
111 #define PUSH_PARENT(stmt) \
112 statement_t *const new_parent = (stmt); \
113 statement_t *const old_parent = current_parent; \
114 ((void)(current_parent = new_parent))
115 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
117 #define PUSH_SCOPE(scope) \
118 size_t const top = environment_top(); \
119 scope_t *const new_scope = (scope); \
120 scope_t *const old_scope = scope_push(new_scope)
121 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
123 #define PUSH_EXTENSION() \
125 bool const old_gcc_extension = in_gcc_extension; \
126 while (next_if(T___extension__)) { \
127 in_gcc_extension = true; \
130 #define POP_EXTENSION() \
131 ((void)(in_gcc_extension = old_gcc_extension))
133 /** special symbol used for anonymous entities. */
134 static symbol_t *sym_anonymous = NULL;
136 /** The token anchor set */
137 static unsigned short token_anchor_set[T_LAST_TOKEN];
139 /** The current source position. */
140 #define HERE (&token.base.source_position)
142 /** true if we are in GCC mode. */
143 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
145 static statement_t *parse_compound_statement(bool inside_expression_statement);
146 static statement_t *parse_statement(void);
148 static expression_t *parse_subexpression(precedence_t);
149 static expression_t *parse_expression(void);
150 static type_t *parse_typename(void);
151 static void parse_externals(void);
152 static void parse_external(void);
154 static void parse_compound_type_entries(compound_t *compound_declaration);
156 static void check_call_argument(type_t *expected_type,
157 call_argument_t *argument, unsigned pos);
159 typedef enum declarator_flags_t {
161 DECL_MAY_BE_ABSTRACT = 1U << 0,
162 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
163 DECL_IS_PARAMETER = 1U << 2
164 } declarator_flags_t;
166 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
167 declarator_flags_t flags);
169 static void semantic_comparison(binary_expression_t *expression);
171 #define STORAGE_CLASSES \
172 STORAGE_CLASSES_NO_EXTERN \
175 #define STORAGE_CLASSES_NO_EXTERN \
182 #define TYPE_QUALIFIERS \
187 case T__forceinline: \
188 case T___attribute__:
190 #define COMPLEX_SPECIFIERS \
192 #define IMAGINARY_SPECIFIERS \
195 #define TYPE_SPECIFIERS \
197 case T___builtin_va_list: \
222 #define DECLARATION_START \
227 #define DECLARATION_START_NO_EXTERN \
228 STORAGE_CLASSES_NO_EXTERN \
232 #define EXPRESSION_START \
241 case T_CHARACTER_CONSTANT: \
242 case T_FLOATINGPOINT: \
243 case T_FLOATINGPOINT_HEXADECIMAL: \
245 case T_INTEGER_HEXADECIMAL: \
246 case T_INTEGER_OCTAL: \
249 case T_STRING_LITERAL: \
250 case T_WIDE_CHARACTER_CONSTANT: \
251 case T_WIDE_STRING_LITERAL: \
252 case T___FUNCDNAME__: \
253 case T___FUNCSIG__: \
254 case T___FUNCTION__: \
255 case T___PRETTY_FUNCTION__: \
256 case T___alignof__: \
257 case T___builtin_classify_type: \
258 case T___builtin_constant_p: \
259 case T___builtin_isgreater: \
260 case T___builtin_isgreaterequal: \
261 case T___builtin_isless: \
262 case T___builtin_islessequal: \
263 case T___builtin_islessgreater: \
264 case T___builtin_isunordered: \
265 case T___builtin_offsetof: \
266 case T___builtin_va_arg: \
267 case T___builtin_va_copy: \
268 case T___builtin_va_start: \
279 * Returns the size of a statement node.
281 * @param kind the statement kind
283 static size_t get_statement_struct_size(statement_kind_t kind)
285 static const size_t sizes[] = {
286 [STATEMENT_ERROR] = sizeof(statement_base_t),
287 [STATEMENT_EMPTY] = sizeof(statement_base_t),
288 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
289 [STATEMENT_RETURN] = sizeof(return_statement_t),
290 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
291 [STATEMENT_IF] = sizeof(if_statement_t),
292 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
293 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
294 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
295 [STATEMENT_BREAK] = sizeof(statement_base_t),
296 [STATEMENT_GOTO] = sizeof(goto_statement_t),
297 [STATEMENT_LABEL] = sizeof(label_statement_t),
298 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
299 [STATEMENT_WHILE] = sizeof(while_statement_t),
300 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
301 [STATEMENT_FOR] = sizeof(for_statement_t),
302 [STATEMENT_ASM] = sizeof(asm_statement_t),
303 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
304 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
306 assert((size_t)kind < lengthof(sizes));
307 assert(sizes[kind] != 0);
312 * Returns the size of an expression node.
314 * @param kind the expression kind
316 static size_t get_expression_struct_size(expression_kind_t kind)
318 static const size_t sizes[] = {
319 [EXPR_ERROR] = sizeof(expression_base_t),
320 [EXPR_REFERENCE] = sizeof(reference_expression_t),
321 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
322 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
323 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
324 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
326 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
330 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
331 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
332 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
333 [EXPR_CALL] = sizeof(call_expression_t),
334 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
335 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
336 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
337 [EXPR_SELECT] = sizeof(select_expression_t),
338 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
339 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
340 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
341 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
342 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
343 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
344 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
345 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
346 [EXPR_VA_START] = sizeof(va_start_expression_t),
347 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
348 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
349 [EXPR_STATEMENT] = sizeof(statement_expression_t),
350 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
352 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
353 return sizes[EXPR_UNARY_FIRST];
355 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
356 return sizes[EXPR_BINARY_FIRST];
358 assert((size_t)kind < lengthof(sizes));
359 assert(sizes[kind] != 0);
364 * Allocate a statement node of given kind and initialize all
365 * fields with zero. Sets its source position to the position
366 * of the current token.
368 static statement_t *allocate_statement_zero(statement_kind_t kind)
370 size_t size = get_statement_struct_size(kind);
371 statement_t *res = allocate_ast_zero(size);
373 res->base.kind = kind;
374 res->base.parent = current_parent;
375 res->base.source_position = token.base.source_position;
380 * Allocate an expression node of given kind and initialize all
383 * @param kind the kind of the expression to allocate
385 static expression_t *allocate_expression_zero(expression_kind_t kind)
387 size_t size = get_expression_struct_size(kind);
388 expression_t *res = allocate_ast_zero(size);
390 res->base.kind = kind;
391 res->base.type = type_error_type;
392 res->base.source_position = token.base.source_position;
397 * Creates a new invalid expression at the source position
398 * of the current token.
400 static expression_t *create_error_expression(void)
402 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
403 expression->base.type = type_error_type;
408 * Creates a new invalid statement.
410 static statement_t *create_error_statement(void)
412 return allocate_statement_zero(STATEMENT_ERROR);
416 * Allocate a new empty statement.
418 static statement_t *create_empty_statement(void)
420 return allocate_statement_zero(STATEMENT_EMPTY);
424 * Returns the size of an initializer node.
426 * @param kind the initializer kind
428 static size_t get_initializer_size(initializer_kind_t kind)
430 static const size_t sizes[] = {
431 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
432 [INITIALIZER_STRING] = sizeof(initializer_string_t),
433 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
434 [INITIALIZER_LIST] = sizeof(initializer_list_t),
435 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
437 assert((size_t)kind < lengthof(sizes));
438 assert(sizes[kind] != 0);
443 * Allocate an initializer node of given kind and initialize all
446 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
448 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
455 * Returns the index of the top element of the environment stack.
457 static size_t environment_top(void)
459 return ARR_LEN(environment_stack);
463 * Returns the index of the top element of the global label stack.
465 static size_t label_top(void)
467 return ARR_LEN(label_stack);
471 * Return the next token.
473 static inline void next_token(void)
475 token = lookahead_buffer[lookahead_bufpos];
476 lookahead_buffer[lookahead_bufpos] = lexer_token;
479 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
482 print_token(stderr, &token);
483 fprintf(stderr, "\n");
487 static inline bool next_if(int const type)
489 if (token.kind == type) {
498 * Return the next token with a given lookahead.
500 static inline const token_t *look_ahead(size_t num)
502 assert(0 < num && num <= MAX_LOOKAHEAD);
503 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
504 return &lookahead_buffer[pos];
508 * Adds a token type to the token type anchor set (a multi-set).
510 static void add_anchor_token(int token_kind)
512 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
513 ++token_anchor_set[token_kind];
517 * Set the number of tokens types of the given type
518 * to zero and return the old count.
520 static int save_and_reset_anchor_state(int token_kind)
522 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
523 int count = token_anchor_set[token_kind];
524 token_anchor_set[token_kind] = 0;
529 * Restore the number of token types to the given count.
531 static void restore_anchor_state(int token_kind, int count)
533 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
534 token_anchor_set[token_kind] = count;
538 * Remove a token type from the token type anchor set (a multi-set).
540 static void rem_anchor_token(int token_kind)
542 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
543 assert(token_anchor_set[token_kind] != 0);
544 --token_anchor_set[token_kind];
548 * Return true if the token type of the current token is
551 static bool at_anchor(void)
555 return token_anchor_set[token.kind];
559 * Eat tokens until a matching token type is found.
561 static void eat_until_matching_token(int type)
565 case '(': end_token = ')'; break;
566 case '{': end_token = '}'; break;
567 case '[': end_token = ']'; break;
568 default: end_token = type; break;
571 unsigned parenthesis_count = 0;
572 unsigned brace_count = 0;
573 unsigned bracket_count = 0;
574 while (token.kind != end_token ||
575 parenthesis_count != 0 ||
577 bracket_count != 0) {
578 switch (token.kind) {
580 case '(': ++parenthesis_count; break;
581 case '{': ++brace_count; break;
582 case '[': ++bracket_count; break;
585 if (parenthesis_count > 0)
595 if (bracket_count > 0)
598 if (token.kind == end_token &&
599 parenthesis_count == 0 &&
613 * Eat input tokens until an anchor is found.
615 static void eat_until_anchor(void)
617 while (token_anchor_set[token.kind] == 0) {
618 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
619 eat_until_matching_token(token.kind);
625 * Eat a whole block from input tokens.
627 static void eat_block(void)
629 eat_until_matching_token('{');
633 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
636 * Report a parse error because an expected token was not found.
639 #if defined __GNUC__ && __GNUC__ >= 4
640 __attribute__((sentinel))
642 void parse_error_expected(const char *message, ...)
644 if (message != NULL) {
645 errorf(HERE, "%s", message);
648 va_start(ap, message);
649 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
654 * Report an incompatible type.
656 static void type_error_incompatible(const char *msg,
657 const source_position_t *source_position, type_t *type1, type_t *type2)
659 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
664 * Expect the current token is the expected token.
665 * If not, generate an error, eat the current statement,
666 * and goto the error_label label.
668 #define expect(expected, error_label) \
670 if (UNLIKELY(token.kind != (expected))) { \
671 parse_error_expected(NULL, (expected), NULL); \
672 add_anchor_token(expected); \
673 eat_until_anchor(); \
674 rem_anchor_token(expected); \
675 if (token.kind != (expected)) \
682 * Push a given scope on the scope stack and make it the
685 static scope_t *scope_push(scope_t *new_scope)
687 if (current_scope != NULL) {
688 new_scope->depth = current_scope->depth + 1;
691 scope_t *old_scope = current_scope;
692 current_scope = new_scope;
697 * Pop the current scope from the scope stack.
699 static void scope_pop(scope_t *old_scope)
701 current_scope = old_scope;
705 * Search an entity by its symbol in a given namespace.
707 static entity_t *get_entity(const symbol_t *const symbol,
708 namespace_tag_t namespc)
710 entity_t *entity = symbol->entity;
711 for (; entity != NULL; entity = entity->base.symbol_next) {
712 if ((namespace_tag_t)entity->base.namespc == namespc)
719 /* §6.2.3:1 24) There is only one name space for tags even though three are
721 static entity_t *get_tag(symbol_t const *const symbol,
722 entity_kind_tag_t const kind)
724 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
725 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
727 "'%Y' defined as wrong kind of tag (previous definition %P)",
728 symbol, &entity->base.source_position);
735 * pushs an entity on the environment stack and links the corresponding symbol
738 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
740 symbol_t *symbol = entity->base.symbol;
741 entity_namespace_t namespc = entity->base.namespc;
742 assert(namespc != 0);
744 /* replace/add entity into entity list of the symbol */
747 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
752 /* replace an entry? */
753 if (iter->base.namespc == namespc) {
754 entity->base.symbol_next = iter->base.symbol_next;
760 /* remember old declaration */
762 entry.symbol = symbol;
763 entry.old_entity = iter;
764 entry.namespc = namespc;
765 ARR_APP1(stack_entry_t, *stack_ptr, entry);
769 * Push an entity on the environment stack.
771 static void environment_push(entity_t *entity)
773 assert(entity->base.source_position.input_name != NULL);
774 assert(entity->base.parent_scope != NULL);
775 stack_push(&environment_stack, entity);
779 * Push a declaration on the global label stack.
781 * @param declaration the declaration
783 static void label_push(entity_t *label)
785 /* we abuse the parameters scope as parent for the labels */
786 label->base.parent_scope = ¤t_function->parameters;
787 stack_push(&label_stack, label);
791 * pops symbols from the environment stack until @p new_top is the top element
793 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
795 stack_entry_t *stack = *stack_ptr;
796 size_t top = ARR_LEN(stack);
799 assert(new_top <= top);
803 for (i = top; i > new_top; --i) {
804 stack_entry_t *entry = &stack[i - 1];
806 entity_t *old_entity = entry->old_entity;
807 symbol_t *symbol = entry->symbol;
808 entity_namespace_t namespc = entry->namespc;
810 /* replace with old_entity/remove */
813 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
815 assert(iter != NULL);
816 /* replace an entry? */
817 if (iter->base.namespc == namespc)
821 /* restore definition from outer scopes (if there was one) */
822 if (old_entity != NULL) {
823 old_entity->base.symbol_next = iter->base.symbol_next;
824 *anchor = old_entity;
826 /* remove entry from list */
827 *anchor = iter->base.symbol_next;
831 ARR_SHRINKLEN(*stack_ptr, new_top);
835 * Pop all entries from the environment stack until the new_top
838 * @param new_top the new stack top
840 static void environment_pop_to(size_t new_top)
842 stack_pop_to(&environment_stack, new_top);
846 * Pop all entries from the global label stack until the new_top
849 * @param new_top the new stack top
851 static void label_pop_to(size_t new_top)
853 stack_pop_to(&label_stack, new_top);
856 static int get_akind_rank(atomic_type_kind_t akind)
862 * Return the type rank for an atomic type.
864 static int get_rank(const type_t *type)
866 assert(!is_typeref(type));
867 if (type->kind == TYPE_ENUM)
868 return get_akind_rank(type->enumt.akind);
870 assert(type->kind == TYPE_ATOMIC);
871 return get_akind_rank(type->atomic.akind);
875 * §6.3.1.1:2 Do integer promotion for a given type.
877 * @param type the type to promote
878 * @return the promoted type
880 static type_t *promote_integer(type_t *type)
882 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
889 * Check if a given expression represents a null pointer constant.
891 * @param expression the expression to check
893 static bool is_null_pointer_constant(const expression_t *expression)
895 /* skip void* cast */
896 if (expression->kind == EXPR_UNARY_CAST) {
897 type_t *const type = skip_typeref(expression->base.type);
898 if (types_compatible(type, type_void_ptr))
899 expression = expression->unary.value;
902 type_t *const type = skip_typeref(expression->base.type);
903 if (!is_type_integer(type))
905 switch (is_constant_expression(expression)) {
906 case EXPR_CLASS_ERROR: return true;
907 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
908 default: return false;
913 * Create an implicit cast expression.
915 * @param expression the expression to cast
916 * @param dest_type the destination type
918 static expression_t *create_implicit_cast(expression_t *expression,
921 type_t *const source_type = expression->base.type;
923 if (source_type == dest_type)
926 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
927 cast->unary.value = expression;
928 cast->base.type = dest_type;
929 cast->base.implicit = true;
934 typedef enum assign_error_t {
936 ASSIGN_ERROR_INCOMPATIBLE,
937 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
938 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
939 ASSIGN_WARNING_POINTER_FROM_INT,
940 ASSIGN_WARNING_INT_FROM_POINTER
943 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)
945 type_t *const orig_type_right = right->base.type;
946 type_t *const type_left = skip_typeref(orig_type_left);
947 type_t *const type_right = skip_typeref(orig_type_right);
952 case ASSIGN_ERROR_INCOMPATIBLE:
953 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
956 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
957 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
958 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
960 /* the left type has all qualifiers from the right type */
961 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
962 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);
966 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
967 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
970 case ASSIGN_WARNING_POINTER_FROM_INT:
971 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
974 case ASSIGN_WARNING_INT_FROM_POINTER:
975 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
979 panic("invalid error value");
983 /** Implements the rules from §6.5.16.1 */
984 static assign_error_t semantic_assign(type_t *orig_type_left,
985 const expression_t *const right)
987 type_t *const orig_type_right = right->base.type;
988 type_t *const type_left = skip_typeref(orig_type_left);
989 type_t *const type_right = skip_typeref(orig_type_right);
991 if (is_type_pointer(type_left)) {
992 if (is_null_pointer_constant(right)) {
993 return ASSIGN_SUCCESS;
994 } else if (is_type_pointer(type_right)) {
995 type_t *points_to_left
996 = skip_typeref(type_left->pointer.points_to);
997 type_t *points_to_right
998 = skip_typeref(type_right->pointer.points_to);
999 assign_error_t res = ASSIGN_SUCCESS;
1001 /* the left type has all qualifiers from the right type */
1002 unsigned missing_qualifiers
1003 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1004 if (missing_qualifiers != 0) {
1005 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1008 points_to_left = get_unqualified_type(points_to_left);
1009 points_to_right = get_unqualified_type(points_to_right);
1011 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1014 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1015 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1016 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1019 if (!types_compatible(points_to_left, points_to_right)) {
1020 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1024 } else if (is_type_integer(type_right)) {
1025 return ASSIGN_WARNING_POINTER_FROM_INT;
1027 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1028 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1029 && is_type_pointer(type_right))) {
1030 return ASSIGN_SUCCESS;
1031 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1032 type_t *const unqual_type_left = get_unqualified_type(type_left);
1033 type_t *const unqual_type_right = get_unqualified_type(type_right);
1034 if (types_compatible(unqual_type_left, unqual_type_right)) {
1035 return ASSIGN_SUCCESS;
1037 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1038 return ASSIGN_WARNING_INT_FROM_POINTER;
1041 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1042 return ASSIGN_SUCCESS;
1044 return ASSIGN_ERROR_INCOMPATIBLE;
1047 static expression_t *parse_constant_expression(void)
1049 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1051 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1052 errorf(&result->base.source_position,
1053 "expression '%E' is not constant", result);
1059 static expression_t *parse_assignment_expression(void)
1061 return parse_subexpression(PREC_ASSIGNMENT);
1064 static void warn_string_concat(const source_position_t *pos)
1066 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1069 static string_t parse_string_literals(void)
1071 assert(token.kind == T_STRING_LITERAL);
1072 string_t result = token.string.string;
1076 while (token.kind == T_STRING_LITERAL) {
1077 warn_string_concat(&token.base.source_position);
1078 result = concat_strings(&result, &token.string.string);
1086 * compare two string, ignoring double underscores on the second.
1088 static int strcmp_underscore(const char *s1, const char *s2)
1090 if (s2[0] == '_' && s2[1] == '_') {
1091 size_t len2 = strlen(s2);
1092 size_t len1 = strlen(s1);
1093 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1094 return strncmp(s1, s2+2, len2-4);
1098 return strcmp(s1, s2);
1101 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1103 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1104 attribute->kind = kind;
1105 attribute->source_position = *HERE;
1110 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1113 * __attribute__ ( ( attribute-list ) )
1117 * attribute_list , attrib
1122 * any-word ( identifier )
1123 * any-word ( identifier , nonempty-expr-list )
1124 * any-word ( expr-list )
1126 * where the "identifier" must not be declared as a type, and
1127 * "any-word" may be any identifier (including one declared as a
1128 * type), a reserved word storage class specifier, type specifier or
1129 * type qualifier. ??? This still leaves out most reserved keywords
1130 * (following the old parser), shouldn't we include them, and why not
1131 * allow identifiers declared as types to start the arguments?
1133 * Matze: this all looks confusing and little systematic, so we're even less
1134 * strict and parse any list of things which are identifiers or
1135 * (assignment-)expressions.
1137 static attribute_argument_t *parse_attribute_arguments(void)
1139 attribute_argument_t *first = NULL;
1140 attribute_argument_t **anchor = &first;
1141 if (token.kind != ')') do {
1142 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1144 /* is it an identifier */
1145 if (token.kind == T_IDENTIFIER
1146 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1147 symbol_t *symbol = token.identifier.symbol;
1148 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1149 argument->v.symbol = symbol;
1152 /* must be an expression */
1153 expression_t *expression = parse_assignment_expression();
1155 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1156 argument->v.expression = expression;
1159 /* append argument */
1161 anchor = &argument->next;
1162 } while (next_if(','));
1163 expect(')', end_error);
1172 static attribute_t *parse_attribute_asm(void)
1174 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1177 expect('(', end_error);
1178 attribute->a.arguments = parse_attribute_arguments();
1185 static symbol_t *get_symbol_from_token(void)
1187 switch(token.kind) {
1189 return token.identifier.symbol;
1218 /* maybe we need more tokens ... add them on demand */
1219 return get_token_kind_symbol(token.kind);
1225 static attribute_t *parse_attribute_gnu_single(void)
1227 /* parse "any-word" */
1228 symbol_t *symbol = get_symbol_from_token();
1229 if (symbol == NULL) {
1230 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1234 attribute_kind_t kind;
1235 char const *const name = symbol->string;
1236 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1237 if (kind > ATTRIBUTE_GNU_LAST) {
1238 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1239 /* TODO: we should still save the attribute in the list... */
1240 kind = ATTRIBUTE_UNKNOWN;
1244 const char *attribute_name = get_attribute_name(kind);
1245 if (attribute_name != NULL
1246 && strcmp_underscore(attribute_name, name) == 0)
1250 attribute_t *attribute = allocate_attribute_zero(kind);
1253 /* parse arguments */
1255 attribute->a.arguments = parse_attribute_arguments();
1260 static attribute_t *parse_attribute_gnu(void)
1262 attribute_t *first = NULL;
1263 attribute_t **anchor = &first;
1265 eat(T___attribute__);
1266 expect('(', end_error);
1267 expect('(', end_error);
1269 if (token.kind != ')') do {
1270 attribute_t *attribute = parse_attribute_gnu_single();
1271 if (attribute == NULL)
1274 *anchor = attribute;
1275 anchor = &attribute->next;
1276 } while (next_if(','));
1277 expect(')', end_error);
1278 expect(')', end_error);
1284 /** Parse attributes. */
1285 static attribute_t *parse_attributes(attribute_t *first)
1287 attribute_t **anchor = &first;
1289 while (*anchor != NULL)
1290 anchor = &(*anchor)->next;
1292 attribute_t *attribute;
1293 switch (token.kind) {
1294 case T___attribute__:
1295 attribute = parse_attribute_gnu();
1296 if (attribute == NULL)
1301 attribute = parse_attribute_asm();
1305 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1310 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1314 case T__forceinline:
1315 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1316 eat(T__forceinline);
1320 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1325 /* TODO record modifier */
1326 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1327 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1335 *anchor = attribute;
1336 anchor = &attribute->next;
1340 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1342 static entity_t *determine_lhs_ent(expression_t *const expr,
1345 switch (expr->kind) {
1346 case EXPR_REFERENCE: {
1347 entity_t *const entity = expr->reference.entity;
1348 /* we should only find variables as lvalues... */
1349 if (entity->base.kind != ENTITY_VARIABLE
1350 && entity->base.kind != ENTITY_PARAMETER)
1356 case EXPR_ARRAY_ACCESS: {
1357 expression_t *const ref = expr->array_access.array_ref;
1358 entity_t * ent = NULL;
1359 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1360 ent = determine_lhs_ent(ref, lhs_ent);
1363 mark_vars_read(ref, lhs_ent);
1365 mark_vars_read(expr->array_access.index, lhs_ent);
1370 mark_vars_read(expr->select.compound, lhs_ent);
1371 if (is_type_compound(skip_typeref(expr->base.type)))
1372 return determine_lhs_ent(expr->select.compound, lhs_ent);
1376 case EXPR_UNARY_DEREFERENCE: {
1377 expression_t *const val = expr->unary.value;
1378 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1380 return determine_lhs_ent(val->unary.value, lhs_ent);
1382 mark_vars_read(val, NULL);
1388 mark_vars_read(expr, NULL);
1393 #define ENT_ANY ((entity_t*)-1)
1396 * Mark declarations, which are read. This is used to detect variables, which
1400 * x is not marked as "read", because it is only read to calculate its own new
1404 * x and y are not detected as "not read", because multiple variables are
1407 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1409 switch (expr->kind) {
1410 case EXPR_REFERENCE: {
1411 entity_t *const entity = expr->reference.entity;
1412 if (entity->kind != ENTITY_VARIABLE
1413 && entity->kind != ENTITY_PARAMETER)
1416 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1417 if (entity->kind == ENTITY_VARIABLE) {
1418 entity->variable.read = true;
1420 entity->parameter.read = true;
1427 // TODO respect pure/const
1428 mark_vars_read(expr->call.function, NULL);
1429 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1430 mark_vars_read(arg->expression, NULL);
1434 case EXPR_CONDITIONAL:
1435 // TODO lhs_decl should depend on whether true/false have an effect
1436 mark_vars_read(expr->conditional.condition, NULL);
1437 if (expr->conditional.true_expression != NULL)
1438 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1439 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1443 if (lhs_ent == ENT_ANY
1444 && !is_type_compound(skip_typeref(expr->base.type)))
1446 mark_vars_read(expr->select.compound, lhs_ent);
1449 case EXPR_ARRAY_ACCESS: {
1450 mark_vars_read(expr->array_access.index, lhs_ent);
1451 expression_t *const ref = expr->array_access.array_ref;
1452 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1453 if (lhs_ent == ENT_ANY)
1456 mark_vars_read(ref, lhs_ent);
1461 mark_vars_read(expr->va_arge.ap, lhs_ent);
1465 mark_vars_read(expr->va_copye.src, lhs_ent);
1468 case EXPR_UNARY_CAST:
1469 /* Special case: Use void cast to mark a variable as "read" */
1470 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1475 case EXPR_UNARY_THROW:
1476 if (expr->unary.value == NULL)
1479 case EXPR_UNARY_DEREFERENCE:
1480 case EXPR_UNARY_DELETE:
1481 case EXPR_UNARY_DELETE_ARRAY:
1482 if (lhs_ent == ENT_ANY)
1486 case EXPR_UNARY_NEGATE:
1487 case EXPR_UNARY_PLUS:
1488 case EXPR_UNARY_BITWISE_NEGATE:
1489 case EXPR_UNARY_NOT:
1490 case EXPR_UNARY_TAKE_ADDRESS:
1491 case EXPR_UNARY_POSTFIX_INCREMENT:
1492 case EXPR_UNARY_POSTFIX_DECREMENT:
1493 case EXPR_UNARY_PREFIX_INCREMENT:
1494 case EXPR_UNARY_PREFIX_DECREMENT:
1495 case EXPR_UNARY_ASSUME:
1497 mark_vars_read(expr->unary.value, lhs_ent);
1500 case EXPR_BINARY_ADD:
1501 case EXPR_BINARY_SUB:
1502 case EXPR_BINARY_MUL:
1503 case EXPR_BINARY_DIV:
1504 case EXPR_BINARY_MOD:
1505 case EXPR_BINARY_EQUAL:
1506 case EXPR_BINARY_NOTEQUAL:
1507 case EXPR_BINARY_LESS:
1508 case EXPR_BINARY_LESSEQUAL:
1509 case EXPR_BINARY_GREATER:
1510 case EXPR_BINARY_GREATEREQUAL:
1511 case EXPR_BINARY_BITWISE_AND:
1512 case EXPR_BINARY_BITWISE_OR:
1513 case EXPR_BINARY_BITWISE_XOR:
1514 case EXPR_BINARY_LOGICAL_AND:
1515 case EXPR_BINARY_LOGICAL_OR:
1516 case EXPR_BINARY_SHIFTLEFT:
1517 case EXPR_BINARY_SHIFTRIGHT:
1518 case EXPR_BINARY_COMMA:
1519 case EXPR_BINARY_ISGREATER:
1520 case EXPR_BINARY_ISGREATEREQUAL:
1521 case EXPR_BINARY_ISLESS:
1522 case EXPR_BINARY_ISLESSEQUAL:
1523 case EXPR_BINARY_ISLESSGREATER:
1524 case EXPR_BINARY_ISUNORDERED:
1525 mark_vars_read(expr->binary.left, lhs_ent);
1526 mark_vars_read(expr->binary.right, lhs_ent);
1529 case EXPR_BINARY_ASSIGN:
1530 case EXPR_BINARY_MUL_ASSIGN:
1531 case EXPR_BINARY_DIV_ASSIGN:
1532 case EXPR_BINARY_MOD_ASSIGN:
1533 case EXPR_BINARY_ADD_ASSIGN:
1534 case EXPR_BINARY_SUB_ASSIGN:
1535 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1536 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1537 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1538 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1539 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1540 if (lhs_ent == ENT_ANY)
1542 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1543 mark_vars_read(expr->binary.right, lhs_ent);
1548 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1553 case EXPR_STRING_LITERAL:
1554 case EXPR_WIDE_STRING_LITERAL:
1555 case EXPR_COMPOUND_LITERAL: // TODO init?
1557 case EXPR_CLASSIFY_TYPE:
1560 case EXPR_BUILTIN_CONSTANT_P:
1561 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1563 case EXPR_STATEMENT: // TODO
1564 case EXPR_LABEL_ADDRESS:
1565 case EXPR_REFERENCE_ENUM_VALUE:
1569 panic("unhandled expression");
1572 static designator_t *parse_designation(void)
1574 designator_t *result = NULL;
1575 designator_t **anchor = &result;
1578 designator_t *designator;
1579 switch (token.kind) {
1581 designator = allocate_ast_zero(sizeof(designator[0]));
1582 designator->source_position = token.base.source_position;
1584 add_anchor_token(']');
1585 designator->array_index = parse_constant_expression();
1586 rem_anchor_token(']');
1587 expect(']', end_error);
1590 designator = allocate_ast_zero(sizeof(designator[0]));
1591 designator->source_position = token.base.source_position;
1593 if (token.kind != T_IDENTIFIER) {
1594 parse_error_expected("while parsing designator",
1595 T_IDENTIFIER, NULL);
1598 designator->symbol = token.identifier.symbol;
1602 expect('=', end_error);
1606 assert(designator != NULL);
1607 *anchor = designator;
1608 anchor = &designator->next;
1614 static initializer_t *initializer_from_string(array_type_t *const type,
1615 const string_t *const string)
1617 /* TODO: check len vs. size of array type */
1620 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1621 initializer->string.string = *string;
1626 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1627 const string_t *const string)
1629 /* TODO: check len vs. size of array type */
1632 initializer_t *const initializer =
1633 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1634 initializer->wide_string.string = *string;
1640 * Build an initializer from a given expression.
1642 static initializer_t *initializer_from_expression(type_t *orig_type,
1643 expression_t *expression)
1645 /* TODO check that expression is a constant expression */
1647 /* §6.7.8.14/15 char array may be initialized by string literals */
1648 type_t *type = skip_typeref(orig_type);
1649 type_t *expr_type_orig = expression->base.type;
1650 type_t *expr_type = skip_typeref(expr_type_orig);
1652 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1653 array_type_t *const array_type = &type->array;
1654 type_t *const element_type = skip_typeref(array_type->element_type);
1656 if (element_type->kind == TYPE_ATOMIC) {
1657 atomic_type_kind_t akind = element_type->atomic.akind;
1658 switch (expression->kind) {
1659 case EXPR_STRING_LITERAL:
1660 if (akind == ATOMIC_TYPE_CHAR
1661 || akind == ATOMIC_TYPE_SCHAR
1662 || akind == ATOMIC_TYPE_UCHAR) {
1663 return initializer_from_string(array_type,
1664 &expression->string_literal.value);
1668 case EXPR_WIDE_STRING_LITERAL: {
1669 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1670 if (get_unqualified_type(element_type) == bare_wchar_type) {
1671 return initializer_from_wide_string(array_type,
1672 &expression->string_literal.value);
1683 assign_error_t error = semantic_assign(type, expression);
1684 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1686 report_assign_error(error, type, expression, "initializer",
1687 &expression->base.source_position);
1689 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1690 result->value.value = create_implicit_cast(expression, type);
1696 * Checks if a given expression can be used as a constant initializer.
1698 static bool is_initializer_constant(const expression_t *expression)
1700 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1701 is_linker_constant(expression) != EXPR_CLASS_VARIABLE;
1705 * Parses an scalar initializer.
1707 * §6.7.8.11; eat {} without warning
1709 static initializer_t *parse_scalar_initializer(type_t *type,
1710 bool must_be_constant)
1712 /* there might be extra {} hierarchies */
1714 if (token.kind == '{') {
1715 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1719 } while (token.kind == '{');
1722 expression_t *expression = parse_assignment_expression();
1723 mark_vars_read(expression, NULL);
1724 if (must_be_constant && !is_initializer_constant(expression)) {
1725 errorf(&expression->base.source_position,
1726 "initialisation expression '%E' is not constant",
1730 initializer_t *initializer = initializer_from_expression(type, expression);
1732 if (initializer == NULL) {
1733 errorf(&expression->base.source_position,
1734 "expression '%E' (type '%T') doesn't match expected type '%T'",
1735 expression, expression->base.type, type);
1740 bool additional_warning_displayed = false;
1741 while (braces > 0) {
1743 if (token.kind != '}') {
1744 if (!additional_warning_displayed) {
1745 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1746 additional_warning_displayed = true;
1757 * An entry in the type path.
1759 typedef struct type_path_entry_t type_path_entry_t;
1760 struct type_path_entry_t {
1761 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1763 size_t index; /**< For array types: the current index. */
1764 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1769 * A type path expression a position inside compound or array types.
1771 typedef struct type_path_t type_path_t;
1772 struct type_path_t {
1773 type_path_entry_t *path; /**< An flexible array containing the current path. */
1774 type_t *top_type; /**< type of the element the path points */
1775 size_t max_index; /**< largest index in outermost array */
1779 * Prints a type path for debugging.
1781 static __attribute__((unused)) void debug_print_type_path(
1782 const type_path_t *path)
1784 size_t len = ARR_LEN(path->path);
1786 for (size_t i = 0; i < len; ++i) {
1787 const type_path_entry_t *entry = & path->path[i];
1789 type_t *type = skip_typeref(entry->type);
1790 if (is_type_compound(type)) {
1791 /* in gcc mode structs can have no members */
1792 if (entry->v.compound_entry == NULL) {
1796 fprintf(stderr, ".%s",
1797 entry->v.compound_entry->base.symbol->string);
1798 } else if (is_type_array(type)) {
1799 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1801 fprintf(stderr, "-INVALID-");
1804 if (path->top_type != NULL) {
1805 fprintf(stderr, " (");
1806 print_type(path->top_type);
1807 fprintf(stderr, ")");
1812 * Return the top type path entry, ie. in a path
1813 * (type).a.b returns the b.
1815 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1817 size_t len = ARR_LEN(path->path);
1819 return &path->path[len-1];
1823 * Enlarge the type path by an (empty) element.
1825 static type_path_entry_t *append_to_type_path(type_path_t *path)
1827 size_t len = ARR_LEN(path->path);
1828 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1830 type_path_entry_t *result = & path->path[len];
1831 memset(result, 0, sizeof(result[0]));
1836 * Descending into a sub-type. Enter the scope of the current top_type.
1838 static void descend_into_subtype(type_path_t *path)
1840 type_t *orig_top_type = path->top_type;
1841 type_t *top_type = skip_typeref(orig_top_type);
1843 type_path_entry_t *top = append_to_type_path(path);
1844 top->type = top_type;
1846 if (is_type_compound(top_type)) {
1847 compound_t *compound = top_type->compound.compound;
1848 entity_t *entry = compound->members.entities;
1850 if (entry != NULL) {
1851 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1852 top->v.compound_entry = &entry->declaration;
1853 path->top_type = entry->declaration.type;
1855 path->top_type = NULL;
1857 } else if (is_type_array(top_type)) {
1859 path->top_type = top_type->array.element_type;
1861 assert(!is_type_valid(top_type));
1866 * Pop an entry from the given type path, ie. returning from
1867 * (type).a.b to (type).a
1869 static void ascend_from_subtype(type_path_t *path)
1871 type_path_entry_t *top = get_type_path_top(path);
1873 path->top_type = top->type;
1875 size_t len = ARR_LEN(path->path);
1876 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1880 * Pop entries from the given type path until the given
1881 * path level is reached.
1883 static void ascend_to(type_path_t *path, size_t top_path_level)
1885 size_t len = ARR_LEN(path->path);
1887 while (len > top_path_level) {
1888 ascend_from_subtype(path);
1889 len = ARR_LEN(path->path);
1893 static bool walk_designator(type_path_t *path, const designator_t *designator,
1894 bool used_in_offsetof)
1896 for (; designator != NULL; designator = designator->next) {
1897 type_path_entry_t *top = get_type_path_top(path);
1898 type_t *orig_type = top->type;
1900 type_t *type = skip_typeref(orig_type);
1902 if (designator->symbol != NULL) {
1903 symbol_t *symbol = designator->symbol;
1904 if (!is_type_compound(type)) {
1905 if (is_type_valid(type)) {
1906 errorf(&designator->source_position,
1907 "'.%Y' designator used for non-compound type '%T'",
1911 top->type = type_error_type;
1912 top->v.compound_entry = NULL;
1913 orig_type = type_error_type;
1915 compound_t *compound = type->compound.compound;
1916 entity_t *iter = compound->members.entities;
1917 for (; iter != NULL; iter = iter->base.next) {
1918 if (iter->base.symbol == symbol) {
1923 errorf(&designator->source_position,
1924 "'%T' has no member named '%Y'", orig_type, symbol);
1927 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1928 if (used_in_offsetof && iter->compound_member.bitfield) {
1929 errorf(&designator->source_position,
1930 "offsetof designator '%Y' must not specify bitfield",
1935 top->type = orig_type;
1936 top->v.compound_entry = &iter->declaration;
1937 orig_type = iter->declaration.type;
1940 expression_t *array_index = designator->array_index;
1941 assert(designator->array_index != NULL);
1943 if (!is_type_array(type)) {
1944 if (is_type_valid(type)) {
1945 errorf(&designator->source_position,
1946 "[%E] designator used for non-array type '%T'",
1947 array_index, orig_type);
1952 long index = fold_constant_to_int(array_index);
1953 if (!used_in_offsetof) {
1955 errorf(&designator->source_position,
1956 "array index [%E] must be positive", array_index);
1957 } else if (type->array.size_constant) {
1958 long array_size = type->array.size;
1959 if (index >= array_size) {
1960 errorf(&designator->source_position,
1961 "designator [%E] (%d) exceeds array size %d",
1962 array_index, index, array_size);
1967 top->type = orig_type;
1968 top->v.index = (size_t) index;
1969 orig_type = type->array.element_type;
1971 path->top_type = orig_type;
1973 if (designator->next != NULL) {
1974 descend_into_subtype(path);
1980 static void advance_current_object(type_path_t *path, size_t top_path_level)
1982 type_path_entry_t *top = get_type_path_top(path);
1984 type_t *type = skip_typeref(top->type);
1985 if (is_type_union(type)) {
1986 /* in unions only the first element is initialized */
1987 top->v.compound_entry = NULL;
1988 } else if (is_type_struct(type)) {
1989 declaration_t *entry = top->v.compound_entry;
1991 entity_t *next_entity = entry->base.next;
1992 if (next_entity != NULL) {
1993 assert(is_declaration(next_entity));
1994 entry = &next_entity->declaration;
1999 top->v.compound_entry = entry;
2000 if (entry != NULL) {
2001 path->top_type = entry->type;
2004 } else if (is_type_array(type)) {
2005 assert(is_type_array(type));
2009 if (!type->array.size_constant || top->v.index < type->array.size) {
2013 assert(!is_type_valid(type));
2017 /* we're past the last member of the current sub-aggregate, try if we
2018 * can ascend in the type hierarchy and continue with another subobject */
2019 size_t len = ARR_LEN(path->path);
2021 if (len > top_path_level) {
2022 ascend_from_subtype(path);
2023 advance_current_object(path, top_path_level);
2025 path->top_type = NULL;
2030 * skip any {...} blocks until a closing bracket is reached.
2032 static void skip_initializers(void)
2036 while (token.kind != '}') {
2037 if (token.kind == T_EOF)
2039 if (token.kind == '{') {
2047 static initializer_t *create_empty_initializer(void)
2049 static initializer_t empty_initializer
2050 = { .list = { { INITIALIZER_LIST }, 0 } };
2051 return &empty_initializer;
2055 * Parse a part of an initialiser for a struct or union,
2057 static initializer_t *parse_sub_initializer(type_path_t *path,
2058 type_t *outer_type, size_t top_path_level,
2059 parse_initializer_env_t *env)
2061 if (token.kind == '}') {
2062 /* empty initializer */
2063 return create_empty_initializer();
2066 type_t *orig_type = path->top_type;
2067 type_t *type = NULL;
2069 if (orig_type == NULL) {
2070 /* We are initializing an empty compound. */
2072 type = skip_typeref(orig_type);
2075 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2078 designator_t *designator = NULL;
2079 if (token.kind == '.' || token.kind == '[') {
2080 designator = parse_designation();
2081 goto finish_designator;
2082 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2083 /* GNU-style designator ("identifier: value") */
2084 designator = allocate_ast_zero(sizeof(designator[0]));
2085 designator->source_position = token.base.source_position;
2086 designator->symbol = token.identifier.symbol;
2091 /* reset path to toplevel, evaluate designator from there */
2092 ascend_to(path, top_path_level);
2093 if (!walk_designator(path, designator, false)) {
2094 /* can't continue after designation error */
2098 initializer_t *designator_initializer
2099 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2100 designator_initializer->designator.designator = designator;
2101 ARR_APP1(initializer_t*, initializers, designator_initializer);
2103 orig_type = path->top_type;
2104 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2109 if (token.kind == '{') {
2110 if (type != NULL && is_type_scalar(type)) {
2111 sub = parse_scalar_initializer(type, env->must_be_constant);
2114 if (env->entity != NULL) {
2116 "extra brace group at end of initializer for '%Y'",
2117 env->entity->base.symbol);
2119 errorf(HERE, "extra brace group at end of initializer");
2124 descend_into_subtype(path);
2127 add_anchor_token('}');
2128 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2130 rem_anchor_token('}');
2133 ascend_from_subtype(path);
2134 expect('}', end_error);
2136 expect('}', end_error);
2137 goto error_parse_next;
2141 /* must be an expression */
2142 expression_t *expression = parse_assignment_expression();
2143 mark_vars_read(expression, NULL);
2145 if (env->must_be_constant && !is_initializer_constant(expression)) {
2146 errorf(&expression->base.source_position,
2147 "Initialisation expression '%E' is not constant",
2152 /* we are already outside, ... */
2153 if (outer_type == NULL)
2154 goto error_parse_next;
2155 type_t *const outer_type_skip = skip_typeref(outer_type);
2156 if (is_type_compound(outer_type_skip) &&
2157 !outer_type_skip->compound.compound->complete) {
2158 goto error_parse_next;
2161 source_position_t const* const pos = &expression->base.source_position;
2162 if (env->entity != NULL) {
2163 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2165 warningf(WARN_OTHER, pos, "excess elements in initializer");
2167 goto error_parse_next;
2170 /* handle { "string" } special case */
2171 if ((expression->kind == EXPR_STRING_LITERAL
2172 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2173 && outer_type != NULL) {
2174 sub = initializer_from_expression(outer_type, expression);
2177 if (token.kind != '}') {
2178 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2180 /* TODO: eat , ... */
2185 /* descend into subtypes until expression matches type */
2187 orig_type = path->top_type;
2188 type = skip_typeref(orig_type);
2190 sub = initializer_from_expression(orig_type, expression);
2194 if (!is_type_valid(type)) {
2197 if (is_type_scalar(type)) {
2198 errorf(&expression->base.source_position,
2199 "expression '%E' doesn't match expected type '%T'",
2200 expression, orig_type);
2204 descend_into_subtype(path);
2208 /* update largest index of top array */
2209 const type_path_entry_t *first = &path->path[0];
2210 type_t *first_type = first->type;
2211 first_type = skip_typeref(first_type);
2212 if (is_type_array(first_type)) {
2213 size_t index = first->v.index;
2214 if (index > path->max_index)
2215 path->max_index = index;
2218 /* append to initializers list */
2219 ARR_APP1(initializer_t*, initializers, sub);
2222 if (token.kind == '}') {
2225 expect(',', end_error);
2226 if (token.kind == '}') {
2231 /* advance to the next declaration if we are not at the end */
2232 advance_current_object(path, top_path_level);
2233 orig_type = path->top_type;
2234 if (orig_type != NULL)
2235 type = skip_typeref(orig_type);
2241 size_t len = ARR_LEN(initializers);
2242 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2243 initializer_t *result = allocate_ast_zero(size);
2244 result->kind = INITIALIZER_LIST;
2245 result->list.len = len;
2246 memcpy(&result->list.initializers, initializers,
2247 len * sizeof(initializers[0]));
2249 DEL_ARR_F(initializers);
2250 ascend_to(path, top_path_level+1);
2255 skip_initializers();
2256 DEL_ARR_F(initializers);
2257 ascend_to(path, top_path_level+1);
2261 static expression_t *make_size_literal(size_t value)
2263 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2264 literal->base.type = type_size_t;
2267 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2268 literal->literal.value = make_string(buf);
2274 * Parses an initializer. Parsers either a compound literal
2275 * (env->declaration == NULL) or an initializer of a declaration.
2277 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2279 type_t *type = skip_typeref(env->type);
2280 size_t max_index = 0;
2281 initializer_t *result;
2283 if (is_type_scalar(type)) {
2284 result = parse_scalar_initializer(type, env->must_be_constant);
2285 } else if (token.kind == '{') {
2289 memset(&path, 0, sizeof(path));
2290 path.top_type = env->type;
2291 path.path = NEW_ARR_F(type_path_entry_t, 0);
2293 descend_into_subtype(&path);
2295 add_anchor_token('}');
2296 result = parse_sub_initializer(&path, env->type, 1, env);
2297 rem_anchor_token('}');
2299 max_index = path.max_index;
2300 DEL_ARR_F(path.path);
2302 expect('}', end_error);
2305 /* parse_scalar_initializer() also works in this case: we simply
2306 * have an expression without {} around it */
2307 result = parse_scalar_initializer(type, env->must_be_constant);
2310 /* §6.7.8:22 array initializers for arrays with unknown size determine
2311 * the array type size */
2312 if (is_type_array(type) && type->array.size_expression == NULL
2313 && result != NULL) {
2315 switch (result->kind) {
2316 case INITIALIZER_LIST:
2317 assert(max_index != 0xdeadbeaf);
2318 size = max_index + 1;
2321 case INITIALIZER_STRING:
2322 size = result->string.string.size;
2325 case INITIALIZER_WIDE_STRING:
2326 size = result->wide_string.string.size;
2329 case INITIALIZER_DESIGNATOR:
2330 case INITIALIZER_VALUE:
2331 /* can happen for parse errors */
2336 internal_errorf(HERE, "invalid initializer type");
2339 type_t *new_type = duplicate_type(type);
2341 new_type->array.size_expression = make_size_literal(size);
2342 new_type->array.size_constant = true;
2343 new_type->array.has_implicit_size = true;
2344 new_type->array.size = size;
2345 env->type = new_type;
2351 static void append_entity(scope_t *scope, entity_t *entity)
2353 if (scope->last_entity != NULL) {
2354 scope->last_entity->base.next = entity;
2356 scope->entities = entity;
2358 entity->base.parent_entity = current_entity;
2359 scope->last_entity = entity;
2363 static compound_t *parse_compound_type_specifier(bool is_struct)
2365 source_position_t const pos = *HERE;
2366 eat(is_struct ? T_struct : T_union);
2368 symbol_t *symbol = NULL;
2369 entity_t *entity = NULL;
2370 attribute_t *attributes = NULL;
2372 if (token.kind == T___attribute__) {
2373 attributes = parse_attributes(NULL);
2376 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2377 if (token.kind == T_IDENTIFIER) {
2378 /* the compound has a name, check if we have seen it already */
2379 symbol = token.identifier.symbol;
2380 entity = get_tag(symbol, kind);
2383 if (entity != NULL) {
2384 if (entity->base.parent_scope != current_scope &&
2385 (token.kind == '{' || token.kind == ';')) {
2386 /* we're in an inner scope and have a definition. Shadow
2387 * existing definition in outer scope */
2389 } else if (entity->compound.complete && token.kind == '{') {
2390 source_position_t const *const ppos = &entity->base.source_position;
2391 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2392 /* clear members in the hope to avoid further errors */
2393 entity->compound.members.entities = NULL;
2396 } else if (token.kind != '{') {
2397 char const *const msg =
2398 is_struct ? "while parsing struct type specifier" :
2399 "while parsing union type specifier";
2400 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2405 if (entity == NULL) {
2406 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2407 entity->compound.alignment = 1;
2408 entity->base.source_position = pos;
2409 entity->base.parent_scope = current_scope;
2410 if (symbol != NULL) {
2411 environment_push(entity);
2413 append_entity(current_scope, entity);
2416 if (token.kind == '{') {
2417 parse_compound_type_entries(&entity->compound);
2419 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2420 if (symbol == NULL) {
2421 assert(anonymous_entity == NULL);
2422 anonymous_entity = entity;
2426 if (attributes != NULL) {
2427 handle_entity_attributes(attributes, entity);
2430 return &entity->compound;
2433 static void parse_enum_entries(type_t *const enum_type)
2437 if (token.kind == '}') {
2438 errorf(HERE, "empty enum not allowed");
2443 add_anchor_token('}');
2445 if (token.kind != T_IDENTIFIER) {
2446 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2448 rem_anchor_token('}');
2452 symbol_t *symbol = token.identifier.symbol;
2453 entity_t *const entity
2454 = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol);
2455 entity->enum_value.enum_type = enum_type;
2456 entity->base.source_position = token.base.source_position;
2460 expression_t *value = parse_constant_expression();
2462 value = create_implicit_cast(value, enum_type);
2463 entity->enum_value.value = value;
2468 record_entity(entity, false);
2469 } while (next_if(',') && token.kind != '}');
2470 rem_anchor_token('}');
2472 expect('}', end_error);
2478 static type_t *parse_enum_specifier(void)
2480 source_position_t const pos = *HERE;
2485 switch (token.kind) {
2487 symbol = token.identifier.symbol;
2488 entity = get_tag(symbol, ENTITY_ENUM);
2491 if (entity != NULL) {
2492 if (entity->base.parent_scope != current_scope &&
2493 (token.kind == '{' || token.kind == ';')) {
2494 /* we're in an inner scope and have a definition. Shadow
2495 * existing definition in outer scope */
2497 } else if (entity->enume.complete && token.kind == '{') {
2498 source_position_t const *const ppos = &entity->base.source_position;
2499 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2510 parse_error_expected("while parsing enum type specifier",
2511 T_IDENTIFIER, '{', NULL);
2515 if (entity == NULL) {
2516 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2517 entity->base.source_position = pos;
2518 entity->base.parent_scope = current_scope;
2521 type_t *const type = allocate_type_zero(TYPE_ENUM);
2522 type->enumt.enume = &entity->enume;
2523 type->enumt.akind = ATOMIC_TYPE_INT;
2525 if (token.kind == '{') {
2526 if (symbol != NULL) {
2527 environment_push(entity);
2529 append_entity(current_scope, entity);
2530 entity->enume.complete = true;
2532 parse_enum_entries(type);
2533 parse_attributes(NULL);
2535 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2536 if (symbol == NULL) {
2537 assert(anonymous_entity == NULL);
2538 anonymous_entity = entity;
2540 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2541 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2548 * if a symbol is a typedef to another type, return true
2550 static bool is_typedef_symbol(symbol_t *symbol)
2552 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2553 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2556 static type_t *parse_typeof(void)
2562 expect('(', end_error);
2563 add_anchor_token(')');
2565 expression_t *expression = NULL;
2567 switch (token.kind) {
2569 if (is_typedef_symbol(token.identifier.symbol)) {
2571 type = parse_typename();
2574 expression = parse_expression();
2575 type = revert_automatic_type_conversion(expression);
2580 rem_anchor_token(')');
2581 expect(')', end_error);
2583 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2584 typeof_type->typeoft.expression = expression;
2585 typeof_type->typeoft.typeof_type = type;
2592 typedef enum specifiers_t {
2593 SPECIFIER_SIGNED = 1 << 0,
2594 SPECIFIER_UNSIGNED = 1 << 1,
2595 SPECIFIER_LONG = 1 << 2,
2596 SPECIFIER_INT = 1 << 3,
2597 SPECIFIER_DOUBLE = 1 << 4,
2598 SPECIFIER_CHAR = 1 << 5,
2599 SPECIFIER_WCHAR_T = 1 << 6,
2600 SPECIFIER_SHORT = 1 << 7,
2601 SPECIFIER_LONG_LONG = 1 << 8,
2602 SPECIFIER_FLOAT = 1 << 9,
2603 SPECIFIER_BOOL = 1 << 10,
2604 SPECIFIER_VOID = 1 << 11,
2605 SPECIFIER_INT8 = 1 << 12,
2606 SPECIFIER_INT16 = 1 << 13,
2607 SPECIFIER_INT32 = 1 << 14,
2608 SPECIFIER_INT64 = 1 << 15,
2609 SPECIFIER_INT128 = 1 << 16,
2610 SPECIFIER_COMPLEX = 1 << 17,
2611 SPECIFIER_IMAGINARY = 1 << 18,
2614 static type_t *get_typedef_type(symbol_t *symbol)
2616 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2617 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2620 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2621 type->typedeft.typedefe = &entity->typedefe;
2626 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2628 expect('(', end_error);
2630 attribute_property_argument_t *property
2631 = allocate_ast_zero(sizeof(*property));
2634 if (token.kind != T_IDENTIFIER) {
2635 parse_error_expected("while parsing property declspec",
2636 T_IDENTIFIER, NULL);
2641 symbol_t *symbol = token.identifier.symbol;
2642 if (strcmp(symbol->string, "put") == 0) {
2643 prop = &property->put_symbol;
2644 } else if (strcmp(symbol->string, "get") == 0) {
2645 prop = &property->get_symbol;
2647 errorf(HERE, "expected put or get in property declspec");
2651 expect('=', end_error);
2652 if (token.kind != T_IDENTIFIER) {
2653 parse_error_expected("while parsing property declspec",
2654 T_IDENTIFIER, NULL);
2658 *prop = token.identifier.symbol;
2660 } while (next_if(','));
2662 attribute->a.property = property;
2664 expect(')', end_error);
2670 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2672 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2673 if (next_if(T_restrict)) {
2674 kind = ATTRIBUTE_MS_RESTRICT;
2675 } else if (token.kind == T_IDENTIFIER) {
2676 const char *name = token.identifier.symbol->string;
2677 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2679 const char *attribute_name = get_attribute_name(k);
2680 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2686 if (kind == ATTRIBUTE_UNKNOWN) {
2687 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2690 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2694 attribute_t *attribute = allocate_attribute_zero(kind);
2697 if (kind == ATTRIBUTE_MS_PROPERTY) {
2698 return parse_attribute_ms_property(attribute);
2701 /* parse arguments */
2703 attribute->a.arguments = parse_attribute_arguments();
2708 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2712 expect('(', end_error);
2717 add_anchor_token(')');
2719 attribute_t **anchor = &first;
2721 while (*anchor != NULL)
2722 anchor = &(*anchor)->next;
2724 attribute_t *attribute
2725 = parse_microsoft_extended_decl_modifier_single();
2726 if (attribute == NULL)
2729 *anchor = attribute;
2730 anchor = &attribute->next;
2731 } while (next_if(','));
2733 rem_anchor_token(')');
2734 expect(')', end_error);
2738 rem_anchor_token(')');
2742 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2744 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2745 entity->base.source_position = *HERE;
2746 if (is_declaration(entity)) {
2747 entity->declaration.type = type_error_type;
2748 entity->declaration.implicit = true;
2749 } else if (kind == ENTITY_TYPEDEF) {
2750 entity->typedefe.type = type_error_type;
2751 entity->typedefe.builtin = true;
2753 if (kind != ENTITY_COMPOUND_MEMBER)
2754 record_entity(entity, false);
2758 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2760 type_t *type = NULL;
2761 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2762 unsigned type_specifiers = 0;
2763 bool newtype = false;
2764 bool saw_error = false;
2766 memset(specifiers, 0, sizeof(*specifiers));
2767 specifiers->source_position = token.base.source_position;
2770 specifiers->attributes = parse_attributes(specifiers->attributes);
2772 switch (token.kind) {
2774 #define MATCH_STORAGE_CLASS(token, class) \
2776 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2777 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2779 specifiers->storage_class = class; \
2780 if (specifiers->thread_local) \
2781 goto check_thread_storage_class; \
2785 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2786 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2787 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2788 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2789 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2792 specifiers->attributes
2793 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2797 if (specifiers->thread_local) {
2798 errorf(HERE, "duplicate '__thread'");
2800 specifiers->thread_local = true;
2801 check_thread_storage_class:
2802 switch (specifiers->storage_class) {
2803 case STORAGE_CLASS_EXTERN:
2804 case STORAGE_CLASS_NONE:
2805 case STORAGE_CLASS_STATIC:
2809 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2810 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2811 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2812 wrong_thread_storage_class:
2813 errorf(HERE, "'__thread' used with '%s'", wrong);
2820 /* type qualifiers */
2821 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2823 qualifiers |= qualifier; \
2827 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2828 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2829 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2830 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2831 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2832 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2833 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2834 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2836 /* type specifiers */
2837 #define MATCH_SPECIFIER(token, specifier, name) \
2839 if (type_specifiers & specifier) { \
2840 errorf(HERE, "multiple " name " type specifiers given"); \
2842 type_specifiers |= specifier; \
2847 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2848 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2849 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2850 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2851 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2852 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2853 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2854 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2855 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2856 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2857 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2858 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2859 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2860 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2861 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2862 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2863 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2864 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2868 specifiers->is_inline = true;
2872 case T__forceinline:
2874 specifiers->modifiers |= DM_FORCEINLINE;
2879 if (type_specifiers & SPECIFIER_LONG_LONG) {
2880 errorf(HERE, "too many long type specifiers given");
2881 } else if (type_specifiers & SPECIFIER_LONG) {
2882 type_specifiers |= SPECIFIER_LONG_LONG;
2884 type_specifiers |= SPECIFIER_LONG;
2889 #define CHECK_DOUBLE_TYPE() \
2890 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2893 CHECK_DOUBLE_TYPE();
2894 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2896 type->compound.compound = parse_compound_type_specifier(true);
2899 CHECK_DOUBLE_TYPE();
2900 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2901 type->compound.compound = parse_compound_type_specifier(false);
2904 CHECK_DOUBLE_TYPE();
2905 type = parse_enum_specifier();
2908 CHECK_DOUBLE_TYPE();
2909 type = parse_typeof();
2911 case T___builtin_va_list:
2912 CHECK_DOUBLE_TYPE();
2913 type = duplicate_type(type_valist);
2917 case T_IDENTIFIER: {
2918 /* only parse identifier if we haven't found a type yet */
2919 if (type != NULL || type_specifiers != 0) {
2920 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2921 * declaration, so it doesn't generate errors about expecting '(' or
2923 switch (look_ahead(1)->kind) {
2930 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2934 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2939 goto finish_specifiers;
2943 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2944 if (typedef_type == NULL) {
2945 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2946 * declaration, so it doesn't generate 'implicit int' followed by more
2947 * errors later on. */
2948 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2954 errorf(HERE, "%K does not name a type", &token);
2956 symbol_t *symbol = token.identifier.symbol;
2958 = create_error_entity(symbol, ENTITY_TYPEDEF);
2960 type = allocate_type_zero(TYPE_TYPEDEF);
2961 type->typedeft.typedefe = &entity->typedefe;
2969 goto finish_specifiers;
2974 type = typedef_type;
2978 /* function specifier */
2980 goto finish_specifiers;
2985 specifiers->attributes = parse_attributes(specifiers->attributes);
2987 if (type == NULL || (saw_error && type_specifiers != 0)) {
2988 atomic_type_kind_t atomic_type;
2990 /* match valid basic types */
2991 switch (type_specifiers) {
2992 case SPECIFIER_VOID:
2993 atomic_type = ATOMIC_TYPE_VOID;
2995 case SPECIFIER_WCHAR_T:
2996 atomic_type = ATOMIC_TYPE_WCHAR_T;
2998 case SPECIFIER_CHAR:
2999 atomic_type = ATOMIC_TYPE_CHAR;
3001 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3002 atomic_type = ATOMIC_TYPE_SCHAR;
3004 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3005 atomic_type = ATOMIC_TYPE_UCHAR;
3007 case SPECIFIER_SHORT:
3008 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3009 case SPECIFIER_SHORT | SPECIFIER_INT:
3010 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3011 atomic_type = ATOMIC_TYPE_SHORT;
3013 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3014 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3015 atomic_type = ATOMIC_TYPE_USHORT;
3018 case SPECIFIER_SIGNED:
3019 case SPECIFIER_SIGNED | SPECIFIER_INT:
3020 atomic_type = ATOMIC_TYPE_INT;
3022 case SPECIFIER_UNSIGNED:
3023 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3024 atomic_type = ATOMIC_TYPE_UINT;
3026 case SPECIFIER_LONG:
3027 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3028 case SPECIFIER_LONG | SPECIFIER_INT:
3029 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3030 atomic_type = ATOMIC_TYPE_LONG;
3032 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3033 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3034 atomic_type = ATOMIC_TYPE_ULONG;
3037 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3038 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3039 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3040 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3042 atomic_type = ATOMIC_TYPE_LONGLONG;
3043 goto warn_about_long_long;
3045 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3046 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3048 atomic_type = ATOMIC_TYPE_ULONGLONG;
3049 warn_about_long_long:
3050 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3053 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3054 atomic_type = unsigned_int8_type_kind;
3057 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3058 atomic_type = unsigned_int16_type_kind;
3061 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3062 atomic_type = unsigned_int32_type_kind;
3065 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3066 atomic_type = unsigned_int64_type_kind;
3069 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3070 atomic_type = unsigned_int128_type_kind;
3073 case SPECIFIER_INT8:
3074 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3075 atomic_type = int8_type_kind;
3078 case SPECIFIER_INT16:
3079 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3080 atomic_type = int16_type_kind;
3083 case SPECIFIER_INT32:
3084 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3085 atomic_type = int32_type_kind;
3088 case SPECIFIER_INT64:
3089 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3090 atomic_type = int64_type_kind;
3093 case SPECIFIER_INT128:
3094 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3095 atomic_type = int128_type_kind;
3098 case SPECIFIER_FLOAT:
3099 atomic_type = ATOMIC_TYPE_FLOAT;
3101 case SPECIFIER_DOUBLE:
3102 atomic_type = ATOMIC_TYPE_DOUBLE;
3104 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3105 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3107 case SPECIFIER_BOOL:
3108 atomic_type = ATOMIC_TYPE_BOOL;
3110 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3111 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3112 atomic_type = ATOMIC_TYPE_FLOAT;
3114 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3115 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3116 atomic_type = ATOMIC_TYPE_DOUBLE;
3118 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3119 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3120 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3123 /* invalid specifier combination, give an error message */
3124 source_position_t const* const pos = &specifiers->source_position;
3125 if (type_specifiers == 0) {
3127 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3128 if (!(c_mode & _CXX) && !strict_mode) {
3129 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3130 atomic_type = ATOMIC_TYPE_INT;
3133 errorf(pos, "no type specifiers given in declaration");
3136 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3137 (type_specifiers & SPECIFIER_UNSIGNED)) {
3138 errorf(pos, "signed and unsigned specifiers given");
3139 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3140 errorf(pos, "only integer types can be signed or unsigned");
3142 errorf(pos, "multiple datatypes in declaration");
3148 if (type_specifiers & SPECIFIER_COMPLEX) {
3149 type = allocate_type_zero(TYPE_COMPLEX);
3150 type->complex.akind = atomic_type;
3151 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3152 type = allocate_type_zero(TYPE_IMAGINARY);
3153 type->imaginary.akind = atomic_type;
3155 type = allocate_type_zero(TYPE_ATOMIC);
3156 type->atomic.akind = atomic_type;
3159 } else if (type_specifiers != 0) {
3160 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3163 /* FIXME: check type qualifiers here */
3164 type->base.qualifiers = qualifiers;
3167 type = identify_new_type(type);
3169 type = typehash_insert(type);
3172 if (specifiers->attributes != NULL)
3173 type = handle_type_attributes(specifiers->attributes, type);
3174 specifiers->type = type;
3178 specifiers->type = type_error_type;
3181 static type_qualifiers_t parse_type_qualifiers(void)
3183 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3186 switch (token.kind) {
3187 /* type qualifiers */
3188 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3189 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3190 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3191 /* microsoft extended type modifiers */
3192 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3193 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3194 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3195 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3196 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3205 * Parses an K&R identifier list
3207 static void parse_identifier_list(scope_t *scope)
3209 assert(token.kind == T_IDENTIFIER);
3211 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol);
3212 entity->base.source_position = token.base.source_position;
3213 /* a K&R parameter has no type, yet */
3217 append_entity(scope, entity);
3218 } while (next_if(',') && token.kind == T_IDENTIFIER);
3221 static entity_t *parse_parameter(void)
3223 declaration_specifiers_t specifiers;
3224 parse_declaration_specifiers(&specifiers);
3226 entity_t *entity = parse_declarator(&specifiers,
3227 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3228 anonymous_entity = NULL;
3232 static void semantic_parameter_incomplete(const entity_t *entity)
3234 assert(entity->kind == ENTITY_PARAMETER);
3236 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3237 * list in a function declarator that is part of a
3238 * definition of that function shall not have
3239 * incomplete type. */
3240 type_t *type = skip_typeref(entity->declaration.type);
3241 if (is_type_incomplete(type)) {
3242 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3246 static bool has_parameters(void)
3248 /* func(void) is not a parameter */
3249 if (token.kind == T_IDENTIFIER) {
3250 entity_t const *const entity
3251 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3254 if (entity->kind != ENTITY_TYPEDEF)
3256 if (skip_typeref(entity->typedefe.type) != type_void)
3258 } else if (token.kind != T_void) {
3261 if (look_ahead(1)->kind != ')')
3268 * Parses function type parameters (and optionally creates variable_t entities
3269 * for them in a scope)
3271 static void parse_parameters(function_type_t *type, scope_t *scope)
3274 add_anchor_token(')');
3275 int saved_comma_state = save_and_reset_anchor_state(',');
3277 if (token.kind == T_IDENTIFIER
3278 && !is_typedef_symbol(token.identifier.symbol)) {
3279 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3280 if (la1_type == ',' || la1_type == ')') {
3281 type->kr_style_parameters = true;
3282 parse_identifier_list(scope);
3283 goto parameters_finished;
3287 if (token.kind == ')') {
3288 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3289 if (!(c_mode & _CXX))
3290 type->unspecified_parameters = true;
3291 } else if (has_parameters()) {
3292 function_parameter_t **anchor = &type->parameters;
3294 switch (token.kind) {
3297 type->variadic = true;
3298 goto parameters_finished;
3303 entity_t *entity = parse_parameter();
3304 if (entity->kind == ENTITY_TYPEDEF) {
3305 errorf(&entity->base.source_position,
3306 "typedef not allowed as function parameter");
3309 assert(is_declaration(entity));
3311 semantic_parameter_incomplete(entity);
3313 function_parameter_t *const parameter =
3314 allocate_parameter(entity->declaration.type);
3316 if (scope != NULL) {
3317 append_entity(scope, entity);
3320 *anchor = parameter;
3321 anchor = ¶meter->next;
3326 goto parameters_finished;
3328 } while (next_if(','));
3331 parameters_finished:
3332 rem_anchor_token(')');
3333 expect(')', end_error);
3336 restore_anchor_state(',', saved_comma_state);
3339 typedef enum construct_type_kind_t {
3340 CONSTRUCT_POINTER = 1,
3341 CONSTRUCT_REFERENCE,
3344 } construct_type_kind_t;
3346 typedef union construct_type_t construct_type_t;
3348 typedef struct construct_type_base_t {
3349 construct_type_kind_t kind;
3350 source_position_t pos;
3351 construct_type_t *next;
3352 } construct_type_base_t;
3354 typedef struct parsed_pointer_t {
3355 construct_type_base_t base;
3356 type_qualifiers_t type_qualifiers;
3357 variable_t *base_variable; /**< MS __based extension. */
3360 typedef struct parsed_reference_t {
3361 construct_type_base_t base;
3362 } parsed_reference_t;
3364 typedef struct construct_function_type_t {
3365 construct_type_base_t base;
3366 type_t *function_type;
3367 } construct_function_type_t;
3369 typedef struct parsed_array_t {
3370 construct_type_base_t base;
3371 type_qualifiers_t type_qualifiers;
3377 union construct_type_t {
3378 construct_type_kind_t kind;
3379 construct_type_base_t base;
3380 parsed_pointer_t pointer;
3381 parsed_reference_t reference;
3382 construct_function_type_t function;
3383 parsed_array_t array;
3386 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3388 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3389 memset(cons, 0, size);
3391 cons->base.pos = *HERE;
3396 static construct_type_t *parse_pointer_declarator(void)
3398 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3400 cons->pointer.type_qualifiers = parse_type_qualifiers();
3401 //cons->pointer.base_variable = base_variable;
3406 /* ISO/IEC 14882:1998(E) §8.3.2 */
3407 static construct_type_t *parse_reference_declarator(void)
3409 if (!(c_mode & _CXX))
3410 errorf(HERE, "references are only available for C++");
3412 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3419 static construct_type_t *parse_array_declarator(void)
3421 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3422 parsed_array_t *const array = &cons->array;
3425 add_anchor_token(']');
3427 bool is_static = next_if(T_static);
3429 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3432 is_static = next_if(T_static);
3434 array->type_qualifiers = type_qualifiers;
3435 array->is_static = is_static;
3437 expression_t *size = NULL;
3438 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3439 array->is_variable = true;
3441 } else if (token.kind != ']') {
3442 size = parse_assignment_expression();
3444 /* §6.7.5.2:1 Array size must have integer type */
3445 type_t *const orig_type = size->base.type;
3446 type_t *const type = skip_typeref(orig_type);
3447 if (!is_type_integer(type) && is_type_valid(type)) {
3448 errorf(&size->base.source_position,
3449 "array size '%E' must have integer type but has type '%T'",
3454 mark_vars_read(size, NULL);
3457 if (is_static && size == NULL)
3458 errorf(&array->base.pos, "static array parameters require a size");
3460 rem_anchor_token(']');
3461 expect(']', end_error);
3468 static construct_type_t *parse_function_declarator(scope_t *scope)
3470 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3472 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3473 function_type_t *ftype = &type->function;
3475 ftype->linkage = current_linkage;
3476 ftype->calling_convention = CC_DEFAULT;
3478 parse_parameters(ftype, scope);
3480 cons->function.function_type = type;
3485 typedef struct parse_declarator_env_t {
3486 bool may_be_abstract : 1;
3487 bool must_be_abstract : 1;
3488 decl_modifiers_t modifiers;
3490 source_position_t source_position;
3492 attribute_t *attributes;
3493 } parse_declarator_env_t;
3496 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3498 /* construct a single linked list of construct_type_t's which describe
3499 * how to construct the final declarator type */
3500 construct_type_t *first = NULL;
3501 construct_type_t **anchor = &first;
3503 env->attributes = parse_attributes(env->attributes);
3506 construct_type_t *type;
3507 //variable_t *based = NULL; /* MS __based extension */
3508 switch (token.kind) {
3510 type = parse_reference_declarator();
3514 panic("based not supported anymore");
3519 type = parse_pointer_declarator();
3523 goto ptr_operator_end;
3527 anchor = &type->base.next;
3529 /* TODO: find out if this is correct */
3530 env->attributes = parse_attributes(env->attributes);
3534 construct_type_t *inner_types = NULL;
3536 switch (token.kind) {
3538 if (env->must_be_abstract) {
3539 errorf(HERE, "no identifier expected in typename");
3541 env->symbol = token.identifier.symbol;
3542 env->source_position = token.base.source_position;
3548 /* Parenthesized declarator or function declarator? */
3549 token_t const *const la1 = look_ahead(1);
3550 switch (la1->kind) {
3552 if (is_typedef_symbol(la1->identifier.symbol)) {
3554 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3555 * interpreted as ``function with no parameter specification'', rather
3556 * than redundant parentheses around the omitted identifier. */
3558 /* Function declarator. */
3559 if (!env->may_be_abstract) {
3560 errorf(HERE, "function declarator must have a name");
3567 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3568 /* Paranthesized declarator. */
3570 add_anchor_token(')');
3571 inner_types = parse_inner_declarator(env);
3572 if (inner_types != NULL) {
3573 /* All later declarators only modify the return type */
3574 env->must_be_abstract = true;
3576 rem_anchor_token(')');
3577 expect(')', end_error);
3585 if (env->may_be_abstract)
3587 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3592 construct_type_t **const p = anchor;
3595 construct_type_t *type;
3596 switch (token.kind) {
3598 scope_t *scope = NULL;
3599 if (!env->must_be_abstract) {
3600 scope = &env->parameters;
3603 type = parse_function_declarator(scope);
3607 type = parse_array_declarator();
3610 goto declarator_finished;
3613 /* insert in the middle of the list (at p) */
3614 type->base.next = *p;
3617 anchor = &type->base.next;
3620 declarator_finished:
3621 /* append inner_types at the end of the list, we don't to set anchor anymore
3622 * as it's not needed anymore */
3623 *anchor = inner_types;
3630 static type_t *construct_declarator_type(construct_type_t *construct_list,
3633 construct_type_t *iter = construct_list;
3634 for (; iter != NULL; iter = iter->base.next) {
3635 source_position_t const* const pos = &iter->base.pos;
3636 switch (iter->kind) {
3637 case CONSTRUCT_FUNCTION: {
3638 construct_function_type_t *function = &iter->function;
3639 type_t *function_type = function->function_type;
3641 function_type->function.return_type = type;
3643 type_t *skipped_return_type = skip_typeref(type);
3645 if (is_type_function(skipped_return_type)) {
3646 errorf(pos, "function returning function is not allowed");
3647 } else if (is_type_array(skipped_return_type)) {
3648 errorf(pos, "function returning array is not allowed");
3650 if (skipped_return_type->base.qualifiers != 0) {
3651 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3655 /* The function type was constructed earlier. Freeing it here will
3656 * destroy other types. */
3657 type = typehash_insert(function_type);
3661 case CONSTRUCT_POINTER: {
3662 if (is_type_reference(skip_typeref(type)))
3663 errorf(pos, "cannot declare a pointer to reference");
3665 parsed_pointer_t *pointer = &iter->pointer;
3666 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3670 case CONSTRUCT_REFERENCE:
3671 if (is_type_reference(skip_typeref(type)))
3672 errorf(pos, "cannot declare a reference to reference");
3674 type = make_reference_type(type);
3677 case CONSTRUCT_ARRAY: {
3678 if (is_type_reference(skip_typeref(type)))
3679 errorf(pos, "cannot declare an array of references");
3681 parsed_array_t *array = &iter->array;
3682 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3684 expression_t *size_expression = array->size;
3685 if (size_expression != NULL) {
3687 = create_implicit_cast(size_expression, type_size_t);
3690 array_type->base.qualifiers = array->type_qualifiers;
3691 array_type->array.element_type = type;
3692 array_type->array.is_static = array->is_static;
3693 array_type->array.is_variable = array->is_variable;
3694 array_type->array.size_expression = size_expression;
3696 if (size_expression != NULL) {
3697 switch (is_constant_expression(size_expression)) {
3698 case EXPR_CLASS_CONSTANT: {
3699 long const size = fold_constant_to_int(size_expression);
3700 array_type->array.size = size;
3701 array_type->array.size_constant = true;
3702 /* §6.7.5.2:1 If the expression is a constant expression,
3703 * it shall have a value greater than zero. */
3705 errorf(&size_expression->base.source_position,
3706 "size of array must be greater than zero");
3707 } else if (size == 0 && !GNU_MODE) {
3708 errorf(&size_expression->base.source_position,
3709 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3714 case EXPR_CLASS_VARIABLE:
3715 array_type->array.is_vla = true;
3718 case EXPR_CLASS_ERROR:
3723 type_t *skipped_type = skip_typeref(type);
3725 if (is_type_incomplete(skipped_type)) {
3726 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3727 } else if (is_type_function(skipped_type)) {
3728 errorf(pos, "array of functions is not allowed");
3730 type = identify_new_type(array_type);
3734 internal_errorf(pos, "invalid type construction found");
3740 static type_t *automatic_type_conversion(type_t *orig_type);
3742 static type_t *semantic_parameter(const source_position_t *pos,
3744 const declaration_specifiers_t *specifiers,
3745 entity_t const *const param)
3747 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3748 * shall be adjusted to ``qualified pointer to type'',
3750 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3751 * type'' shall be adjusted to ``pointer to function
3752 * returning type'', as in 6.3.2.1. */
3753 type = automatic_type_conversion(type);
3755 if (specifiers->is_inline && is_type_valid(type)) {
3756 errorf(pos, "'%N' declared 'inline'", param);
3759 /* §6.9.1:6 The declarations in the declaration list shall contain
3760 * no storage-class specifier other than register and no
3761 * initializations. */
3762 if (specifiers->thread_local || (
3763 specifiers->storage_class != STORAGE_CLASS_NONE &&
3764 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3766 errorf(pos, "invalid storage class for '%N'", param);
3769 /* delay test for incomplete type, because we might have (void)
3770 * which is legal but incomplete... */
3775 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3776 declarator_flags_t flags)
3778 parse_declarator_env_t env;
3779 memset(&env, 0, sizeof(env));
3780 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3782 construct_type_t *construct_type = parse_inner_declarator(&env);
3784 construct_declarator_type(construct_type, specifiers->type);
3785 type_t *type = skip_typeref(orig_type);
3787 if (construct_type != NULL) {
3788 obstack_free(&temp_obst, construct_type);
3791 attribute_t *attributes = parse_attributes(env.attributes);
3792 /* append (shared) specifier attribute behind attributes of this
3794 attribute_t **anchor = &attributes;
3795 while (*anchor != NULL)
3796 anchor = &(*anchor)->next;
3797 *anchor = specifiers->attributes;
3800 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3801 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3802 entity->base.source_position = env.source_position;
3803 entity->typedefe.type = orig_type;
3805 if (anonymous_entity != NULL) {
3806 if (is_type_compound(type)) {
3807 assert(anonymous_entity->compound.alias == NULL);
3808 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3809 anonymous_entity->kind == ENTITY_UNION);
3810 anonymous_entity->compound.alias = entity;
3811 anonymous_entity = NULL;
3812 } else if (is_type_enum(type)) {
3813 assert(anonymous_entity->enume.alias == NULL);
3814 assert(anonymous_entity->kind == ENTITY_ENUM);
3815 anonymous_entity->enume.alias = entity;
3816 anonymous_entity = NULL;
3820 /* create a declaration type entity */
3821 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3822 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3824 if (env.symbol != NULL) {
3825 if (specifiers->is_inline && is_type_valid(type)) {
3826 errorf(&env.source_position,
3827 "compound member '%Y' declared 'inline'", env.symbol);
3830 if (specifiers->thread_local ||
3831 specifiers->storage_class != STORAGE_CLASS_NONE) {
3832 errorf(&env.source_position,
3833 "compound member '%Y' must have no storage class",
3837 } else if (flags & DECL_IS_PARAMETER) {
3838 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3839 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3840 } else if (is_type_function(type)) {
3841 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3842 entity->function.is_inline = specifiers->is_inline;
3843 entity->function.elf_visibility = default_visibility;
3844 entity->function.parameters = env.parameters;
3846 if (env.symbol != NULL) {
3847 /* this needs fixes for C++ */
3848 bool in_function_scope = current_function != NULL;
3850 if (specifiers->thread_local || (
3851 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3852 specifiers->storage_class != STORAGE_CLASS_NONE &&
3853 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3855 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3859 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3860 entity->variable.elf_visibility = default_visibility;
3861 entity->variable.thread_local = specifiers->thread_local;
3863 if (env.symbol != NULL) {
3864 if (specifiers->is_inline && is_type_valid(type)) {
3865 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3868 bool invalid_storage_class = false;
3869 if (current_scope == file_scope) {
3870 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3871 specifiers->storage_class != STORAGE_CLASS_NONE &&
3872 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3873 invalid_storage_class = true;
3876 if (specifiers->thread_local &&
3877 specifiers->storage_class == STORAGE_CLASS_NONE) {
3878 invalid_storage_class = true;
3881 if (invalid_storage_class) {
3882 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3887 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3888 entity->declaration.type = orig_type;
3889 entity->declaration.alignment = get_type_alignment(orig_type);
3890 entity->declaration.modifiers = env.modifiers;
3891 entity->declaration.attributes = attributes;
3893 storage_class_t storage_class = specifiers->storage_class;
3894 entity->declaration.declared_storage_class = storage_class;
3896 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3897 storage_class = STORAGE_CLASS_AUTO;
3898 entity->declaration.storage_class = storage_class;
3901 if (attributes != NULL) {
3902 handle_entity_attributes(attributes, entity);
3908 static type_t *parse_abstract_declarator(type_t *base_type)
3910 parse_declarator_env_t env;
3911 memset(&env, 0, sizeof(env));
3912 env.may_be_abstract = true;
3913 env.must_be_abstract = true;
3915 construct_type_t *construct_type = parse_inner_declarator(&env);
3917 type_t *result = construct_declarator_type(construct_type, base_type);
3918 if (construct_type != NULL) {
3919 obstack_free(&temp_obst, construct_type);
3921 result = handle_type_attributes(env.attributes, result);
3927 * Check if the declaration of main is suspicious. main should be a
3928 * function with external linkage, returning int, taking either zero
3929 * arguments, two, or three arguments of appropriate types, ie.
3931 * int main([ int argc, char **argv [, char **env ] ]).
3933 * @param decl the declaration to check
3934 * @param type the function type of the declaration
3936 static void check_main(const entity_t *entity)
3938 const source_position_t *pos = &entity->base.source_position;
3939 if (entity->kind != ENTITY_FUNCTION) {
3940 warningf(WARN_MAIN, pos, "'main' is not a function");
3944 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3945 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3948 type_t *type = skip_typeref(entity->declaration.type);
3949 assert(is_type_function(type));
3951 function_type_t const *const func_type = &type->function;
3952 type_t *const ret_type = func_type->return_type;
3953 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3954 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3956 const function_parameter_t *parm = func_type->parameters;
3958 type_t *const first_type = skip_typeref(parm->type);
3959 type_t *const first_type_unqual = get_unqualified_type(first_type);
3960 if (!types_compatible(first_type_unqual, type_int)) {
3961 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3965 type_t *const second_type = skip_typeref(parm->type);
3966 type_t *const second_type_unqual
3967 = get_unqualified_type(second_type);
3968 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3969 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3973 type_t *const third_type = skip_typeref(parm->type);
3974 type_t *const third_type_unqual
3975 = get_unqualified_type(third_type);
3976 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3977 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3981 goto warn_arg_count;
3985 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3991 * Check if a symbol is the equal to "main".
3993 static bool is_sym_main(const symbol_t *const sym)
3995 return strcmp(sym->string, "main") == 0;
3998 static void error_redefined_as_different_kind(const source_position_t *pos,
3999 const entity_t *old, entity_kind_t new_kind)
4001 char const *const what = get_entity_kind_name(new_kind);
4002 source_position_t const *const ppos = &old->base.source_position;
4003 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4006 static bool is_entity_valid(entity_t *const ent)
4008 if (is_declaration(ent)) {
4009 return is_type_valid(skip_typeref(ent->declaration.type));
4010 } else if (ent->kind == ENTITY_TYPEDEF) {
4011 return is_type_valid(skip_typeref(ent->typedefe.type));
4016 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4018 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4019 if (attributes_equal(tattr, attr))
4026 * test wether new_list contains any attributes not included in old_list
4028 static bool has_new_attributes(const attribute_t *old_list,
4029 const attribute_t *new_list)
4031 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4032 if (!contains_attribute(old_list, attr))
4039 * Merge in attributes from an attribute list (probably from a previous
4040 * declaration with the same name). Warning: destroys the old structure
4041 * of the attribute list - don't reuse attributes after this call.
4043 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4046 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4048 if (contains_attribute(decl->attributes, attr))
4051 /* move attribute to new declarations attributes list */
4052 attr->next = decl->attributes;
4053 decl->attributes = attr;
4058 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4059 * for various problems that occur for multiple definitions
4061 entity_t *record_entity(entity_t *entity, const bool is_definition)
4063 const symbol_t *const symbol = entity->base.symbol;
4064 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4065 const source_position_t *pos = &entity->base.source_position;
4067 /* can happen in error cases */
4071 entity_t *const previous_entity = get_entity(symbol, namespc);
4072 /* pushing the same entity twice will break the stack structure */
4073 assert(previous_entity != entity);
4075 if (entity->kind == ENTITY_FUNCTION) {
4076 type_t *const orig_type = entity->declaration.type;
4077 type_t *const type = skip_typeref(orig_type);
4079 assert(is_type_function(type));
4080 if (type->function.unspecified_parameters &&
4081 previous_entity == NULL &&
4082 !entity->declaration.implicit) {
4083 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4086 if (current_scope == file_scope && is_sym_main(symbol)) {
4091 if (is_declaration(entity) &&
4092 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4093 current_scope != file_scope &&
4094 !entity->declaration.implicit) {
4095 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4098 if (previous_entity != NULL) {
4099 source_position_t const *const ppos = &previous_entity->base.source_position;
4101 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4102 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4103 assert(previous_entity->kind == ENTITY_PARAMETER);
4104 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4108 if (previous_entity->base.parent_scope == current_scope) {
4109 if (previous_entity->kind != entity->kind) {
4110 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4111 error_redefined_as_different_kind(pos, previous_entity,
4116 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4117 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4120 if (previous_entity->kind == ENTITY_TYPEDEF) {
4121 /* TODO: C++ allows this for exactly the same type */
4122 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4126 /* at this point we should have only VARIABLES or FUNCTIONS */
4127 assert(is_declaration(previous_entity) && is_declaration(entity));
4129 declaration_t *const prev_decl = &previous_entity->declaration;
4130 declaration_t *const decl = &entity->declaration;
4132 /* can happen for K&R style declarations */
4133 if (prev_decl->type == NULL &&
4134 previous_entity->kind == ENTITY_PARAMETER &&
4135 entity->kind == ENTITY_PARAMETER) {
4136 prev_decl->type = decl->type;
4137 prev_decl->storage_class = decl->storage_class;
4138 prev_decl->declared_storage_class = decl->declared_storage_class;
4139 prev_decl->modifiers = decl->modifiers;
4140 return previous_entity;
4143 type_t *const type = skip_typeref(decl->type);
4144 type_t *const prev_type = skip_typeref(prev_decl->type);
4146 if (!types_compatible(type, prev_type)) {
4147 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4149 unsigned old_storage_class = prev_decl->storage_class;
4151 if (is_definition &&
4153 !(prev_decl->modifiers & DM_USED) &&
4154 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4155 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4158 storage_class_t new_storage_class = decl->storage_class;
4160 /* pretend no storage class means extern for function
4161 * declarations (except if the previous declaration is neither
4162 * none nor extern) */
4163 if (entity->kind == ENTITY_FUNCTION) {
4164 /* the previous declaration could have unspecified parameters or
4165 * be a typedef, so use the new type */
4166 if (prev_type->function.unspecified_parameters || is_definition)
4167 prev_decl->type = type;
4169 switch (old_storage_class) {
4170 case STORAGE_CLASS_NONE:
4171 old_storage_class = STORAGE_CLASS_EXTERN;
4174 case STORAGE_CLASS_EXTERN:
4175 if (is_definition) {
4176 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4177 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4179 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4180 new_storage_class = STORAGE_CLASS_EXTERN;
4187 } else if (is_type_incomplete(prev_type)) {
4188 prev_decl->type = type;
4191 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4192 new_storage_class == STORAGE_CLASS_EXTERN) {
4194 warn_redundant_declaration: ;
4196 = has_new_attributes(prev_decl->attributes,
4198 if (has_new_attrs) {
4199 merge_in_attributes(decl, prev_decl->attributes);
4200 } else if (!is_definition &&
4201 is_type_valid(prev_type) &&
4202 strcmp(ppos->input_name, "<builtin>") != 0) {
4203 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4205 } else if (current_function == NULL) {
4206 if (old_storage_class != STORAGE_CLASS_STATIC &&
4207 new_storage_class == STORAGE_CLASS_STATIC) {
4208 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4209 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4210 prev_decl->storage_class = STORAGE_CLASS_NONE;
4211 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4213 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4215 goto error_redeclaration;
4216 goto warn_redundant_declaration;
4218 } else if (is_type_valid(prev_type)) {
4219 if (old_storage_class == new_storage_class) {
4220 error_redeclaration:
4221 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4223 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4228 prev_decl->modifiers |= decl->modifiers;
4229 if (entity->kind == ENTITY_FUNCTION) {
4230 previous_entity->function.is_inline |= entity->function.is_inline;
4232 return previous_entity;
4236 if (is_warn_on(why = WARN_SHADOW) ||
4237 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4238 char const *const what = get_entity_kind_name(previous_entity->kind);
4239 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4243 if (entity->kind == ENTITY_FUNCTION) {
4244 if (is_definition &&
4245 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4246 !is_sym_main(symbol)) {
4247 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4248 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4250 goto warn_missing_declaration;
4253 } else if (entity->kind == ENTITY_VARIABLE) {
4254 if (current_scope == file_scope &&
4255 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4256 !entity->declaration.implicit) {
4257 warn_missing_declaration:
4258 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4263 assert(entity->base.parent_scope == NULL);
4264 assert(current_scope != NULL);
4266 entity->base.parent_scope = current_scope;
4267 environment_push(entity);
4268 append_entity(current_scope, entity);
4273 static void parser_error_multiple_definition(entity_t *entity,
4274 const source_position_t *source_position)
4276 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4277 entity->base.symbol, &entity->base.source_position);
4280 static bool is_declaration_specifier(const token_t *token)
4282 switch (token->kind) {
4286 return is_typedef_symbol(token->identifier.symbol);
4293 static void parse_init_declarator_rest(entity_t *entity)
4295 type_t *orig_type = type_error_type;
4297 if (entity->base.kind == ENTITY_TYPEDEF) {
4298 source_position_t const *const pos = &entity->base.source_position;
4299 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4301 assert(is_declaration(entity));
4302 orig_type = entity->declaration.type;
4305 type_t *type = skip_typeref(orig_type);
4307 if (entity->kind == ENTITY_VARIABLE
4308 && entity->variable.initializer != NULL) {
4309 parser_error_multiple_definition(entity, HERE);
4313 declaration_t *const declaration = &entity->declaration;
4314 bool must_be_constant = false;
4315 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4316 entity->base.parent_scope == file_scope) {
4317 must_be_constant = true;
4320 if (is_type_function(type)) {
4321 source_position_t const *const pos = &entity->base.source_position;
4322 errorf(pos, "'%N' is initialized like a variable", entity);
4323 orig_type = type_error_type;
4326 parse_initializer_env_t env;
4327 env.type = orig_type;
4328 env.must_be_constant = must_be_constant;
4329 env.entity = entity;
4331 initializer_t *initializer = parse_initializer(&env);
4333 if (entity->kind == ENTITY_VARIABLE) {
4334 /* §6.7.5:22 array initializers for arrays with unknown size
4335 * determine the array type size */
4336 declaration->type = env.type;
4337 entity->variable.initializer = initializer;
4341 /* parse rest of a declaration without any declarator */
4342 static void parse_anonymous_declaration_rest(
4343 const declaration_specifiers_t *specifiers)
4346 anonymous_entity = NULL;
4348 source_position_t const *const pos = &specifiers->source_position;
4349 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4350 specifiers->thread_local) {
4351 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4354 type_t *type = specifiers->type;
4355 switch (type->kind) {
4356 case TYPE_COMPOUND_STRUCT:
4357 case TYPE_COMPOUND_UNION: {
4358 if (type->compound.compound->base.symbol == NULL) {
4359 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4368 warningf(WARN_OTHER, pos, "empty declaration");
4373 static void check_variable_type_complete(entity_t *ent)
4375 if (ent->kind != ENTITY_VARIABLE)
4378 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4379 * type for the object shall be complete [...] */
4380 declaration_t *decl = &ent->declaration;
4381 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4382 decl->storage_class == STORAGE_CLASS_STATIC)
4385 type_t *const type = skip_typeref(decl->type);
4386 if (!is_type_incomplete(type))
4389 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4390 * are given length one. */
4391 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4392 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4396 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4400 static void parse_declaration_rest(entity_t *ndeclaration,
4401 const declaration_specifiers_t *specifiers,
4402 parsed_declaration_func finished_declaration,
4403 declarator_flags_t flags)
4405 add_anchor_token(';');
4406 add_anchor_token(',');
4408 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4410 if (token.kind == '=') {
4411 parse_init_declarator_rest(entity);
4412 } else if (entity->kind == ENTITY_VARIABLE) {
4413 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4414 * [...] where the extern specifier is explicitly used. */
4415 declaration_t *decl = &entity->declaration;
4416 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4417 type_t *type = decl->type;
4418 if (is_type_reference(skip_typeref(type))) {
4419 source_position_t const *const pos = &entity->base.source_position;
4420 errorf(pos, "reference '%#N' must be initialized", entity);
4425 check_variable_type_complete(entity);
4430 add_anchor_token('=');
4431 ndeclaration = parse_declarator(specifiers, flags);
4432 rem_anchor_token('=');
4434 expect(';', end_error);
4437 anonymous_entity = NULL;
4438 rem_anchor_token(';');
4439 rem_anchor_token(',');
4442 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4444 symbol_t *symbol = entity->base.symbol;
4448 assert(entity->base.namespc == NAMESPACE_NORMAL);
4449 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4450 if (previous_entity == NULL
4451 || previous_entity->base.parent_scope != current_scope) {
4452 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4457 if (is_definition) {
4458 errorf(HERE, "'%N' is initialised", entity);
4461 return record_entity(entity, false);
4464 static void parse_declaration(parsed_declaration_func finished_declaration,
4465 declarator_flags_t flags)
4467 add_anchor_token(';');
4468 declaration_specifiers_t specifiers;
4469 parse_declaration_specifiers(&specifiers);
4470 rem_anchor_token(';');
4472 if (token.kind == ';') {
4473 parse_anonymous_declaration_rest(&specifiers);
4475 entity_t *entity = parse_declarator(&specifiers, flags);
4476 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4481 static type_t *get_default_promoted_type(type_t *orig_type)
4483 type_t *result = orig_type;
4485 type_t *type = skip_typeref(orig_type);
4486 if (is_type_integer(type)) {
4487 result = promote_integer(type);
4488 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4489 result = type_double;
4495 static void parse_kr_declaration_list(entity_t *entity)
4497 if (entity->kind != ENTITY_FUNCTION)
4500 type_t *type = skip_typeref(entity->declaration.type);
4501 assert(is_type_function(type));
4502 if (!type->function.kr_style_parameters)
4505 add_anchor_token('{');
4507 PUSH_SCOPE(&entity->function.parameters);
4509 entity_t *parameter = entity->function.parameters.entities;
4510 for ( ; parameter != NULL; parameter = parameter->base.next) {
4511 assert(parameter->base.parent_scope == NULL);
4512 parameter->base.parent_scope = current_scope;
4513 environment_push(parameter);
4516 /* parse declaration list */
4518 switch (token.kind) {
4520 /* This covers symbols, which are no type, too, and results in
4521 * better error messages. The typical cases are misspelled type
4522 * names and missing includes. */
4524 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4534 /* update function type */
4535 type_t *new_type = duplicate_type(type);
4537 function_parameter_t *parameters = NULL;
4538 function_parameter_t **anchor = ¶meters;
4540 /* did we have an earlier prototype? */
4541 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4542 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4545 function_parameter_t *proto_parameter = NULL;
4546 if (proto_type != NULL) {
4547 type_t *proto_type_type = proto_type->declaration.type;
4548 proto_parameter = proto_type_type->function.parameters;
4549 /* If a K&R function definition has a variadic prototype earlier, then
4550 * make the function definition variadic, too. This should conform to
4551 * §6.7.5.3:15 and §6.9.1:8. */
4552 new_type->function.variadic = proto_type_type->function.variadic;
4554 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4556 new_type->function.unspecified_parameters = true;
4559 bool need_incompatible_warning = false;
4560 parameter = entity->function.parameters.entities;
4561 for (; parameter != NULL; parameter = parameter->base.next,
4563 proto_parameter == NULL ? NULL : proto_parameter->next) {
4564 if (parameter->kind != ENTITY_PARAMETER)
4567 type_t *parameter_type = parameter->declaration.type;
4568 if (parameter_type == NULL) {
4569 source_position_t const* const pos = ¶meter->base.source_position;
4571 errorf(pos, "no type specified for function '%N'", parameter);
4572 parameter_type = type_error_type;
4574 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4575 parameter_type = type_int;
4577 parameter->declaration.type = parameter_type;
4580 semantic_parameter_incomplete(parameter);
4582 /* we need the default promoted types for the function type */
4583 type_t *not_promoted = parameter_type;
4584 parameter_type = get_default_promoted_type(parameter_type);
4586 /* gcc special: if the type of the prototype matches the unpromoted
4587 * type don't promote */
4588 if (!strict_mode && proto_parameter != NULL) {
4589 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4590 type_t *promo_skip = skip_typeref(parameter_type);
4591 type_t *param_skip = skip_typeref(not_promoted);
4592 if (!types_compatible(proto_p_type, promo_skip)
4593 && types_compatible(proto_p_type, param_skip)) {
4595 need_incompatible_warning = true;
4596 parameter_type = not_promoted;
4599 function_parameter_t *const function_parameter
4600 = allocate_parameter(parameter_type);
4602 *anchor = function_parameter;
4603 anchor = &function_parameter->next;
4606 new_type->function.parameters = parameters;
4607 new_type = identify_new_type(new_type);
4609 if (need_incompatible_warning) {
4610 symbol_t const *const sym = entity->base.symbol;
4611 source_position_t const *const pos = &entity->base.source_position;
4612 source_position_t const *const ppos = &proto_type->base.source_position;
4613 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4615 entity->declaration.type = new_type;
4617 rem_anchor_token('{');
4620 static bool first_err = true;
4623 * When called with first_err set, prints the name of the current function,
4626 static void print_in_function(void)
4630 char const *const file = current_function->base.base.source_position.input_name;
4631 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4636 * Check if all labels are defined in the current function.
4637 * Check if all labels are used in the current function.
4639 static void check_labels(void)
4641 for (const goto_statement_t *goto_statement = goto_first;
4642 goto_statement != NULL;
4643 goto_statement = goto_statement->next) {
4644 /* skip computed gotos */
4645 if (goto_statement->expression != NULL)
4648 label_t *label = goto_statement->label;
4649 if (label->base.source_position.input_name == NULL) {
4650 print_in_function();
4651 source_position_t const *const pos = &goto_statement->base.source_position;
4652 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4656 if (is_warn_on(WARN_UNUSED_LABEL)) {
4657 for (const label_statement_t *label_statement = label_first;
4658 label_statement != NULL;
4659 label_statement = label_statement->next) {
4660 label_t *label = label_statement->label;
4662 if (! label->used) {
4663 print_in_function();
4664 source_position_t const *const pos = &label_statement->base.source_position;
4665 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4671 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4673 entity_t const *const end = last != NULL ? last->base.next : NULL;
4674 for (; entity != end; entity = entity->base.next) {
4675 if (!is_declaration(entity))
4678 declaration_t *declaration = &entity->declaration;
4679 if (declaration->implicit)
4682 if (!declaration->used) {
4683 print_in_function();
4684 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4685 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4686 print_in_function();
4687 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4692 static void check_unused_variables(statement_t *const stmt, void *const env)
4696 switch (stmt->kind) {
4697 case STATEMENT_DECLARATION: {
4698 declaration_statement_t const *const decls = &stmt->declaration;
4699 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4704 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4713 * Check declarations of current_function for unused entities.
4715 static void check_declarations(void)
4717 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4718 const scope_t *scope = ¤t_function->parameters;
4720 /* do not issue unused warnings for main */
4721 if (!is_sym_main(current_function->base.base.symbol)) {
4722 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4725 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4726 walk_statements(current_function->statement, check_unused_variables,
4731 static int determine_truth(expression_t const* const cond)
4734 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4735 fold_constant_to_bool(cond) ? 1 :
4739 static void check_reachable(statement_t *);
4740 static bool reaches_end;
4742 static bool expression_returns(expression_t const *const expr)
4744 switch (expr->kind) {
4746 expression_t const *const func = expr->call.function;
4747 if (func->kind == EXPR_REFERENCE) {
4748 entity_t *entity = func->reference.entity;
4749 if (entity->kind == ENTITY_FUNCTION
4750 && entity->declaration.modifiers & DM_NORETURN)
4754 if (!expression_returns(func))
4757 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4758 if (!expression_returns(arg->expression))
4765 case EXPR_REFERENCE:
4766 case EXPR_REFERENCE_ENUM_VALUE:
4768 case EXPR_STRING_LITERAL:
4769 case EXPR_WIDE_STRING_LITERAL:
4770 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4771 case EXPR_LABEL_ADDRESS:
4772 case EXPR_CLASSIFY_TYPE:
4773 case EXPR_SIZEOF: // TODO handle obscure VLA case
4776 case EXPR_BUILTIN_CONSTANT_P:
4777 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4782 case EXPR_STATEMENT: {
4783 bool old_reaches_end = reaches_end;
4784 reaches_end = false;
4785 check_reachable(expr->statement.statement);
4786 bool returns = reaches_end;
4787 reaches_end = old_reaches_end;
4791 case EXPR_CONDITIONAL:
4792 // TODO handle constant expression
4794 if (!expression_returns(expr->conditional.condition))
4797 if (expr->conditional.true_expression != NULL
4798 && expression_returns(expr->conditional.true_expression))
4801 return expression_returns(expr->conditional.false_expression);
4804 return expression_returns(expr->select.compound);
4806 case EXPR_ARRAY_ACCESS:
4808 expression_returns(expr->array_access.array_ref) &&
4809 expression_returns(expr->array_access.index);
4812 return expression_returns(expr->va_starte.ap);
4815 return expression_returns(expr->va_arge.ap);
4818 return expression_returns(expr->va_copye.src);
4820 EXPR_UNARY_CASES_MANDATORY
4821 return expression_returns(expr->unary.value);
4823 case EXPR_UNARY_THROW:
4827 // TODO handle constant lhs of && and ||
4829 expression_returns(expr->binary.left) &&
4830 expression_returns(expr->binary.right);
4833 panic("unhandled expression");
4836 static bool initializer_returns(initializer_t const *const init)
4838 switch (init->kind) {
4839 case INITIALIZER_VALUE:
4840 return expression_returns(init->value.value);
4842 case INITIALIZER_LIST: {
4843 initializer_t * const* i = init->list.initializers;
4844 initializer_t * const* const end = i + init->list.len;
4845 bool returns = true;
4846 for (; i != end; ++i) {
4847 if (!initializer_returns(*i))
4853 case INITIALIZER_STRING:
4854 case INITIALIZER_WIDE_STRING:
4855 case INITIALIZER_DESIGNATOR: // designators have no payload
4858 panic("unhandled initializer");
4861 static bool noreturn_candidate;
4863 static void check_reachable(statement_t *const stmt)
4865 if (stmt->base.reachable)
4867 if (stmt->kind != STATEMENT_DO_WHILE)
4868 stmt->base.reachable = true;
4870 statement_t *last = stmt;
4872 switch (stmt->kind) {
4873 case STATEMENT_ERROR:
4874 case STATEMENT_EMPTY:
4876 next = stmt->base.next;
4879 case STATEMENT_DECLARATION: {
4880 declaration_statement_t const *const decl = &stmt->declaration;
4881 entity_t const * ent = decl->declarations_begin;
4882 entity_t const *const last_decl = decl->declarations_end;
4884 for (;; ent = ent->base.next) {
4885 if (ent->kind == ENTITY_VARIABLE &&
4886 ent->variable.initializer != NULL &&
4887 !initializer_returns(ent->variable.initializer)) {
4890 if (ent == last_decl)
4894 next = stmt->base.next;
4898 case STATEMENT_COMPOUND:
4899 next = stmt->compound.statements;
4901 next = stmt->base.next;
4904 case STATEMENT_RETURN: {
4905 expression_t const *const val = stmt->returns.value;
4906 if (val == NULL || expression_returns(val))
4907 noreturn_candidate = false;
4911 case STATEMENT_IF: {
4912 if_statement_t const *const ifs = &stmt->ifs;
4913 expression_t const *const cond = ifs->condition;
4915 if (!expression_returns(cond))
4918 int const val = determine_truth(cond);
4921 check_reachable(ifs->true_statement);
4926 if (ifs->false_statement != NULL) {
4927 check_reachable(ifs->false_statement);
4931 next = stmt->base.next;
4935 case STATEMENT_SWITCH: {
4936 switch_statement_t const *const switchs = &stmt->switchs;
4937 expression_t const *const expr = switchs->expression;
4939 if (!expression_returns(expr))
4942 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4943 long const val = fold_constant_to_int(expr);
4944 case_label_statement_t * defaults = NULL;
4945 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4946 if (i->expression == NULL) {
4951 if (i->first_case <= val && val <= i->last_case) {
4952 check_reachable((statement_t*)i);
4957 if (defaults != NULL) {
4958 check_reachable((statement_t*)defaults);
4962 bool has_default = false;
4963 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4964 if (i->expression == NULL)
4967 check_reachable((statement_t*)i);
4974 next = stmt->base.next;
4978 case STATEMENT_EXPRESSION: {
4979 /* Check for noreturn function call */
4980 expression_t const *const expr = stmt->expression.expression;
4981 if (!expression_returns(expr))
4984 next = stmt->base.next;
4988 case STATEMENT_CONTINUE:
4989 for (statement_t *parent = stmt;;) {
4990 parent = parent->base.parent;
4991 if (parent == NULL) /* continue not within loop */
4995 switch (parent->kind) {
4996 case STATEMENT_WHILE: goto continue_while;
4997 case STATEMENT_DO_WHILE: goto continue_do_while;
4998 case STATEMENT_FOR: goto continue_for;
5004 case STATEMENT_BREAK:
5005 for (statement_t *parent = stmt;;) {
5006 parent = parent->base.parent;
5007 if (parent == NULL) /* break not within loop/switch */
5010 switch (parent->kind) {
5011 case STATEMENT_SWITCH:
5012 case STATEMENT_WHILE:
5013 case STATEMENT_DO_WHILE:
5016 next = parent->base.next;
5017 goto found_break_parent;
5025 case STATEMENT_GOTO:
5026 if (stmt->gotos.expression) {
5027 if (!expression_returns(stmt->gotos.expression))
5030 statement_t *parent = stmt->base.parent;
5031 if (parent == NULL) /* top level goto */
5035 next = stmt->gotos.label->statement;
5036 if (next == NULL) /* missing label */
5041 case STATEMENT_LABEL:
5042 next = stmt->label.statement;
5045 case STATEMENT_CASE_LABEL:
5046 next = stmt->case_label.statement;
5049 case STATEMENT_WHILE: {
5050 while_statement_t const *const whiles = &stmt->whiles;
5051 expression_t const *const cond = whiles->condition;
5053 if (!expression_returns(cond))
5056 int const val = determine_truth(cond);
5059 check_reachable(whiles->body);
5064 next = stmt->base.next;
5068 case STATEMENT_DO_WHILE:
5069 next = stmt->do_while.body;
5072 case STATEMENT_FOR: {
5073 for_statement_t *const fors = &stmt->fors;
5075 if (fors->condition_reachable)
5077 fors->condition_reachable = true;
5079 expression_t const *const cond = fors->condition;
5084 } else if (expression_returns(cond)) {
5085 val = determine_truth(cond);
5091 check_reachable(fors->body);
5096 next = stmt->base.next;
5100 case STATEMENT_MS_TRY: {
5101 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5102 check_reachable(ms_try->try_statement);
5103 next = ms_try->final_statement;
5107 case STATEMENT_LEAVE: {
5108 statement_t *parent = stmt;
5110 parent = parent->base.parent;
5111 if (parent == NULL) /* __leave not within __try */
5114 if (parent->kind == STATEMENT_MS_TRY) {
5116 next = parent->ms_try.final_statement;
5124 panic("invalid statement kind");
5127 while (next == NULL) {
5128 next = last->base.parent;
5130 noreturn_candidate = false;
5132 type_t *const type = skip_typeref(current_function->base.type);
5133 assert(is_type_function(type));
5134 type_t *const ret = skip_typeref(type->function.return_type);
5135 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5136 is_type_valid(ret) &&
5137 !is_sym_main(current_function->base.base.symbol)) {
5138 source_position_t const *const pos = &stmt->base.source_position;
5139 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5144 switch (next->kind) {
5145 case STATEMENT_ERROR:
5146 case STATEMENT_EMPTY:
5147 case STATEMENT_DECLARATION:
5148 case STATEMENT_EXPRESSION:
5150 case STATEMENT_RETURN:
5151 case STATEMENT_CONTINUE:
5152 case STATEMENT_BREAK:
5153 case STATEMENT_GOTO:
5154 case STATEMENT_LEAVE:
5155 panic("invalid control flow in function");
5157 case STATEMENT_COMPOUND:
5158 if (next->compound.stmt_expr) {
5164 case STATEMENT_SWITCH:
5165 case STATEMENT_LABEL:
5166 case STATEMENT_CASE_LABEL:
5168 next = next->base.next;
5171 case STATEMENT_WHILE: {
5173 if (next->base.reachable)
5175 next->base.reachable = true;
5177 while_statement_t const *const whiles = &next->whiles;
5178 expression_t const *const cond = whiles->condition;
5180 if (!expression_returns(cond))
5183 int const val = determine_truth(cond);
5186 check_reachable(whiles->body);
5192 next = next->base.next;
5196 case STATEMENT_DO_WHILE: {
5198 if (next->base.reachable)
5200 next->base.reachable = true;
5202 do_while_statement_t const *const dw = &next->do_while;
5203 expression_t const *const cond = dw->condition;
5205 if (!expression_returns(cond))
5208 int const val = determine_truth(cond);
5211 check_reachable(dw->body);
5217 next = next->base.next;
5221 case STATEMENT_FOR: {
5223 for_statement_t *const fors = &next->fors;
5225 fors->step_reachable = true;
5227 if (fors->condition_reachable)
5229 fors->condition_reachable = true;
5231 expression_t const *const cond = fors->condition;
5236 } else if (expression_returns(cond)) {
5237 val = determine_truth(cond);
5243 check_reachable(fors->body);
5249 next = next->base.next;
5253 case STATEMENT_MS_TRY:
5255 next = next->ms_try.final_statement;
5260 check_reachable(next);
5263 static void check_unreachable(statement_t* const stmt, void *const env)
5267 switch (stmt->kind) {
5268 case STATEMENT_DO_WHILE:
5269 if (!stmt->base.reachable) {
5270 expression_t const *const cond = stmt->do_while.condition;
5271 if (determine_truth(cond) >= 0) {
5272 source_position_t const *const pos = &cond->base.source_position;
5273 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5278 case STATEMENT_FOR: {
5279 for_statement_t const* const fors = &stmt->fors;
5281 // if init and step are unreachable, cond is unreachable, too
5282 if (!stmt->base.reachable && !fors->step_reachable) {
5283 goto warn_unreachable;
5285 if (!stmt->base.reachable && fors->initialisation != NULL) {
5286 source_position_t const *const pos = &fors->initialisation->base.source_position;
5287 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5290 if (!fors->condition_reachable && fors->condition != NULL) {
5291 source_position_t const *const pos = &fors->condition->base.source_position;
5292 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5295 if (!fors->step_reachable && fors->step != NULL) {
5296 source_position_t const *const pos = &fors->step->base.source_position;
5297 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5303 case STATEMENT_COMPOUND:
5304 if (stmt->compound.statements != NULL)
5306 goto warn_unreachable;
5308 case STATEMENT_DECLARATION: {
5309 /* Only warn if there is at least one declarator with an initializer.
5310 * This typically occurs in switch statements. */
5311 declaration_statement_t const *const decl = &stmt->declaration;
5312 entity_t const * ent = decl->declarations_begin;
5313 entity_t const *const last = decl->declarations_end;
5315 for (;; ent = ent->base.next) {
5316 if (ent->kind == ENTITY_VARIABLE &&
5317 ent->variable.initializer != NULL) {
5318 goto warn_unreachable;
5328 if (!stmt->base.reachable) {
5329 source_position_t const *const pos = &stmt->base.source_position;
5330 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5336 static void parse_external_declaration(void)
5338 /* function-definitions and declarations both start with declaration
5340 add_anchor_token(';');
5341 declaration_specifiers_t specifiers;
5342 parse_declaration_specifiers(&specifiers);
5343 rem_anchor_token(';');
5345 /* must be a declaration */
5346 if (token.kind == ';') {
5347 parse_anonymous_declaration_rest(&specifiers);
5351 add_anchor_token(',');
5352 add_anchor_token('=');
5353 add_anchor_token(';');
5354 add_anchor_token('{');
5356 /* declarator is common to both function-definitions and declarations */
5357 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5359 rem_anchor_token('{');
5360 rem_anchor_token(';');
5361 rem_anchor_token('=');
5362 rem_anchor_token(',');
5364 /* must be a declaration */
5365 switch (token.kind) {
5369 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5374 /* must be a function definition */
5375 parse_kr_declaration_list(ndeclaration);
5377 if (token.kind != '{') {
5378 parse_error_expected("while parsing function definition", '{', NULL);
5379 eat_until_matching_token(';');
5383 assert(is_declaration(ndeclaration));
5384 type_t *const orig_type = ndeclaration->declaration.type;
5385 type_t * type = skip_typeref(orig_type);
5387 if (!is_type_function(type)) {
5388 if (is_type_valid(type)) {
5389 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5395 source_position_t const *const pos = &ndeclaration->base.source_position;
5396 if (is_typeref(orig_type)) {
5398 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5401 if (is_type_compound(skip_typeref(type->function.return_type))) {
5402 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5404 if (type->function.unspecified_parameters) {
5405 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5407 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5410 /* §6.7.5.3:14 a function definition with () means no
5411 * parameters (and not unspecified parameters) */
5412 if (type->function.unspecified_parameters &&
5413 type->function.parameters == NULL) {
5414 type_t *copy = duplicate_type(type);
5415 copy->function.unspecified_parameters = false;
5416 type = identify_new_type(copy);
5418 ndeclaration->declaration.type = type;
5421 entity_t *const entity = record_entity(ndeclaration, true);
5422 assert(entity->kind == ENTITY_FUNCTION);
5423 assert(ndeclaration->kind == ENTITY_FUNCTION);
5425 function_t *const function = &entity->function;
5426 if (ndeclaration != entity) {
5427 function->parameters = ndeclaration->function.parameters;
5429 assert(is_declaration(entity));
5430 type = skip_typeref(entity->declaration.type);
5432 PUSH_SCOPE(&function->parameters);
5434 entity_t *parameter = function->parameters.entities;
5435 for (; parameter != NULL; parameter = parameter->base.next) {
5436 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5437 parameter->base.parent_scope = current_scope;
5439 assert(parameter->base.parent_scope == NULL
5440 || parameter->base.parent_scope == current_scope);
5441 parameter->base.parent_scope = current_scope;
5442 if (parameter->base.symbol == NULL) {
5443 errorf(¶meter->base.source_position, "parameter name omitted");
5446 environment_push(parameter);
5449 if (function->statement != NULL) {
5450 parser_error_multiple_definition(entity, HERE);
5453 /* parse function body */
5454 int label_stack_top = label_top();
5455 function_t *old_current_function = current_function;
5456 entity_t *old_current_entity = current_entity;
5457 current_function = function;
5458 current_entity = entity;
5462 goto_anchor = &goto_first;
5464 label_anchor = &label_first;
5466 statement_t *const body = parse_compound_statement(false);
5467 function->statement = body;
5470 check_declarations();
5471 if (is_warn_on(WARN_RETURN_TYPE) ||
5472 is_warn_on(WARN_UNREACHABLE_CODE) ||
5473 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5474 noreturn_candidate = true;
5475 check_reachable(body);
5476 if (is_warn_on(WARN_UNREACHABLE_CODE))
5477 walk_statements(body, check_unreachable, NULL);
5478 if (noreturn_candidate &&
5479 !(function->base.modifiers & DM_NORETURN)) {
5480 source_position_t const *const pos = &body->base.source_position;
5481 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5486 assert(current_function == function);
5487 assert(current_entity == entity);
5488 current_entity = old_current_entity;
5489 current_function = old_current_function;
5490 label_pop_to(label_stack_top);
5496 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5498 entity_t *iter = compound->members.entities;
5499 for (; iter != NULL; iter = iter->base.next) {
5500 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5503 if (iter->base.symbol == symbol) {
5505 } else if (iter->base.symbol == NULL) {
5506 /* search in anonymous structs and unions */
5507 type_t *type = skip_typeref(iter->declaration.type);
5508 if (is_type_compound(type)) {
5509 if (find_compound_entry(type->compound.compound, symbol)
5520 static void check_deprecated(const source_position_t *source_position,
5521 const entity_t *entity)
5523 if (!is_declaration(entity))
5525 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5528 source_position_t const *const epos = &entity->base.source_position;
5529 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5531 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5533 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5538 static expression_t *create_select(const source_position_t *pos,
5540 type_qualifiers_t qualifiers,
5543 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5545 check_deprecated(pos, entry);
5547 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5548 select->select.compound = addr;
5549 select->select.compound_entry = entry;
5551 type_t *entry_type = entry->declaration.type;
5552 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5554 /* bitfields need special treatment */
5555 if (entry->compound_member.bitfield) {
5556 unsigned bit_size = entry->compound_member.bit_size;
5557 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5558 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5559 res_type = type_int;
5563 /* we always do the auto-type conversions; the & and sizeof parser contains
5564 * code to revert this! */
5565 select->base.type = automatic_type_conversion(res_type);
5572 * Find entry with symbol in compound. Search anonymous structs and unions and
5573 * creates implicit select expressions for them.
5574 * Returns the adress for the innermost compound.
5576 static expression_t *find_create_select(const source_position_t *pos,
5578 type_qualifiers_t qualifiers,
5579 compound_t *compound, symbol_t *symbol)
5581 entity_t *iter = compound->members.entities;
5582 for (; iter != NULL; iter = iter->base.next) {
5583 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5586 symbol_t *iter_symbol = iter->base.symbol;
5587 if (iter_symbol == NULL) {
5588 type_t *type = iter->declaration.type;
5589 if (type->kind != TYPE_COMPOUND_STRUCT
5590 && type->kind != TYPE_COMPOUND_UNION)
5593 compound_t *sub_compound = type->compound.compound;
5595 if (find_compound_entry(sub_compound, symbol) == NULL)
5598 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5599 sub_addr->base.source_position = *pos;
5600 sub_addr->base.implicit = true;
5601 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5605 if (iter_symbol == symbol) {
5606 return create_select(pos, addr, qualifiers, iter);
5613 static void parse_bitfield_member(entity_t *entity)
5617 expression_t *size = parse_constant_expression();
5620 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5621 type_t *type = entity->declaration.type;
5622 if (!is_type_integer(skip_typeref(type))) {
5623 errorf(HERE, "bitfield base type '%T' is not an integer type",
5627 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5628 /* error already reported by parse_constant_expression */
5629 size_long = get_type_size(type) * 8;
5631 size_long = fold_constant_to_int(size);
5633 const symbol_t *symbol = entity->base.symbol;
5634 const symbol_t *user_symbol
5635 = symbol == NULL ? sym_anonymous : symbol;
5636 unsigned bit_size = get_type_size(type) * 8;
5637 if (size_long < 0) {
5638 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5639 } else if (size_long == 0 && symbol != NULL) {
5640 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5641 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5642 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5645 /* hope that people don't invent crazy types with more bits
5646 * than our struct can hold */
5648 (1 << sizeof(entity->compound_member.bit_size)*8));
5652 entity->compound_member.bitfield = true;
5653 entity->compound_member.bit_size = (unsigned char)size_long;
5656 static void parse_compound_declarators(compound_t *compound,
5657 const declaration_specifiers_t *specifiers)
5662 if (token.kind == ':') {
5663 /* anonymous bitfield */
5664 type_t *type = specifiers->type;
5665 entity_t *entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER,
5666 NAMESPACE_NORMAL, NULL);
5667 entity->base.source_position = *HERE;
5668 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5669 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5670 entity->declaration.type = type;
5672 parse_bitfield_member(entity);
5674 attribute_t *attributes = parse_attributes(NULL);
5675 attribute_t **anchor = &attributes;
5676 while (*anchor != NULL)
5677 anchor = &(*anchor)->next;
5678 *anchor = specifiers->attributes;
5679 if (attributes != NULL) {
5680 handle_entity_attributes(attributes, entity);
5682 entity->declaration.attributes = attributes;
5684 append_entity(&compound->members, entity);
5686 entity = parse_declarator(specifiers,
5687 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5688 source_position_t const *const pos = &entity->base.source_position;
5689 if (entity->kind == ENTITY_TYPEDEF) {
5690 errorf(pos, "typedef not allowed as compound member");
5692 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5694 /* make sure we don't define a symbol multiple times */
5695 symbol_t *symbol = entity->base.symbol;
5696 if (symbol != NULL) {
5697 entity_t *prev = find_compound_entry(compound, symbol);
5699 source_position_t const *const ppos = &prev->base.source_position;
5700 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5704 if (token.kind == ':') {
5705 parse_bitfield_member(entity);
5707 attribute_t *attributes = parse_attributes(NULL);
5708 handle_entity_attributes(attributes, entity);
5710 type_t *orig_type = entity->declaration.type;
5711 type_t *type = skip_typeref(orig_type);
5712 if (is_type_function(type)) {
5713 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5714 } else if (is_type_incomplete(type)) {
5715 /* §6.7.2.1:16 flexible array member */
5716 if (!is_type_array(type) ||
5717 token.kind != ';' ||
5718 look_ahead(1)->kind != '}') {
5719 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5724 append_entity(&compound->members, entity);
5727 } while (next_if(','));
5728 expect(';', end_error);
5731 anonymous_entity = NULL;
5734 static void parse_compound_type_entries(compound_t *compound)
5737 add_anchor_token('}');
5740 switch (token.kind) {
5742 case T___extension__:
5743 case T_IDENTIFIER: {
5745 declaration_specifiers_t specifiers;
5746 parse_declaration_specifiers(&specifiers);
5747 parse_compound_declarators(compound, &specifiers);
5753 rem_anchor_token('}');
5754 expect('}', end_error);
5757 compound->complete = true;
5763 static type_t *parse_typename(void)
5765 declaration_specifiers_t specifiers;
5766 parse_declaration_specifiers(&specifiers);
5767 if (specifiers.storage_class != STORAGE_CLASS_NONE
5768 || specifiers.thread_local) {
5769 /* TODO: improve error message, user does probably not know what a
5770 * storage class is...
5772 errorf(&specifiers.source_position, "typename must not have a storage class");
5775 type_t *result = parse_abstract_declarator(specifiers.type);
5783 typedef expression_t* (*parse_expression_function)(void);
5784 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5786 typedef struct expression_parser_function_t expression_parser_function_t;
5787 struct expression_parser_function_t {
5788 parse_expression_function parser;
5789 precedence_t infix_precedence;
5790 parse_expression_infix_function infix_parser;
5793 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5796 * Prints an error message if an expression was expected but not read
5798 static expression_t *expected_expression_error(void)
5800 /* skip the error message if the error token was read */
5801 if (token.kind != T_ERROR) {
5802 errorf(HERE, "expected expression, got token %K", &token);
5806 return create_error_expression();
5809 static type_t *get_string_type(void)
5811 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5814 static type_t *get_wide_string_type(void)
5816 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5820 * Parse a string constant.
5822 static expression_t *parse_string_literal(void)
5824 source_position_t begin = token.base.source_position;
5825 string_t res = token.string.string;
5826 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5829 while (token.kind == T_STRING_LITERAL
5830 || token.kind == T_WIDE_STRING_LITERAL) {
5831 warn_string_concat(&token.base.source_position);
5832 res = concat_strings(&res, &token.string.string);
5834 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5837 expression_t *literal;
5839 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5840 literal->base.type = get_wide_string_type();
5842 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5843 literal->base.type = get_string_type();
5845 literal->base.source_position = begin;
5846 literal->literal.value = res;
5852 * Parse a boolean constant.
5854 static expression_t *parse_boolean_literal(bool value)
5856 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5857 literal->base.type = type_bool;
5858 literal->literal.value.begin = value ? "true" : "false";
5859 literal->literal.value.size = value ? 4 : 5;
5865 static void warn_traditional_suffix(void)
5867 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5868 &token.number.suffix);
5871 static void check_integer_suffix(void)
5873 const string_t *suffix = &token.number.suffix;
5874 if (suffix->size == 0)
5877 bool not_traditional = false;
5878 const char *c = suffix->begin;
5879 if (*c == 'l' || *c == 'L') {
5882 not_traditional = true;
5884 if (*c == 'u' || *c == 'U') {
5887 } else if (*c == 'u' || *c == 'U') {
5888 not_traditional = true;
5891 } else if (*c == 'u' || *c == 'U') {
5892 not_traditional = true;
5894 if (*c == 'l' || *c == 'L') {
5902 errorf(&token.base.source_position,
5903 "invalid suffix '%S' on integer constant", suffix);
5904 } else if (not_traditional) {
5905 warn_traditional_suffix();
5909 static type_t *check_floatingpoint_suffix(void)
5911 const string_t *suffix = &token.number.suffix;
5912 type_t *type = type_double;
5913 if (suffix->size == 0)
5916 bool not_traditional = false;
5917 const char *c = suffix->begin;
5918 if (*c == 'f' || *c == 'F') {
5921 } else if (*c == 'l' || *c == 'L') {
5923 type = type_long_double;
5926 errorf(&token.base.source_position,
5927 "invalid suffix '%S' on floatingpoint constant", suffix);
5928 } else if (not_traditional) {
5929 warn_traditional_suffix();
5936 * Parse an integer constant.
5938 static expression_t *parse_number_literal(void)
5940 expression_kind_t kind;
5943 switch (token.kind) {
5945 kind = EXPR_LITERAL_INTEGER;
5946 check_integer_suffix();
5949 case T_INTEGER_OCTAL:
5950 kind = EXPR_LITERAL_INTEGER_OCTAL;
5951 check_integer_suffix();
5954 case T_INTEGER_HEXADECIMAL:
5955 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5956 check_integer_suffix();
5959 case T_FLOATINGPOINT:
5960 kind = EXPR_LITERAL_FLOATINGPOINT;
5961 type = check_floatingpoint_suffix();
5963 case T_FLOATINGPOINT_HEXADECIMAL:
5964 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5965 type = check_floatingpoint_suffix();
5968 panic("unexpected token type in parse_number_literal");
5971 expression_t *literal = allocate_expression_zero(kind);
5972 literal->base.type = type;
5973 literal->literal.value = token.number.number;
5974 literal->literal.suffix = token.number.suffix;
5977 /* integer type depends on the size of the number and the size
5978 * representable by the types. The backend/codegeneration has to determine
5981 determine_literal_type(&literal->literal);
5986 * Parse a character constant.
5988 static expression_t *parse_character_constant(void)
5990 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5991 literal->base.type = c_mode & _CXX ? type_char : type_int;
5992 literal->literal.value = token.string.string;
5994 size_t len = literal->literal.value.size;
5996 if (!GNU_MODE && !(c_mode & _C99)) {
5997 errorf(HERE, "more than 1 character in character constant");
5999 literal->base.type = type_int;
6000 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6009 * Parse a wide character constant.
6011 static expression_t *parse_wide_character_constant(void)
6013 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6014 literal->base.type = type_int;
6015 literal->literal.value = token.string.string;
6017 size_t len = wstrlen(&literal->literal.value);
6019 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6026 static entity_t *create_implicit_function(symbol_t *symbol,
6027 const source_position_t *source_position)
6029 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6030 ntype->function.return_type = type_int;
6031 ntype->function.unspecified_parameters = true;
6032 ntype->function.linkage = LINKAGE_C;
6033 type_t *type = identify_new_type(ntype);
6035 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6036 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6037 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6038 entity->declaration.type = type;
6039 entity->declaration.implicit = true;
6040 entity->base.source_position = *source_position;
6042 if (current_scope != NULL)
6043 record_entity(entity, false);
6049 * Performs automatic type cast as described in §6.3.2.1.
6051 * @param orig_type the original type
6053 static type_t *automatic_type_conversion(type_t *orig_type)
6055 type_t *type = skip_typeref(orig_type);
6056 if (is_type_array(type)) {
6057 array_type_t *array_type = &type->array;
6058 type_t *element_type = array_type->element_type;
6059 unsigned qualifiers = array_type->base.qualifiers;
6061 return make_pointer_type(element_type, qualifiers);
6064 if (is_type_function(type)) {
6065 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6072 * reverts the automatic casts of array to pointer types and function
6073 * to function-pointer types as defined §6.3.2.1
6075 type_t *revert_automatic_type_conversion(const expression_t *expression)
6077 switch (expression->kind) {
6078 case EXPR_REFERENCE: {
6079 entity_t *entity = expression->reference.entity;
6080 if (is_declaration(entity)) {
6081 return entity->declaration.type;
6082 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6083 return entity->enum_value.enum_type;
6085 panic("no declaration or enum in reference");
6090 entity_t *entity = expression->select.compound_entry;
6091 assert(is_declaration(entity));
6092 type_t *type = entity->declaration.type;
6093 return get_qualified_type(type, expression->base.type->base.qualifiers);
6096 case EXPR_UNARY_DEREFERENCE: {
6097 const expression_t *const value = expression->unary.value;
6098 type_t *const type = skip_typeref(value->base.type);
6099 if (!is_type_pointer(type))
6100 return type_error_type;
6101 return type->pointer.points_to;
6104 case EXPR_ARRAY_ACCESS: {
6105 const expression_t *array_ref = expression->array_access.array_ref;
6106 type_t *type_left = skip_typeref(array_ref->base.type);
6107 if (!is_type_pointer(type_left))
6108 return type_error_type;
6109 return type_left->pointer.points_to;
6112 case EXPR_STRING_LITERAL: {
6113 size_t size = expression->string_literal.value.size;
6114 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6117 case EXPR_WIDE_STRING_LITERAL: {
6118 size_t size = wstrlen(&expression->string_literal.value);
6119 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6122 case EXPR_COMPOUND_LITERAL:
6123 return expression->compound_literal.type;
6128 return expression->base.type;
6132 * Find an entity matching a symbol in a scope.
6133 * Uses current scope if scope is NULL
6135 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6136 namespace_tag_t namespc)
6138 if (scope == NULL) {
6139 return get_entity(symbol, namespc);
6142 /* we should optimize here, if scope grows above a certain size we should
6143 construct a hashmap here... */
6144 entity_t *entity = scope->entities;
6145 for ( ; entity != NULL; entity = entity->base.next) {
6146 if (entity->base.symbol == symbol
6147 && (namespace_tag_t)entity->base.namespc == namespc)
6154 static entity_t *parse_qualified_identifier(void)
6156 /* namespace containing the symbol */
6158 source_position_t pos;
6159 const scope_t *lookup_scope = NULL;
6161 if (next_if(T_COLONCOLON))
6162 lookup_scope = &unit->scope;
6166 if (token.kind != T_IDENTIFIER) {
6167 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6168 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6170 symbol = token.identifier.symbol;
6175 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6177 if (!next_if(T_COLONCOLON))
6180 switch (entity->kind) {
6181 case ENTITY_NAMESPACE:
6182 lookup_scope = &entity->namespacee.members;
6187 lookup_scope = &entity->compound.members;
6190 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6191 symbol, get_entity_kind_name(entity->kind));
6193 /* skip further qualifications */
6194 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6196 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6200 if (entity == NULL) {
6201 if (!strict_mode && token.kind == '(') {
6202 /* an implicitly declared function */
6203 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6204 entity = create_implicit_function(symbol, &pos);
6206 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6207 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6214 static expression_t *parse_reference(void)
6216 source_position_t const pos = token.base.source_position;
6217 entity_t *const entity = parse_qualified_identifier();
6220 if (is_declaration(entity)) {
6221 orig_type = entity->declaration.type;
6222 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6223 orig_type = entity->enum_value.enum_type;
6225 panic("expected declaration or enum value in reference");
6228 /* we always do the auto-type conversions; the & and sizeof parser contains
6229 * code to revert this! */
6230 type_t *type = automatic_type_conversion(orig_type);
6232 expression_kind_t kind = EXPR_REFERENCE;
6233 if (entity->kind == ENTITY_ENUM_VALUE)
6234 kind = EXPR_REFERENCE_ENUM_VALUE;
6236 expression_t *expression = allocate_expression_zero(kind);
6237 expression->base.source_position = pos;
6238 expression->base.type = type;
6239 expression->reference.entity = entity;
6241 /* this declaration is used */
6242 if (is_declaration(entity)) {
6243 entity->declaration.used = true;
6246 if (entity->base.parent_scope != file_scope
6247 && (current_function != NULL
6248 && entity->base.parent_scope->depth < current_function->parameters.depth)
6249 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6250 if (entity->kind == ENTITY_VARIABLE) {
6251 /* access of a variable from an outer function */
6252 entity->variable.address_taken = true;
6253 } else if (entity->kind == ENTITY_PARAMETER) {
6254 entity->parameter.address_taken = true;
6256 current_function->need_closure = true;
6259 check_deprecated(&pos, entity);
6264 static bool semantic_cast(expression_t *cast)
6266 expression_t *expression = cast->unary.value;
6267 type_t *orig_dest_type = cast->base.type;
6268 type_t *orig_type_right = expression->base.type;
6269 type_t const *dst_type = skip_typeref(orig_dest_type);
6270 type_t const *src_type = skip_typeref(orig_type_right);
6271 source_position_t const *pos = &cast->base.source_position;
6273 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6274 if (dst_type == type_void)
6277 /* only integer and pointer can be casted to pointer */
6278 if (is_type_pointer(dst_type) &&
6279 !is_type_pointer(src_type) &&
6280 !is_type_integer(src_type) &&
6281 is_type_valid(src_type)) {
6282 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6286 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6287 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6291 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6292 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6296 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6297 type_t *src = skip_typeref(src_type->pointer.points_to);
6298 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6299 unsigned missing_qualifiers =
6300 src->base.qualifiers & ~dst->base.qualifiers;
6301 if (missing_qualifiers != 0) {
6302 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6308 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6310 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6311 expression->base.source_position = *pos;
6313 parse_initializer_env_t env;
6316 env.must_be_constant = false;
6317 initializer_t *initializer = parse_initializer(&env);
6320 expression->compound_literal.initializer = initializer;
6321 expression->compound_literal.type = type;
6322 expression->base.type = automatic_type_conversion(type);
6328 * Parse a cast expression.
6330 static expression_t *parse_cast(void)
6332 source_position_t const pos = *HERE;
6335 add_anchor_token(')');
6337 type_t *type = parse_typename();
6339 rem_anchor_token(')');
6340 expect(')', end_error);
6342 if (token.kind == '{') {
6343 return parse_compound_literal(&pos, type);
6346 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6347 cast->base.source_position = pos;
6349 expression_t *value = parse_subexpression(PREC_CAST);
6350 cast->base.type = type;
6351 cast->unary.value = value;
6353 if (! semantic_cast(cast)) {
6354 /* TODO: record the error in the AST. else it is impossible to detect it */
6359 return create_error_expression();
6363 * Parse a statement expression.
6365 static expression_t *parse_statement_expression(void)
6367 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6370 add_anchor_token(')');
6372 statement_t *statement = parse_compound_statement(true);
6373 statement->compound.stmt_expr = true;
6374 expression->statement.statement = statement;
6376 /* find last statement and use its type */
6377 type_t *type = type_void;
6378 const statement_t *stmt = statement->compound.statements;
6380 while (stmt->base.next != NULL)
6381 stmt = stmt->base.next;
6383 if (stmt->kind == STATEMENT_EXPRESSION) {
6384 type = stmt->expression.expression->base.type;
6387 source_position_t const *const pos = &expression->base.source_position;
6388 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6390 expression->base.type = type;
6392 rem_anchor_token(')');
6393 expect(')', end_error);
6400 * Parse a parenthesized expression.
6402 static expression_t *parse_parenthesized_expression(void)
6404 token_t const* const la1 = look_ahead(1);
6405 switch (la1->kind) {
6407 /* gcc extension: a statement expression */
6408 return parse_statement_expression();
6411 if (is_typedef_symbol(la1->identifier.symbol)) {
6413 return parse_cast();
6418 add_anchor_token(')');
6419 expression_t *result = parse_expression();
6420 result->base.parenthesized = true;
6421 rem_anchor_token(')');
6422 expect(')', end_error);
6428 static expression_t *parse_function_keyword(void)
6432 if (current_function == NULL) {
6433 errorf(HERE, "'__func__' used outside of a function");
6436 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6437 expression->base.type = type_char_ptr;
6438 expression->funcname.kind = FUNCNAME_FUNCTION;
6445 static expression_t *parse_pretty_function_keyword(void)
6447 if (current_function == NULL) {
6448 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6451 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6452 expression->base.type = type_char_ptr;
6453 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6455 eat(T___PRETTY_FUNCTION__);
6460 static expression_t *parse_funcsig_keyword(void)
6462 if (current_function == NULL) {
6463 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6466 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6467 expression->base.type = type_char_ptr;
6468 expression->funcname.kind = FUNCNAME_FUNCSIG;
6475 static expression_t *parse_funcdname_keyword(void)
6477 if (current_function == NULL) {
6478 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6481 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6482 expression->base.type = type_char_ptr;
6483 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6485 eat(T___FUNCDNAME__);
6490 static designator_t *parse_designator(void)
6492 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6493 result->source_position = *HERE;
6495 if (token.kind != T_IDENTIFIER) {
6496 parse_error_expected("while parsing member designator",
6497 T_IDENTIFIER, NULL);
6500 result->symbol = token.identifier.symbol;
6503 designator_t *last_designator = result;
6506 if (token.kind != T_IDENTIFIER) {
6507 parse_error_expected("while parsing member designator",
6508 T_IDENTIFIER, NULL);
6511 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6512 designator->source_position = *HERE;
6513 designator->symbol = token.identifier.symbol;
6516 last_designator->next = designator;
6517 last_designator = designator;
6521 add_anchor_token(']');
6522 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6523 designator->source_position = *HERE;
6524 designator->array_index = parse_expression();
6525 rem_anchor_token(']');
6526 expect(']', end_error);
6527 if (designator->array_index == NULL) {
6531 last_designator->next = designator;
6532 last_designator = designator;
6544 * Parse the __builtin_offsetof() expression.
6546 static expression_t *parse_offsetof(void)
6548 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6549 expression->base.type = type_size_t;
6551 eat(T___builtin_offsetof);
6553 expect('(', end_error);
6554 add_anchor_token(',');
6555 type_t *type = parse_typename();
6556 rem_anchor_token(',');
6557 expect(',', end_error);
6558 add_anchor_token(')');
6559 designator_t *designator = parse_designator();
6560 rem_anchor_token(')');
6561 expect(')', end_error);
6563 expression->offsetofe.type = type;
6564 expression->offsetofe.designator = designator;
6567 memset(&path, 0, sizeof(path));
6568 path.top_type = type;
6569 path.path = NEW_ARR_F(type_path_entry_t, 0);
6571 descend_into_subtype(&path);
6573 if (!walk_designator(&path, designator, true)) {
6574 return create_error_expression();
6577 DEL_ARR_F(path.path);
6581 return create_error_expression();
6585 * Parses a _builtin_va_start() expression.
6587 static expression_t *parse_va_start(void)
6589 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6591 eat(T___builtin_va_start);
6593 expect('(', end_error);
6594 add_anchor_token(',');
6595 expression->va_starte.ap = parse_assignment_expression();
6596 rem_anchor_token(',');
6597 expect(',', end_error);
6598 expression_t *const expr = parse_assignment_expression();
6599 if (expr->kind == EXPR_REFERENCE) {
6600 entity_t *const entity = expr->reference.entity;
6601 if (!current_function->base.type->function.variadic) {
6602 errorf(&expr->base.source_position,
6603 "'va_start' used in non-variadic function");
6604 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6605 entity->base.next != NULL ||
6606 entity->kind != ENTITY_PARAMETER) {
6607 errorf(&expr->base.source_position,
6608 "second argument of 'va_start' must be last parameter of the current function");
6610 expression->va_starte.parameter = &entity->variable;
6612 expect(')', end_error);
6615 expect(')', end_error);
6617 return create_error_expression();
6621 * Parses a __builtin_va_arg() expression.
6623 static expression_t *parse_va_arg(void)
6625 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6627 eat(T___builtin_va_arg);
6629 expect('(', end_error);
6631 ap.expression = parse_assignment_expression();
6632 expression->va_arge.ap = ap.expression;
6633 check_call_argument(type_valist, &ap, 1);
6635 expect(',', end_error);
6636 expression->base.type = parse_typename();
6637 expect(')', end_error);
6641 return create_error_expression();
6645 * Parses a __builtin_va_copy() expression.
6647 static expression_t *parse_va_copy(void)
6649 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6651 eat(T___builtin_va_copy);
6653 expect('(', end_error);
6654 expression_t *dst = parse_assignment_expression();
6655 assign_error_t error = semantic_assign(type_valist, dst);
6656 report_assign_error(error, type_valist, dst, "call argument 1",
6657 &dst->base.source_position);
6658 expression->va_copye.dst = dst;
6660 expect(',', end_error);
6662 call_argument_t src;
6663 src.expression = parse_assignment_expression();
6664 check_call_argument(type_valist, &src, 2);
6665 expression->va_copye.src = src.expression;
6666 expect(')', end_error);
6670 return create_error_expression();
6674 * Parses a __builtin_constant_p() expression.
6676 static expression_t *parse_builtin_constant(void)
6678 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6680 eat(T___builtin_constant_p);
6682 expect('(', end_error);
6683 add_anchor_token(')');
6684 expression->builtin_constant.value = parse_assignment_expression();
6685 rem_anchor_token(')');
6686 expect(')', end_error);
6687 expression->base.type = type_int;
6691 return create_error_expression();
6695 * Parses a __builtin_types_compatible_p() expression.
6697 static expression_t *parse_builtin_types_compatible(void)
6699 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6701 eat(T___builtin_types_compatible_p);
6703 expect('(', end_error);
6704 add_anchor_token(')');
6705 add_anchor_token(',');
6706 expression->builtin_types_compatible.left = parse_typename();
6707 rem_anchor_token(',');
6708 expect(',', end_error);
6709 expression->builtin_types_compatible.right = parse_typename();
6710 rem_anchor_token(')');
6711 expect(')', end_error);
6712 expression->base.type = type_int;
6716 return create_error_expression();
6720 * Parses a __builtin_is_*() compare expression.
6722 static expression_t *parse_compare_builtin(void)
6724 expression_t *expression;
6726 switch (token.kind) {
6727 case T___builtin_isgreater:
6728 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6730 case T___builtin_isgreaterequal:
6731 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6733 case T___builtin_isless:
6734 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6736 case T___builtin_islessequal:
6737 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6739 case T___builtin_islessgreater:
6740 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6742 case T___builtin_isunordered:
6743 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6746 internal_errorf(HERE, "invalid compare builtin found");
6748 expression->base.source_position = *HERE;
6751 expect('(', end_error);
6752 expression->binary.left = parse_assignment_expression();
6753 expect(',', end_error);
6754 expression->binary.right = parse_assignment_expression();
6755 expect(')', end_error);
6757 type_t *const orig_type_left = expression->binary.left->base.type;
6758 type_t *const orig_type_right = expression->binary.right->base.type;
6760 type_t *const type_left = skip_typeref(orig_type_left);
6761 type_t *const type_right = skip_typeref(orig_type_right);
6762 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6763 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6764 type_error_incompatible("invalid operands in comparison",
6765 &expression->base.source_position, orig_type_left, orig_type_right);
6768 semantic_comparison(&expression->binary);
6773 return create_error_expression();
6777 * Parses a MS assume() expression.
6779 static expression_t *parse_assume(void)
6781 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6785 expect('(', end_error);
6786 add_anchor_token(')');
6787 expression->unary.value = parse_assignment_expression();
6788 rem_anchor_token(')');
6789 expect(')', end_error);
6791 expression->base.type = type_void;
6794 return create_error_expression();
6798 * Return the label for the current symbol or create a new one.
6800 static label_t *get_label(void)
6802 assert(token.kind == T_IDENTIFIER);
6803 assert(current_function != NULL);
6805 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6806 /* If we find a local label, we already created the declaration. */
6807 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6808 if (label->base.parent_scope != current_scope) {
6809 assert(label->base.parent_scope->depth < current_scope->depth);
6810 current_function->goto_to_outer = true;
6812 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6813 /* There is no matching label in the same function, so create a new one. */
6814 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol);
6819 return &label->label;
6823 * Parses a GNU && label address expression.
6825 static expression_t *parse_label_address(void)
6827 source_position_t source_position = token.base.source_position;
6829 if (token.kind != T_IDENTIFIER) {
6830 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6831 return create_error_expression();
6834 label_t *const label = get_label();
6836 label->address_taken = true;
6838 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6839 expression->base.source_position = source_position;
6841 /* label address is treated as a void pointer */
6842 expression->base.type = type_void_ptr;
6843 expression->label_address.label = label;
6848 * Parse a microsoft __noop expression.
6850 static expression_t *parse_noop_expression(void)
6852 /* the result is a (int)0 */
6853 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6854 literal->base.type = type_int;
6855 literal->literal.value.begin = "__noop";
6856 literal->literal.value.size = 6;
6860 if (token.kind == '(') {
6861 /* parse arguments */
6863 add_anchor_token(')');
6864 add_anchor_token(',');
6866 if (token.kind != ')') do {
6867 (void)parse_assignment_expression();
6868 } while (next_if(','));
6870 rem_anchor_token(',');
6871 rem_anchor_token(')');
6872 expect(')', end_error);
6879 * Parses a primary expression.
6881 static expression_t *parse_primary_expression(void)
6883 switch (token.kind) {
6884 case T_false: return parse_boolean_literal(false);
6885 case T_true: return parse_boolean_literal(true);
6887 case T_INTEGER_OCTAL:
6888 case T_INTEGER_HEXADECIMAL:
6889 case T_FLOATINGPOINT:
6890 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6891 case T_CHARACTER_CONSTANT: return parse_character_constant();
6892 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6893 case T_STRING_LITERAL:
6894 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6895 case T___FUNCTION__:
6896 case T___func__: return parse_function_keyword();
6897 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6898 case T___FUNCSIG__: return parse_funcsig_keyword();
6899 case T___FUNCDNAME__: return parse_funcdname_keyword();
6900 case T___builtin_offsetof: return parse_offsetof();
6901 case T___builtin_va_start: return parse_va_start();
6902 case T___builtin_va_arg: return parse_va_arg();
6903 case T___builtin_va_copy: return parse_va_copy();
6904 case T___builtin_isgreater:
6905 case T___builtin_isgreaterequal:
6906 case T___builtin_isless:
6907 case T___builtin_islessequal:
6908 case T___builtin_islessgreater:
6909 case T___builtin_isunordered: return parse_compare_builtin();
6910 case T___builtin_constant_p: return parse_builtin_constant();
6911 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6912 case T__assume: return parse_assume();
6915 return parse_label_address();
6918 case '(': return parse_parenthesized_expression();
6919 case T___noop: return parse_noop_expression();
6921 /* Gracefully handle type names while parsing expressions. */
6923 return parse_reference();
6925 if (!is_typedef_symbol(token.identifier.symbol)) {
6926 return parse_reference();
6930 source_position_t const pos = *HERE;
6931 declaration_specifiers_t specifiers;
6932 parse_declaration_specifiers(&specifiers);
6933 type_t const *const type = parse_abstract_declarator(specifiers.type);
6934 errorf(&pos, "encountered type '%T' while parsing expression", type);
6935 return create_error_expression();
6939 errorf(HERE, "unexpected token %K, expected an expression", &token);
6941 return create_error_expression();
6944 static expression_t *parse_array_expression(expression_t *left)
6946 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6947 array_access_expression_t *const arr = &expr->array_access;
6950 add_anchor_token(']');
6952 expression_t *const inside = parse_expression();
6954 type_t *const orig_type_left = left->base.type;
6955 type_t *const orig_type_inside = inside->base.type;
6957 type_t *const type_left = skip_typeref(orig_type_left);
6958 type_t *const type_inside = skip_typeref(orig_type_inside);
6964 if (is_type_pointer(type_left)) {
6967 idx_type = type_inside;
6968 res_type = type_left->pointer.points_to;
6970 } else if (is_type_pointer(type_inside)) {
6971 arr->flipped = true;
6974 idx_type = type_left;
6975 res_type = type_inside->pointer.points_to;
6977 res_type = automatic_type_conversion(res_type);
6978 if (!is_type_integer(idx_type)) {
6979 errorf(&idx->base.source_position, "array subscript must have integer type");
6980 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6981 source_position_t const *const pos = &idx->base.source_position;
6982 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6985 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6986 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6988 res_type = type_error_type;
6993 arr->array_ref = ref;
6995 arr->base.type = res_type;
6997 rem_anchor_token(']');
6998 expect(']', end_error);
7003 static bool is_bitfield(const expression_t *expression)
7005 return expression->kind == EXPR_SELECT
7006 && expression->select.compound_entry->compound_member.bitfield;
7009 static expression_t *parse_typeprop(expression_kind_t const kind)
7011 expression_t *tp_expression = allocate_expression_zero(kind);
7012 tp_expression->base.type = type_size_t;
7014 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7017 expression_t *expression;
7018 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
7019 source_position_t const pos = *HERE;
7021 add_anchor_token(')');
7022 orig_type = parse_typename();
7023 rem_anchor_token(')');
7024 expect(')', end_error);
7026 if (token.kind == '{') {
7027 /* It was not sizeof(type) after all. It is sizeof of an expression
7028 * starting with a compound literal */
7029 expression = parse_compound_literal(&pos, orig_type);
7030 goto typeprop_expression;
7033 expression = parse_subexpression(PREC_UNARY);
7035 typeprop_expression:
7036 if (is_bitfield(expression)) {
7037 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7038 errorf(&tp_expression->base.source_position,
7039 "operand of %s expression must not be a bitfield", what);
7042 tp_expression->typeprop.tp_expression = expression;
7044 orig_type = revert_automatic_type_conversion(expression);
7045 expression->base.type = orig_type;
7048 tp_expression->typeprop.type = orig_type;
7049 type_t const* const type = skip_typeref(orig_type);
7050 char const* wrong_type = NULL;
7051 if (is_type_incomplete(type)) {
7052 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7053 wrong_type = "incomplete";
7054 } else if (type->kind == TYPE_FUNCTION) {
7056 /* function types are allowed (and return 1) */
7057 source_position_t const *const pos = &tp_expression->base.source_position;
7058 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7059 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7061 wrong_type = "function";
7065 if (wrong_type != NULL) {
7066 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7067 errorf(&tp_expression->base.source_position,
7068 "operand of %s expression must not be of %s type '%T'",
7069 what, wrong_type, orig_type);
7073 return tp_expression;
7076 static expression_t *parse_sizeof(void)
7078 return parse_typeprop(EXPR_SIZEOF);
7081 static expression_t *parse_alignof(void)
7083 return parse_typeprop(EXPR_ALIGNOF);
7086 static expression_t *parse_select_expression(expression_t *addr)
7088 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7089 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7090 source_position_t const pos = *HERE;
7093 if (token.kind != T_IDENTIFIER) {
7094 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7095 return create_error_expression();
7097 symbol_t *symbol = token.identifier.symbol;
7100 type_t *const orig_type = addr->base.type;
7101 type_t *const type = skip_typeref(orig_type);
7104 bool saw_error = false;
7105 if (is_type_pointer(type)) {
7106 if (!select_left_arrow) {
7108 "request for member '%Y' in something not a struct or union, but '%T'",
7112 type_left = skip_typeref(type->pointer.points_to);
7114 if (select_left_arrow && is_type_valid(type)) {
7115 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7121 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7122 type_left->kind != TYPE_COMPOUND_UNION) {
7124 if (is_type_valid(type_left) && !saw_error) {
7126 "request for member '%Y' in something not a struct or union, but '%T'",
7129 return create_error_expression();
7132 compound_t *compound = type_left->compound.compound;
7133 if (!compound->complete) {
7134 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7136 return create_error_expression();
7139 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7140 expression_t *result =
7141 find_create_select(&pos, addr, qualifiers, compound, symbol);
7143 if (result == NULL) {
7144 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7145 return create_error_expression();
7151 static void check_call_argument(type_t *expected_type,
7152 call_argument_t *argument, unsigned pos)
7154 type_t *expected_type_skip = skip_typeref(expected_type);
7155 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7156 expression_t *arg_expr = argument->expression;
7157 type_t *arg_type = skip_typeref(arg_expr->base.type);
7159 /* handle transparent union gnu extension */
7160 if (is_type_union(expected_type_skip)
7161 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7162 compound_t *union_decl = expected_type_skip->compound.compound;
7163 type_t *best_type = NULL;
7164 entity_t *entry = union_decl->members.entities;
7165 for ( ; entry != NULL; entry = entry->base.next) {
7166 assert(is_declaration(entry));
7167 type_t *decl_type = entry->declaration.type;
7168 error = semantic_assign(decl_type, arg_expr);
7169 if (error == ASSIGN_ERROR_INCOMPATIBLE
7170 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7173 if (error == ASSIGN_SUCCESS) {
7174 best_type = decl_type;
7175 } else if (best_type == NULL) {
7176 best_type = decl_type;
7180 if (best_type != NULL) {
7181 expected_type = best_type;
7185 error = semantic_assign(expected_type, arg_expr);
7186 argument->expression = create_implicit_cast(arg_expr, expected_type);
7188 if (error != ASSIGN_SUCCESS) {
7189 /* report exact scope in error messages (like "in argument 3") */
7191 snprintf(buf, sizeof(buf), "call argument %u", pos);
7192 report_assign_error(error, expected_type, arg_expr, buf,
7193 &arg_expr->base.source_position);
7195 type_t *const promoted_type = get_default_promoted_type(arg_type);
7196 if (!types_compatible(expected_type_skip, promoted_type) &&
7197 !types_compatible(expected_type_skip, type_void_ptr) &&
7198 !types_compatible(type_void_ptr, promoted_type)) {
7199 /* Deliberately show the skipped types in this warning */
7200 source_position_t const *const apos = &arg_expr->base.source_position;
7201 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7207 * Handle the semantic restrictions of builtin calls
7209 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7210 switch (call->function->reference.entity->function.btk) {
7211 case bk_gnu_builtin_return_address:
7212 case bk_gnu_builtin_frame_address: {
7213 /* argument must be constant */
7214 call_argument_t *argument = call->arguments;
7216 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7217 errorf(&call->base.source_position,
7218 "argument of '%Y' must be a constant expression",
7219 call->function->reference.entity->base.symbol);
7223 case bk_gnu_builtin_object_size:
7224 if (call->arguments == NULL)
7227 call_argument_t *arg = call->arguments->next;
7228 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7229 errorf(&call->base.source_position,
7230 "second argument of '%Y' must be a constant expression",
7231 call->function->reference.entity->base.symbol);
7234 case bk_gnu_builtin_prefetch:
7235 /* second and third argument must be constant if existent */
7236 if (call->arguments == NULL)
7238 call_argument_t *rw = call->arguments->next;
7239 call_argument_t *locality = NULL;
7242 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7243 errorf(&call->base.source_position,
7244 "second argument of '%Y' must be a constant expression",
7245 call->function->reference.entity->base.symbol);
7247 locality = rw->next;
7249 if (locality != NULL) {
7250 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7251 errorf(&call->base.source_position,
7252 "third argument of '%Y' must be a constant expression",
7253 call->function->reference.entity->base.symbol);
7255 locality = rw->next;
7264 * Parse a call expression, ie. expression '( ... )'.
7266 * @param expression the function address
7268 static expression_t *parse_call_expression(expression_t *expression)
7270 expression_t *result = allocate_expression_zero(EXPR_CALL);
7271 call_expression_t *call = &result->call;
7272 call->function = expression;
7274 type_t *const orig_type = expression->base.type;
7275 type_t *const type = skip_typeref(orig_type);
7277 function_type_t *function_type = NULL;
7278 if (is_type_pointer(type)) {
7279 type_t *const to_type = skip_typeref(type->pointer.points_to);
7281 if (is_type_function(to_type)) {
7282 function_type = &to_type->function;
7283 call->base.type = function_type->return_type;
7287 if (function_type == NULL && is_type_valid(type)) {
7289 "called object '%E' (type '%T') is not a pointer to a function",
7290 expression, orig_type);
7293 /* parse arguments */
7295 add_anchor_token(')');
7296 add_anchor_token(',');
7298 if (token.kind != ')') {
7299 call_argument_t **anchor = &call->arguments;
7301 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7302 argument->expression = parse_assignment_expression();
7305 anchor = &argument->next;
7306 } while (next_if(','));
7308 rem_anchor_token(',');
7309 rem_anchor_token(')');
7310 expect(')', end_error);
7312 if (function_type == NULL)
7315 /* check type and count of call arguments */
7316 function_parameter_t *parameter = function_type->parameters;
7317 call_argument_t *argument = call->arguments;
7318 if (!function_type->unspecified_parameters) {
7319 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7320 parameter = parameter->next, argument = argument->next) {
7321 check_call_argument(parameter->type, argument, ++pos);
7324 if (parameter != NULL) {
7325 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7326 } else if (argument != NULL && !function_type->variadic) {
7327 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7331 /* do default promotion for other arguments */
7332 for (; argument != NULL; argument = argument->next) {
7333 type_t *argument_type = argument->expression->base.type;
7334 if (!is_type_object(skip_typeref(argument_type))) {
7335 errorf(&argument->expression->base.source_position,
7336 "call argument '%E' must not be void", argument->expression);
7339 argument_type = get_default_promoted_type(argument_type);
7341 argument->expression
7342 = create_implicit_cast(argument->expression, argument_type);
7347 if (is_type_compound(skip_typeref(function_type->return_type))) {
7348 source_position_t const *const pos = &expression->base.source_position;
7349 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7352 if (expression->kind == EXPR_REFERENCE) {
7353 reference_expression_t *reference = &expression->reference;
7354 if (reference->entity->kind == ENTITY_FUNCTION &&
7355 reference->entity->function.btk != bk_none)
7356 handle_builtin_argument_restrictions(call);
7363 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7365 static bool same_compound_type(const type_t *type1, const type_t *type2)
7368 is_type_compound(type1) &&
7369 type1->kind == type2->kind &&
7370 type1->compound.compound == type2->compound.compound;
7373 static expression_t const *get_reference_address(expression_t const *expr)
7375 bool regular_take_address = true;
7377 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7378 expr = expr->unary.value;
7380 regular_take_address = false;
7383 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7386 expr = expr->unary.value;
7389 if (expr->kind != EXPR_REFERENCE)
7392 /* special case for functions which are automatically converted to a
7393 * pointer to function without an extra TAKE_ADDRESS operation */
7394 if (!regular_take_address &&
7395 expr->reference.entity->kind != ENTITY_FUNCTION) {
7402 static void warn_reference_address_as_bool(expression_t const* expr)
7404 expr = get_reference_address(expr);
7406 source_position_t const *const pos = &expr->base.source_position;
7407 entity_t const *const ent = expr->reference.entity;
7408 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7412 static void warn_assignment_in_condition(const expression_t *const expr)
7414 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7416 if (expr->base.parenthesized)
7418 source_position_t const *const pos = &expr->base.source_position;
7419 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7422 static void semantic_condition(expression_t const *const expr,
7423 char const *const context)
7425 type_t *const type = skip_typeref(expr->base.type);
7426 if (is_type_scalar(type)) {
7427 warn_reference_address_as_bool(expr);
7428 warn_assignment_in_condition(expr);
7429 } else if (is_type_valid(type)) {
7430 errorf(&expr->base.source_position,
7431 "%s must have scalar type", context);
7436 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7438 * @param expression the conditional expression
7440 static expression_t *parse_conditional_expression(expression_t *expression)
7442 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7444 conditional_expression_t *conditional = &result->conditional;
7445 conditional->condition = expression;
7448 add_anchor_token(':');
7450 /* §6.5.15:2 The first operand shall have scalar type. */
7451 semantic_condition(expression, "condition of conditional operator");
7453 expression_t *true_expression = expression;
7454 bool gnu_cond = false;
7455 if (GNU_MODE && token.kind == ':') {
7458 true_expression = parse_expression();
7460 rem_anchor_token(':');
7461 expect(':', end_error);
7463 expression_t *false_expression =
7464 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7466 type_t *const orig_true_type = true_expression->base.type;
7467 type_t *const orig_false_type = false_expression->base.type;
7468 type_t *const true_type = skip_typeref(orig_true_type);
7469 type_t *const false_type = skip_typeref(orig_false_type);
7472 source_position_t const *const pos = &conditional->base.source_position;
7473 type_t *result_type;
7474 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7475 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7476 /* ISO/IEC 14882:1998(E) §5.16:2 */
7477 if (true_expression->kind == EXPR_UNARY_THROW) {
7478 result_type = false_type;
7479 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7480 result_type = true_type;
7482 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7483 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7484 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7486 result_type = type_void;
7488 } else if (is_type_arithmetic(true_type)
7489 && is_type_arithmetic(false_type)) {
7490 result_type = semantic_arithmetic(true_type, false_type);
7491 } else if (same_compound_type(true_type, false_type)) {
7492 /* just take 1 of the 2 types */
7493 result_type = true_type;
7494 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7495 type_t *pointer_type;
7497 expression_t *other_expression;
7498 if (is_type_pointer(true_type) &&
7499 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7500 pointer_type = true_type;
7501 other_type = false_type;
7502 other_expression = false_expression;
7504 pointer_type = false_type;
7505 other_type = true_type;
7506 other_expression = true_expression;
7509 if (is_null_pointer_constant(other_expression)) {
7510 result_type = pointer_type;
7511 } else if (is_type_pointer(other_type)) {
7512 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7513 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7516 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7517 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7519 } else if (types_compatible(get_unqualified_type(to1),
7520 get_unqualified_type(to2))) {
7523 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7527 type_t *const type =
7528 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7529 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7530 } else if (is_type_integer(other_type)) {
7531 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7532 result_type = pointer_type;
7534 goto types_incompatible;
7538 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7539 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7541 result_type = type_error_type;
7544 conditional->true_expression
7545 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7546 conditional->false_expression
7547 = create_implicit_cast(false_expression, result_type);
7548 conditional->base.type = result_type;
7553 * Parse an extension expression.
7555 static expression_t *parse_extension(void)
7558 expression_t *expression = parse_subexpression(PREC_UNARY);
7564 * Parse a __builtin_classify_type() expression.
7566 static expression_t *parse_builtin_classify_type(void)
7568 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7569 result->base.type = type_int;
7571 eat(T___builtin_classify_type);
7573 expect('(', end_error);
7574 add_anchor_token(')');
7575 expression_t *expression = parse_expression();
7576 rem_anchor_token(')');
7577 expect(')', end_error);
7578 result->classify_type.type_expression = expression;
7582 return create_error_expression();
7586 * Parse a delete expression
7587 * ISO/IEC 14882:1998(E) §5.3.5
7589 static expression_t *parse_delete(void)
7591 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7592 result->base.type = type_void;
7597 result->kind = EXPR_UNARY_DELETE_ARRAY;
7598 expect(']', end_error);
7602 expression_t *const value = parse_subexpression(PREC_CAST);
7603 result->unary.value = value;
7605 type_t *const type = skip_typeref(value->base.type);
7606 if (!is_type_pointer(type)) {
7607 if (is_type_valid(type)) {
7608 errorf(&value->base.source_position,
7609 "operand of delete must have pointer type");
7611 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7612 source_position_t const *const pos = &value->base.source_position;
7613 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7620 * Parse a throw expression
7621 * ISO/IEC 14882:1998(E) §15:1
7623 static expression_t *parse_throw(void)
7625 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7626 result->base.type = type_void;
7630 expression_t *value = NULL;
7631 switch (token.kind) {
7633 value = parse_assignment_expression();
7634 /* ISO/IEC 14882:1998(E) §15.1:3 */
7635 type_t *const orig_type = value->base.type;
7636 type_t *const type = skip_typeref(orig_type);
7637 if (is_type_incomplete(type)) {
7638 errorf(&value->base.source_position,
7639 "cannot throw object of incomplete type '%T'", orig_type);
7640 } else if (is_type_pointer(type)) {
7641 type_t *const points_to = skip_typeref(type->pointer.points_to);
7642 if (is_type_incomplete(points_to) &&
7643 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7644 errorf(&value->base.source_position,
7645 "cannot throw pointer to incomplete type '%T'", orig_type);
7653 result->unary.value = value;
7658 static bool check_pointer_arithmetic(const source_position_t *source_position,
7659 type_t *pointer_type,
7660 type_t *orig_pointer_type)
7662 type_t *points_to = pointer_type->pointer.points_to;
7663 points_to = skip_typeref(points_to);
7665 if (is_type_incomplete(points_to)) {
7666 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7667 errorf(source_position,
7668 "arithmetic with pointer to incomplete type '%T' not allowed",
7672 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7674 } else if (is_type_function(points_to)) {
7676 errorf(source_position,
7677 "arithmetic with pointer to function type '%T' not allowed",
7681 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7687 static bool is_lvalue(const expression_t *expression)
7689 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7690 switch (expression->kind) {
7691 case EXPR_ARRAY_ACCESS:
7692 case EXPR_COMPOUND_LITERAL:
7693 case EXPR_REFERENCE:
7695 case EXPR_UNARY_DEREFERENCE:
7699 type_t *type = skip_typeref(expression->base.type);
7701 /* ISO/IEC 14882:1998(E) §3.10:3 */
7702 is_type_reference(type) ||
7703 /* Claim it is an lvalue, if the type is invalid. There was a parse
7704 * error before, which maybe prevented properly recognizing it as
7706 !is_type_valid(type);
7711 static void semantic_incdec(unary_expression_t *expression)
7713 type_t *const orig_type = expression->value->base.type;
7714 type_t *const type = skip_typeref(orig_type);
7715 if (is_type_pointer(type)) {
7716 if (!check_pointer_arithmetic(&expression->base.source_position,
7720 } else if (!is_type_real(type) && is_type_valid(type)) {
7721 /* TODO: improve error message */
7722 errorf(&expression->base.source_position,
7723 "operation needs an arithmetic or pointer type");
7726 if (!is_lvalue(expression->value)) {
7727 /* TODO: improve error message */
7728 errorf(&expression->base.source_position, "lvalue required as operand");
7730 expression->base.type = orig_type;
7733 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7735 type_t *const orig_type = expression->value->base.type;
7736 type_t *const type = skip_typeref(orig_type);
7737 if (!is_type_arithmetic(type)) {
7738 if (is_type_valid(type)) {
7739 /* TODO: improve error message */
7740 errorf(&expression->base.source_position,
7741 "operation needs an arithmetic type");
7746 expression->base.type = orig_type;
7749 static void semantic_unexpr_plus(unary_expression_t *expression)
7751 semantic_unexpr_arithmetic(expression);
7752 source_position_t const *const pos = &expression->base.source_position;
7753 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7756 static void semantic_not(unary_expression_t *expression)
7758 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7759 semantic_condition(expression->value, "operand of !");
7760 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7763 static void semantic_unexpr_integer(unary_expression_t *expression)
7765 type_t *const orig_type = expression->value->base.type;
7766 type_t *const type = skip_typeref(orig_type);
7767 if (!is_type_integer(type)) {
7768 if (is_type_valid(type)) {
7769 errorf(&expression->base.source_position,
7770 "operand of ~ must be of integer type");
7775 expression->base.type = orig_type;
7778 static void semantic_dereference(unary_expression_t *expression)
7780 type_t *const orig_type = expression->value->base.type;
7781 type_t *const type = skip_typeref(orig_type);
7782 if (!is_type_pointer(type)) {
7783 if (is_type_valid(type)) {
7784 errorf(&expression->base.source_position,
7785 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7790 type_t *result_type = type->pointer.points_to;
7791 result_type = automatic_type_conversion(result_type);
7792 expression->base.type = result_type;
7796 * Record that an address is taken (expression represents an lvalue).
7798 * @param expression the expression
7799 * @param may_be_register if true, the expression might be an register
7801 static void set_address_taken(expression_t *expression, bool may_be_register)
7803 if (expression->kind != EXPR_REFERENCE)
7806 entity_t *const entity = expression->reference.entity;
7808 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7811 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7812 && !may_be_register) {
7813 source_position_t const *const pos = &expression->base.source_position;
7814 errorf(pos, "address of register '%N' requested", entity);
7817 if (entity->kind == ENTITY_VARIABLE) {
7818 entity->variable.address_taken = true;
7820 assert(entity->kind == ENTITY_PARAMETER);
7821 entity->parameter.address_taken = true;
7826 * Check the semantic of the address taken expression.
7828 static void semantic_take_addr(unary_expression_t *expression)
7830 expression_t *value = expression->value;
7831 value->base.type = revert_automatic_type_conversion(value);
7833 type_t *orig_type = value->base.type;
7834 type_t *type = skip_typeref(orig_type);
7835 if (!is_type_valid(type))
7839 if (!is_lvalue(value)) {
7840 errorf(&expression->base.source_position, "'&' requires an lvalue");
7842 if (is_bitfield(value)) {
7843 errorf(&expression->base.source_position,
7844 "'&' not allowed on bitfield");
7847 set_address_taken(value, false);
7849 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7852 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7853 static expression_t *parse_##unexpression_type(void) \
7855 expression_t *unary_expression \
7856 = allocate_expression_zero(unexpression_type); \
7858 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7860 sfunc(&unary_expression->unary); \
7862 return unary_expression; \
7865 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7866 semantic_unexpr_arithmetic)
7867 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7868 semantic_unexpr_plus)
7869 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7871 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7872 semantic_dereference)
7873 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7875 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7876 semantic_unexpr_integer)
7877 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7879 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7882 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7884 static expression_t *parse_##unexpression_type(expression_t *left) \
7886 expression_t *unary_expression \
7887 = allocate_expression_zero(unexpression_type); \
7889 unary_expression->unary.value = left; \
7891 sfunc(&unary_expression->unary); \
7893 return unary_expression; \
7896 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7897 EXPR_UNARY_POSTFIX_INCREMENT,
7899 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7900 EXPR_UNARY_POSTFIX_DECREMENT,
7903 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7905 /* TODO: handle complex + imaginary types */
7907 type_left = get_unqualified_type(type_left);
7908 type_right = get_unqualified_type(type_right);
7910 /* §6.3.1.8 Usual arithmetic conversions */
7911 if (type_left == type_long_double || type_right == type_long_double) {
7912 return type_long_double;
7913 } else if (type_left == type_double || type_right == type_double) {
7915 } else if (type_left == type_float || type_right == type_float) {
7919 type_left = promote_integer(type_left);
7920 type_right = promote_integer(type_right);
7922 if (type_left == type_right)
7925 bool const signed_left = is_type_signed(type_left);
7926 bool const signed_right = is_type_signed(type_right);
7927 int const rank_left = get_rank(type_left);
7928 int const rank_right = get_rank(type_right);
7930 if (signed_left == signed_right)
7931 return rank_left >= rank_right ? type_left : type_right;
7940 u_rank = rank_right;
7941 u_type = type_right;
7943 s_rank = rank_right;
7944 s_type = type_right;
7949 if (u_rank >= s_rank)
7952 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7954 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7955 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7959 case ATOMIC_TYPE_INT: return type_unsigned_int;
7960 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7961 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7963 default: panic("invalid atomic type");
7968 * Check the semantic restrictions for a binary expression.
7970 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7972 expression_t *const left = expression->left;
7973 expression_t *const right = expression->right;
7974 type_t *const orig_type_left = left->base.type;
7975 type_t *const orig_type_right = right->base.type;
7976 type_t *const type_left = skip_typeref(orig_type_left);
7977 type_t *const type_right = skip_typeref(orig_type_right);
7979 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7980 /* TODO: improve error message */
7981 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7982 errorf(&expression->base.source_position,
7983 "operation needs arithmetic types");
7988 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7989 expression->left = create_implicit_cast(left, arithmetic_type);
7990 expression->right = create_implicit_cast(right, arithmetic_type);
7991 expression->base.type = arithmetic_type;
7994 static void semantic_binexpr_integer(binary_expression_t *const expression)
7996 expression_t *const left = expression->left;
7997 expression_t *const right = expression->right;
7998 type_t *const orig_type_left = left->base.type;
7999 type_t *const orig_type_right = right->base.type;
8000 type_t *const type_left = skip_typeref(orig_type_left);
8001 type_t *const type_right = skip_typeref(orig_type_right);
8003 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8004 /* TODO: improve error message */
8005 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8006 errorf(&expression->base.source_position,
8007 "operation needs integer types");
8012 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8013 expression->left = create_implicit_cast(left, result_type);
8014 expression->right = create_implicit_cast(right, result_type);
8015 expression->base.type = result_type;
8018 static void warn_div_by_zero(binary_expression_t const *const expression)
8020 if (!is_type_integer(expression->base.type))
8023 expression_t const *const right = expression->right;
8024 /* The type of the right operand can be different for /= */
8025 if (is_type_integer(right->base.type) &&
8026 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8027 !fold_constant_to_bool(right)) {
8028 source_position_t const *const pos = &expression->base.source_position;
8029 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8034 * Check the semantic restrictions for a div/mod expression.
8036 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8038 semantic_binexpr_arithmetic(expression);
8039 warn_div_by_zero(expression);
8042 static void warn_addsub_in_shift(const expression_t *const expr)
8044 if (expr->base.parenthesized)
8048 switch (expr->kind) {
8049 case EXPR_BINARY_ADD: op = '+'; break;
8050 case EXPR_BINARY_SUB: op = '-'; break;
8054 source_position_t const *const pos = &expr->base.source_position;
8055 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8058 static bool semantic_shift(binary_expression_t *expression)
8060 expression_t *const left = expression->left;
8061 expression_t *const right = expression->right;
8062 type_t *const orig_type_left = left->base.type;
8063 type_t *const orig_type_right = right->base.type;
8064 type_t * type_left = skip_typeref(orig_type_left);
8065 type_t * type_right = skip_typeref(orig_type_right);
8067 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8068 /* TODO: improve error message */
8069 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8070 errorf(&expression->base.source_position,
8071 "operands of shift operation must have integer types");
8076 type_left = promote_integer(type_left);
8078 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8079 source_position_t const *const pos = &right->base.source_position;
8080 long const count = fold_constant_to_int(right);
8082 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8083 } else if ((unsigned long)count >=
8084 get_atomic_type_size(type_left->atomic.akind) * 8) {
8085 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8089 type_right = promote_integer(type_right);
8090 expression->right = create_implicit_cast(right, type_right);
8095 static void semantic_shift_op(binary_expression_t *expression)
8097 expression_t *const left = expression->left;
8098 expression_t *const right = expression->right;
8100 if (!semantic_shift(expression))
8103 warn_addsub_in_shift(left);
8104 warn_addsub_in_shift(right);
8106 type_t *const orig_type_left = left->base.type;
8107 type_t * type_left = skip_typeref(orig_type_left);
8109 type_left = promote_integer(type_left);
8110 expression->left = create_implicit_cast(left, type_left);
8111 expression->base.type = type_left;
8114 static void semantic_add(binary_expression_t *expression)
8116 expression_t *const left = expression->left;
8117 expression_t *const right = expression->right;
8118 type_t *const orig_type_left = left->base.type;
8119 type_t *const orig_type_right = right->base.type;
8120 type_t *const type_left = skip_typeref(orig_type_left);
8121 type_t *const type_right = skip_typeref(orig_type_right);
8124 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8125 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8126 expression->left = create_implicit_cast(left, arithmetic_type);
8127 expression->right = create_implicit_cast(right, arithmetic_type);
8128 expression->base.type = arithmetic_type;
8129 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8130 check_pointer_arithmetic(&expression->base.source_position,
8131 type_left, orig_type_left);
8132 expression->base.type = type_left;
8133 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8134 check_pointer_arithmetic(&expression->base.source_position,
8135 type_right, orig_type_right);
8136 expression->base.type = type_right;
8137 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8138 errorf(&expression->base.source_position,
8139 "invalid operands to binary + ('%T', '%T')",
8140 orig_type_left, orig_type_right);
8144 static void semantic_sub(binary_expression_t *expression)
8146 expression_t *const left = expression->left;
8147 expression_t *const right = expression->right;
8148 type_t *const orig_type_left = left->base.type;
8149 type_t *const orig_type_right = right->base.type;
8150 type_t *const type_left = skip_typeref(orig_type_left);
8151 type_t *const type_right = skip_typeref(orig_type_right);
8152 source_position_t const *const pos = &expression->base.source_position;
8155 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8156 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8157 expression->left = create_implicit_cast(left, arithmetic_type);
8158 expression->right = create_implicit_cast(right, arithmetic_type);
8159 expression->base.type = arithmetic_type;
8160 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8161 check_pointer_arithmetic(&expression->base.source_position,
8162 type_left, orig_type_left);
8163 expression->base.type = type_left;
8164 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8165 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8166 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8167 if (!types_compatible(unqual_left, unqual_right)) {
8169 "subtracting pointers to incompatible types '%T' and '%T'",
8170 orig_type_left, orig_type_right);
8171 } else if (!is_type_object(unqual_left)) {
8172 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8173 errorf(pos, "subtracting pointers to non-object types '%T'",
8176 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8179 expression->base.type = type_ptrdiff_t;
8180 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8181 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8182 orig_type_left, orig_type_right);
8186 static void warn_string_literal_address(expression_t const* expr)
8188 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8189 expr = expr->unary.value;
8190 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8192 expr = expr->unary.value;
8195 if (expr->kind == EXPR_STRING_LITERAL
8196 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8197 source_position_t const *const pos = &expr->base.source_position;
8198 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8202 static bool maybe_negative(expression_t const *const expr)
8204 switch (is_constant_expression(expr)) {
8205 case EXPR_CLASS_ERROR: return false;
8206 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8207 default: return true;
8211 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8213 warn_string_literal_address(expr);
8215 expression_t const* const ref = get_reference_address(expr);
8216 if (ref != NULL && is_null_pointer_constant(other)) {
8217 entity_t const *const ent = ref->reference.entity;
8218 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8221 if (!expr->base.parenthesized) {
8222 switch (expr->base.kind) {
8223 case EXPR_BINARY_LESS:
8224 case EXPR_BINARY_GREATER:
8225 case EXPR_BINARY_LESSEQUAL:
8226 case EXPR_BINARY_GREATEREQUAL:
8227 case EXPR_BINARY_NOTEQUAL:
8228 case EXPR_BINARY_EQUAL:
8229 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8238 * Check the semantics of comparison expressions.
8240 * @param expression The expression to check.
8242 static void semantic_comparison(binary_expression_t *expression)
8244 source_position_t const *const pos = &expression->base.source_position;
8245 expression_t *const left = expression->left;
8246 expression_t *const right = expression->right;
8248 warn_comparison(pos, left, right);
8249 warn_comparison(pos, right, left);
8251 type_t *orig_type_left = left->base.type;
8252 type_t *orig_type_right = right->base.type;
8253 type_t *type_left = skip_typeref(orig_type_left);
8254 type_t *type_right = skip_typeref(orig_type_right);
8256 /* TODO non-arithmetic types */
8257 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8258 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8260 /* test for signed vs unsigned compares */
8261 if (is_type_integer(arithmetic_type)) {
8262 bool const signed_left = is_type_signed(type_left);
8263 bool const signed_right = is_type_signed(type_right);
8264 if (signed_left != signed_right) {
8265 /* FIXME long long needs better const folding magic */
8266 /* TODO check whether constant value can be represented by other type */
8267 if ((signed_left && maybe_negative(left)) ||
8268 (signed_right && maybe_negative(right))) {
8269 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8274 expression->left = create_implicit_cast(left, arithmetic_type);
8275 expression->right = create_implicit_cast(right, arithmetic_type);
8276 expression->base.type = arithmetic_type;
8277 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8278 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8279 is_type_float(arithmetic_type)) {
8280 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8282 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8283 /* TODO check compatibility */
8284 } else if (is_type_pointer(type_left)) {
8285 expression->right = create_implicit_cast(right, type_left);
8286 } else if (is_type_pointer(type_right)) {
8287 expression->left = create_implicit_cast(left, type_right);
8288 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8289 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8291 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8295 * Checks if a compound type has constant fields.
8297 static bool has_const_fields(const compound_type_t *type)
8299 compound_t *compound = type->compound;
8300 entity_t *entry = compound->members.entities;
8302 for (; entry != NULL; entry = entry->base.next) {
8303 if (!is_declaration(entry))
8306 const type_t *decl_type = skip_typeref(entry->declaration.type);
8307 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8314 static bool is_valid_assignment_lhs(expression_t const* const left)
8316 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8317 type_t *const type_left = skip_typeref(orig_type_left);
8319 if (!is_lvalue(left)) {
8320 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8325 if (left->kind == EXPR_REFERENCE
8326 && left->reference.entity->kind == ENTITY_FUNCTION) {
8327 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8331 if (is_type_array(type_left)) {
8332 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8335 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8336 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8340 if (is_type_incomplete(type_left)) {
8341 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8342 left, orig_type_left);
8345 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8346 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8347 left, orig_type_left);
8354 static void semantic_arithmetic_assign(binary_expression_t *expression)
8356 expression_t *left = expression->left;
8357 expression_t *right = expression->right;
8358 type_t *orig_type_left = left->base.type;
8359 type_t *orig_type_right = right->base.type;
8361 if (!is_valid_assignment_lhs(left))
8364 type_t *type_left = skip_typeref(orig_type_left);
8365 type_t *type_right = skip_typeref(orig_type_right);
8367 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8368 /* TODO: improve error message */
8369 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8370 errorf(&expression->base.source_position,
8371 "operation needs arithmetic types");
8376 /* combined instructions are tricky. We can't create an implicit cast on
8377 * the left side, because we need the uncasted form for the store.
8378 * The ast2firm pass has to know that left_type must be right_type
8379 * for the arithmetic operation and create a cast by itself */
8380 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8381 expression->right = create_implicit_cast(right, arithmetic_type);
8382 expression->base.type = type_left;
8385 static void semantic_divmod_assign(binary_expression_t *expression)
8387 semantic_arithmetic_assign(expression);
8388 warn_div_by_zero(expression);
8391 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8393 expression_t *const left = expression->left;
8394 expression_t *const right = expression->right;
8395 type_t *const orig_type_left = left->base.type;
8396 type_t *const orig_type_right = right->base.type;
8397 type_t *const type_left = skip_typeref(orig_type_left);
8398 type_t *const type_right = skip_typeref(orig_type_right);
8400 if (!is_valid_assignment_lhs(left))
8403 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8404 /* combined instructions are tricky. We can't create an implicit cast on
8405 * the left side, because we need the uncasted form for the store.
8406 * The ast2firm pass has to know that left_type must be right_type
8407 * for the arithmetic operation and create a cast by itself */
8408 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8409 expression->right = create_implicit_cast(right, arithmetic_type);
8410 expression->base.type = type_left;
8411 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8412 check_pointer_arithmetic(&expression->base.source_position,
8413 type_left, orig_type_left);
8414 expression->base.type = type_left;
8415 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8416 errorf(&expression->base.source_position,
8417 "incompatible types '%T' and '%T' in assignment",
8418 orig_type_left, orig_type_right);
8422 static void semantic_integer_assign(binary_expression_t *expression)
8424 expression_t *left = expression->left;
8425 expression_t *right = expression->right;
8426 type_t *orig_type_left = left->base.type;
8427 type_t *orig_type_right = right->base.type;
8429 if (!is_valid_assignment_lhs(left))
8432 type_t *type_left = skip_typeref(orig_type_left);
8433 type_t *type_right = skip_typeref(orig_type_right);
8435 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8436 /* TODO: improve error message */
8437 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8438 errorf(&expression->base.source_position,
8439 "operation needs integer types");
8444 /* combined instructions are tricky. We can't create an implicit cast on
8445 * the left side, because we need the uncasted form for the store.
8446 * The ast2firm pass has to know that left_type must be right_type
8447 * for the arithmetic operation and create a cast by itself */
8448 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8449 expression->right = create_implicit_cast(right, arithmetic_type);
8450 expression->base.type = type_left;
8453 static void semantic_shift_assign(binary_expression_t *expression)
8455 expression_t *left = expression->left;
8457 if (!is_valid_assignment_lhs(left))
8460 if (!semantic_shift(expression))
8463 expression->base.type = skip_typeref(left->base.type);
8466 static void warn_logical_and_within_or(const expression_t *const expr)
8468 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8470 if (expr->base.parenthesized)
8472 source_position_t const *const pos = &expr->base.source_position;
8473 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8477 * Check the semantic restrictions of a logical expression.
8479 static void semantic_logical_op(binary_expression_t *expression)
8481 /* §6.5.13:2 Each of the operands shall have scalar type.
8482 * §6.5.14:2 Each of the operands shall have scalar type. */
8483 semantic_condition(expression->left, "left operand of logical operator");
8484 semantic_condition(expression->right, "right operand of logical operator");
8485 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8486 warn_logical_and_within_or(expression->left);
8487 warn_logical_and_within_or(expression->right);
8489 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8493 * Check the semantic restrictions of a binary assign expression.
8495 static void semantic_binexpr_assign(binary_expression_t *expression)
8497 expression_t *left = expression->left;
8498 type_t *orig_type_left = left->base.type;
8500 if (!is_valid_assignment_lhs(left))
8503 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8504 report_assign_error(error, orig_type_left, expression->right,
8505 "assignment", &left->base.source_position);
8506 expression->right = create_implicit_cast(expression->right, orig_type_left);
8507 expression->base.type = orig_type_left;
8511 * Determine if the outermost operation (or parts thereof) of the given
8512 * expression has no effect in order to generate a warning about this fact.
8513 * Therefore in some cases this only examines some of the operands of the
8514 * expression (see comments in the function and examples below).
8516 * f() + 23; // warning, because + has no effect
8517 * x || f(); // no warning, because x controls execution of f()
8518 * x ? y : f(); // warning, because y has no effect
8519 * (void)x; // no warning to be able to suppress the warning
8520 * This function can NOT be used for an "expression has definitely no effect"-
8522 static bool expression_has_effect(const expression_t *const expr)
8524 switch (expr->kind) {
8525 case EXPR_ERROR: return true; /* do NOT warn */
8526 case EXPR_REFERENCE: return false;
8527 case EXPR_REFERENCE_ENUM_VALUE: return false;
8528 case EXPR_LABEL_ADDRESS: return false;
8530 /* suppress the warning for microsoft __noop operations */
8531 case EXPR_LITERAL_MS_NOOP: return true;
8532 case EXPR_LITERAL_BOOLEAN:
8533 case EXPR_LITERAL_CHARACTER:
8534 case EXPR_LITERAL_WIDE_CHARACTER:
8535 case EXPR_LITERAL_INTEGER:
8536 case EXPR_LITERAL_INTEGER_OCTAL:
8537 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8538 case EXPR_LITERAL_FLOATINGPOINT:
8539 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8540 case EXPR_STRING_LITERAL: return false;
8541 case EXPR_WIDE_STRING_LITERAL: return false;
8544 const call_expression_t *const call = &expr->call;
8545 if (call->function->kind != EXPR_REFERENCE)
8548 switch (call->function->reference.entity->function.btk) {
8549 /* FIXME: which builtins have no effect? */
8550 default: return true;
8554 /* Generate the warning if either the left or right hand side of a
8555 * conditional expression has no effect */
8556 case EXPR_CONDITIONAL: {
8557 conditional_expression_t const *const cond = &expr->conditional;
8558 expression_t const *const t = cond->true_expression;
8560 (t == NULL || expression_has_effect(t)) &&
8561 expression_has_effect(cond->false_expression);
8564 case EXPR_SELECT: return false;
8565 case EXPR_ARRAY_ACCESS: return false;
8566 case EXPR_SIZEOF: return false;
8567 case EXPR_CLASSIFY_TYPE: return false;
8568 case EXPR_ALIGNOF: return false;
8570 case EXPR_FUNCNAME: return false;
8571 case EXPR_BUILTIN_CONSTANT_P: return false;
8572 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8573 case EXPR_OFFSETOF: return false;
8574 case EXPR_VA_START: return true;
8575 case EXPR_VA_ARG: return true;
8576 case EXPR_VA_COPY: return true;
8577 case EXPR_STATEMENT: return true; // TODO
8578 case EXPR_COMPOUND_LITERAL: return false;
8580 case EXPR_UNARY_NEGATE: return false;
8581 case EXPR_UNARY_PLUS: return false;
8582 case EXPR_UNARY_BITWISE_NEGATE: return false;
8583 case EXPR_UNARY_NOT: return false;
8584 case EXPR_UNARY_DEREFERENCE: return false;
8585 case EXPR_UNARY_TAKE_ADDRESS: return false;
8586 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8587 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8588 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8589 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8591 /* Treat void casts as if they have an effect in order to being able to
8592 * suppress the warning */
8593 case EXPR_UNARY_CAST: {
8594 type_t *const type = skip_typeref(expr->base.type);
8595 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8598 case EXPR_UNARY_ASSUME: return true;
8599 case EXPR_UNARY_DELETE: return true;
8600 case EXPR_UNARY_DELETE_ARRAY: return true;
8601 case EXPR_UNARY_THROW: return true;
8603 case EXPR_BINARY_ADD: return false;
8604 case EXPR_BINARY_SUB: return false;
8605 case EXPR_BINARY_MUL: return false;
8606 case EXPR_BINARY_DIV: return false;
8607 case EXPR_BINARY_MOD: return false;
8608 case EXPR_BINARY_EQUAL: return false;
8609 case EXPR_BINARY_NOTEQUAL: return false;
8610 case EXPR_BINARY_LESS: return false;
8611 case EXPR_BINARY_LESSEQUAL: return false;
8612 case EXPR_BINARY_GREATER: return false;
8613 case EXPR_BINARY_GREATEREQUAL: return false;
8614 case EXPR_BINARY_BITWISE_AND: return false;
8615 case EXPR_BINARY_BITWISE_OR: return false;
8616 case EXPR_BINARY_BITWISE_XOR: return false;
8617 case EXPR_BINARY_SHIFTLEFT: return false;
8618 case EXPR_BINARY_SHIFTRIGHT: return false;
8619 case EXPR_BINARY_ASSIGN: return true;
8620 case EXPR_BINARY_MUL_ASSIGN: return true;
8621 case EXPR_BINARY_DIV_ASSIGN: return true;
8622 case EXPR_BINARY_MOD_ASSIGN: return true;
8623 case EXPR_BINARY_ADD_ASSIGN: return true;
8624 case EXPR_BINARY_SUB_ASSIGN: return true;
8625 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8626 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8627 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8628 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8629 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8631 /* Only examine the right hand side of && and ||, because the left hand
8632 * side already has the effect of controlling the execution of the right
8634 case EXPR_BINARY_LOGICAL_AND:
8635 case EXPR_BINARY_LOGICAL_OR:
8636 /* Only examine the right hand side of a comma expression, because the left
8637 * hand side has a separate warning */
8638 case EXPR_BINARY_COMMA:
8639 return expression_has_effect(expr->binary.right);
8641 case EXPR_BINARY_ISGREATER: return false;
8642 case EXPR_BINARY_ISGREATEREQUAL: return false;
8643 case EXPR_BINARY_ISLESS: return false;
8644 case EXPR_BINARY_ISLESSEQUAL: return false;
8645 case EXPR_BINARY_ISLESSGREATER: return false;
8646 case EXPR_BINARY_ISUNORDERED: return false;
8649 internal_errorf(HERE, "unexpected expression");
8652 static void semantic_comma(binary_expression_t *expression)
8654 const expression_t *const left = expression->left;
8655 if (!expression_has_effect(left)) {
8656 source_position_t const *const pos = &left->base.source_position;
8657 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8659 expression->base.type = expression->right->base.type;
8663 * @param prec_r precedence of the right operand
8665 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8666 static expression_t *parse_##binexpression_type(expression_t *left) \
8668 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8669 binexpr->binary.left = left; \
8672 expression_t *right = parse_subexpression(prec_r); \
8674 binexpr->binary.right = right; \
8675 sfunc(&binexpr->binary); \
8680 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8681 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8682 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8683 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8684 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8685 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8686 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8687 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8688 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8689 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8690 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8691 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8692 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8693 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8694 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8695 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8696 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8697 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8698 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8699 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8700 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8701 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8702 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8703 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8704 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8705 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8706 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8707 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8708 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8709 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8712 static expression_t *parse_subexpression(precedence_t precedence)
8714 if (token.kind < 0) {
8715 return expected_expression_error();
8718 expression_parser_function_t *parser
8719 = &expression_parsers[token.kind];
8722 if (parser->parser != NULL) {
8723 left = parser->parser();
8725 left = parse_primary_expression();
8727 assert(left != NULL);
8730 if (token.kind < 0) {
8731 return expected_expression_error();
8734 parser = &expression_parsers[token.kind];
8735 if (parser->infix_parser == NULL)
8737 if (parser->infix_precedence < precedence)
8740 left = parser->infix_parser(left);
8742 assert(left != NULL);
8749 * Parse an expression.
8751 static expression_t *parse_expression(void)
8753 return parse_subexpression(PREC_EXPRESSION);
8757 * Register a parser for a prefix-like operator.
8759 * @param parser the parser function
8760 * @param token_kind the token type of the prefix token
8762 static void register_expression_parser(parse_expression_function parser,
8765 expression_parser_function_t *entry = &expression_parsers[token_kind];
8767 if (entry->parser != NULL) {
8768 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8769 panic("trying to register multiple expression parsers for a token");
8771 entry->parser = parser;
8775 * Register a parser for an infix operator with given precedence.
8777 * @param parser the parser function
8778 * @param token_kind the token type of the infix operator
8779 * @param precedence the precedence of the operator
8781 static void register_infix_parser(parse_expression_infix_function parser,
8782 int token_kind, precedence_t precedence)
8784 expression_parser_function_t *entry = &expression_parsers[token_kind];
8786 if (entry->infix_parser != NULL) {
8787 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8788 panic("trying to register multiple infix expression parsers for a "
8791 entry->infix_parser = parser;
8792 entry->infix_precedence = precedence;
8796 * Initialize the expression parsers.
8798 static void init_expression_parsers(void)
8800 memset(&expression_parsers, 0, sizeof(expression_parsers));
8802 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8803 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8804 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8805 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8806 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8807 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8808 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8809 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8810 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8811 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8812 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8813 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8814 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8815 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8816 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8817 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8818 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8819 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8820 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8821 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8822 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8823 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8824 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8825 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8826 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8827 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8828 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8829 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8830 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8831 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8832 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8833 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8834 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8835 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8836 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8837 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8838 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8840 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8841 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8842 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8843 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8844 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8845 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8846 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8847 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8848 register_expression_parser(parse_sizeof, T_sizeof);
8849 register_expression_parser(parse_alignof, T___alignof__);
8850 register_expression_parser(parse_extension, T___extension__);
8851 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8852 register_expression_parser(parse_delete, T_delete);
8853 register_expression_parser(parse_throw, T_throw);
8857 * Parse a asm statement arguments specification.
8859 static asm_argument_t *parse_asm_arguments(bool is_out)
8861 asm_argument_t *result = NULL;
8862 asm_argument_t **anchor = &result;
8864 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8865 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8866 memset(argument, 0, sizeof(argument[0]));
8869 if (token.kind != T_IDENTIFIER) {
8870 parse_error_expected("while parsing asm argument",
8871 T_IDENTIFIER, NULL);
8874 argument->symbol = token.identifier.symbol;
8876 expect(']', end_error);
8879 argument->constraints = parse_string_literals();
8880 expect('(', end_error);
8881 add_anchor_token(')');
8882 expression_t *expression = parse_expression();
8883 rem_anchor_token(')');
8885 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8886 * change size or type representation (e.g. int -> long is ok, but
8887 * int -> float is not) */
8888 if (expression->kind == EXPR_UNARY_CAST) {
8889 type_t *const type = expression->base.type;
8890 type_kind_t const kind = type->kind;
8891 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8894 if (kind == TYPE_ATOMIC) {
8895 atomic_type_kind_t const akind = type->atomic.akind;
8896 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8897 size = get_atomic_type_size(akind);
8899 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8900 size = get_type_size(type_void_ptr);
8904 expression_t *const value = expression->unary.value;
8905 type_t *const value_type = value->base.type;
8906 type_kind_t const value_kind = value_type->kind;
8908 unsigned value_flags;
8909 unsigned value_size;
8910 if (value_kind == TYPE_ATOMIC) {
8911 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8912 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8913 value_size = get_atomic_type_size(value_akind);
8914 } else if (value_kind == TYPE_POINTER) {
8915 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8916 value_size = get_type_size(type_void_ptr);
8921 if (value_flags != flags || value_size != size)
8925 } while (expression->kind == EXPR_UNARY_CAST);
8929 if (!is_lvalue(expression)) {
8930 errorf(&expression->base.source_position,
8931 "asm output argument is not an lvalue");
8934 if (argument->constraints.begin[0] == '=')
8935 determine_lhs_ent(expression, NULL);
8937 mark_vars_read(expression, NULL);
8939 mark_vars_read(expression, NULL);
8941 argument->expression = expression;
8942 expect(')', end_error);
8944 set_address_taken(expression, true);
8947 anchor = &argument->next;
8959 * Parse a asm statement clobber specification.
8961 static asm_clobber_t *parse_asm_clobbers(void)
8963 asm_clobber_t *result = NULL;
8964 asm_clobber_t **anchor = &result;
8966 while (token.kind == T_STRING_LITERAL) {
8967 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8968 clobber->clobber = parse_string_literals();
8971 anchor = &clobber->next;
8981 * Parse an asm statement.
8983 static statement_t *parse_asm_statement(void)
8985 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8986 asm_statement_t *asm_statement = &statement->asms;
8990 if (next_if(T_volatile))
8991 asm_statement->is_volatile = true;
8993 expect('(', end_error);
8994 add_anchor_token(')');
8995 if (token.kind != T_STRING_LITERAL) {
8996 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8999 asm_statement->asm_text = parse_string_literals();
9001 add_anchor_token(':');
9002 if (!next_if(':')) {
9003 rem_anchor_token(':');
9007 asm_statement->outputs = parse_asm_arguments(true);
9008 if (!next_if(':')) {
9009 rem_anchor_token(':');
9013 asm_statement->inputs = parse_asm_arguments(false);
9014 if (!next_if(':')) {
9015 rem_anchor_token(':');
9018 rem_anchor_token(':');
9020 asm_statement->clobbers = parse_asm_clobbers();
9023 rem_anchor_token(')');
9024 expect(')', end_error);
9025 expect(';', end_error);
9027 if (asm_statement->outputs == NULL) {
9028 /* GCC: An 'asm' instruction without any output operands will be treated
9029 * identically to a volatile 'asm' instruction. */
9030 asm_statement->is_volatile = true;
9035 return create_error_statement();
9038 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9040 statement_t *inner_stmt;
9041 switch (token.kind) {
9043 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9044 inner_stmt = create_error_statement();
9048 if (label->kind == STATEMENT_LABEL) {
9049 /* Eat an empty statement here, to avoid the warning about an empty
9050 * statement after a label. label:; is commonly used to have a label
9051 * before a closing brace. */
9052 inner_stmt = create_empty_statement();
9059 inner_stmt = parse_statement();
9060 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9061 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9062 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9063 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9071 * Parse a case statement.
9073 static statement_t *parse_case_statement(void)
9075 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9076 source_position_t *const pos = &statement->base.source_position;
9080 expression_t *const expression = parse_expression();
9081 statement->case_label.expression = expression;
9082 expression_classification_t const expr_class = is_constant_expression(expression);
9083 if (expr_class != EXPR_CLASS_CONSTANT) {
9084 if (expr_class != EXPR_CLASS_ERROR) {
9085 errorf(pos, "case label does not reduce to an integer constant");
9087 statement->case_label.is_bad = true;
9089 long const val = fold_constant_to_int(expression);
9090 statement->case_label.first_case = val;
9091 statement->case_label.last_case = val;
9095 if (next_if(T_DOTDOTDOT)) {
9096 expression_t *const end_range = parse_expression();
9097 statement->case_label.end_range = end_range;
9098 expression_classification_t const end_class = is_constant_expression(end_range);
9099 if (end_class != EXPR_CLASS_CONSTANT) {
9100 if (end_class != EXPR_CLASS_ERROR) {
9101 errorf(pos, "case range does not reduce to an integer constant");
9103 statement->case_label.is_bad = true;
9105 long const val = fold_constant_to_int(end_range);
9106 statement->case_label.last_case = val;
9108 if (val < statement->case_label.first_case) {
9109 statement->case_label.is_empty_range = true;
9110 warningf(WARN_OTHER, pos, "empty range specified");
9116 PUSH_PARENT(statement);
9118 expect(':', end_error);
9121 if (current_switch != NULL) {
9122 if (! statement->case_label.is_bad) {
9123 /* Check for duplicate case values */
9124 case_label_statement_t *c = &statement->case_label;
9125 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9126 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9129 if (c->last_case < l->first_case || c->first_case > l->last_case)
9132 errorf(pos, "duplicate case value (previously used %P)",
9133 &l->base.source_position);
9137 /* link all cases into the switch statement */
9138 if (current_switch->last_case == NULL) {
9139 current_switch->first_case = &statement->case_label;
9141 current_switch->last_case->next = &statement->case_label;
9143 current_switch->last_case = &statement->case_label;
9145 errorf(pos, "case label not within a switch statement");
9148 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9155 * Parse a default statement.
9157 static statement_t *parse_default_statement(void)
9159 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9163 PUSH_PARENT(statement);
9165 expect(':', end_error);
9168 if (current_switch != NULL) {
9169 const case_label_statement_t *def_label = current_switch->default_label;
9170 if (def_label != NULL) {
9171 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9173 current_switch->default_label = &statement->case_label;
9175 /* link all cases into the switch statement */
9176 if (current_switch->last_case == NULL) {
9177 current_switch->first_case = &statement->case_label;
9179 current_switch->last_case->next = &statement->case_label;
9181 current_switch->last_case = &statement->case_label;
9184 errorf(&statement->base.source_position,
9185 "'default' label not within a switch statement");
9188 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9195 * Parse a label statement.
9197 static statement_t *parse_label_statement(void)
9199 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9200 label_t *const label = get_label();
9201 statement->label.label = label;
9203 PUSH_PARENT(statement);
9205 /* if statement is already set then the label is defined twice,
9206 * otherwise it was just mentioned in a goto/local label declaration so far
9208 source_position_t const* const pos = &statement->base.source_position;
9209 if (label->statement != NULL) {
9210 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9212 label->base.source_position = *pos;
9213 label->statement = statement;
9218 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9219 parse_attributes(NULL); // TODO process attributes
9222 statement->label.statement = parse_label_inner_statement(statement, "label");
9224 /* remember the labels in a list for later checking */
9225 *label_anchor = &statement->label;
9226 label_anchor = &statement->label.next;
9232 static statement_t *parse_inner_statement(void)
9234 statement_t *const stmt = parse_statement();
9235 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9236 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9237 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9238 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9244 * Parse an if statement.
9246 static statement_t *parse_if(void)
9248 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9252 PUSH_PARENT(statement);
9254 add_anchor_token('{');
9256 expect('(', end_error);
9257 add_anchor_token(')');
9258 expression_t *const expr = parse_expression();
9259 statement->ifs.condition = expr;
9260 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9262 semantic_condition(expr, "condition of 'if'-statment");
9263 mark_vars_read(expr, NULL);
9264 rem_anchor_token(')');
9265 expect(')', end_error);
9268 rem_anchor_token('{');
9270 add_anchor_token(T_else);
9271 statement_t *const true_stmt = parse_inner_statement();
9272 statement->ifs.true_statement = true_stmt;
9273 rem_anchor_token(T_else);
9275 if (true_stmt->kind == STATEMENT_EMPTY) {
9276 warningf(WARN_EMPTY_BODY, HERE,
9277 "suggest braces around empty body in an ‘if’ statement");
9280 if (next_if(T_else)) {
9281 statement->ifs.false_statement = parse_inner_statement();
9283 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9284 warningf(WARN_EMPTY_BODY, HERE,
9285 "suggest braces around empty body in an ‘if’ statement");
9287 } else if (true_stmt->kind == STATEMENT_IF &&
9288 true_stmt->ifs.false_statement != NULL) {
9289 source_position_t const *const pos = &true_stmt->base.source_position;
9290 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9298 * Check that all enums are handled in a switch.
9300 * @param statement the switch statement to check
9302 static void check_enum_cases(const switch_statement_t *statement)
9304 if (!is_warn_on(WARN_SWITCH_ENUM))
9306 const type_t *type = skip_typeref(statement->expression->base.type);
9307 if (! is_type_enum(type))
9309 const enum_type_t *enumt = &type->enumt;
9311 /* if we have a default, no warnings */
9312 if (statement->default_label != NULL)
9315 /* FIXME: calculation of value should be done while parsing */
9316 /* TODO: quadratic algorithm here. Change to an n log n one */
9317 long last_value = -1;
9318 const entity_t *entry = enumt->enume->base.next;
9319 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9320 entry = entry->base.next) {
9321 const expression_t *expression = entry->enum_value.value;
9322 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9324 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9325 if (l->expression == NULL)
9327 if (l->first_case <= value && value <= l->last_case) {
9333 source_position_t const *const pos = &statement->base.source_position;
9334 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9341 * Parse a switch statement.
9343 static statement_t *parse_switch(void)
9345 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9349 PUSH_PARENT(statement);
9351 expect('(', end_error);
9352 add_anchor_token(')');
9353 expression_t *const expr = parse_expression();
9354 mark_vars_read(expr, NULL);
9355 type_t * type = skip_typeref(expr->base.type);
9356 if (is_type_integer(type)) {
9357 type = promote_integer(type);
9358 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9359 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9361 } else if (is_type_valid(type)) {
9362 errorf(&expr->base.source_position,
9363 "switch quantity is not an integer, but '%T'", type);
9364 type = type_error_type;
9366 statement->switchs.expression = create_implicit_cast(expr, type);
9367 expect(')', end_error);
9368 rem_anchor_token(')');
9370 switch_statement_t *rem = current_switch;
9371 current_switch = &statement->switchs;
9372 statement->switchs.body = parse_inner_statement();
9373 current_switch = rem;
9375 if (statement->switchs.default_label == NULL) {
9376 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9378 check_enum_cases(&statement->switchs);
9384 return create_error_statement();
9387 static statement_t *parse_loop_body(statement_t *const loop)
9389 statement_t *const rem = current_loop;
9390 current_loop = loop;
9392 statement_t *const body = parse_inner_statement();
9399 * Parse a while statement.
9401 static statement_t *parse_while(void)
9403 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9407 PUSH_PARENT(statement);
9409 expect('(', end_error);
9410 add_anchor_token(')');
9411 expression_t *const cond = parse_expression();
9412 statement->whiles.condition = cond;
9413 /* §6.8.5:2 The controlling expression of an iteration statement shall
9414 * have scalar type. */
9415 semantic_condition(cond, "condition of 'while'-statement");
9416 mark_vars_read(cond, NULL);
9417 rem_anchor_token(')');
9418 expect(')', end_error);
9420 statement->whiles.body = parse_loop_body(statement);
9426 return create_error_statement();
9430 * Parse a do statement.
9432 static statement_t *parse_do(void)
9434 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9438 PUSH_PARENT(statement);
9440 add_anchor_token(T_while);
9441 statement->do_while.body = parse_loop_body(statement);
9442 rem_anchor_token(T_while);
9444 expect(T_while, end_error);
9445 expect('(', end_error);
9446 add_anchor_token(')');
9447 expression_t *const cond = parse_expression();
9448 statement->do_while.condition = cond;
9449 /* §6.8.5:2 The controlling expression of an iteration statement shall
9450 * have scalar type. */
9451 semantic_condition(cond, "condition of 'do-while'-statement");
9452 mark_vars_read(cond, NULL);
9453 rem_anchor_token(')');
9454 expect(')', end_error);
9455 expect(';', end_error);
9461 return create_error_statement();
9465 * Parse a for statement.
9467 static statement_t *parse_for(void)
9469 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9473 expect('(', end_error1);
9474 add_anchor_token(')');
9476 PUSH_PARENT(statement);
9477 PUSH_SCOPE(&statement->fors.scope);
9482 } else if (is_declaration_specifier(&token)) {
9483 parse_declaration(record_entity, DECL_FLAGS_NONE);
9485 add_anchor_token(';');
9486 expression_t *const init = parse_expression();
9487 statement->fors.initialisation = init;
9488 mark_vars_read(init, ENT_ANY);
9489 if (!expression_has_effect(init)) {
9490 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9492 rem_anchor_token(';');
9493 expect(';', end_error2);
9498 if (token.kind != ';') {
9499 add_anchor_token(';');
9500 expression_t *const cond = parse_expression();
9501 statement->fors.condition = cond;
9502 /* §6.8.5:2 The controlling expression of an iteration statement
9503 * shall have scalar type. */
9504 semantic_condition(cond, "condition of 'for'-statement");
9505 mark_vars_read(cond, NULL);
9506 rem_anchor_token(';');
9508 expect(';', end_error2);
9509 if (token.kind != ')') {
9510 expression_t *const step = parse_expression();
9511 statement->fors.step = step;
9512 mark_vars_read(step, ENT_ANY);
9513 if (!expression_has_effect(step)) {
9514 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9517 expect(')', end_error2);
9518 rem_anchor_token(')');
9519 statement->fors.body = parse_loop_body(statement);
9527 rem_anchor_token(')');
9532 return create_error_statement();
9536 * Parse a goto statement.
9538 static statement_t *parse_goto(void)
9540 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9543 if (GNU_MODE && next_if('*')) {
9544 expression_t *expression = parse_expression();
9545 mark_vars_read(expression, NULL);
9547 /* Argh: although documentation says the expression must be of type void*,
9548 * gcc accepts anything that can be casted into void* without error */
9549 type_t *type = expression->base.type;
9551 if (type != type_error_type) {
9552 if (!is_type_pointer(type) && !is_type_integer(type)) {
9553 errorf(&expression->base.source_position,
9554 "cannot convert to a pointer type");
9555 } else if (type != type_void_ptr) {
9556 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9558 expression = create_implicit_cast(expression, type_void_ptr);
9561 statement->gotos.expression = expression;
9562 } else if (token.kind == T_IDENTIFIER) {
9563 label_t *const label = get_label();
9565 statement->gotos.label = label;
9568 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9570 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9572 return create_error_statement();
9575 /* remember the goto's in a list for later checking */
9576 *goto_anchor = &statement->gotos;
9577 goto_anchor = &statement->gotos.next;
9579 expect(';', end_error);
9586 * Parse a continue statement.
9588 static statement_t *parse_continue(void)
9590 if (current_loop == NULL) {
9591 errorf(HERE, "continue statement not within loop");
9594 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9597 expect(';', end_error);
9604 * Parse a break statement.
9606 static statement_t *parse_break(void)
9608 if (current_switch == NULL && current_loop == NULL) {
9609 errorf(HERE, "break statement not within loop or switch");
9612 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9615 expect(';', end_error);
9622 * Parse a __leave statement.
9624 static statement_t *parse_leave_statement(void)
9626 if (current_try == NULL) {
9627 errorf(HERE, "__leave statement not within __try");
9630 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9633 expect(';', end_error);
9640 * Check if a given entity represents a local variable.
9642 static bool is_local_variable(const entity_t *entity)
9644 if (entity->kind != ENTITY_VARIABLE)
9647 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9648 case STORAGE_CLASS_AUTO:
9649 case STORAGE_CLASS_REGISTER: {
9650 const type_t *type = skip_typeref(entity->declaration.type);
9651 if (is_type_function(type)) {
9663 * Check if a given expression represents a local variable.
9665 static bool expression_is_local_variable(const expression_t *expression)
9667 if (expression->base.kind != EXPR_REFERENCE) {
9670 const entity_t *entity = expression->reference.entity;
9671 return is_local_variable(entity);
9675 * Check if a given expression represents a local variable and
9676 * return its declaration then, else return NULL.
9678 entity_t *expression_is_variable(const expression_t *expression)
9680 if (expression->base.kind != EXPR_REFERENCE) {
9683 entity_t *entity = expression->reference.entity;
9684 if (entity->kind != ENTITY_VARIABLE)
9691 * Parse a return statement.
9693 static statement_t *parse_return(void)
9695 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9698 expression_t *return_value = NULL;
9699 if (token.kind != ';') {
9700 return_value = parse_expression();
9701 mark_vars_read(return_value, NULL);
9704 const type_t *const func_type = skip_typeref(current_function->base.type);
9705 assert(is_type_function(func_type));
9706 type_t *const return_type = skip_typeref(func_type->function.return_type);
9708 source_position_t const *const pos = &statement->base.source_position;
9709 if (return_value != NULL) {
9710 type_t *return_value_type = skip_typeref(return_value->base.type);
9712 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9713 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9714 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9715 /* Only warn in C mode, because GCC does the same */
9716 if (c_mode & _CXX || strict_mode) {
9718 "'return' with a value, in function returning 'void'");
9720 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9722 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9723 /* Only warn in C mode, because GCC does the same */
9726 "'return' with expression in function returning 'void'");
9728 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9732 assign_error_t error = semantic_assign(return_type, return_value);
9733 report_assign_error(error, return_type, return_value, "'return'",
9736 return_value = create_implicit_cast(return_value, return_type);
9737 /* check for returning address of a local var */
9738 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9739 const expression_t *expression = return_value->unary.value;
9740 if (expression_is_local_variable(expression)) {
9741 warningf(WARN_OTHER, pos, "function returns address of local variable");
9744 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9745 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9746 if (c_mode & _CXX || strict_mode) {
9748 "'return' without value, in function returning non-void");
9750 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9753 statement->returns.value = return_value;
9755 expect(';', end_error);
9762 * Parse a declaration statement.
9764 static statement_t *parse_declaration_statement(void)
9766 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9768 entity_t *before = current_scope->last_entity;
9770 parse_external_declaration();
9772 parse_declaration(record_entity, DECL_FLAGS_NONE);
9775 declaration_statement_t *const decl = &statement->declaration;
9776 entity_t *const begin =
9777 before != NULL ? before->base.next : current_scope->entities;
9778 decl->declarations_begin = begin;
9779 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9785 * Parse an expression statement, ie. expr ';'.
9787 static statement_t *parse_expression_statement(void)
9789 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9791 expression_t *const expr = parse_expression();
9792 statement->expression.expression = expr;
9793 mark_vars_read(expr, ENT_ANY);
9795 expect(';', end_error);
9802 * Parse a microsoft __try { } __finally { } or
9803 * __try{ } __except() { }
9805 static statement_t *parse_ms_try_statment(void)
9807 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9810 PUSH_PARENT(statement);
9812 ms_try_statement_t *rem = current_try;
9813 current_try = &statement->ms_try;
9814 statement->ms_try.try_statement = parse_compound_statement(false);
9819 if (next_if(T___except)) {
9820 expect('(', end_error);
9821 add_anchor_token(')');
9822 expression_t *const expr = parse_expression();
9823 mark_vars_read(expr, NULL);
9824 type_t * type = skip_typeref(expr->base.type);
9825 if (is_type_integer(type)) {
9826 type = promote_integer(type);
9827 } else if (is_type_valid(type)) {
9828 errorf(&expr->base.source_position,
9829 "__expect expression is not an integer, but '%T'", type);
9830 type = type_error_type;
9832 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9833 rem_anchor_token(')');
9834 expect(')', end_error);
9835 statement->ms_try.final_statement = parse_compound_statement(false);
9836 } else if (next_if(T__finally)) {
9837 statement->ms_try.final_statement = parse_compound_statement(false);
9839 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9840 return create_error_statement();
9844 return create_error_statement();
9847 static statement_t *parse_empty_statement(void)
9849 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9850 statement_t *const statement = create_empty_statement();
9855 static statement_t *parse_local_label_declaration(void)
9857 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9861 entity_t *begin = NULL;
9862 entity_t *end = NULL;
9863 entity_t **anchor = &begin;
9865 if (token.kind != T_IDENTIFIER) {
9866 parse_error_expected("while parsing local label declaration",
9867 T_IDENTIFIER, NULL);
9870 symbol_t *symbol = token.identifier.symbol;
9871 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9872 if (entity != NULL && entity->base.parent_scope == current_scope) {
9873 source_position_t const *const ppos = &entity->base.source_position;
9874 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9876 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9877 entity->base.parent_scope = current_scope;
9878 entity->base.source_position = token.base.source_position;
9881 anchor = &entity->base.next;
9884 environment_push(entity);
9887 } while (next_if(','));
9888 expect(';', end_error);
9890 statement->declaration.declarations_begin = begin;
9891 statement->declaration.declarations_end = end;
9895 static void parse_namespace_definition(void)
9899 entity_t *entity = NULL;
9900 symbol_t *symbol = NULL;
9902 if (token.kind == T_IDENTIFIER) {
9903 symbol = token.identifier.symbol;
9906 entity = get_entity(symbol, NAMESPACE_NORMAL);
9908 && entity->kind != ENTITY_NAMESPACE
9909 && entity->base.parent_scope == current_scope) {
9910 if (is_entity_valid(entity)) {
9911 error_redefined_as_different_kind(&token.base.source_position,
9912 entity, ENTITY_NAMESPACE);
9918 if (entity == NULL) {
9919 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9920 entity->base.source_position = token.base.source_position;
9921 entity->base.parent_scope = current_scope;
9924 if (token.kind == '=') {
9925 /* TODO: parse namespace alias */
9926 panic("namespace alias definition not supported yet");
9929 environment_push(entity);
9930 append_entity(current_scope, entity);
9932 PUSH_SCOPE(&entity->namespacee.members);
9934 entity_t *old_current_entity = current_entity;
9935 current_entity = entity;
9937 expect('{', end_error);
9939 expect('}', end_error);
9942 assert(current_entity == entity);
9943 current_entity = old_current_entity;
9948 * Parse a statement.
9949 * There's also parse_statement() which additionally checks for
9950 * "statement has no effect" warnings
9952 static statement_t *intern_parse_statement(void)
9954 statement_t *statement = NULL;
9956 /* declaration or statement */
9957 add_anchor_token(';');
9958 switch (token.kind) {
9959 case T_IDENTIFIER: {
9960 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9961 if (la1_type == ':') {
9962 statement = parse_label_statement();
9963 } else if (is_typedef_symbol(token.identifier.symbol)) {
9964 statement = parse_declaration_statement();
9966 /* it's an identifier, the grammar says this must be an
9967 * expression statement. However it is common that users mistype
9968 * declaration types, so we guess a bit here to improve robustness
9969 * for incorrect programs */
9973 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9975 statement = parse_expression_statement();
9979 statement = parse_declaration_statement();
9987 case T___extension__: {
9988 /* This can be a prefix to a declaration or an expression statement.
9989 * We simply eat it now and parse the rest with tail recursion. */
9991 statement = intern_parse_statement();
9997 statement = parse_declaration_statement();
10001 statement = parse_local_label_declaration();
10004 case ';': statement = parse_empty_statement(); break;
10005 case '{': statement = parse_compound_statement(false); break;
10006 case T___leave: statement = parse_leave_statement(); break;
10007 case T___try: statement = parse_ms_try_statment(); break;
10008 case T_asm: statement = parse_asm_statement(); break;
10009 case T_break: statement = parse_break(); break;
10010 case T_case: statement = parse_case_statement(); break;
10011 case T_continue: statement = parse_continue(); break;
10012 case T_default: statement = parse_default_statement(); break;
10013 case T_do: statement = parse_do(); break;
10014 case T_for: statement = parse_for(); break;
10015 case T_goto: statement = parse_goto(); break;
10016 case T_if: statement = parse_if(); break;
10017 case T_return: statement = parse_return(); break;
10018 case T_switch: statement = parse_switch(); break;
10019 case T_while: statement = parse_while(); break;
10022 statement = parse_expression_statement();
10026 errorf(HERE, "unexpected token %K while parsing statement", &token);
10027 statement = create_error_statement();
10032 rem_anchor_token(';');
10034 assert(statement != NULL
10035 && statement->base.source_position.input_name != NULL);
10041 * parse a statement and emits "statement has no effect" warning if needed
10042 * (This is really a wrapper around intern_parse_statement with check for 1
10043 * single warning. It is needed, because for statement expressions we have
10044 * to avoid the warning on the last statement)
10046 static statement_t *parse_statement(void)
10048 statement_t *statement = intern_parse_statement();
10050 if (statement->kind == STATEMENT_EXPRESSION) {
10051 expression_t *expression = statement->expression.expression;
10052 if (!expression_has_effect(expression)) {
10053 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10061 * Parse a compound statement.
10063 static statement_t *parse_compound_statement(bool inside_expression_statement)
10065 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10067 PUSH_PARENT(statement);
10068 PUSH_SCOPE(&statement->compound.scope);
10071 add_anchor_token('}');
10072 /* tokens, which can start a statement */
10073 /* TODO MS, __builtin_FOO */
10074 add_anchor_token('!');
10075 add_anchor_token('&');
10076 add_anchor_token('(');
10077 add_anchor_token('*');
10078 add_anchor_token('+');
10079 add_anchor_token('-');
10080 add_anchor_token('{');
10081 add_anchor_token('~');
10082 add_anchor_token(T_CHARACTER_CONSTANT);
10083 add_anchor_token(T_COLONCOLON);
10084 add_anchor_token(T_FLOATINGPOINT);
10085 add_anchor_token(T_IDENTIFIER);
10086 add_anchor_token(T_INTEGER);
10087 add_anchor_token(T_MINUSMINUS);
10088 add_anchor_token(T_PLUSPLUS);
10089 add_anchor_token(T_STRING_LITERAL);
10090 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10091 add_anchor_token(T_WIDE_STRING_LITERAL);
10092 add_anchor_token(T__Bool);
10093 add_anchor_token(T__Complex);
10094 add_anchor_token(T__Imaginary);
10095 add_anchor_token(T___FUNCTION__);
10096 add_anchor_token(T___PRETTY_FUNCTION__);
10097 add_anchor_token(T___alignof__);
10098 add_anchor_token(T___attribute__);
10099 add_anchor_token(T___builtin_va_start);
10100 add_anchor_token(T___extension__);
10101 add_anchor_token(T___func__);
10102 add_anchor_token(T___imag__);
10103 add_anchor_token(T___label__);
10104 add_anchor_token(T___real__);
10105 add_anchor_token(T___thread);
10106 add_anchor_token(T_asm);
10107 add_anchor_token(T_auto);
10108 add_anchor_token(T_bool);
10109 add_anchor_token(T_break);
10110 add_anchor_token(T_case);
10111 add_anchor_token(T_char);
10112 add_anchor_token(T_class);
10113 add_anchor_token(T_const);
10114 add_anchor_token(T_const_cast);
10115 add_anchor_token(T_continue);
10116 add_anchor_token(T_default);
10117 add_anchor_token(T_delete);
10118 add_anchor_token(T_double);
10119 add_anchor_token(T_do);
10120 add_anchor_token(T_dynamic_cast);
10121 add_anchor_token(T_enum);
10122 add_anchor_token(T_extern);
10123 add_anchor_token(T_false);
10124 add_anchor_token(T_float);
10125 add_anchor_token(T_for);
10126 add_anchor_token(T_goto);
10127 add_anchor_token(T_if);
10128 add_anchor_token(T_inline);
10129 add_anchor_token(T_int);
10130 add_anchor_token(T_long);
10131 add_anchor_token(T_new);
10132 add_anchor_token(T_operator);
10133 add_anchor_token(T_register);
10134 add_anchor_token(T_reinterpret_cast);
10135 add_anchor_token(T_restrict);
10136 add_anchor_token(T_return);
10137 add_anchor_token(T_short);
10138 add_anchor_token(T_signed);
10139 add_anchor_token(T_sizeof);
10140 add_anchor_token(T_static);
10141 add_anchor_token(T_static_cast);
10142 add_anchor_token(T_struct);
10143 add_anchor_token(T_switch);
10144 add_anchor_token(T_template);
10145 add_anchor_token(T_this);
10146 add_anchor_token(T_throw);
10147 add_anchor_token(T_true);
10148 add_anchor_token(T_try);
10149 add_anchor_token(T_typedef);
10150 add_anchor_token(T_typeid);
10151 add_anchor_token(T_typename);
10152 add_anchor_token(T_typeof);
10153 add_anchor_token(T_union);
10154 add_anchor_token(T_unsigned);
10155 add_anchor_token(T_using);
10156 add_anchor_token(T_void);
10157 add_anchor_token(T_volatile);
10158 add_anchor_token(T_wchar_t);
10159 add_anchor_token(T_while);
10161 statement_t **anchor = &statement->compound.statements;
10162 bool only_decls_so_far = true;
10163 while (token.kind != '}') {
10164 if (token.kind == T_EOF) {
10165 errorf(&statement->base.source_position,
10166 "EOF while parsing compound statement");
10169 statement_t *sub_statement = intern_parse_statement();
10170 if (sub_statement->kind == STATEMENT_ERROR) {
10171 /* an error occurred. if we are at an anchor, return */
10177 if (sub_statement->kind != STATEMENT_DECLARATION) {
10178 only_decls_so_far = false;
10179 } else if (!only_decls_so_far) {
10180 source_position_t const *const pos = &sub_statement->base.source_position;
10181 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10184 *anchor = sub_statement;
10186 while (sub_statement->base.next != NULL)
10187 sub_statement = sub_statement->base.next;
10189 anchor = &sub_statement->base.next;
10193 /* look over all statements again to produce no effect warnings */
10194 if (is_warn_on(WARN_UNUSED_VALUE)) {
10195 statement_t *sub_statement = statement->compound.statements;
10196 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10197 if (sub_statement->kind != STATEMENT_EXPRESSION)
10199 /* don't emit a warning for the last expression in an expression
10200 * statement as it has always an effect */
10201 if (inside_expression_statement && sub_statement->base.next == NULL)
10204 expression_t *expression = sub_statement->expression.expression;
10205 if (!expression_has_effect(expression)) {
10206 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10212 rem_anchor_token(T_while);
10213 rem_anchor_token(T_wchar_t);
10214 rem_anchor_token(T_volatile);
10215 rem_anchor_token(T_void);
10216 rem_anchor_token(T_using);
10217 rem_anchor_token(T_unsigned);
10218 rem_anchor_token(T_union);
10219 rem_anchor_token(T_typeof);
10220 rem_anchor_token(T_typename);
10221 rem_anchor_token(T_typeid);
10222 rem_anchor_token(T_typedef);
10223 rem_anchor_token(T_try);
10224 rem_anchor_token(T_true);
10225 rem_anchor_token(T_throw);
10226 rem_anchor_token(T_this);
10227 rem_anchor_token(T_template);
10228 rem_anchor_token(T_switch);
10229 rem_anchor_token(T_struct);
10230 rem_anchor_token(T_static_cast);
10231 rem_anchor_token(T_static);
10232 rem_anchor_token(T_sizeof);
10233 rem_anchor_token(T_signed);
10234 rem_anchor_token(T_short);
10235 rem_anchor_token(T_return);
10236 rem_anchor_token(T_restrict);
10237 rem_anchor_token(T_reinterpret_cast);
10238 rem_anchor_token(T_register);
10239 rem_anchor_token(T_operator);
10240 rem_anchor_token(T_new);
10241 rem_anchor_token(T_long);
10242 rem_anchor_token(T_int);
10243 rem_anchor_token(T_inline);
10244 rem_anchor_token(T_if);
10245 rem_anchor_token(T_goto);
10246 rem_anchor_token(T_for);
10247 rem_anchor_token(T_float);
10248 rem_anchor_token(T_false);
10249 rem_anchor_token(T_extern);
10250 rem_anchor_token(T_enum);
10251 rem_anchor_token(T_dynamic_cast);
10252 rem_anchor_token(T_do);
10253 rem_anchor_token(T_double);
10254 rem_anchor_token(T_delete);
10255 rem_anchor_token(T_default);
10256 rem_anchor_token(T_continue);
10257 rem_anchor_token(T_const_cast);
10258 rem_anchor_token(T_const);
10259 rem_anchor_token(T_class);
10260 rem_anchor_token(T_char);
10261 rem_anchor_token(T_case);
10262 rem_anchor_token(T_break);
10263 rem_anchor_token(T_bool);
10264 rem_anchor_token(T_auto);
10265 rem_anchor_token(T_asm);
10266 rem_anchor_token(T___thread);
10267 rem_anchor_token(T___real__);
10268 rem_anchor_token(T___label__);
10269 rem_anchor_token(T___imag__);
10270 rem_anchor_token(T___func__);
10271 rem_anchor_token(T___extension__);
10272 rem_anchor_token(T___builtin_va_start);
10273 rem_anchor_token(T___attribute__);
10274 rem_anchor_token(T___alignof__);
10275 rem_anchor_token(T___PRETTY_FUNCTION__);
10276 rem_anchor_token(T___FUNCTION__);
10277 rem_anchor_token(T__Imaginary);
10278 rem_anchor_token(T__Complex);
10279 rem_anchor_token(T__Bool);
10280 rem_anchor_token(T_WIDE_STRING_LITERAL);
10281 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10282 rem_anchor_token(T_STRING_LITERAL);
10283 rem_anchor_token(T_PLUSPLUS);
10284 rem_anchor_token(T_MINUSMINUS);
10285 rem_anchor_token(T_INTEGER);
10286 rem_anchor_token(T_IDENTIFIER);
10287 rem_anchor_token(T_FLOATINGPOINT);
10288 rem_anchor_token(T_COLONCOLON);
10289 rem_anchor_token(T_CHARACTER_CONSTANT);
10290 rem_anchor_token('~');
10291 rem_anchor_token('{');
10292 rem_anchor_token('-');
10293 rem_anchor_token('+');
10294 rem_anchor_token('*');
10295 rem_anchor_token('(');
10296 rem_anchor_token('&');
10297 rem_anchor_token('!');
10298 rem_anchor_token('}');
10306 * Check for unused global static functions and variables
10308 static void check_unused_globals(void)
10310 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10313 for (const entity_t *entity = file_scope->entities; entity != NULL;
10314 entity = entity->base.next) {
10315 if (!is_declaration(entity))
10318 const declaration_t *declaration = &entity->declaration;
10319 if (declaration->used ||
10320 declaration->modifiers & DM_UNUSED ||
10321 declaration->modifiers & DM_USED ||
10322 declaration->storage_class != STORAGE_CLASS_STATIC)
10327 if (entity->kind == ENTITY_FUNCTION) {
10328 /* inhibit warning for static inline functions */
10329 if (entity->function.is_inline)
10332 why = WARN_UNUSED_FUNCTION;
10333 s = entity->function.statement != NULL ? "defined" : "declared";
10335 why = WARN_UNUSED_VARIABLE;
10339 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10343 static void parse_global_asm(void)
10345 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10348 expect('(', end_error);
10350 statement->asms.asm_text = parse_string_literals();
10351 statement->base.next = unit->global_asm;
10352 unit->global_asm = statement;
10354 expect(')', end_error);
10355 expect(';', end_error);
10360 static void parse_linkage_specification(void)
10364 source_position_t const pos = *HERE;
10365 char const *const linkage = parse_string_literals().begin;
10367 linkage_kind_t old_linkage = current_linkage;
10368 linkage_kind_t new_linkage;
10369 if (strcmp(linkage, "C") == 0) {
10370 new_linkage = LINKAGE_C;
10371 } else if (strcmp(linkage, "C++") == 0) {
10372 new_linkage = LINKAGE_CXX;
10374 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10375 new_linkage = LINKAGE_C;
10377 current_linkage = new_linkage;
10379 if (next_if('{')) {
10381 expect('}', end_error);
10387 assert(current_linkage == new_linkage);
10388 current_linkage = old_linkage;
10391 static void parse_external(void)
10393 switch (token.kind) {
10395 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10396 parse_linkage_specification();
10398 DECLARATION_START_NO_EXTERN
10400 case T___extension__:
10401 /* tokens below are for implicit int */
10402 case '&': /* & x; -> int& x; (and error later, because C++ has no
10404 case '*': /* * x; -> int* x; */
10405 case '(': /* (x); -> int (x); */
10407 parse_external_declaration();
10413 parse_global_asm();
10417 parse_namespace_definition();
10421 if (!strict_mode) {
10422 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10429 errorf(HERE, "stray %K outside of function", &token);
10430 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10431 eat_until_matching_token(token.kind);
10437 static void parse_externals(void)
10439 add_anchor_token('}');
10440 add_anchor_token(T_EOF);
10443 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10444 unsigned short token_anchor_copy[T_LAST_TOKEN];
10445 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10448 while (token.kind != T_EOF && token.kind != '}') {
10450 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10451 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10453 /* the anchor set and its copy differs */
10454 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10457 if (in_gcc_extension) {
10458 /* an gcc extension scope was not closed */
10459 internal_errorf(HERE, "Leaked __extension__");
10466 rem_anchor_token(T_EOF);
10467 rem_anchor_token('}');
10471 * Parse a translation unit.
10473 static void parse_translation_unit(void)
10475 add_anchor_token(T_EOF);
10480 if (token.kind == T_EOF)
10483 errorf(HERE, "stray %K outside of function", &token);
10484 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10485 eat_until_matching_token(token.kind);
10490 void set_default_visibility(elf_visibility_tag_t visibility)
10492 default_visibility = visibility;
10498 * @return the translation unit or NULL if errors occurred.
10500 void start_parsing(void)
10502 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10503 label_stack = NEW_ARR_F(stack_entry_t, 0);
10504 diagnostic_count = 0;
10508 print_to_file(stderr);
10510 assert(unit == NULL);
10511 unit = allocate_ast_zero(sizeof(unit[0]));
10513 assert(file_scope == NULL);
10514 file_scope = &unit->scope;
10516 assert(current_scope == NULL);
10517 scope_push(&unit->scope);
10519 create_gnu_builtins();
10521 create_microsoft_intrinsics();
10524 translation_unit_t *finish_parsing(void)
10526 assert(current_scope == &unit->scope);
10529 assert(file_scope == &unit->scope);
10530 check_unused_globals();
10533 DEL_ARR_F(environment_stack);
10534 DEL_ARR_F(label_stack);
10536 translation_unit_t *result = unit;
10541 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10542 * are given length one. */
10543 static void complete_incomplete_arrays(void)
10545 size_t n = ARR_LEN(incomplete_arrays);
10546 for (size_t i = 0; i != n; ++i) {
10547 declaration_t *const decl = incomplete_arrays[i];
10548 type_t *const type = skip_typeref(decl->type);
10550 if (!is_type_incomplete(type))
10553 source_position_t const *const pos = &decl->base.source_position;
10554 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10556 type_t *const new_type = duplicate_type(type);
10557 new_type->array.size_constant = true;
10558 new_type->array.has_implicit_size = true;
10559 new_type->array.size = 1;
10561 type_t *const result = identify_new_type(new_type);
10563 decl->type = result;
10567 void prepare_main_collect2(entity_t *entity)
10569 // create call to __main
10570 symbol_t *symbol = symbol_table_insert("__main");
10571 entity_t *subsubmain_ent
10572 = create_implicit_function(symbol, &builtin_source_position);
10574 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10575 type_t *ftype = subsubmain_ent->declaration.type;
10576 ref->base.source_position = builtin_source_position;
10577 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10578 ref->reference.entity = subsubmain_ent;
10580 expression_t *call = allocate_expression_zero(EXPR_CALL);
10581 call->base.source_position = builtin_source_position;
10582 call->base.type = type_void;
10583 call->call.function = ref;
10585 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10586 expr_statement->base.source_position = builtin_source_position;
10587 expr_statement->expression.expression = call;
10589 statement_t *statement = entity->function.statement;
10590 assert(statement->kind == STATEMENT_COMPOUND);
10591 compound_statement_t *compounds = &statement->compound;
10593 expr_statement->base.next = compounds->statements;
10594 compounds->statements = expr_statement;
10599 lookahead_bufpos = 0;
10600 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10603 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10604 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10605 parse_translation_unit();
10606 complete_incomplete_arrays();
10607 DEL_ARR_F(incomplete_arrays);
10608 incomplete_arrays = NULL;
10612 * Initialize the parser.
10614 void init_parser(void)
10616 sym_anonymous = symbol_table_insert("<anonymous>");
10618 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10620 init_expression_parsers();
10621 obstack_init(&temp_obst);
10625 * Terminate the parser.
10627 void exit_parser(void)
10629 obstack_free(&temp_obst, NULL);