2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_PARENT(stmt) \
115 statement_t *const new_parent = (stmt); \
116 statement_t *const old_parent = current_parent; \
117 ((void)(current_parent = new_parent))
118 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
120 #define PUSH_SCOPE(scope) \
121 size_t const top = environment_top(); \
122 scope_t *const new_scope = (scope); \
123 scope_t *const old_scope = scope_push(new_scope)
124 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
126 #define PUSH_EXTENSION() \
127 bool const old_gcc_extension = in_gcc_extension; \
128 while (next_if(T___extension__)) { \
129 in_gcc_extension = true; \
132 #define POP_EXTENSION() \
133 ((void)(in_gcc_extension = old_gcc_extension))
135 /** special symbol used for anonymous entities. */
136 static symbol_t *sym_anonymous = NULL;
138 /** The token anchor set */
139 static unsigned char token_anchor_set[T_LAST_TOKEN];
141 /** The current source position. */
142 #define HERE (&token.source_position)
144 /** true if we are in GCC mode. */
145 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
147 static statement_t *parse_compound_statement(bool inside_expression_statement);
148 static statement_t *parse_statement(void);
150 static expression_t *parse_subexpression(precedence_t);
151 static expression_t *parse_expression(void);
152 static type_t *parse_typename(void);
153 static void parse_externals(void);
154 static void parse_external(void);
156 static void parse_compound_type_entries(compound_t *compound_declaration);
158 static void check_call_argument(type_t *expected_type,
159 call_argument_t *argument, unsigned pos);
161 typedef enum declarator_flags_t {
163 DECL_MAY_BE_ABSTRACT = 1U << 0,
164 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
165 DECL_IS_PARAMETER = 1U << 2
166 } declarator_flags_t;
168 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
169 declarator_flags_t flags);
171 static void semantic_comparison(binary_expression_t *expression);
173 #define STORAGE_CLASSES \
174 STORAGE_CLASSES_NO_EXTERN \
177 #define STORAGE_CLASSES_NO_EXTERN \
184 #define TYPE_QUALIFIERS \
189 case T__forceinline: \
190 case T___attribute__:
192 #define COMPLEX_SPECIFIERS \
194 #define IMAGINARY_SPECIFIERS \
197 #define TYPE_SPECIFIERS \
199 case T___builtin_va_list: \
224 #define DECLARATION_START \
229 #define DECLARATION_START_NO_EXTERN \
230 STORAGE_CLASSES_NO_EXTERN \
234 #define EXPRESSION_START \
243 case T_CHARACTER_CONSTANT: \
244 case T_FLOATINGPOINT: \
245 case T_FLOATINGPOINT_HEXADECIMAL: \
247 case T_INTEGER_HEXADECIMAL: \
248 case T_INTEGER_OCTAL: \
251 case T_STRING_LITERAL: \
252 case T_WIDE_CHARACTER_CONSTANT: \
253 case T_WIDE_STRING_LITERAL: \
254 case T___FUNCDNAME__: \
255 case T___FUNCSIG__: \
256 case T___FUNCTION__: \
257 case T___PRETTY_FUNCTION__: \
258 case T___alignof__: \
259 case T___builtin_classify_type: \
260 case T___builtin_constant_p: \
261 case T___builtin_isgreater: \
262 case T___builtin_isgreaterequal: \
263 case T___builtin_isless: \
264 case T___builtin_islessequal: \
265 case T___builtin_islessgreater: \
266 case T___builtin_isunordered: \
267 case T___builtin_offsetof: \
268 case T___builtin_va_arg: \
269 case T___builtin_va_copy: \
270 case T___builtin_va_start: \
281 * Returns the size of a statement node.
283 * @param kind the statement kind
285 static size_t get_statement_struct_size(statement_kind_t kind)
287 static const size_t sizes[] = {
288 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
289 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
290 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
291 [STATEMENT_RETURN] = sizeof(return_statement_t),
292 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
293 [STATEMENT_IF] = sizeof(if_statement_t),
294 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
295 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
296 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
297 [STATEMENT_BREAK] = sizeof(statement_base_t),
298 [STATEMENT_GOTO] = sizeof(goto_statement_t),
299 [STATEMENT_LABEL] = sizeof(label_statement_t),
300 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
301 [STATEMENT_WHILE] = sizeof(while_statement_t),
302 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
303 [STATEMENT_FOR] = sizeof(for_statement_t),
304 [STATEMENT_ASM] = sizeof(asm_statement_t),
305 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
306 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
308 assert((size_t)kind < lengthof(sizes));
309 assert(sizes[kind] != 0);
314 * Returns the size of an expression node.
316 * @param kind the expression kind
318 static size_t get_expression_struct_size(expression_kind_t kind)
320 static const size_t sizes[] = {
321 [EXPR_INVALID] = sizeof(expression_base_t),
322 [EXPR_REFERENCE] = sizeof(reference_expression_t),
323 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
324 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
328 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
332 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
333 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
334 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
335 [EXPR_CALL] = sizeof(call_expression_t),
336 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
337 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
338 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
339 [EXPR_SELECT] = sizeof(select_expression_t),
340 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
341 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
342 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
343 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
344 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
345 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
346 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
347 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
348 [EXPR_VA_START] = sizeof(va_start_expression_t),
349 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
350 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
351 [EXPR_STATEMENT] = sizeof(statement_expression_t),
352 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
354 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
355 return sizes[EXPR_UNARY_FIRST];
357 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
358 return sizes[EXPR_BINARY_FIRST];
360 assert((size_t)kind < lengthof(sizes));
361 assert(sizes[kind] != 0);
366 * Allocate a statement node of given kind and initialize all
367 * fields with zero. Sets its source position to the position
368 * of the current token.
370 static statement_t *allocate_statement_zero(statement_kind_t kind)
372 size_t size = get_statement_struct_size(kind);
373 statement_t *res = allocate_ast_zero(size);
375 res->base.kind = kind;
376 res->base.parent = current_parent;
377 res->base.source_position = token.source_position;
382 * Allocate an expression node of given kind and initialize all
385 * @param kind the kind of the expression to allocate
387 static expression_t *allocate_expression_zero(expression_kind_t kind)
389 size_t size = get_expression_struct_size(kind);
390 expression_t *res = allocate_ast_zero(size);
392 res->base.kind = kind;
393 res->base.type = type_error_type;
394 res->base.source_position = token.source_position;
399 * Creates a new invalid expression at the source position
400 * of the current token.
402 static expression_t *create_invalid_expression(void)
404 return allocate_expression_zero(EXPR_INVALID);
408 * Creates a new invalid statement.
410 static statement_t *create_invalid_statement(void)
412 return allocate_statement_zero(STATEMENT_INVALID);
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.type == 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_type)
512 assert(0 <= token_type && token_type < T_LAST_TOKEN);
513 ++token_anchor_set[token_type];
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_type)
522 assert(0 <= token_type && token_type < T_LAST_TOKEN);
523 int count = token_anchor_set[token_type];
524 token_anchor_set[token_type] = 0;
529 * Restore the number of token types to the given count.
531 static void restore_anchor_state(int token_type, int count)
533 assert(0 <= token_type && token_type < T_LAST_TOKEN);
534 token_anchor_set[token_type] = count;
538 * Remove a token type from the token type anchor set (a multi-set).
540 static void rem_anchor_token(int token_type)
542 assert(0 <= token_type && token_type < T_LAST_TOKEN);
543 assert(token_anchor_set[token_type] != 0);
544 --token_anchor_set[token_type];
548 * Return true if the token type of the current token is
551 static bool at_anchor(void)
555 return token_anchor_set[token.type];
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.type != end_token ||
575 parenthesis_count != 0 ||
577 bracket_count != 0) {
578 switch (token.type) {
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.type == 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.type] == 0) {
618 if (token.type == '(' || token.type == '{' || token.type == '[')
619 eat_until_matching_token(token.type);
625 * Eat a whole block from input tokens.
627 static void eat_block(void)
629 eat_until_matching_token('{');
633 #define eat(token_type) (assert(token.type == (token_type)), 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.type != (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.type != (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 assert(namespc != NAMESPACE_INVALID);
711 entity_t *entity = symbol->entity;
712 for (; entity != NULL; entity = entity->base.symbol_next) {
713 if ((namespace_tag_t)entity->base.namespc == namespc)
720 /* §6.2.3:1 24) There is only one name space for tags even though three are
722 static entity_t *get_tag(symbol_t const *const symbol,
723 entity_kind_tag_t const kind)
725 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
726 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
728 "'%Y' defined as wrong kind of tag (previous definition %P)",
729 symbol, &entity->base.source_position);
736 * pushs an entity on the environment stack and links the corresponding symbol
739 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
741 symbol_t *symbol = entity->base.symbol;
742 entity_namespace_t namespc = entity->base.namespc;
743 assert(namespc != NAMESPACE_INVALID);
745 /* replace/add entity into entity list of the symbol */
748 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
753 /* replace an entry? */
754 if (iter->base.namespc == namespc) {
755 entity->base.symbol_next = iter->base.symbol_next;
761 /* remember old declaration */
763 entry.symbol = symbol;
764 entry.old_entity = iter;
765 entry.namespc = namespc;
766 ARR_APP1(stack_entry_t, *stack_ptr, entry);
770 * Push an entity on the environment stack.
772 static void environment_push(entity_t *entity)
774 assert(entity->base.source_position.input_name != NULL);
775 assert(entity->base.parent_scope != NULL);
776 stack_push(&environment_stack, entity);
780 * Push a declaration on the global label stack.
782 * @param declaration the declaration
784 static void label_push(entity_t *label)
786 /* we abuse the parameters scope as parent for the labels */
787 label->base.parent_scope = ¤t_function->parameters;
788 stack_push(&label_stack, label);
792 * pops symbols from the environment stack until @p new_top is the top element
794 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
796 stack_entry_t *stack = *stack_ptr;
797 size_t top = ARR_LEN(stack);
800 assert(new_top <= top);
804 for (i = top; i > new_top; --i) {
805 stack_entry_t *entry = &stack[i - 1];
807 entity_t *old_entity = entry->old_entity;
808 symbol_t *symbol = entry->symbol;
809 entity_namespace_t namespc = entry->namespc;
811 /* replace with old_entity/remove */
814 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
816 assert(iter != NULL);
817 /* replace an entry? */
818 if (iter->base.namespc == namespc)
822 /* restore definition from outer scopes (if there was one) */
823 if (old_entity != NULL) {
824 old_entity->base.symbol_next = iter->base.symbol_next;
825 *anchor = old_entity;
827 /* remove entry from list */
828 *anchor = iter->base.symbol_next;
832 ARR_SHRINKLEN(*stack_ptr, new_top);
836 * Pop all entries from the environment stack until the new_top
839 * @param new_top the new stack top
841 static void environment_pop_to(size_t new_top)
843 stack_pop_to(&environment_stack, new_top);
847 * Pop all entries from the global label stack until the new_top
850 * @param new_top the new stack top
852 static void label_pop_to(size_t new_top)
854 stack_pop_to(&label_stack, new_top);
857 static int get_akind_rank(atomic_type_kind_t akind)
863 * Return the type rank for an atomic type.
865 static int get_rank(const type_t *type)
867 assert(!is_typeref(type));
868 if (type->kind == TYPE_ENUM)
869 return get_akind_rank(type->enumt.akind);
871 assert(type->kind == TYPE_ATOMIC);
872 return get_akind_rank(type->atomic.akind);
876 * §6.3.1.1:2 Do integer promotion for a given type.
878 * @param type the type to promote
879 * @return the promoted type
881 static type_t *promote_integer(type_t *type)
883 if (type->kind == TYPE_BITFIELD)
884 type = type->bitfield.base_type;
886 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
893 * Create a cast expression.
895 * @param expression the expression to cast
896 * @param dest_type the destination type
898 static expression_t *create_cast_expression(expression_t *expression,
901 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
903 cast->unary.value = expression;
904 cast->base.type = dest_type;
910 * Check if a given expression represents a null pointer constant.
912 * @param expression the expression to check
914 static bool is_null_pointer_constant(const expression_t *expression)
916 /* skip void* cast */
917 if (expression->kind == EXPR_UNARY_CAST ||
918 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
919 type_t *const type = skip_typeref(expression->base.type);
920 if (types_compatible(type, type_void_ptr))
921 expression = expression->unary.value;
924 type_t *const type = skip_typeref(expression->base.type);
925 if (!is_type_integer(type))
927 switch (is_constant_expression(expression)) {
928 case EXPR_CLASS_ERROR: return true;
929 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
930 default: return false;
935 * Create an implicit cast expression.
937 * @param expression the expression to cast
938 * @param dest_type the destination type
940 static expression_t *create_implicit_cast(expression_t *expression,
943 type_t *const source_type = expression->base.type;
945 if (source_type == dest_type)
948 return create_cast_expression(expression, dest_type);
951 typedef enum assign_error_t {
953 ASSIGN_ERROR_INCOMPATIBLE,
954 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
955 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
956 ASSIGN_WARNING_POINTER_FROM_INT,
957 ASSIGN_WARNING_INT_FROM_POINTER
960 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)
962 type_t *const orig_type_right = right->base.type;
963 type_t *const type_left = skip_typeref(orig_type_left);
964 type_t *const type_right = skip_typeref(orig_type_right);
969 case ASSIGN_ERROR_INCOMPATIBLE:
970 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
973 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
974 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
975 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
977 /* the left type has all qualifiers from the right type */
978 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
979 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);
983 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
984 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
987 case ASSIGN_WARNING_POINTER_FROM_INT:
988 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
991 case ASSIGN_WARNING_INT_FROM_POINTER:
992 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
996 panic("invalid error value");
1000 /** Implements the rules from §6.5.16.1 */
1001 static assign_error_t semantic_assign(type_t *orig_type_left,
1002 const expression_t *const right)
1004 type_t *const orig_type_right = right->base.type;
1005 type_t *const type_left = skip_typeref(orig_type_left);
1006 type_t *const type_right = skip_typeref(orig_type_right);
1008 if (is_type_pointer(type_left)) {
1009 if (is_null_pointer_constant(right)) {
1010 return ASSIGN_SUCCESS;
1011 } else if (is_type_pointer(type_right)) {
1012 type_t *points_to_left
1013 = skip_typeref(type_left->pointer.points_to);
1014 type_t *points_to_right
1015 = skip_typeref(type_right->pointer.points_to);
1016 assign_error_t res = ASSIGN_SUCCESS;
1018 /* the left type has all qualifiers from the right type */
1019 unsigned missing_qualifiers
1020 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1021 if (missing_qualifiers != 0) {
1022 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1025 points_to_left = get_unqualified_type(points_to_left);
1026 points_to_right = get_unqualified_type(points_to_right);
1028 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1031 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1032 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1033 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1036 if (!types_compatible(points_to_left, points_to_right)) {
1037 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1041 } else if (is_type_integer(type_right)) {
1042 return ASSIGN_WARNING_POINTER_FROM_INT;
1044 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1045 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1046 && is_type_pointer(type_right))) {
1047 return ASSIGN_SUCCESS;
1048 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1049 type_t *const unqual_type_left = get_unqualified_type(type_left);
1050 type_t *const unqual_type_right = get_unqualified_type(type_right);
1051 if (types_compatible(unqual_type_left, unqual_type_right)) {
1052 return ASSIGN_SUCCESS;
1054 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1055 return ASSIGN_WARNING_INT_FROM_POINTER;
1058 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1059 return ASSIGN_SUCCESS;
1061 return ASSIGN_ERROR_INCOMPATIBLE;
1064 static expression_t *parse_constant_expression(void)
1066 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1068 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1069 errorf(&result->base.source_position,
1070 "expression '%E' is not constant", result);
1076 static expression_t *parse_assignment_expression(void)
1078 return parse_subexpression(PREC_ASSIGNMENT);
1081 static void warn_string_concat(const source_position_t *pos)
1083 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1086 static string_t parse_string_literals(void)
1088 assert(token.type == T_STRING_LITERAL);
1089 string_t result = token.literal;
1093 while (token.type == T_STRING_LITERAL) {
1094 warn_string_concat(&token.source_position);
1095 result = concat_strings(&result, &token.literal);
1103 * compare two string, ignoring double underscores on the second.
1105 static int strcmp_underscore(const char *s1, const char *s2)
1107 if (s2[0] == '_' && s2[1] == '_') {
1108 size_t len2 = strlen(s2);
1109 size_t len1 = strlen(s1);
1110 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1111 return strncmp(s1, s2+2, len2-4);
1115 return strcmp(s1, s2);
1118 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1120 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1121 attribute->kind = kind;
1122 attribute->source_position = *HERE;
1127 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1130 * __attribute__ ( ( attribute-list ) )
1134 * attribute_list , attrib
1139 * any-word ( identifier )
1140 * any-word ( identifier , nonempty-expr-list )
1141 * any-word ( expr-list )
1143 * where the "identifier" must not be declared as a type, and
1144 * "any-word" may be any identifier (including one declared as a
1145 * type), a reserved word storage class specifier, type specifier or
1146 * type qualifier. ??? This still leaves out most reserved keywords
1147 * (following the old parser), shouldn't we include them, and why not
1148 * allow identifiers declared as types to start the arguments?
1150 * Matze: this all looks confusing and little systematic, so we're even less
1151 * strict and parse any list of things which are identifiers or
1152 * (assignment-)expressions.
1154 static attribute_argument_t *parse_attribute_arguments(void)
1156 attribute_argument_t *first = NULL;
1157 attribute_argument_t **anchor = &first;
1158 if (token.type != ')') do {
1159 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1161 /* is it an identifier */
1162 if (token.type == T_IDENTIFIER
1163 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1164 symbol_t *symbol = token.symbol;
1165 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1166 argument->v.symbol = symbol;
1169 /* must be an expression */
1170 expression_t *expression = parse_assignment_expression();
1172 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1173 argument->v.expression = expression;
1176 /* append argument */
1178 anchor = &argument->next;
1179 } while (next_if(','));
1180 expect(')', end_error);
1189 static attribute_t *parse_attribute_asm(void)
1191 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1194 expect('(', end_error);
1195 attribute->a.arguments = parse_attribute_arguments();
1202 static symbol_t *get_symbol_from_token(void)
1204 switch(token.type) {
1206 return token.symbol;
1235 /* maybe we need more tokens ... add them on demand */
1236 return get_token_symbol(&token);
1242 static attribute_t *parse_attribute_gnu_single(void)
1244 /* parse "any-word" */
1245 symbol_t *symbol = get_symbol_from_token();
1246 if (symbol == NULL) {
1247 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1251 attribute_kind_t kind;
1252 char const *const name = symbol->string;
1253 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1254 if (kind > ATTRIBUTE_GNU_LAST) {
1255 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1256 /* TODO: we should still save the attribute in the list... */
1257 kind = ATTRIBUTE_UNKNOWN;
1261 const char *attribute_name = get_attribute_name(kind);
1262 if (attribute_name != NULL
1263 && strcmp_underscore(attribute_name, name) == 0)
1267 attribute_t *attribute = allocate_attribute_zero(kind);
1270 /* parse arguments */
1272 attribute->a.arguments = parse_attribute_arguments();
1277 static attribute_t *parse_attribute_gnu(void)
1279 attribute_t *first = NULL;
1280 attribute_t **anchor = &first;
1282 eat(T___attribute__);
1283 expect('(', end_error);
1284 expect('(', end_error);
1286 if (token.type != ')') do {
1287 attribute_t *attribute = parse_attribute_gnu_single();
1288 if (attribute == NULL)
1291 *anchor = attribute;
1292 anchor = &attribute->next;
1293 } while (next_if(','));
1294 expect(')', end_error);
1295 expect(')', end_error);
1301 /** Parse attributes. */
1302 static attribute_t *parse_attributes(attribute_t *first)
1304 attribute_t **anchor = &first;
1306 while (*anchor != NULL)
1307 anchor = &(*anchor)->next;
1309 attribute_t *attribute;
1310 switch (token.type) {
1311 case T___attribute__:
1312 attribute = parse_attribute_gnu();
1313 if (attribute == NULL)
1318 attribute = parse_attribute_asm();
1322 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1327 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1331 case T__forceinline:
1332 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1333 eat(T__forceinline);
1337 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1342 /* TODO record modifier */
1343 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1344 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1352 *anchor = attribute;
1353 anchor = &attribute->next;
1357 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1359 static entity_t *determine_lhs_ent(expression_t *const expr,
1362 switch (expr->kind) {
1363 case EXPR_REFERENCE: {
1364 entity_t *const entity = expr->reference.entity;
1365 /* we should only find variables as lvalues... */
1366 if (entity->base.kind != ENTITY_VARIABLE
1367 && entity->base.kind != ENTITY_PARAMETER)
1373 case EXPR_ARRAY_ACCESS: {
1374 expression_t *const ref = expr->array_access.array_ref;
1375 entity_t * ent = NULL;
1376 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1377 ent = determine_lhs_ent(ref, lhs_ent);
1380 mark_vars_read(expr->select.compound, lhs_ent);
1382 mark_vars_read(expr->array_access.index, lhs_ent);
1387 if (is_type_compound(skip_typeref(expr->base.type))) {
1388 return determine_lhs_ent(expr->select.compound, lhs_ent);
1390 mark_vars_read(expr->select.compound, lhs_ent);
1395 case EXPR_UNARY_DEREFERENCE: {
1396 expression_t *const val = expr->unary.value;
1397 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1399 return determine_lhs_ent(val->unary.value, lhs_ent);
1401 mark_vars_read(val, NULL);
1407 mark_vars_read(expr, NULL);
1412 #define ENT_ANY ((entity_t*)-1)
1415 * Mark declarations, which are read. This is used to detect variables, which
1419 * x is not marked as "read", because it is only read to calculate its own new
1423 * x and y are not detected as "not read", because multiple variables are
1426 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1428 switch (expr->kind) {
1429 case EXPR_REFERENCE: {
1430 entity_t *const entity = expr->reference.entity;
1431 if (entity->kind != ENTITY_VARIABLE
1432 && entity->kind != ENTITY_PARAMETER)
1435 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1436 if (entity->kind == ENTITY_VARIABLE) {
1437 entity->variable.read = true;
1439 entity->parameter.read = true;
1446 // TODO respect pure/const
1447 mark_vars_read(expr->call.function, NULL);
1448 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1449 mark_vars_read(arg->expression, NULL);
1453 case EXPR_CONDITIONAL:
1454 // TODO lhs_decl should depend on whether true/false have an effect
1455 mark_vars_read(expr->conditional.condition, NULL);
1456 if (expr->conditional.true_expression != NULL)
1457 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1458 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1462 if (lhs_ent == ENT_ANY
1463 && !is_type_compound(skip_typeref(expr->base.type)))
1465 mark_vars_read(expr->select.compound, lhs_ent);
1468 case EXPR_ARRAY_ACCESS: {
1469 expression_t *const ref = expr->array_access.array_ref;
1470 mark_vars_read(ref, lhs_ent);
1471 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1472 mark_vars_read(expr->array_access.index, lhs_ent);
1477 mark_vars_read(expr->va_arge.ap, lhs_ent);
1481 mark_vars_read(expr->va_copye.src, lhs_ent);
1484 case EXPR_UNARY_CAST:
1485 /* Special case: Use void cast to mark a variable as "read" */
1486 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1491 case EXPR_UNARY_THROW:
1492 if (expr->unary.value == NULL)
1495 case EXPR_UNARY_DEREFERENCE:
1496 case EXPR_UNARY_DELETE:
1497 case EXPR_UNARY_DELETE_ARRAY:
1498 if (lhs_ent == ENT_ANY)
1502 case EXPR_UNARY_NEGATE:
1503 case EXPR_UNARY_PLUS:
1504 case EXPR_UNARY_BITWISE_NEGATE:
1505 case EXPR_UNARY_NOT:
1506 case EXPR_UNARY_TAKE_ADDRESS:
1507 case EXPR_UNARY_POSTFIX_INCREMENT:
1508 case EXPR_UNARY_POSTFIX_DECREMENT:
1509 case EXPR_UNARY_PREFIX_INCREMENT:
1510 case EXPR_UNARY_PREFIX_DECREMENT:
1511 case EXPR_UNARY_CAST_IMPLICIT:
1512 case EXPR_UNARY_ASSUME:
1514 mark_vars_read(expr->unary.value, lhs_ent);
1517 case EXPR_BINARY_ADD:
1518 case EXPR_BINARY_SUB:
1519 case EXPR_BINARY_MUL:
1520 case EXPR_BINARY_DIV:
1521 case EXPR_BINARY_MOD:
1522 case EXPR_BINARY_EQUAL:
1523 case EXPR_BINARY_NOTEQUAL:
1524 case EXPR_BINARY_LESS:
1525 case EXPR_BINARY_LESSEQUAL:
1526 case EXPR_BINARY_GREATER:
1527 case EXPR_BINARY_GREATEREQUAL:
1528 case EXPR_BINARY_BITWISE_AND:
1529 case EXPR_BINARY_BITWISE_OR:
1530 case EXPR_BINARY_BITWISE_XOR:
1531 case EXPR_BINARY_LOGICAL_AND:
1532 case EXPR_BINARY_LOGICAL_OR:
1533 case EXPR_BINARY_SHIFTLEFT:
1534 case EXPR_BINARY_SHIFTRIGHT:
1535 case EXPR_BINARY_COMMA:
1536 case EXPR_BINARY_ISGREATER:
1537 case EXPR_BINARY_ISGREATEREQUAL:
1538 case EXPR_BINARY_ISLESS:
1539 case EXPR_BINARY_ISLESSEQUAL:
1540 case EXPR_BINARY_ISLESSGREATER:
1541 case EXPR_BINARY_ISUNORDERED:
1542 mark_vars_read(expr->binary.left, lhs_ent);
1543 mark_vars_read(expr->binary.right, lhs_ent);
1546 case EXPR_BINARY_ASSIGN:
1547 case EXPR_BINARY_MUL_ASSIGN:
1548 case EXPR_BINARY_DIV_ASSIGN:
1549 case EXPR_BINARY_MOD_ASSIGN:
1550 case EXPR_BINARY_ADD_ASSIGN:
1551 case EXPR_BINARY_SUB_ASSIGN:
1552 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1553 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1554 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1555 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1556 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1557 if (lhs_ent == ENT_ANY)
1559 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1560 mark_vars_read(expr->binary.right, lhs_ent);
1565 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1571 case EXPR_STRING_LITERAL:
1572 case EXPR_WIDE_STRING_LITERAL:
1573 case EXPR_COMPOUND_LITERAL: // TODO init?
1575 case EXPR_CLASSIFY_TYPE:
1578 case EXPR_BUILTIN_CONSTANT_P:
1579 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1581 case EXPR_STATEMENT: // TODO
1582 case EXPR_LABEL_ADDRESS:
1583 case EXPR_REFERENCE_ENUM_VALUE:
1587 panic("unhandled expression");
1590 static designator_t *parse_designation(void)
1592 designator_t *result = NULL;
1593 designator_t **anchor = &result;
1596 designator_t *designator;
1597 switch (token.type) {
1599 designator = allocate_ast_zero(sizeof(designator[0]));
1600 designator->source_position = token.source_position;
1602 add_anchor_token(']');
1603 designator->array_index = parse_constant_expression();
1604 rem_anchor_token(']');
1605 expect(']', end_error);
1608 designator = allocate_ast_zero(sizeof(designator[0]));
1609 designator->source_position = token.source_position;
1611 if (token.type != T_IDENTIFIER) {
1612 parse_error_expected("while parsing designator",
1613 T_IDENTIFIER, NULL);
1616 designator->symbol = token.symbol;
1620 expect('=', end_error);
1624 assert(designator != NULL);
1625 *anchor = designator;
1626 anchor = &designator->next;
1632 static initializer_t *initializer_from_string(array_type_t *const type,
1633 const string_t *const string)
1635 /* TODO: check len vs. size of array type */
1638 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1639 initializer->string.string = *string;
1644 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1645 const string_t *const string)
1647 /* TODO: check len vs. size of array type */
1650 initializer_t *const initializer =
1651 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1652 initializer->wide_string.string = *string;
1658 * Build an initializer from a given expression.
1660 static initializer_t *initializer_from_expression(type_t *orig_type,
1661 expression_t *expression)
1663 /* TODO check that expression is a constant expression */
1665 /* §6.7.8.14/15 char array may be initialized by string literals */
1666 type_t *type = skip_typeref(orig_type);
1667 type_t *expr_type_orig = expression->base.type;
1668 type_t *expr_type = skip_typeref(expr_type_orig);
1670 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1671 array_type_t *const array_type = &type->array;
1672 type_t *const element_type = skip_typeref(array_type->element_type);
1674 if (element_type->kind == TYPE_ATOMIC) {
1675 atomic_type_kind_t akind = element_type->atomic.akind;
1676 switch (expression->kind) {
1677 case EXPR_STRING_LITERAL:
1678 if (akind == ATOMIC_TYPE_CHAR
1679 || akind == ATOMIC_TYPE_SCHAR
1680 || akind == ATOMIC_TYPE_UCHAR) {
1681 return initializer_from_string(array_type,
1682 &expression->string_literal.value);
1686 case EXPR_WIDE_STRING_LITERAL: {
1687 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1688 if (get_unqualified_type(element_type) == bare_wchar_type) {
1689 return initializer_from_wide_string(array_type,
1690 &expression->string_literal.value);
1701 assign_error_t error = semantic_assign(type, expression);
1702 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1704 report_assign_error(error, type, expression, "initializer",
1705 &expression->base.source_position);
1707 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1708 result->value.value = create_implicit_cast(expression, type);
1714 * Checks if a given expression can be used as a constant initializer.
1716 static bool is_initializer_constant(const expression_t *expression)
1718 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1719 is_linker_constant(expression) != EXPR_CLASS_VARIABLE;
1723 * Parses an scalar initializer.
1725 * §6.7.8.11; eat {} without warning
1727 static initializer_t *parse_scalar_initializer(type_t *type,
1728 bool must_be_constant)
1730 /* there might be extra {} hierarchies */
1732 if (token.type == '{') {
1733 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1737 } while (token.type == '{');
1740 expression_t *expression = parse_assignment_expression();
1741 mark_vars_read(expression, NULL);
1742 if (must_be_constant && !is_initializer_constant(expression)) {
1743 errorf(&expression->base.source_position,
1744 "initialisation expression '%E' is not constant",
1748 initializer_t *initializer = initializer_from_expression(type, expression);
1750 if (initializer == NULL) {
1751 errorf(&expression->base.source_position,
1752 "expression '%E' (type '%T') doesn't match expected type '%T'",
1753 expression, expression->base.type, type);
1758 bool additional_warning_displayed = false;
1759 while (braces > 0) {
1761 if (token.type != '}') {
1762 if (!additional_warning_displayed) {
1763 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1764 additional_warning_displayed = true;
1775 * An entry in the type path.
1777 typedef struct type_path_entry_t type_path_entry_t;
1778 struct type_path_entry_t {
1779 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1781 size_t index; /**< For array types: the current index. */
1782 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1787 * A type path expression a position inside compound or array types.
1789 typedef struct type_path_t type_path_t;
1790 struct type_path_t {
1791 type_path_entry_t *path; /**< An flexible array containing the current path. */
1792 type_t *top_type; /**< type of the element the path points */
1793 size_t max_index; /**< largest index in outermost array */
1797 * Prints a type path for debugging.
1799 static __attribute__((unused)) void debug_print_type_path(
1800 const type_path_t *path)
1802 size_t len = ARR_LEN(path->path);
1804 for (size_t i = 0; i < len; ++i) {
1805 const type_path_entry_t *entry = & path->path[i];
1807 type_t *type = skip_typeref(entry->type);
1808 if (is_type_compound(type)) {
1809 /* in gcc mode structs can have no members */
1810 if (entry->v.compound_entry == NULL) {
1814 fprintf(stderr, ".%s",
1815 entry->v.compound_entry->base.symbol->string);
1816 } else if (is_type_array(type)) {
1817 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1819 fprintf(stderr, "-INVALID-");
1822 if (path->top_type != NULL) {
1823 fprintf(stderr, " (");
1824 print_type(path->top_type);
1825 fprintf(stderr, ")");
1830 * Return the top type path entry, ie. in a path
1831 * (type).a.b returns the b.
1833 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1835 size_t len = ARR_LEN(path->path);
1837 return &path->path[len-1];
1841 * Enlarge the type path by an (empty) element.
1843 static type_path_entry_t *append_to_type_path(type_path_t *path)
1845 size_t len = ARR_LEN(path->path);
1846 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1848 type_path_entry_t *result = & path->path[len];
1849 memset(result, 0, sizeof(result[0]));
1854 * Descending into a sub-type. Enter the scope of the current top_type.
1856 static void descend_into_subtype(type_path_t *path)
1858 type_t *orig_top_type = path->top_type;
1859 type_t *top_type = skip_typeref(orig_top_type);
1861 type_path_entry_t *top = append_to_type_path(path);
1862 top->type = top_type;
1864 if (is_type_compound(top_type)) {
1865 compound_t *compound = top_type->compound.compound;
1866 entity_t *entry = compound->members.entities;
1868 if (entry != NULL) {
1869 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1870 top->v.compound_entry = &entry->declaration;
1871 path->top_type = entry->declaration.type;
1873 path->top_type = NULL;
1875 } else if (is_type_array(top_type)) {
1877 path->top_type = top_type->array.element_type;
1879 assert(!is_type_valid(top_type));
1884 * Pop an entry from the given type path, ie. returning from
1885 * (type).a.b to (type).a
1887 static void ascend_from_subtype(type_path_t *path)
1889 type_path_entry_t *top = get_type_path_top(path);
1891 path->top_type = top->type;
1893 size_t len = ARR_LEN(path->path);
1894 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1898 * Pop entries from the given type path until the given
1899 * path level is reached.
1901 static void ascend_to(type_path_t *path, size_t top_path_level)
1903 size_t len = ARR_LEN(path->path);
1905 while (len > top_path_level) {
1906 ascend_from_subtype(path);
1907 len = ARR_LEN(path->path);
1911 static bool walk_designator(type_path_t *path, const designator_t *designator,
1912 bool used_in_offsetof)
1914 for (; designator != NULL; designator = designator->next) {
1915 type_path_entry_t *top = get_type_path_top(path);
1916 type_t *orig_type = top->type;
1918 type_t *type = skip_typeref(orig_type);
1920 if (designator->symbol != NULL) {
1921 symbol_t *symbol = designator->symbol;
1922 if (!is_type_compound(type)) {
1923 if (is_type_valid(type)) {
1924 errorf(&designator->source_position,
1925 "'.%Y' designator used for non-compound type '%T'",
1929 top->type = type_error_type;
1930 top->v.compound_entry = NULL;
1931 orig_type = type_error_type;
1933 compound_t *compound = type->compound.compound;
1934 entity_t *iter = compound->members.entities;
1935 for (; iter != NULL; iter = iter->base.next) {
1936 if (iter->base.symbol == symbol) {
1941 errorf(&designator->source_position,
1942 "'%T' has no member named '%Y'", orig_type, symbol);
1945 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1946 if (used_in_offsetof) {
1947 type_t *real_type = skip_typeref(iter->declaration.type);
1948 if (real_type->kind == TYPE_BITFIELD) {
1949 errorf(&designator->source_position,
1950 "offsetof designator '%Y' must not specify bitfield",
1956 top->type = orig_type;
1957 top->v.compound_entry = &iter->declaration;
1958 orig_type = iter->declaration.type;
1961 expression_t *array_index = designator->array_index;
1962 assert(designator->array_index != NULL);
1964 if (!is_type_array(type)) {
1965 if (is_type_valid(type)) {
1966 errorf(&designator->source_position,
1967 "[%E] designator used for non-array type '%T'",
1968 array_index, orig_type);
1973 long index = fold_constant_to_int(array_index);
1974 if (!used_in_offsetof) {
1976 errorf(&designator->source_position,
1977 "array index [%E] must be positive", array_index);
1978 } else if (type->array.size_constant) {
1979 long array_size = type->array.size;
1980 if (index >= array_size) {
1981 errorf(&designator->source_position,
1982 "designator [%E] (%d) exceeds array size %d",
1983 array_index, index, array_size);
1988 top->type = orig_type;
1989 top->v.index = (size_t) index;
1990 orig_type = type->array.element_type;
1992 path->top_type = orig_type;
1994 if (designator->next != NULL) {
1995 descend_into_subtype(path);
2001 static void advance_current_object(type_path_t *path, size_t top_path_level)
2003 type_path_entry_t *top = get_type_path_top(path);
2005 type_t *type = skip_typeref(top->type);
2006 if (is_type_union(type)) {
2007 /* in unions only the first element is initialized */
2008 top->v.compound_entry = NULL;
2009 } else if (is_type_struct(type)) {
2010 declaration_t *entry = top->v.compound_entry;
2012 entity_t *next_entity = entry->base.next;
2013 if (next_entity != NULL) {
2014 assert(is_declaration(next_entity));
2015 entry = &next_entity->declaration;
2020 top->v.compound_entry = entry;
2021 if (entry != NULL) {
2022 path->top_type = entry->type;
2025 } else if (is_type_array(type)) {
2026 assert(is_type_array(type));
2030 if (!type->array.size_constant || top->v.index < type->array.size) {
2034 assert(!is_type_valid(type));
2038 /* we're past the last member of the current sub-aggregate, try if we
2039 * can ascend in the type hierarchy and continue with another subobject */
2040 size_t len = ARR_LEN(path->path);
2042 if (len > top_path_level) {
2043 ascend_from_subtype(path);
2044 advance_current_object(path, top_path_level);
2046 path->top_type = NULL;
2051 * skip any {...} blocks until a closing bracket is reached.
2053 static void skip_initializers(void)
2057 while (token.type != '}') {
2058 if (token.type == T_EOF)
2060 if (token.type == '{') {
2068 static initializer_t *create_empty_initializer(void)
2070 static initializer_t empty_initializer
2071 = { .list = { { INITIALIZER_LIST }, 0 } };
2072 return &empty_initializer;
2076 * Parse a part of an initialiser for a struct or union,
2078 static initializer_t *parse_sub_initializer(type_path_t *path,
2079 type_t *outer_type, size_t top_path_level,
2080 parse_initializer_env_t *env)
2082 if (token.type == '}') {
2083 /* empty initializer */
2084 return create_empty_initializer();
2087 type_t *orig_type = path->top_type;
2088 type_t *type = NULL;
2090 if (orig_type == NULL) {
2091 /* We are initializing an empty compound. */
2093 type = skip_typeref(orig_type);
2096 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2099 designator_t *designator = NULL;
2100 if (token.type == '.' || token.type == '[') {
2101 designator = parse_designation();
2102 goto finish_designator;
2103 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2104 /* GNU-style designator ("identifier: value") */
2105 designator = allocate_ast_zero(sizeof(designator[0]));
2106 designator->source_position = token.source_position;
2107 designator->symbol = token.symbol;
2112 /* reset path to toplevel, evaluate designator from there */
2113 ascend_to(path, top_path_level);
2114 if (!walk_designator(path, designator, false)) {
2115 /* can't continue after designation error */
2119 initializer_t *designator_initializer
2120 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2121 designator_initializer->designator.designator = designator;
2122 ARR_APP1(initializer_t*, initializers, designator_initializer);
2124 orig_type = path->top_type;
2125 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2130 if (token.type == '{') {
2131 if (type != NULL && is_type_scalar(type)) {
2132 sub = parse_scalar_initializer(type, env->must_be_constant);
2135 if (env->entity != NULL) {
2137 "extra brace group at end of initializer for '%Y'",
2138 env->entity->base.symbol);
2140 errorf(HERE, "extra brace group at end of initializer");
2145 descend_into_subtype(path);
2148 add_anchor_token('}');
2149 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2151 rem_anchor_token('}');
2154 ascend_from_subtype(path);
2155 expect('}', end_error);
2157 expect('}', end_error);
2158 goto error_parse_next;
2162 /* must be an expression */
2163 expression_t *expression = parse_assignment_expression();
2164 mark_vars_read(expression, NULL);
2166 if (env->must_be_constant && !is_initializer_constant(expression)) {
2167 errorf(&expression->base.source_position,
2168 "Initialisation expression '%E' is not constant",
2173 /* we are already outside, ... */
2174 if (outer_type == NULL)
2175 goto error_parse_next;
2176 type_t *const outer_type_skip = skip_typeref(outer_type);
2177 if (is_type_compound(outer_type_skip) &&
2178 !outer_type_skip->compound.compound->complete) {
2179 goto error_parse_next;
2182 source_position_t const* const pos = &expression->base.source_position;
2183 if (env->entity != NULL) {
2184 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2186 warningf(WARN_OTHER, pos, "excess elements in initializer");
2188 goto error_parse_next;
2191 /* handle { "string" } special case */
2192 if ((expression->kind == EXPR_STRING_LITERAL
2193 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2194 && outer_type != NULL) {
2195 sub = initializer_from_expression(outer_type, expression);
2198 if (token.type != '}') {
2199 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2201 /* TODO: eat , ... */
2206 /* descend into subtypes until expression matches type */
2208 orig_type = path->top_type;
2209 type = skip_typeref(orig_type);
2211 sub = initializer_from_expression(orig_type, expression);
2215 if (!is_type_valid(type)) {
2218 if (is_type_scalar(type)) {
2219 errorf(&expression->base.source_position,
2220 "expression '%E' doesn't match expected type '%T'",
2221 expression, orig_type);
2225 descend_into_subtype(path);
2229 /* update largest index of top array */
2230 const type_path_entry_t *first = &path->path[0];
2231 type_t *first_type = first->type;
2232 first_type = skip_typeref(first_type);
2233 if (is_type_array(first_type)) {
2234 size_t index = first->v.index;
2235 if (index > path->max_index)
2236 path->max_index = index;
2239 /* append to initializers list */
2240 ARR_APP1(initializer_t*, initializers, sub);
2243 if (token.type == '}') {
2246 expect(',', end_error);
2247 if (token.type == '}') {
2252 /* advance to the next declaration if we are not at the end */
2253 advance_current_object(path, top_path_level);
2254 orig_type = path->top_type;
2255 if (orig_type != NULL)
2256 type = skip_typeref(orig_type);
2262 size_t len = ARR_LEN(initializers);
2263 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2264 initializer_t *result = allocate_ast_zero(size);
2265 result->kind = INITIALIZER_LIST;
2266 result->list.len = len;
2267 memcpy(&result->list.initializers, initializers,
2268 len * sizeof(initializers[0]));
2270 DEL_ARR_F(initializers);
2271 ascend_to(path, top_path_level+1);
2276 skip_initializers();
2277 DEL_ARR_F(initializers);
2278 ascend_to(path, top_path_level+1);
2282 static expression_t *make_size_literal(size_t value)
2284 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2285 literal->base.type = type_size_t;
2288 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2289 literal->literal.value = make_string(buf);
2295 * Parses an initializer. Parsers either a compound literal
2296 * (env->declaration == NULL) or an initializer of a declaration.
2298 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2300 type_t *type = skip_typeref(env->type);
2301 size_t max_index = 0;
2302 initializer_t *result;
2304 if (is_type_scalar(type)) {
2305 result = parse_scalar_initializer(type, env->must_be_constant);
2306 } else if (token.type == '{') {
2310 memset(&path, 0, sizeof(path));
2311 path.top_type = env->type;
2312 path.path = NEW_ARR_F(type_path_entry_t, 0);
2314 descend_into_subtype(&path);
2316 add_anchor_token('}');
2317 result = parse_sub_initializer(&path, env->type, 1, env);
2318 rem_anchor_token('}');
2320 max_index = path.max_index;
2321 DEL_ARR_F(path.path);
2323 expect('}', end_error);
2326 /* parse_scalar_initializer() also works in this case: we simply
2327 * have an expression without {} around it */
2328 result = parse_scalar_initializer(type, env->must_be_constant);
2331 /* §6.7.8:22 array initializers for arrays with unknown size determine
2332 * the array type size */
2333 if (is_type_array(type) && type->array.size_expression == NULL
2334 && result != NULL) {
2336 switch (result->kind) {
2337 case INITIALIZER_LIST:
2338 assert(max_index != 0xdeadbeaf);
2339 size = max_index + 1;
2342 case INITIALIZER_STRING:
2343 size = result->string.string.size;
2346 case INITIALIZER_WIDE_STRING:
2347 size = result->wide_string.string.size;
2350 case INITIALIZER_DESIGNATOR:
2351 case INITIALIZER_VALUE:
2352 /* can happen for parse errors */
2357 internal_errorf(HERE, "invalid initializer type");
2360 type_t *new_type = duplicate_type(type);
2362 new_type->array.size_expression = make_size_literal(size);
2363 new_type->array.size_constant = true;
2364 new_type->array.has_implicit_size = true;
2365 new_type->array.size = size;
2366 env->type = new_type;
2372 static void append_entity(scope_t *scope, entity_t *entity)
2374 if (scope->last_entity != NULL) {
2375 scope->last_entity->base.next = entity;
2377 scope->entities = entity;
2379 entity->base.parent_entity = current_entity;
2380 scope->last_entity = entity;
2384 static compound_t *parse_compound_type_specifier(bool is_struct)
2386 source_position_t const pos = *HERE;
2387 eat(is_struct ? T_struct : T_union);
2389 symbol_t *symbol = NULL;
2390 entity_t *entity = NULL;
2391 attribute_t *attributes = NULL;
2393 if (token.type == T___attribute__) {
2394 attributes = parse_attributes(NULL);
2397 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2398 if (token.type == T_IDENTIFIER) {
2399 /* the compound has a name, check if we have seen it already */
2400 symbol = token.symbol;
2401 entity = get_tag(symbol, kind);
2404 if (entity != NULL) {
2405 if (entity->base.parent_scope != current_scope &&
2406 (token.type == '{' || token.type == ';')) {
2407 /* we're in an inner scope and have a definition. Shadow
2408 * existing definition in outer scope */
2410 } else if (entity->compound.complete && token.type == '{') {
2411 source_position_t const *const ppos = &entity->base.source_position;
2412 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2413 /* clear members in the hope to avoid further errors */
2414 entity->compound.members.entities = NULL;
2417 } else if (token.type != '{') {
2418 char const *const msg =
2419 is_struct ? "while parsing struct type specifier" :
2420 "while parsing union type specifier";
2421 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2426 if (entity == NULL) {
2427 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2428 entity->compound.alignment = 1;
2429 entity->base.source_position = pos;
2430 entity->base.parent_scope = current_scope;
2431 if (symbol != NULL) {
2432 environment_push(entity);
2434 append_entity(current_scope, entity);
2437 if (token.type == '{') {
2438 parse_compound_type_entries(&entity->compound);
2440 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2441 if (symbol == NULL) {
2442 assert(anonymous_entity == NULL);
2443 anonymous_entity = entity;
2447 if (attributes != NULL) {
2448 handle_entity_attributes(attributes, entity);
2451 return &entity->compound;
2454 static void parse_enum_entries(type_t *const enum_type)
2458 if (token.type == '}') {
2459 errorf(HERE, "empty enum not allowed");
2464 add_anchor_token('}');
2466 if (token.type != T_IDENTIFIER) {
2467 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2469 rem_anchor_token('}');
2473 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, token.symbol);
2474 entity->enum_value.enum_type = enum_type;
2475 entity->base.source_position = token.source_position;
2479 expression_t *value = parse_constant_expression();
2481 value = create_implicit_cast(value, enum_type);
2482 entity->enum_value.value = value;
2487 record_entity(entity, false);
2488 } while (next_if(',') && token.type != '}');
2489 rem_anchor_token('}');
2491 expect('}', end_error);
2497 static type_t *parse_enum_specifier(void)
2499 source_position_t const pos = *HERE;
2504 switch (token.type) {
2506 symbol = token.symbol;
2507 entity = get_tag(symbol, ENTITY_ENUM);
2510 if (entity != NULL) {
2511 if (entity->base.parent_scope != current_scope &&
2512 (token.type == '{' || token.type == ';')) {
2513 /* we're in an inner scope and have a definition. Shadow
2514 * existing definition in outer scope */
2516 } else if (entity->enume.complete && token.type == '{') {
2517 source_position_t const *const ppos = &entity->base.source_position;
2518 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2529 parse_error_expected("while parsing enum type specifier",
2530 T_IDENTIFIER, '{', NULL);
2534 if (entity == NULL) {
2535 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2536 entity->base.source_position = pos;
2537 entity->base.parent_scope = current_scope;
2540 type_t *const type = allocate_type_zero(TYPE_ENUM);
2541 type->enumt.enume = &entity->enume;
2542 type->enumt.akind = ATOMIC_TYPE_INT;
2544 if (token.type == '{') {
2545 if (symbol != NULL) {
2546 environment_push(entity);
2548 append_entity(current_scope, entity);
2549 entity->enume.complete = true;
2551 parse_enum_entries(type);
2552 parse_attributes(NULL);
2554 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2555 if (symbol == NULL) {
2556 assert(anonymous_entity == NULL);
2557 anonymous_entity = entity;
2559 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2560 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2567 * if a symbol is a typedef to another type, return true
2569 static bool is_typedef_symbol(symbol_t *symbol)
2571 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2572 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2575 static type_t *parse_typeof(void)
2581 expect('(', end_error);
2582 add_anchor_token(')');
2584 expression_t *expression = NULL;
2586 bool old_type_prop = in_type_prop;
2587 bool old_gcc_extension = in_gcc_extension;
2588 in_type_prop = true;
2590 while (next_if(T___extension__)) {
2591 /* This can be a prefix to a typename or an expression. */
2592 in_gcc_extension = true;
2594 switch (token.type) {
2596 if (is_typedef_symbol(token.symbol)) {
2598 type = parse_typename();
2601 expression = parse_expression();
2602 type = revert_automatic_type_conversion(expression);
2606 in_type_prop = old_type_prop;
2607 in_gcc_extension = old_gcc_extension;
2609 rem_anchor_token(')');
2610 expect(')', end_error);
2612 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2613 typeof_type->typeoft.expression = expression;
2614 typeof_type->typeoft.typeof_type = type;
2621 typedef enum specifiers_t {
2622 SPECIFIER_SIGNED = 1 << 0,
2623 SPECIFIER_UNSIGNED = 1 << 1,
2624 SPECIFIER_LONG = 1 << 2,
2625 SPECIFIER_INT = 1 << 3,
2626 SPECIFIER_DOUBLE = 1 << 4,
2627 SPECIFIER_CHAR = 1 << 5,
2628 SPECIFIER_WCHAR_T = 1 << 6,
2629 SPECIFIER_SHORT = 1 << 7,
2630 SPECIFIER_LONG_LONG = 1 << 8,
2631 SPECIFIER_FLOAT = 1 << 9,
2632 SPECIFIER_BOOL = 1 << 10,
2633 SPECIFIER_VOID = 1 << 11,
2634 SPECIFIER_INT8 = 1 << 12,
2635 SPECIFIER_INT16 = 1 << 13,
2636 SPECIFIER_INT32 = 1 << 14,
2637 SPECIFIER_INT64 = 1 << 15,
2638 SPECIFIER_INT128 = 1 << 16,
2639 SPECIFIER_COMPLEX = 1 << 17,
2640 SPECIFIER_IMAGINARY = 1 << 18,
2643 static type_t *get_typedef_type(symbol_t *symbol)
2645 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2646 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2649 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2650 type->typedeft.typedefe = &entity->typedefe;
2655 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2657 expect('(', end_error);
2659 attribute_property_argument_t *property
2660 = allocate_ast_zero(sizeof(*property));
2663 if (token.type != T_IDENTIFIER) {
2664 parse_error_expected("while parsing property declspec",
2665 T_IDENTIFIER, NULL);
2670 symbol_t *symbol = token.symbol;
2671 if (strcmp(symbol->string, "put") == 0) {
2672 prop = &property->put_symbol;
2673 } else if (strcmp(symbol->string, "get") == 0) {
2674 prop = &property->get_symbol;
2676 errorf(HERE, "expected put or get in property declspec");
2680 expect('=', end_error);
2681 if (token.type != T_IDENTIFIER) {
2682 parse_error_expected("while parsing property declspec",
2683 T_IDENTIFIER, NULL);
2687 *prop = token.symbol;
2689 } while (next_if(','));
2691 attribute->a.property = property;
2693 expect(')', end_error);
2699 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2701 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2702 if (next_if(T_restrict)) {
2703 kind = ATTRIBUTE_MS_RESTRICT;
2704 } else if (token.type == T_IDENTIFIER) {
2705 const char *name = token.symbol->string;
2706 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2708 const char *attribute_name = get_attribute_name(k);
2709 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2715 if (kind == ATTRIBUTE_UNKNOWN) {
2716 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2719 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2723 attribute_t *attribute = allocate_attribute_zero(kind);
2726 if (kind == ATTRIBUTE_MS_PROPERTY) {
2727 return parse_attribute_ms_property(attribute);
2730 /* parse arguments */
2732 attribute->a.arguments = parse_attribute_arguments();
2737 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2741 expect('(', end_error);
2746 add_anchor_token(')');
2748 attribute_t **anchor = &first;
2750 while (*anchor != NULL)
2751 anchor = &(*anchor)->next;
2753 attribute_t *attribute
2754 = parse_microsoft_extended_decl_modifier_single();
2755 if (attribute == NULL)
2758 *anchor = attribute;
2759 anchor = &attribute->next;
2760 } while (next_if(','));
2762 rem_anchor_token(')');
2763 expect(')', end_error);
2767 rem_anchor_token(')');
2771 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2773 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2774 entity->base.source_position = *HERE;
2775 if (is_declaration(entity)) {
2776 entity->declaration.type = type_error_type;
2777 entity->declaration.implicit = true;
2778 } else if (kind == ENTITY_TYPEDEF) {
2779 entity->typedefe.type = type_error_type;
2780 entity->typedefe.builtin = true;
2782 if (kind != ENTITY_COMPOUND_MEMBER)
2783 record_entity(entity, false);
2787 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2789 type_t *type = NULL;
2790 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2791 unsigned type_specifiers = 0;
2792 bool newtype = false;
2793 bool saw_error = false;
2794 bool old_gcc_extension = in_gcc_extension;
2796 memset(specifiers, 0, sizeof(*specifiers));
2797 specifiers->source_position = token.source_position;
2800 specifiers->attributes = parse_attributes(specifiers->attributes);
2802 switch (token.type) {
2804 #define MATCH_STORAGE_CLASS(token, class) \
2806 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2807 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2809 specifiers->storage_class = class; \
2810 if (specifiers->thread_local) \
2811 goto check_thread_storage_class; \
2815 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2816 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2817 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2818 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2819 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2822 specifiers->attributes
2823 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2827 if (specifiers->thread_local) {
2828 errorf(HERE, "duplicate '__thread'");
2830 specifiers->thread_local = true;
2831 check_thread_storage_class:
2832 switch (specifiers->storage_class) {
2833 case STORAGE_CLASS_EXTERN:
2834 case STORAGE_CLASS_NONE:
2835 case STORAGE_CLASS_STATIC:
2839 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2840 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2841 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2842 wrong_thread_storage_class:
2843 errorf(HERE, "'__thread' used with '%s'", wrong);
2850 /* type qualifiers */
2851 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2853 qualifiers |= qualifier; \
2857 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2858 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2859 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2860 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2861 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2862 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2863 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2864 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2866 case T___extension__:
2868 in_gcc_extension = true;
2871 /* type specifiers */
2872 #define MATCH_SPECIFIER(token, specifier, name) \
2874 if (type_specifiers & specifier) { \
2875 errorf(HERE, "multiple " name " type specifiers given"); \
2877 type_specifiers |= specifier; \
2882 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2883 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2884 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2885 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2886 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2887 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2888 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2889 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2890 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2891 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2892 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2893 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2894 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2895 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2896 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2897 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2898 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2899 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2903 specifiers->is_inline = true;
2907 case T__forceinline:
2909 specifiers->modifiers |= DM_FORCEINLINE;
2914 if (type_specifiers & SPECIFIER_LONG_LONG) {
2915 errorf(HERE, "too many long type specifiers given");
2916 } else if (type_specifiers & SPECIFIER_LONG) {
2917 type_specifiers |= SPECIFIER_LONG_LONG;
2919 type_specifiers |= SPECIFIER_LONG;
2924 #define CHECK_DOUBLE_TYPE() \
2925 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2928 CHECK_DOUBLE_TYPE();
2929 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2931 type->compound.compound = parse_compound_type_specifier(true);
2934 CHECK_DOUBLE_TYPE();
2935 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2936 type->compound.compound = parse_compound_type_specifier(false);
2939 CHECK_DOUBLE_TYPE();
2940 type = parse_enum_specifier();
2943 CHECK_DOUBLE_TYPE();
2944 type = parse_typeof();
2946 case T___builtin_va_list:
2947 CHECK_DOUBLE_TYPE();
2948 type = duplicate_type(type_valist);
2952 case T_IDENTIFIER: {
2953 /* only parse identifier if we haven't found a type yet */
2954 if (type != NULL || type_specifiers != 0) {
2955 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2956 * declaration, so it doesn't generate errors about expecting '(' or
2958 switch (look_ahead(1)->type) {
2965 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2969 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2974 goto finish_specifiers;
2978 type_t *const typedef_type = get_typedef_type(token.symbol);
2979 if (typedef_type == NULL) {
2980 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2981 * declaration, so it doesn't generate 'implicit int' followed by more
2982 * errors later on. */
2983 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
2989 errorf(HERE, "%K does not name a type", &token);
2992 create_error_entity(token.symbol, ENTITY_TYPEDEF);
2994 type = allocate_type_zero(TYPE_TYPEDEF);
2995 type->typedeft.typedefe = &entity->typedefe;
3003 goto finish_specifiers;
3008 type = typedef_type;
3012 /* function specifier */
3014 goto finish_specifiers;
3019 specifiers->attributes = parse_attributes(specifiers->attributes);
3021 in_gcc_extension = old_gcc_extension;
3023 if (type == NULL || (saw_error && type_specifiers != 0)) {
3024 atomic_type_kind_t atomic_type;
3026 /* match valid basic types */
3027 switch (type_specifiers) {
3028 case SPECIFIER_VOID:
3029 atomic_type = ATOMIC_TYPE_VOID;
3031 case SPECIFIER_WCHAR_T:
3032 atomic_type = ATOMIC_TYPE_WCHAR_T;
3034 case SPECIFIER_CHAR:
3035 atomic_type = ATOMIC_TYPE_CHAR;
3037 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3038 atomic_type = ATOMIC_TYPE_SCHAR;
3040 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3041 atomic_type = ATOMIC_TYPE_UCHAR;
3043 case SPECIFIER_SHORT:
3044 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3045 case SPECIFIER_SHORT | SPECIFIER_INT:
3046 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3047 atomic_type = ATOMIC_TYPE_SHORT;
3049 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3050 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3051 atomic_type = ATOMIC_TYPE_USHORT;
3054 case SPECIFIER_SIGNED:
3055 case SPECIFIER_SIGNED | SPECIFIER_INT:
3056 atomic_type = ATOMIC_TYPE_INT;
3058 case SPECIFIER_UNSIGNED:
3059 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3060 atomic_type = ATOMIC_TYPE_UINT;
3062 case SPECIFIER_LONG:
3063 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3064 case SPECIFIER_LONG | SPECIFIER_INT:
3065 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3066 atomic_type = ATOMIC_TYPE_LONG;
3068 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3069 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3070 atomic_type = ATOMIC_TYPE_ULONG;
3073 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3074 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3075 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3076 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3078 atomic_type = ATOMIC_TYPE_LONGLONG;
3079 goto warn_about_long_long;
3081 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3082 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3084 atomic_type = ATOMIC_TYPE_ULONGLONG;
3085 warn_about_long_long:
3086 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3089 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3090 atomic_type = unsigned_int8_type_kind;
3093 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3094 atomic_type = unsigned_int16_type_kind;
3097 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3098 atomic_type = unsigned_int32_type_kind;
3101 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3102 atomic_type = unsigned_int64_type_kind;
3105 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3106 atomic_type = unsigned_int128_type_kind;
3109 case SPECIFIER_INT8:
3110 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3111 atomic_type = int8_type_kind;
3114 case SPECIFIER_INT16:
3115 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3116 atomic_type = int16_type_kind;
3119 case SPECIFIER_INT32:
3120 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3121 atomic_type = int32_type_kind;
3124 case SPECIFIER_INT64:
3125 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3126 atomic_type = int64_type_kind;
3129 case SPECIFIER_INT128:
3130 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3131 atomic_type = int128_type_kind;
3134 case SPECIFIER_FLOAT:
3135 atomic_type = ATOMIC_TYPE_FLOAT;
3137 case SPECIFIER_DOUBLE:
3138 atomic_type = ATOMIC_TYPE_DOUBLE;
3140 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3141 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3143 case SPECIFIER_BOOL:
3144 atomic_type = ATOMIC_TYPE_BOOL;
3146 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3147 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3148 atomic_type = ATOMIC_TYPE_FLOAT;
3150 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3151 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3152 atomic_type = ATOMIC_TYPE_DOUBLE;
3154 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3155 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3156 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3159 /* invalid specifier combination, give an error message */
3160 source_position_t const* const pos = &specifiers->source_position;
3161 if (type_specifiers == 0) {
3163 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3164 if (!(c_mode & _CXX) && !strict_mode) {
3165 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3166 atomic_type = ATOMIC_TYPE_INT;
3169 errorf(pos, "no type specifiers given in declaration");
3172 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3173 (type_specifiers & SPECIFIER_UNSIGNED)) {
3174 errorf(pos, "signed and unsigned specifiers given");
3175 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3176 errorf(pos, "only integer types can be signed or unsigned");
3178 errorf(pos, "multiple datatypes in declaration");
3184 if (type_specifiers & SPECIFIER_COMPLEX) {
3185 type = allocate_type_zero(TYPE_COMPLEX);
3186 type->complex.akind = atomic_type;
3187 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3188 type = allocate_type_zero(TYPE_IMAGINARY);
3189 type->imaginary.akind = atomic_type;
3191 type = allocate_type_zero(TYPE_ATOMIC);
3192 type->atomic.akind = atomic_type;
3195 } else if (type_specifiers != 0) {
3196 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3199 /* FIXME: check type qualifiers here */
3200 type->base.qualifiers = qualifiers;
3203 type = identify_new_type(type);
3205 type = typehash_insert(type);
3208 if (specifiers->attributes != NULL)
3209 type = handle_type_attributes(specifiers->attributes, type);
3210 specifiers->type = type;
3214 specifiers->type = type_error_type;
3217 static type_qualifiers_t parse_type_qualifiers(void)
3219 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3222 switch (token.type) {
3223 /* type qualifiers */
3224 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3225 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3226 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3227 /* microsoft extended type modifiers */
3228 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3229 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3230 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3231 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3232 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3241 * Parses an K&R identifier list
3243 static void parse_identifier_list(scope_t *scope)
3246 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.symbol);
3247 entity->base.source_position = token.source_position;
3248 /* a K&R parameter has no type, yet */
3252 append_entity(scope, entity);
3253 } while (next_if(',') && token.type == T_IDENTIFIER);
3256 static entity_t *parse_parameter(void)
3258 declaration_specifiers_t specifiers;
3259 parse_declaration_specifiers(&specifiers);
3261 entity_t *entity = parse_declarator(&specifiers,
3262 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3263 anonymous_entity = NULL;
3267 static void semantic_parameter_incomplete(const entity_t *entity)
3269 assert(entity->kind == ENTITY_PARAMETER);
3271 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3272 * list in a function declarator that is part of a
3273 * definition of that function shall not have
3274 * incomplete type. */
3275 type_t *type = skip_typeref(entity->declaration.type);
3276 if (is_type_incomplete(type)) {
3277 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3281 static bool has_parameters(void)
3283 /* func(void) is not a parameter */
3284 if (token.type == T_IDENTIFIER) {
3285 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3288 if (entity->kind != ENTITY_TYPEDEF)
3290 if (skip_typeref(entity->typedefe.type) != type_void)
3292 } else if (token.type != T_void) {
3295 if (look_ahead(1)->type != ')')
3302 * Parses function type parameters (and optionally creates variable_t entities
3303 * for them in a scope)
3305 static void parse_parameters(function_type_t *type, scope_t *scope)
3308 add_anchor_token(')');
3309 int saved_comma_state = save_and_reset_anchor_state(',');
3311 if (token.type == T_IDENTIFIER &&
3312 !is_typedef_symbol(token.symbol)) {
3313 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3314 if (la1_type == ',' || la1_type == ')') {
3315 type->kr_style_parameters = true;
3316 parse_identifier_list(scope);
3317 goto parameters_finished;
3321 if (token.type == ')') {
3322 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3323 if (!(c_mode & _CXX))
3324 type->unspecified_parameters = true;
3325 } else if (has_parameters()) {
3326 function_parameter_t **anchor = &type->parameters;
3328 switch (token.type) {
3331 type->variadic = true;
3332 goto parameters_finished;
3335 case T___extension__:
3338 entity_t *entity = parse_parameter();
3339 if (entity->kind == ENTITY_TYPEDEF) {
3340 errorf(&entity->base.source_position,
3341 "typedef not allowed as function parameter");
3344 assert(is_declaration(entity));
3346 semantic_parameter_incomplete(entity);
3348 function_parameter_t *const parameter =
3349 allocate_parameter(entity->declaration.type);
3351 if (scope != NULL) {
3352 append_entity(scope, entity);
3355 *anchor = parameter;
3356 anchor = ¶meter->next;
3361 goto parameters_finished;
3363 } while (next_if(','));
3366 parameters_finished:
3367 rem_anchor_token(')');
3368 expect(')', end_error);
3371 restore_anchor_state(',', saved_comma_state);
3374 typedef enum construct_type_kind_t {
3377 CONSTRUCT_REFERENCE,
3380 } construct_type_kind_t;
3382 typedef union construct_type_t construct_type_t;
3384 typedef struct construct_type_base_t {
3385 construct_type_kind_t kind;
3386 source_position_t pos;
3387 construct_type_t *next;
3388 } construct_type_base_t;
3390 typedef struct parsed_pointer_t {
3391 construct_type_base_t base;
3392 type_qualifiers_t type_qualifiers;
3393 variable_t *base_variable; /**< MS __based extension. */
3396 typedef struct parsed_reference_t {
3397 construct_type_base_t base;
3398 } parsed_reference_t;
3400 typedef struct construct_function_type_t {
3401 construct_type_base_t base;
3402 type_t *function_type;
3403 } construct_function_type_t;
3405 typedef struct parsed_array_t {
3406 construct_type_base_t base;
3407 type_qualifiers_t type_qualifiers;
3413 union construct_type_t {
3414 construct_type_kind_t kind;
3415 construct_type_base_t base;
3416 parsed_pointer_t pointer;
3417 parsed_reference_t reference;
3418 construct_function_type_t function;
3419 parsed_array_t array;
3422 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3424 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3425 memset(cons, 0, size);
3427 cons->base.pos = *HERE;
3432 static construct_type_t *parse_pointer_declarator(void)
3434 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3436 cons->pointer.type_qualifiers = parse_type_qualifiers();
3437 //cons->pointer.base_variable = base_variable;
3442 /* ISO/IEC 14882:1998(E) §8.3.2 */
3443 static construct_type_t *parse_reference_declarator(void)
3445 if (!(c_mode & _CXX))
3446 errorf(HERE, "references are only available for C++");
3448 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3455 static construct_type_t *parse_array_declarator(void)
3457 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3458 parsed_array_t *const array = &cons->array;
3461 add_anchor_token(']');
3463 bool is_static = next_if(T_static);
3465 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3468 is_static = next_if(T_static);
3470 array->type_qualifiers = type_qualifiers;
3471 array->is_static = is_static;
3473 expression_t *size = NULL;
3474 if (token.type == '*' && look_ahead(1)->type == ']') {
3475 array->is_variable = true;
3477 } else if (token.type != ']') {
3478 size = parse_assignment_expression();
3480 /* §6.7.5.2:1 Array size must have integer type */
3481 type_t *const orig_type = size->base.type;
3482 type_t *const type = skip_typeref(orig_type);
3483 if (!is_type_integer(type) && is_type_valid(type)) {
3484 errorf(&size->base.source_position,
3485 "array size '%E' must have integer type but has type '%T'",
3490 mark_vars_read(size, NULL);
3493 if (is_static && size == NULL)
3494 errorf(&array->base.pos, "static array parameters require a size");
3496 rem_anchor_token(']');
3497 expect(']', end_error);
3504 static construct_type_t *parse_function_declarator(scope_t *scope)
3506 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3508 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3509 function_type_t *ftype = &type->function;
3511 ftype->linkage = current_linkage;
3512 ftype->calling_convention = CC_DEFAULT;
3514 parse_parameters(ftype, scope);
3516 cons->function.function_type = type;
3521 typedef struct parse_declarator_env_t {
3522 bool may_be_abstract : 1;
3523 bool must_be_abstract : 1;
3524 decl_modifiers_t modifiers;
3526 source_position_t source_position;
3528 attribute_t *attributes;
3529 } parse_declarator_env_t;
3532 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3534 /* construct a single linked list of construct_type_t's which describe
3535 * how to construct the final declarator type */
3536 construct_type_t *first = NULL;
3537 construct_type_t **anchor = &first;
3539 env->attributes = parse_attributes(env->attributes);
3542 construct_type_t *type;
3543 //variable_t *based = NULL; /* MS __based extension */
3544 switch (token.type) {
3546 type = parse_reference_declarator();
3550 panic("based not supported anymore");
3555 type = parse_pointer_declarator();
3559 goto ptr_operator_end;
3563 anchor = &type->base.next;
3565 /* TODO: find out if this is correct */
3566 env->attributes = parse_attributes(env->attributes);
3570 construct_type_t *inner_types = NULL;
3572 switch (token.type) {
3574 if (env->must_be_abstract) {
3575 errorf(HERE, "no identifier expected in typename");
3577 env->symbol = token.symbol;
3578 env->source_position = token.source_position;
3584 /* Parenthesized declarator or function declarator? */
3585 token_t const *const la1 = look_ahead(1);
3586 switch (la1->type) {
3588 if (is_typedef_symbol(la1->symbol)) {
3590 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3591 * interpreted as ``function with no parameter specification'', rather
3592 * than redundant parentheses around the omitted identifier. */
3594 /* Function declarator. */
3595 if (!env->may_be_abstract) {
3596 errorf(HERE, "function declarator must have a name");
3603 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3604 /* Paranthesized declarator. */
3606 add_anchor_token(')');
3607 inner_types = parse_inner_declarator(env);
3608 if (inner_types != NULL) {
3609 /* All later declarators only modify the return type */
3610 env->must_be_abstract = true;
3612 rem_anchor_token(')');
3613 expect(')', end_error);
3621 if (env->may_be_abstract)
3623 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3628 construct_type_t **const p = anchor;
3631 construct_type_t *type;
3632 switch (token.type) {
3634 scope_t *scope = NULL;
3635 if (!env->must_be_abstract) {
3636 scope = &env->parameters;
3639 type = parse_function_declarator(scope);
3643 type = parse_array_declarator();
3646 goto declarator_finished;
3649 /* insert in the middle of the list (at p) */
3650 type->base.next = *p;
3653 anchor = &type->base.next;
3656 declarator_finished:
3657 /* append inner_types at the end of the list, we don't to set anchor anymore
3658 * as it's not needed anymore */
3659 *anchor = inner_types;
3666 static type_t *construct_declarator_type(construct_type_t *construct_list,
3669 construct_type_t *iter = construct_list;
3670 for (; iter != NULL; iter = iter->base.next) {
3671 source_position_t const* const pos = &iter->base.pos;
3672 switch (iter->kind) {
3673 case CONSTRUCT_INVALID:
3675 case CONSTRUCT_FUNCTION: {
3676 construct_function_type_t *function = &iter->function;
3677 type_t *function_type = function->function_type;
3679 function_type->function.return_type = type;
3681 type_t *skipped_return_type = skip_typeref(type);
3683 if (is_type_function(skipped_return_type)) {
3684 errorf(pos, "function returning function is not allowed");
3685 } else if (is_type_array(skipped_return_type)) {
3686 errorf(pos, "function returning array is not allowed");
3688 if (skipped_return_type->base.qualifiers != 0) {
3689 warningf(WARN_OTHER, pos, "type qualifiers in return type of function type are meaningless");
3693 /* The function type was constructed earlier. Freeing it here will
3694 * destroy other types. */
3695 type = typehash_insert(function_type);
3699 case CONSTRUCT_POINTER: {
3700 if (is_type_reference(skip_typeref(type)))
3701 errorf(pos, "cannot declare a pointer to reference");
3703 parsed_pointer_t *pointer = &iter->pointer;
3704 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3708 case CONSTRUCT_REFERENCE:
3709 if (is_type_reference(skip_typeref(type)))
3710 errorf(pos, "cannot declare a reference to reference");
3712 type = make_reference_type(type);
3715 case CONSTRUCT_ARRAY: {
3716 if (is_type_reference(skip_typeref(type)))
3717 errorf(pos, "cannot declare an array of references");
3719 parsed_array_t *array = &iter->array;
3720 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3722 expression_t *size_expression = array->size;
3723 if (size_expression != NULL) {
3725 = create_implicit_cast(size_expression, type_size_t);
3728 array_type->base.qualifiers = array->type_qualifiers;
3729 array_type->array.element_type = type;
3730 array_type->array.is_static = array->is_static;
3731 array_type->array.is_variable = array->is_variable;
3732 array_type->array.size_expression = size_expression;
3734 if (size_expression != NULL) {
3735 switch (is_constant_expression(size_expression)) {
3736 case EXPR_CLASS_CONSTANT: {
3737 long const size = fold_constant_to_int(size_expression);
3738 array_type->array.size = size;
3739 array_type->array.size_constant = true;
3740 /* §6.7.5.2:1 If the expression is a constant expression,
3741 * it shall have a value greater than zero. */
3743 errorf(&size_expression->base.source_position,
3744 "size of array must be greater than zero");
3745 } else if (size == 0 && !GNU_MODE) {
3746 errorf(&size_expression->base.source_position,
3747 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3752 case EXPR_CLASS_VARIABLE:
3753 array_type->array.is_vla = true;
3756 case EXPR_CLASS_ERROR:
3761 type_t *skipped_type = skip_typeref(type);
3763 if (is_type_incomplete(skipped_type)) {
3764 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3765 } else if (is_type_function(skipped_type)) {
3766 errorf(pos, "array of functions is not allowed");
3768 type = identify_new_type(array_type);
3772 internal_errorf(pos, "invalid type construction found");
3778 static type_t *automatic_type_conversion(type_t *orig_type);
3780 static type_t *semantic_parameter(const source_position_t *pos,
3782 const declaration_specifiers_t *specifiers,
3783 entity_t const *const param)
3785 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3786 * shall be adjusted to ``qualified pointer to type'',
3788 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3789 * type'' shall be adjusted to ``pointer to function
3790 * returning type'', as in 6.3.2.1. */
3791 type = automatic_type_conversion(type);
3793 if (specifiers->is_inline && is_type_valid(type)) {
3794 errorf(pos, "'%N' declared 'inline'", param);
3797 /* §6.9.1:6 The declarations in the declaration list shall contain
3798 * no storage-class specifier other than register and no
3799 * initializations. */
3800 if (specifiers->thread_local || (
3801 specifiers->storage_class != STORAGE_CLASS_NONE &&
3802 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3804 errorf(pos, "invalid storage class for '%N'", param);
3807 /* delay test for incomplete type, because we might have (void)
3808 * which is legal but incomplete... */
3813 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3814 declarator_flags_t flags)
3816 parse_declarator_env_t env;
3817 memset(&env, 0, sizeof(env));
3818 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3820 construct_type_t *construct_type = parse_inner_declarator(&env);
3822 construct_declarator_type(construct_type, specifiers->type);
3823 type_t *type = skip_typeref(orig_type);
3825 if (construct_type != NULL) {
3826 obstack_free(&temp_obst, construct_type);
3829 attribute_t *attributes = parse_attributes(env.attributes);
3830 /* append (shared) specifier attribute behind attributes of this
3832 attribute_t **anchor = &attributes;
3833 while (*anchor != NULL)
3834 anchor = &(*anchor)->next;
3835 *anchor = specifiers->attributes;
3838 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3839 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3840 entity->base.source_position = env.source_position;
3841 entity->typedefe.type = orig_type;
3843 if (anonymous_entity != NULL) {
3844 if (is_type_compound(type)) {
3845 assert(anonymous_entity->compound.alias == NULL);
3846 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3847 anonymous_entity->kind == ENTITY_UNION);
3848 anonymous_entity->compound.alias = entity;
3849 anonymous_entity = NULL;
3850 } else if (is_type_enum(type)) {
3851 assert(anonymous_entity->enume.alias == NULL);
3852 assert(anonymous_entity->kind == ENTITY_ENUM);
3853 anonymous_entity->enume.alias = entity;
3854 anonymous_entity = NULL;
3858 /* create a declaration type entity */
3859 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3860 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3862 if (env.symbol != NULL) {
3863 if (specifiers->is_inline && is_type_valid(type)) {
3864 errorf(&env.source_position,
3865 "compound member '%Y' declared 'inline'", env.symbol);
3868 if (specifiers->thread_local ||
3869 specifiers->storage_class != STORAGE_CLASS_NONE) {
3870 errorf(&env.source_position,
3871 "compound member '%Y' must have no storage class",
3875 } else if (flags & DECL_IS_PARAMETER) {
3876 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3877 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3878 } else if (is_type_function(type)) {
3879 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3880 entity->function.is_inline = specifiers->is_inline;
3881 entity->function.elf_visibility = default_visibility;
3882 entity->function.parameters = env.parameters;
3884 if (env.symbol != NULL) {
3885 /* this needs fixes for C++ */
3886 bool in_function_scope = current_function != NULL;
3888 if (specifiers->thread_local || (
3889 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3890 specifiers->storage_class != STORAGE_CLASS_NONE &&
3891 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3893 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3897 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3898 entity->variable.elf_visibility = default_visibility;
3899 entity->variable.thread_local = specifiers->thread_local;
3901 if (env.symbol != NULL) {
3902 if (specifiers->is_inline && is_type_valid(type)) {
3903 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3906 bool invalid_storage_class = false;
3907 if (current_scope == file_scope) {
3908 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3909 specifiers->storage_class != STORAGE_CLASS_NONE &&
3910 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3911 invalid_storage_class = true;
3914 if (specifiers->thread_local &&
3915 specifiers->storage_class == STORAGE_CLASS_NONE) {
3916 invalid_storage_class = true;
3919 if (invalid_storage_class) {
3920 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3925 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3926 entity->declaration.type = orig_type;
3927 entity->declaration.alignment = get_type_alignment(orig_type);
3928 entity->declaration.modifiers = env.modifiers;
3929 entity->declaration.attributes = attributes;
3931 storage_class_t storage_class = specifiers->storage_class;
3932 entity->declaration.declared_storage_class = storage_class;
3934 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3935 storage_class = STORAGE_CLASS_AUTO;
3936 entity->declaration.storage_class = storage_class;
3939 if (attributes != NULL) {
3940 handle_entity_attributes(attributes, entity);
3946 static type_t *parse_abstract_declarator(type_t *base_type)
3948 parse_declarator_env_t env;
3949 memset(&env, 0, sizeof(env));
3950 env.may_be_abstract = true;
3951 env.must_be_abstract = true;
3953 construct_type_t *construct_type = parse_inner_declarator(&env);
3955 type_t *result = construct_declarator_type(construct_type, base_type);
3956 if (construct_type != NULL) {
3957 obstack_free(&temp_obst, construct_type);
3959 result = handle_type_attributes(env.attributes, result);
3965 * Check if the declaration of main is suspicious. main should be a
3966 * function with external linkage, returning int, taking either zero
3967 * arguments, two, or three arguments of appropriate types, ie.
3969 * int main([ int argc, char **argv [, char **env ] ]).
3971 * @param decl the declaration to check
3972 * @param type the function type of the declaration
3974 static void check_main(const entity_t *entity)
3976 const source_position_t *pos = &entity->base.source_position;
3977 if (entity->kind != ENTITY_FUNCTION) {
3978 warningf(WARN_MAIN, pos, "'main' is not a function");
3982 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3983 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3986 type_t *type = skip_typeref(entity->declaration.type);
3987 assert(is_type_function(type));
3989 function_type_t const *const func_type = &type->function;
3990 type_t *const ret_type = func_type->return_type;
3991 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3992 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3994 const function_parameter_t *parm = func_type->parameters;
3996 type_t *const first_type = skip_typeref(parm->type);
3997 type_t *const first_type_unqual = get_unqualified_type(first_type);
3998 if (!types_compatible(first_type_unqual, type_int)) {
3999 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
4003 type_t *const second_type = skip_typeref(parm->type);
4004 type_t *const second_type_unqual
4005 = get_unqualified_type(second_type);
4006 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4007 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
4011 type_t *const third_type = skip_typeref(parm->type);
4012 type_t *const third_type_unqual
4013 = get_unqualified_type(third_type);
4014 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4015 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
4019 goto warn_arg_count;
4023 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
4029 * Check if a symbol is the equal to "main".
4031 static bool is_sym_main(const symbol_t *const sym)
4033 return strcmp(sym->string, "main") == 0;
4036 static void error_redefined_as_different_kind(const source_position_t *pos,
4037 const entity_t *old, entity_kind_t new_kind)
4039 char const *const what = get_entity_kind_name(new_kind);
4040 source_position_t const *const ppos = &old->base.source_position;
4041 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4044 static bool is_entity_valid(entity_t *const ent)
4046 if (is_declaration(ent)) {
4047 return is_type_valid(skip_typeref(ent->declaration.type));
4048 } else if (ent->kind == ENTITY_TYPEDEF) {
4049 return is_type_valid(skip_typeref(ent->typedefe.type));
4054 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4056 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4057 if (attributes_equal(tattr, attr))
4064 * test wether new_list contains any attributes not included in old_list
4066 static bool has_new_attributes(const attribute_t *old_list,
4067 const attribute_t *new_list)
4069 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4070 if (!contains_attribute(old_list, attr))
4077 * Merge in attributes from an attribute list (probably from a previous
4078 * declaration with the same name). Warning: destroys the old structure
4079 * of the attribute list - don't reuse attributes after this call.
4081 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4084 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4086 if (contains_attribute(decl->attributes, attr))
4089 /* move attribute to new declarations attributes list */
4090 attr->next = decl->attributes;
4091 decl->attributes = attr;
4096 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4097 * for various problems that occur for multiple definitions
4099 entity_t *record_entity(entity_t *entity, const bool is_definition)
4101 const symbol_t *const symbol = entity->base.symbol;
4102 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4103 const source_position_t *pos = &entity->base.source_position;
4105 /* can happen in error cases */
4109 entity_t *const previous_entity = get_entity(symbol, namespc);
4110 /* pushing the same entity twice will break the stack structure */
4111 assert(previous_entity != entity);
4113 if (entity->kind == ENTITY_FUNCTION) {
4114 type_t *const orig_type = entity->declaration.type;
4115 type_t *const type = skip_typeref(orig_type);
4117 assert(is_type_function(type));
4118 if (type->function.unspecified_parameters &&
4119 previous_entity == NULL &&
4120 !entity->declaration.implicit) {
4121 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4124 if (current_scope == file_scope && is_sym_main(symbol)) {
4129 if (is_declaration(entity) &&
4130 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4131 current_scope != file_scope &&
4132 !entity->declaration.implicit) {
4133 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4136 if (previous_entity != NULL) {
4137 source_position_t const *const ppos = &previous_entity->base.source_position;
4139 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4140 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4141 assert(previous_entity->kind == ENTITY_PARAMETER);
4142 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4146 if (previous_entity->base.parent_scope == current_scope) {
4147 if (previous_entity->kind != entity->kind) {
4148 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4149 error_redefined_as_different_kind(pos, previous_entity,
4154 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4155 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4158 if (previous_entity->kind == ENTITY_TYPEDEF) {
4159 /* TODO: C++ allows this for exactly the same type */
4160 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4164 /* at this point we should have only VARIABLES or FUNCTIONS */
4165 assert(is_declaration(previous_entity) && is_declaration(entity));
4167 declaration_t *const prev_decl = &previous_entity->declaration;
4168 declaration_t *const decl = &entity->declaration;
4170 /* can happen for K&R style declarations */
4171 if (prev_decl->type == NULL &&
4172 previous_entity->kind == ENTITY_PARAMETER &&
4173 entity->kind == ENTITY_PARAMETER) {
4174 prev_decl->type = decl->type;
4175 prev_decl->storage_class = decl->storage_class;
4176 prev_decl->declared_storage_class = decl->declared_storage_class;
4177 prev_decl->modifiers = decl->modifiers;
4178 return previous_entity;
4181 type_t *const type = skip_typeref(decl->type);
4182 type_t *const prev_type = skip_typeref(prev_decl->type);
4184 if (!types_compatible(type, prev_type)) {
4185 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4187 unsigned old_storage_class = prev_decl->storage_class;
4189 if (is_definition &&
4191 !(prev_decl->modifiers & DM_USED) &&
4192 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4193 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4196 storage_class_t new_storage_class = decl->storage_class;
4198 /* pretend no storage class means extern for function
4199 * declarations (except if the previous declaration is neither
4200 * none nor extern) */
4201 if (entity->kind == ENTITY_FUNCTION) {
4202 /* the previous declaration could have unspecified parameters or
4203 * be a typedef, so use the new type */
4204 if (prev_type->function.unspecified_parameters || is_definition)
4205 prev_decl->type = type;
4207 switch (old_storage_class) {
4208 case STORAGE_CLASS_NONE:
4209 old_storage_class = STORAGE_CLASS_EXTERN;
4212 case STORAGE_CLASS_EXTERN:
4213 if (is_definition) {
4214 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4215 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4217 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4218 new_storage_class = STORAGE_CLASS_EXTERN;
4225 } else if (is_type_incomplete(prev_type)) {
4226 prev_decl->type = type;
4229 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4230 new_storage_class == STORAGE_CLASS_EXTERN) {
4232 warn_redundant_declaration: ;
4234 = has_new_attributes(prev_decl->attributes,
4236 if (has_new_attrs) {
4237 merge_in_attributes(decl, prev_decl->attributes);
4238 } else if (!is_definition &&
4239 is_type_valid(prev_type) &&
4240 strcmp(ppos->input_name, "<builtin>") != 0) {
4241 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4243 } else if (current_function == NULL) {
4244 if (old_storage_class != STORAGE_CLASS_STATIC &&
4245 new_storage_class == STORAGE_CLASS_STATIC) {
4246 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4247 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4248 prev_decl->storage_class = STORAGE_CLASS_NONE;
4249 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4251 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4253 goto error_redeclaration;
4254 goto warn_redundant_declaration;
4256 } else if (is_type_valid(prev_type)) {
4257 if (old_storage_class == new_storage_class) {
4258 error_redeclaration:
4259 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4261 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4266 prev_decl->modifiers |= decl->modifiers;
4267 if (entity->kind == ENTITY_FUNCTION) {
4268 previous_entity->function.is_inline |= entity->function.is_inline;
4270 return previous_entity;
4274 if (is_warn_on(why = WARN_SHADOW) ||
4275 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4276 char const *const what = get_entity_kind_name(previous_entity->kind);
4277 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4281 if (entity->kind == ENTITY_FUNCTION) {
4282 if (is_definition &&
4283 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4284 !is_sym_main(symbol)) {
4285 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4286 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4288 goto warn_missing_declaration;
4291 } else if (entity->kind == ENTITY_VARIABLE) {
4292 if (current_scope == file_scope &&
4293 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4294 !entity->declaration.implicit) {
4295 warn_missing_declaration:
4296 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4301 assert(entity->base.parent_scope == NULL);
4302 assert(current_scope != NULL);
4304 entity->base.parent_scope = current_scope;
4305 environment_push(entity);
4306 append_entity(current_scope, entity);
4311 static void parser_error_multiple_definition(entity_t *entity,
4312 const source_position_t *source_position)
4314 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4315 entity->base.symbol, &entity->base.source_position);
4318 static bool is_declaration_specifier(const token_t *token)
4320 switch (token->type) {
4324 return is_typedef_symbol(token->symbol);
4331 static void parse_init_declarator_rest(entity_t *entity)
4333 type_t *orig_type = type_error_type;
4335 if (entity->base.kind == ENTITY_TYPEDEF) {
4336 source_position_t const *const pos = &entity->base.source_position;
4337 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4339 assert(is_declaration(entity));
4340 orig_type = entity->declaration.type;
4343 type_t *type = skip_typeref(orig_type);
4345 if (entity->kind == ENTITY_VARIABLE
4346 && entity->variable.initializer != NULL) {
4347 parser_error_multiple_definition(entity, HERE);
4351 declaration_t *const declaration = &entity->declaration;
4352 bool must_be_constant = false;
4353 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4354 entity->base.parent_scope == file_scope) {
4355 must_be_constant = true;
4358 if (is_type_function(type)) {
4359 source_position_t const *const pos = &entity->base.source_position;
4360 errorf(pos, "'%N' is initialized like a variable", entity);
4361 orig_type = type_error_type;
4364 parse_initializer_env_t env;
4365 env.type = orig_type;
4366 env.must_be_constant = must_be_constant;
4367 env.entity = entity;
4368 current_init_decl = entity;
4370 initializer_t *initializer = parse_initializer(&env);
4371 current_init_decl = NULL;
4373 if (entity->kind == ENTITY_VARIABLE) {
4374 /* §6.7.5:22 array initializers for arrays with unknown size
4375 * determine the array type size */
4376 declaration->type = env.type;
4377 entity->variable.initializer = initializer;
4381 /* parse rest of a declaration without any declarator */
4382 static void parse_anonymous_declaration_rest(
4383 const declaration_specifiers_t *specifiers)
4386 anonymous_entity = NULL;
4388 source_position_t const *const pos = &specifiers->source_position;
4389 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4390 specifiers->thread_local) {
4391 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4394 type_t *type = specifiers->type;
4395 switch (type->kind) {
4396 case TYPE_COMPOUND_STRUCT:
4397 case TYPE_COMPOUND_UNION: {
4398 if (type->compound.compound->base.symbol == NULL) {
4399 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4408 warningf(WARN_OTHER, pos, "empty declaration");
4413 static void check_variable_type_complete(entity_t *ent)
4415 if (ent->kind != ENTITY_VARIABLE)
4418 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4419 * type for the object shall be complete [...] */
4420 declaration_t *decl = &ent->declaration;
4421 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4422 decl->storage_class == STORAGE_CLASS_STATIC)
4425 type_t *const type = skip_typeref(decl->type);
4426 if (!is_type_incomplete(type))
4429 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4430 * are given length one. */
4431 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4432 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4436 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4440 static void parse_declaration_rest(entity_t *ndeclaration,
4441 const declaration_specifiers_t *specifiers,
4442 parsed_declaration_func finished_declaration,
4443 declarator_flags_t flags)
4445 add_anchor_token(';');
4446 add_anchor_token(',');
4448 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4450 if (token.type == '=') {
4451 parse_init_declarator_rest(entity);
4452 } else if (entity->kind == ENTITY_VARIABLE) {
4453 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4454 * [...] where the extern specifier is explicitly used. */
4455 declaration_t *decl = &entity->declaration;
4456 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4457 type_t *type = decl->type;
4458 if (is_type_reference(skip_typeref(type))) {
4459 source_position_t const *const pos = &entity->base.source_position;
4460 errorf(pos, "reference '%#N' must be initialized", entity);
4465 check_variable_type_complete(entity);
4470 add_anchor_token('=');
4471 ndeclaration = parse_declarator(specifiers, flags);
4472 rem_anchor_token('=');
4474 expect(';', end_error);
4477 anonymous_entity = NULL;
4478 rem_anchor_token(';');
4479 rem_anchor_token(',');
4482 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4484 symbol_t *symbol = entity->base.symbol;
4488 assert(entity->base.namespc == NAMESPACE_NORMAL);
4489 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4490 if (previous_entity == NULL
4491 || previous_entity->base.parent_scope != current_scope) {
4492 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4497 if (is_definition) {
4498 errorf(HERE, "'%N' is initialised", entity);
4501 return record_entity(entity, false);
4504 static void parse_declaration(parsed_declaration_func finished_declaration,
4505 declarator_flags_t flags)
4507 add_anchor_token(';');
4508 declaration_specifiers_t specifiers;
4509 parse_declaration_specifiers(&specifiers);
4510 rem_anchor_token(';');
4512 if (token.type == ';') {
4513 parse_anonymous_declaration_rest(&specifiers);
4515 entity_t *entity = parse_declarator(&specifiers, flags);
4516 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4521 static type_t *get_default_promoted_type(type_t *orig_type)
4523 type_t *result = orig_type;
4525 type_t *type = skip_typeref(orig_type);
4526 if (is_type_integer(type)) {
4527 result = promote_integer(type);
4528 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4529 result = type_double;
4535 static void parse_kr_declaration_list(entity_t *entity)
4537 if (entity->kind != ENTITY_FUNCTION)
4540 type_t *type = skip_typeref(entity->declaration.type);
4541 assert(is_type_function(type));
4542 if (!type->function.kr_style_parameters)
4545 add_anchor_token('{');
4547 PUSH_SCOPE(&entity->function.parameters);
4549 entity_t *parameter = entity->function.parameters.entities;
4550 for ( ; parameter != NULL; parameter = parameter->base.next) {
4551 assert(parameter->base.parent_scope == NULL);
4552 parameter->base.parent_scope = current_scope;
4553 environment_push(parameter);
4556 /* parse declaration list */
4558 switch (token.type) {
4560 case T___extension__:
4561 /* This covers symbols, which are no type, too, and results in
4562 * better error messages. The typical cases are misspelled type
4563 * names and missing includes. */
4565 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4575 /* update function type */
4576 type_t *new_type = duplicate_type(type);
4578 function_parameter_t *parameters = NULL;
4579 function_parameter_t **anchor = ¶meters;
4581 /* did we have an earlier prototype? */
4582 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4583 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4586 function_parameter_t *proto_parameter = NULL;
4587 if (proto_type != NULL) {
4588 type_t *proto_type_type = proto_type->declaration.type;
4589 proto_parameter = proto_type_type->function.parameters;
4590 /* If a K&R function definition has a variadic prototype earlier, then
4591 * make the function definition variadic, too. This should conform to
4592 * §6.7.5.3:15 and §6.9.1:8. */
4593 new_type->function.variadic = proto_type_type->function.variadic;
4595 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4597 new_type->function.unspecified_parameters = true;
4600 bool need_incompatible_warning = false;
4601 parameter = entity->function.parameters.entities;
4602 for (; parameter != NULL; parameter = parameter->base.next,
4604 proto_parameter == NULL ? NULL : proto_parameter->next) {
4605 if (parameter->kind != ENTITY_PARAMETER)
4608 type_t *parameter_type = parameter->declaration.type;
4609 if (parameter_type == NULL) {
4610 source_position_t const* const pos = ¶meter->base.source_position;
4612 errorf(pos, "no type specified for function '%N'", parameter);
4613 parameter_type = type_error_type;
4615 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4616 parameter_type = type_int;
4618 parameter->declaration.type = parameter_type;
4621 semantic_parameter_incomplete(parameter);
4623 /* we need the default promoted types for the function type */
4624 type_t *not_promoted = parameter_type;
4625 parameter_type = get_default_promoted_type(parameter_type);
4627 /* gcc special: if the type of the prototype matches the unpromoted
4628 * type don't promote */
4629 if (!strict_mode && proto_parameter != NULL) {
4630 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4631 type_t *promo_skip = skip_typeref(parameter_type);
4632 type_t *param_skip = skip_typeref(not_promoted);
4633 if (!types_compatible(proto_p_type, promo_skip)
4634 && types_compatible(proto_p_type, param_skip)) {
4636 need_incompatible_warning = true;
4637 parameter_type = not_promoted;
4640 function_parameter_t *const function_parameter
4641 = allocate_parameter(parameter_type);
4643 *anchor = function_parameter;
4644 anchor = &function_parameter->next;
4647 new_type->function.parameters = parameters;
4648 new_type = identify_new_type(new_type);
4650 if (need_incompatible_warning) {
4651 symbol_t const *const sym = entity->base.symbol;
4652 source_position_t const *const pos = &entity->base.source_position;
4653 source_position_t const *const ppos = &proto_type->base.source_position;
4654 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4656 entity->declaration.type = new_type;
4658 rem_anchor_token('{');
4661 static bool first_err = true;
4664 * When called with first_err set, prints the name of the current function,
4667 static void print_in_function(void)
4671 char const *const file = current_function->base.base.source_position.input_name;
4672 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4677 * Check if all labels are defined in the current function.
4678 * Check if all labels are used in the current function.
4680 static void check_labels(void)
4682 for (const goto_statement_t *goto_statement = goto_first;
4683 goto_statement != NULL;
4684 goto_statement = goto_statement->next) {
4685 /* skip computed gotos */
4686 if (goto_statement->expression != NULL)
4689 label_t *label = goto_statement->label;
4690 if (label->base.source_position.input_name == NULL) {
4691 print_in_function();
4692 source_position_t const *const pos = &goto_statement->base.source_position;
4693 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4697 if (is_warn_on(WARN_UNUSED_LABEL)) {
4698 for (const label_statement_t *label_statement = label_first;
4699 label_statement != NULL;
4700 label_statement = label_statement->next) {
4701 label_t *label = label_statement->label;
4703 if (! label->used) {
4704 print_in_function();
4705 source_position_t const *const pos = &label_statement->base.source_position;
4706 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4712 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4714 entity_t const *const end = last != NULL ? last->base.next : NULL;
4715 for (; entity != end; entity = entity->base.next) {
4716 if (!is_declaration(entity))
4719 declaration_t *declaration = &entity->declaration;
4720 if (declaration->implicit)
4723 if (!declaration->used) {
4724 print_in_function();
4725 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4726 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4727 print_in_function();
4728 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4733 static void check_unused_variables(statement_t *const stmt, void *const env)
4737 switch (stmt->kind) {
4738 case STATEMENT_DECLARATION: {
4739 declaration_statement_t const *const decls = &stmt->declaration;
4740 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4745 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4754 * Check declarations of current_function for unused entities.
4756 static void check_declarations(void)
4758 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4759 const scope_t *scope = ¤t_function->parameters;
4761 /* do not issue unused warnings for main */
4762 if (!is_sym_main(current_function->base.base.symbol)) {
4763 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4766 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4767 walk_statements(current_function->statement, check_unused_variables,
4772 static int determine_truth(expression_t const* const cond)
4775 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4776 fold_constant_to_bool(cond) ? 1 :
4780 static void check_reachable(statement_t *);
4781 static bool reaches_end;
4783 static bool expression_returns(expression_t const *const expr)
4785 switch (expr->kind) {
4787 expression_t const *const func = expr->call.function;
4788 if (func->kind == EXPR_REFERENCE) {
4789 entity_t *entity = func->reference.entity;
4790 if (entity->kind == ENTITY_FUNCTION
4791 && entity->declaration.modifiers & DM_NORETURN)
4795 if (!expression_returns(func))
4798 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4799 if (!expression_returns(arg->expression))
4806 case EXPR_REFERENCE:
4807 case EXPR_REFERENCE_ENUM_VALUE:
4809 case EXPR_STRING_LITERAL:
4810 case EXPR_WIDE_STRING_LITERAL:
4811 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4812 case EXPR_LABEL_ADDRESS:
4813 case EXPR_CLASSIFY_TYPE:
4814 case EXPR_SIZEOF: // TODO handle obscure VLA case
4817 case EXPR_BUILTIN_CONSTANT_P:
4818 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4823 case EXPR_STATEMENT: {
4824 bool old_reaches_end = reaches_end;
4825 reaches_end = false;
4826 check_reachable(expr->statement.statement);
4827 bool returns = reaches_end;
4828 reaches_end = old_reaches_end;
4832 case EXPR_CONDITIONAL:
4833 // TODO handle constant expression
4835 if (!expression_returns(expr->conditional.condition))
4838 if (expr->conditional.true_expression != NULL
4839 && expression_returns(expr->conditional.true_expression))
4842 return expression_returns(expr->conditional.false_expression);
4845 return expression_returns(expr->select.compound);
4847 case EXPR_ARRAY_ACCESS:
4849 expression_returns(expr->array_access.array_ref) &&
4850 expression_returns(expr->array_access.index);
4853 return expression_returns(expr->va_starte.ap);
4856 return expression_returns(expr->va_arge.ap);
4859 return expression_returns(expr->va_copye.src);
4861 EXPR_UNARY_CASES_MANDATORY
4862 return expression_returns(expr->unary.value);
4864 case EXPR_UNARY_THROW:
4868 // TODO handle constant lhs of && and ||
4870 expression_returns(expr->binary.left) &&
4871 expression_returns(expr->binary.right);
4877 panic("unhandled expression");
4880 static bool initializer_returns(initializer_t const *const init)
4882 switch (init->kind) {
4883 case INITIALIZER_VALUE:
4884 return expression_returns(init->value.value);
4886 case INITIALIZER_LIST: {
4887 initializer_t * const* i = init->list.initializers;
4888 initializer_t * const* const end = i + init->list.len;
4889 bool returns = true;
4890 for (; i != end; ++i) {
4891 if (!initializer_returns(*i))
4897 case INITIALIZER_STRING:
4898 case INITIALIZER_WIDE_STRING:
4899 case INITIALIZER_DESIGNATOR: // designators have no payload
4902 panic("unhandled initializer");
4905 static bool noreturn_candidate;
4907 static void check_reachable(statement_t *const stmt)
4909 if (stmt->base.reachable)
4911 if (stmt->kind != STATEMENT_DO_WHILE)
4912 stmt->base.reachable = true;
4914 statement_t *last = stmt;
4916 switch (stmt->kind) {
4917 case STATEMENT_INVALID:
4918 case STATEMENT_EMPTY:
4920 next = stmt->base.next;
4923 case STATEMENT_DECLARATION: {
4924 declaration_statement_t const *const decl = &stmt->declaration;
4925 entity_t const * ent = decl->declarations_begin;
4926 entity_t const *const last_decl = decl->declarations_end;
4928 for (;; ent = ent->base.next) {
4929 if (ent->kind == ENTITY_VARIABLE &&
4930 ent->variable.initializer != NULL &&
4931 !initializer_returns(ent->variable.initializer)) {
4934 if (ent == last_decl)
4938 next = stmt->base.next;
4942 case STATEMENT_COMPOUND:
4943 next = stmt->compound.statements;
4945 next = stmt->base.next;
4948 case STATEMENT_RETURN: {
4949 expression_t const *const val = stmt->returns.value;
4950 if (val == NULL || expression_returns(val))
4951 noreturn_candidate = false;
4955 case STATEMENT_IF: {
4956 if_statement_t const *const ifs = &stmt->ifs;
4957 expression_t const *const cond = ifs->condition;
4959 if (!expression_returns(cond))
4962 int const val = determine_truth(cond);
4965 check_reachable(ifs->true_statement);
4970 if (ifs->false_statement != NULL) {
4971 check_reachable(ifs->false_statement);
4975 next = stmt->base.next;
4979 case STATEMENT_SWITCH: {
4980 switch_statement_t const *const switchs = &stmt->switchs;
4981 expression_t const *const expr = switchs->expression;
4983 if (!expression_returns(expr))
4986 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4987 long const val = fold_constant_to_int(expr);
4988 case_label_statement_t * defaults = NULL;
4989 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4990 if (i->expression == NULL) {
4995 if (i->first_case <= val && val <= i->last_case) {
4996 check_reachable((statement_t*)i);
5001 if (defaults != NULL) {
5002 check_reachable((statement_t*)defaults);
5006 bool has_default = false;
5007 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5008 if (i->expression == NULL)
5011 check_reachable((statement_t*)i);
5018 next = stmt->base.next;
5022 case STATEMENT_EXPRESSION: {
5023 /* Check for noreturn function call */
5024 expression_t const *const expr = stmt->expression.expression;
5025 if (!expression_returns(expr))
5028 next = stmt->base.next;
5032 case STATEMENT_CONTINUE:
5033 for (statement_t *parent = stmt;;) {
5034 parent = parent->base.parent;
5035 if (parent == NULL) /* continue not within loop */
5039 switch (parent->kind) {
5040 case STATEMENT_WHILE: goto continue_while;
5041 case STATEMENT_DO_WHILE: goto continue_do_while;
5042 case STATEMENT_FOR: goto continue_for;
5048 case STATEMENT_BREAK:
5049 for (statement_t *parent = stmt;;) {
5050 parent = parent->base.parent;
5051 if (parent == NULL) /* break not within loop/switch */
5054 switch (parent->kind) {
5055 case STATEMENT_SWITCH:
5056 case STATEMENT_WHILE:
5057 case STATEMENT_DO_WHILE:
5060 next = parent->base.next;
5061 goto found_break_parent;
5069 case STATEMENT_GOTO:
5070 if (stmt->gotos.expression) {
5071 if (!expression_returns(stmt->gotos.expression))
5074 statement_t *parent = stmt->base.parent;
5075 if (parent == NULL) /* top level goto */
5079 next = stmt->gotos.label->statement;
5080 if (next == NULL) /* missing label */
5085 case STATEMENT_LABEL:
5086 next = stmt->label.statement;
5089 case STATEMENT_CASE_LABEL:
5090 next = stmt->case_label.statement;
5093 case STATEMENT_WHILE: {
5094 while_statement_t const *const whiles = &stmt->whiles;
5095 expression_t const *const cond = whiles->condition;
5097 if (!expression_returns(cond))
5100 int const val = determine_truth(cond);
5103 check_reachable(whiles->body);
5108 next = stmt->base.next;
5112 case STATEMENT_DO_WHILE:
5113 next = stmt->do_while.body;
5116 case STATEMENT_FOR: {
5117 for_statement_t *const fors = &stmt->fors;
5119 if (fors->condition_reachable)
5121 fors->condition_reachable = true;
5123 expression_t const *const cond = fors->condition;
5128 } else if (expression_returns(cond)) {
5129 val = determine_truth(cond);
5135 check_reachable(fors->body);
5140 next = stmt->base.next;
5144 case STATEMENT_MS_TRY: {
5145 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5146 check_reachable(ms_try->try_statement);
5147 next = ms_try->final_statement;
5151 case STATEMENT_LEAVE: {
5152 statement_t *parent = stmt;
5154 parent = parent->base.parent;
5155 if (parent == NULL) /* __leave not within __try */
5158 if (parent->kind == STATEMENT_MS_TRY) {
5160 next = parent->ms_try.final_statement;
5168 panic("invalid statement kind");
5171 while (next == NULL) {
5172 next = last->base.parent;
5174 noreturn_candidate = false;
5176 type_t *const type = skip_typeref(current_function->base.type);
5177 assert(is_type_function(type));
5178 type_t *const ret = skip_typeref(type->function.return_type);
5179 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5180 is_type_valid(ret) &&
5181 !is_sym_main(current_function->base.base.symbol)) {
5182 source_position_t const *const pos = &stmt->base.source_position;
5183 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5188 switch (next->kind) {
5189 case STATEMENT_INVALID:
5190 case STATEMENT_EMPTY:
5191 case STATEMENT_DECLARATION:
5192 case STATEMENT_EXPRESSION:
5194 case STATEMENT_RETURN:
5195 case STATEMENT_CONTINUE:
5196 case STATEMENT_BREAK:
5197 case STATEMENT_GOTO:
5198 case STATEMENT_LEAVE:
5199 panic("invalid control flow in function");
5201 case STATEMENT_COMPOUND:
5202 if (next->compound.stmt_expr) {
5208 case STATEMENT_SWITCH:
5209 case STATEMENT_LABEL:
5210 case STATEMENT_CASE_LABEL:
5212 next = next->base.next;
5215 case STATEMENT_WHILE: {
5217 if (next->base.reachable)
5219 next->base.reachable = true;
5221 while_statement_t const *const whiles = &next->whiles;
5222 expression_t const *const cond = whiles->condition;
5224 if (!expression_returns(cond))
5227 int const val = determine_truth(cond);
5230 check_reachable(whiles->body);
5236 next = next->base.next;
5240 case STATEMENT_DO_WHILE: {
5242 if (next->base.reachable)
5244 next->base.reachable = true;
5246 do_while_statement_t const *const dw = &next->do_while;
5247 expression_t const *const cond = dw->condition;
5249 if (!expression_returns(cond))
5252 int const val = determine_truth(cond);
5255 check_reachable(dw->body);
5261 next = next->base.next;
5265 case STATEMENT_FOR: {
5267 for_statement_t *const fors = &next->fors;
5269 fors->step_reachable = true;
5271 if (fors->condition_reachable)
5273 fors->condition_reachable = true;
5275 expression_t const *const cond = fors->condition;
5280 } else if (expression_returns(cond)) {
5281 val = determine_truth(cond);
5287 check_reachable(fors->body);
5293 next = next->base.next;
5297 case STATEMENT_MS_TRY:
5299 next = next->ms_try.final_statement;
5304 check_reachable(next);
5307 static void check_unreachable(statement_t* const stmt, void *const env)
5311 switch (stmt->kind) {
5312 case STATEMENT_DO_WHILE:
5313 if (!stmt->base.reachable) {
5314 expression_t const *const cond = stmt->do_while.condition;
5315 if (determine_truth(cond) >= 0) {
5316 source_position_t const *const pos = &cond->base.source_position;
5317 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5322 case STATEMENT_FOR: {
5323 for_statement_t const* const fors = &stmt->fors;
5325 // if init and step are unreachable, cond is unreachable, too
5326 if (!stmt->base.reachable && !fors->step_reachable) {
5327 goto warn_unreachable;
5329 if (!stmt->base.reachable && fors->initialisation != NULL) {
5330 source_position_t const *const pos = &fors->initialisation->base.source_position;
5331 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5334 if (!fors->condition_reachable && fors->condition != NULL) {
5335 source_position_t const *const pos = &fors->condition->base.source_position;
5336 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5339 if (!fors->step_reachable && fors->step != NULL) {
5340 source_position_t const *const pos = &fors->step->base.source_position;
5341 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5347 case STATEMENT_COMPOUND:
5348 if (stmt->compound.statements != NULL)
5350 goto warn_unreachable;
5352 case STATEMENT_DECLARATION: {
5353 /* Only warn if there is at least one declarator with an initializer.
5354 * This typically occurs in switch statements. */
5355 declaration_statement_t const *const decl = &stmt->declaration;
5356 entity_t const * ent = decl->declarations_begin;
5357 entity_t const *const last = decl->declarations_end;
5359 for (;; ent = ent->base.next) {
5360 if (ent->kind == ENTITY_VARIABLE &&
5361 ent->variable.initializer != NULL) {
5362 goto warn_unreachable;
5372 if (!stmt->base.reachable) {
5373 source_position_t const *const pos = &stmt->base.source_position;
5374 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5380 static void parse_external_declaration(void)
5382 /* function-definitions and declarations both start with declaration
5384 add_anchor_token(';');
5385 declaration_specifiers_t specifiers;
5386 parse_declaration_specifiers(&specifiers);
5387 rem_anchor_token(';');
5389 /* must be a declaration */
5390 if (token.type == ';') {
5391 parse_anonymous_declaration_rest(&specifiers);
5395 add_anchor_token(',');
5396 add_anchor_token('=');
5397 add_anchor_token(';');
5398 add_anchor_token('{');
5400 /* declarator is common to both function-definitions and declarations */
5401 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5403 rem_anchor_token('{');
5404 rem_anchor_token(';');
5405 rem_anchor_token('=');
5406 rem_anchor_token(',');
5408 /* must be a declaration */
5409 switch (token.type) {
5413 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5418 /* must be a function definition */
5419 parse_kr_declaration_list(ndeclaration);
5421 if (token.type != '{') {
5422 parse_error_expected("while parsing function definition", '{', NULL);
5423 eat_until_matching_token(';');
5427 assert(is_declaration(ndeclaration));
5428 type_t *const orig_type = ndeclaration->declaration.type;
5429 type_t * type = skip_typeref(orig_type);
5431 if (!is_type_function(type)) {
5432 if (is_type_valid(type)) {
5433 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5439 source_position_t const *const pos = &ndeclaration->base.source_position;
5440 if (is_typeref(orig_type)) {
5442 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5445 if (is_type_compound(skip_typeref(type->function.return_type))) {
5446 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5448 if (type->function.unspecified_parameters) {
5449 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5451 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5454 /* §6.7.5.3:14 a function definition with () means no
5455 * parameters (and not unspecified parameters) */
5456 if (type->function.unspecified_parameters &&
5457 type->function.parameters == NULL) {
5458 type_t *copy = duplicate_type(type);
5459 copy->function.unspecified_parameters = false;
5460 type = identify_new_type(copy);
5462 ndeclaration->declaration.type = type;
5465 entity_t *const entity = record_entity(ndeclaration, true);
5466 assert(entity->kind == ENTITY_FUNCTION);
5467 assert(ndeclaration->kind == ENTITY_FUNCTION);
5469 function_t *const function = &entity->function;
5470 if (ndeclaration != entity) {
5471 function->parameters = ndeclaration->function.parameters;
5473 assert(is_declaration(entity));
5474 type = skip_typeref(entity->declaration.type);
5476 PUSH_SCOPE(&function->parameters);
5478 entity_t *parameter = function->parameters.entities;
5479 for (; parameter != NULL; parameter = parameter->base.next) {
5480 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5481 parameter->base.parent_scope = current_scope;
5483 assert(parameter->base.parent_scope == NULL
5484 || parameter->base.parent_scope == current_scope);
5485 parameter->base.parent_scope = current_scope;
5486 if (parameter->base.symbol == NULL) {
5487 errorf(¶meter->base.source_position, "parameter name omitted");
5490 environment_push(parameter);
5493 if (function->statement != NULL) {
5494 parser_error_multiple_definition(entity, HERE);
5497 /* parse function body */
5498 int label_stack_top = label_top();
5499 function_t *old_current_function = current_function;
5500 entity_t *old_current_entity = current_entity;
5501 current_function = function;
5502 current_entity = entity;
5506 goto_anchor = &goto_first;
5508 label_anchor = &label_first;
5510 statement_t *const body = parse_compound_statement(false);
5511 function->statement = body;
5514 check_declarations();
5515 if (is_warn_on(WARN_RETURN_TYPE) ||
5516 is_warn_on(WARN_UNREACHABLE_CODE) ||
5517 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5518 noreturn_candidate = true;
5519 check_reachable(body);
5520 if (is_warn_on(WARN_UNREACHABLE_CODE))
5521 walk_statements(body, check_unreachable, NULL);
5522 if (noreturn_candidate &&
5523 !(function->base.modifiers & DM_NORETURN)) {
5524 source_position_t const *const pos = &body->base.source_position;
5525 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5530 assert(current_function == function);
5531 assert(current_entity == entity);
5532 current_entity = old_current_entity;
5533 current_function = old_current_function;
5534 label_pop_to(label_stack_top);
5540 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5541 source_position_t *source_position,
5542 const symbol_t *symbol)
5544 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5546 type->bitfield.base_type = base_type;
5547 type->bitfield.size_expression = size;
5550 type_t *skipped_type = skip_typeref(base_type);
5551 if (!is_type_integer(skipped_type)) {
5552 errorf(source_position, "bitfield base type '%T' is not an integer type", base_type);
5555 bit_size = get_type_size(base_type) * 8;
5558 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5559 long v = fold_constant_to_int(size);
5560 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5563 errorf(source_position, "negative width in bit-field '%Y'",
5565 } else if (v == 0 && symbol != NULL) {
5566 errorf(source_position, "zero width for bit-field '%Y'",
5568 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5569 errorf(source_position, "width of '%Y' exceeds its type",
5572 type->bitfield.bit_size = v;
5579 static entity_t *find_compound_entry(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 if (iter->base.symbol == symbol) {
5588 } else if (iter->base.symbol == NULL) {
5589 /* search in anonymous structs and unions */
5590 type_t *type = skip_typeref(iter->declaration.type);
5591 if (is_type_compound(type)) {
5592 if (find_compound_entry(type->compound.compound, symbol)
5603 static void check_deprecated(const source_position_t *source_position,
5604 const entity_t *entity)
5606 if (!is_declaration(entity))
5608 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5611 source_position_t const *const epos = &entity->base.source_position;
5612 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5614 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5616 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5621 static expression_t *create_select(const source_position_t *pos,
5623 type_qualifiers_t qualifiers,
5626 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5628 check_deprecated(pos, entry);
5630 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5631 select->select.compound = addr;
5632 select->select.compound_entry = entry;
5634 type_t *entry_type = entry->declaration.type;
5635 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5637 /* we always do the auto-type conversions; the & and sizeof parser contains
5638 * code to revert this! */
5639 select->base.type = automatic_type_conversion(res_type);
5640 if (res_type->kind == TYPE_BITFIELD) {
5641 select->base.type = res_type->bitfield.base_type;
5648 * Find entry with symbol in compound. Search anonymous structs and unions and
5649 * creates implicit select expressions for them.
5650 * Returns the adress for the innermost compound.
5652 static expression_t *find_create_select(const source_position_t *pos,
5654 type_qualifiers_t qualifiers,
5655 compound_t *compound, symbol_t *symbol)
5657 entity_t *iter = compound->members.entities;
5658 for (; iter != NULL; iter = iter->base.next) {
5659 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5662 symbol_t *iter_symbol = iter->base.symbol;
5663 if (iter_symbol == NULL) {
5664 type_t *type = iter->declaration.type;
5665 if (type->kind != TYPE_COMPOUND_STRUCT
5666 && type->kind != TYPE_COMPOUND_UNION)
5669 compound_t *sub_compound = type->compound.compound;
5671 if (find_compound_entry(sub_compound, symbol) == NULL)
5674 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5675 sub_addr->base.source_position = *pos;
5676 sub_addr->select.implicit = true;
5677 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5681 if (iter_symbol == symbol) {
5682 return create_select(pos, addr, qualifiers, iter);
5689 static void parse_compound_declarators(compound_t *compound,
5690 const declaration_specifiers_t *specifiers)
5695 if (token.type == ':') {
5696 source_position_t source_position = *HERE;
5699 type_t *base_type = specifiers->type;
5700 expression_t *size = parse_constant_expression();
5702 type_t *type = make_bitfield_type(base_type, size,
5703 &source_position, NULL);
5705 attribute_t *attributes = parse_attributes(NULL);
5706 attribute_t **anchor = &attributes;
5707 while (*anchor != NULL)
5708 anchor = &(*anchor)->next;
5709 *anchor = specifiers->attributes;
5711 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL);
5712 entity->base.source_position = source_position;
5713 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5714 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5715 entity->declaration.type = type;
5716 entity->declaration.attributes = attributes;
5718 if (attributes != NULL) {
5719 handle_entity_attributes(attributes, entity);
5721 append_entity(&compound->members, entity);
5723 entity = parse_declarator(specifiers,
5724 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5725 source_position_t const *const pos = &entity->base.source_position;
5726 if (entity->kind == ENTITY_TYPEDEF) {
5727 errorf(pos, "typedef not allowed as compound member");
5729 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5731 /* make sure we don't define a symbol multiple times */
5732 symbol_t *symbol = entity->base.symbol;
5733 if (symbol != NULL) {
5734 entity_t *prev = find_compound_entry(compound, symbol);
5736 source_position_t const *const ppos = &prev->base.source_position;
5737 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5741 if (token.type == ':') {
5742 source_position_t source_position = *HERE;
5744 expression_t *size = parse_constant_expression();
5746 type_t *type = entity->declaration.type;
5747 type_t *bitfield_type = make_bitfield_type(type, size,
5748 &source_position, entity->base.symbol);
5750 attribute_t *attributes = parse_attributes(NULL);
5751 entity->declaration.type = bitfield_type;
5752 handle_entity_attributes(attributes, entity);
5754 type_t *orig_type = entity->declaration.type;
5755 type_t *type = skip_typeref(orig_type);
5756 if (is_type_function(type)) {
5757 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5758 } else if (is_type_incomplete(type)) {
5759 /* §6.7.2.1:16 flexible array member */
5760 if (!is_type_array(type) ||
5761 token.type != ';' ||
5762 look_ahead(1)->type != '}') {
5763 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5768 append_entity(&compound->members, entity);
5771 } while (next_if(','));
5772 expect(';', end_error);
5775 anonymous_entity = NULL;
5778 static void parse_compound_type_entries(compound_t *compound)
5781 add_anchor_token('}');
5784 switch (token.type) {
5786 case T___extension__:
5787 case T_IDENTIFIER: {
5789 declaration_specifiers_t specifiers;
5790 parse_declaration_specifiers(&specifiers);
5791 parse_compound_declarators(compound, &specifiers);
5797 rem_anchor_token('}');
5798 expect('}', end_error);
5801 compound->complete = true;
5807 static type_t *parse_typename(void)
5809 declaration_specifiers_t specifiers;
5810 parse_declaration_specifiers(&specifiers);
5811 if (specifiers.storage_class != STORAGE_CLASS_NONE
5812 || specifiers.thread_local) {
5813 /* TODO: improve error message, user does probably not know what a
5814 * storage class is...
5816 errorf(&specifiers.source_position, "typename must not have a storage class");
5819 type_t *result = parse_abstract_declarator(specifiers.type);
5827 typedef expression_t* (*parse_expression_function)(void);
5828 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5830 typedef struct expression_parser_function_t expression_parser_function_t;
5831 struct expression_parser_function_t {
5832 parse_expression_function parser;
5833 precedence_t infix_precedence;
5834 parse_expression_infix_function infix_parser;
5837 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5840 * Prints an error message if an expression was expected but not read
5842 static expression_t *expected_expression_error(void)
5844 /* skip the error message if the error token was read */
5845 if (token.type != T_ERROR) {
5846 errorf(HERE, "expected expression, got token %K", &token);
5850 return create_invalid_expression();
5853 static type_t *get_string_type(void)
5855 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5858 static type_t *get_wide_string_type(void)
5860 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5864 * Parse a string constant.
5866 static expression_t *parse_string_literal(void)
5868 source_position_t begin = token.source_position;
5869 string_t res = token.literal;
5870 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5873 while (token.type == T_STRING_LITERAL
5874 || token.type == T_WIDE_STRING_LITERAL) {
5875 warn_string_concat(&token.source_position);
5876 res = concat_strings(&res, &token.literal);
5878 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5881 expression_t *literal;
5883 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5884 literal->base.type = get_wide_string_type();
5886 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5887 literal->base.type = get_string_type();
5889 literal->base.source_position = begin;
5890 literal->literal.value = res;
5896 * Parse a boolean constant.
5898 static expression_t *parse_boolean_literal(bool value)
5900 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5901 literal->base.type = type_bool;
5902 literal->literal.value.begin = value ? "true" : "false";
5903 literal->literal.value.size = value ? 4 : 5;
5909 static void warn_traditional_suffix(void)
5911 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%Y' suffix", token.symbol);
5914 static void check_integer_suffix(void)
5916 symbol_t *suffix = token.symbol;
5920 bool not_traditional = false;
5921 const char *c = suffix->string;
5922 if (*c == 'l' || *c == 'L') {
5925 not_traditional = true;
5927 if (*c == 'u' || *c == 'U') {
5930 } else if (*c == 'u' || *c == 'U') {
5931 not_traditional = true;
5934 } else if (*c == 'u' || *c == 'U') {
5935 not_traditional = true;
5937 if (*c == 'l' || *c == 'L') {
5945 errorf(&token.source_position,
5946 "invalid suffix '%s' on integer constant", suffix->string);
5947 } else if (not_traditional) {
5948 warn_traditional_suffix();
5952 static type_t *check_floatingpoint_suffix(void)
5954 symbol_t *suffix = token.symbol;
5955 type_t *type = type_double;
5959 bool not_traditional = false;
5960 const char *c = suffix->string;
5961 if (*c == 'f' || *c == 'F') {
5964 } else if (*c == 'l' || *c == 'L') {
5966 type = type_long_double;
5969 errorf(&token.source_position,
5970 "invalid suffix '%s' on floatingpoint constant", suffix->string);
5971 } else if (not_traditional) {
5972 warn_traditional_suffix();
5979 * Parse an integer constant.
5981 static expression_t *parse_number_literal(void)
5983 expression_kind_t kind;
5986 switch (token.type) {
5988 kind = EXPR_LITERAL_INTEGER;
5989 check_integer_suffix();
5992 case T_INTEGER_OCTAL:
5993 kind = EXPR_LITERAL_INTEGER_OCTAL;
5994 check_integer_suffix();
5997 case T_INTEGER_HEXADECIMAL:
5998 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5999 check_integer_suffix();
6002 case T_FLOATINGPOINT:
6003 kind = EXPR_LITERAL_FLOATINGPOINT;
6004 type = check_floatingpoint_suffix();
6006 case T_FLOATINGPOINT_HEXADECIMAL:
6007 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6008 type = check_floatingpoint_suffix();
6011 panic("unexpected token type in parse_number_literal");
6014 expression_t *literal = allocate_expression_zero(kind);
6015 literal->base.type = type;
6016 literal->literal.value = token.literal;
6017 literal->literal.suffix = token.symbol;
6020 /* integer type depends on the size of the number and the size
6021 * representable by the types. The backend/codegeneration has to determine
6024 determine_literal_type(&literal->literal);
6029 * Parse a character constant.
6031 static expression_t *parse_character_constant(void)
6033 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6034 literal->base.type = c_mode & _CXX ? type_char : type_int;
6035 literal->literal.value = token.literal;
6037 size_t len = literal->literal.value.size;
6039 if (!GNU_MODE && !(c_mode & _C99)) {
6040 errorf(HERE, "more than 1 character in character constant");
6042 literal->base.type = type_int;
6043 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6052 * Parse a wide character constant.
6054 static expression_t *parse_wide_character_constant(void)
6056 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6057 literal->base.type = type_int;
6058 literal->literal.value = token.literal;
6060 size_t len = wstrlen(&literal->literal.value);
6062 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6069 static entity_t *create_implicit_function(symbol_t *symbol,
6070 const source_position_t *source_position)
6072 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6073 ntype->function.return_type = type_int;
6074 ntype->function.unspecified_parameters = true;
6075 ntype->function.linkage = LINKAGE_C;
6076 type_t *type = identify_new_type(ntype);
6078 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6079 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6080 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6081 entity->declaration.type = type;
6082 entity->declaration.implicit = true;
6083 entity->base.source_position = *source_position;
6085 if (current_scope != NULL)
6086 record_entity(entity, false);
6092 * Performs automatic type cast as described in §6.3.2.1.
6094 * @param orig_type the original type
6096 static type_t *automatic_type_conversion(type_t *orig_type)
6098 type_t *type = skip_typeref(orig_type);
6099 if (is_type_array(type)) {
6100 array_type_t *array_type = &type->array;
6101 type_t *element_type = array_type->element_type;
6102 unsigned qualifiers = array_type->base.qualifiers;
6104 return make_pointer_type(element_type, qualifiers);
6107 if (is_type_function(type)) {
6108 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6115 * reverts the automatic casts of array to pointer types and function
6116 * to function-pointer types as defined §6.3.2.1
6118 type_t *revert_automatic_type_conversion(const expression_t *expression)
6120 switch (expression->kind) {
6121 case EXPR_REFERENCE: {
6122 entity_t *entity = expression->reference.entity;
6123 if (is_declaration(entity)) {
6124 return entity->declaration.type;
6125 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6126 return entity->enum_value.enum_type;
6128 panic("no declaration or enum in reference");
6133 entity_t *entity = expression->select.compound_entry;
6134 assert(is_declaration(entity));
6135 type_t *type = entity->declaration.type;
6136 return get_qualified_type(type,
6137 expression->base.type->base.qualifiers);
6140 case EXPR_UNARY_DEREFERENCE: {
6141 const expression_t *const value = expression->unary.value;
6142 type_t *const type = skip_typeref(value->base.type);
6143 if (!is_type_pointer(type))
6144 return type_error_type;
6145 return type->pointer.points_to;
6148 case EXPR_ARRAY_ACCESS: {
6149 const expression_t *array_ref = expression->array_access.array_ref;
6150 type_t *type_left = skip_typeref(array_ref->base.type);
6151 if (!is_type_pointer(type_left))
6152 return type_error_type;
6153 return type_left->pointer.points_to;
6156 case EXPR_STRING_LITERAL: {
6157 size_t size = expression->string_literal.value.size;
6158 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6161 case EXPR_WIDE_STRING_LITERAL: {
6162 size_t size = wstrlen(&expression->string_literal.value);
6163 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6166 case EXPR_COMPOUND_LITERAL:
6167 return expression->compound_literal.type;
6172 return expression->base.type;
6176 * Find an entity matching a symbol in a scope.
6177 * Uses current scope if scope is NULL
6179 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6180 namespace_tag_t namespc)
6182 if (scope == NULL) {
6183 return get_entity(symbol, namespc);
6186 /* we should optimize here, if scope grows above a certain size we should
6187 construct a hashmap here... */
6188 entity_t *entity = scope->entities;
6189 for ( ; entity != NULL; entity = entity->base.next) {
6190 if (entity->base.symbol == symbol
6191 && (namespace_tag_t)entity->base.namespc == namespc)
6198 static entity_t *parse_qualified_identifier(void)
6200 /* namespace containing the symbol */
6202 source_position_t pos;
6203 const scope_t *lookup_scope = NULL;
6205 if (next_if(T_COLONCOLON))
6206 lookup_scope = &unit->scope;
6210 if (token.type != T_IDENTIFIER) {
6211 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6212 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6214 symbol = token.symbol;
6219 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6221 if (!next_if(T_COLONCOLON))
6224 switch (entity->kind) {
6225 case ENTITY_NAMESPACE:
6226 lookup_scope = &entity->namespacee.members;
6231 lookup_scope = &entity->compound.members;
6234 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6235 symbol, get_entity_kind_name(entity->kind));
6237 /* skip further qualifications */
6238 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6240 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6244 if (entity == NULL) {
6245 if (!strict_mode && token.type == '(') {
6246 /* an implicitly declared function */
6247 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6248 entity = create_implicit_function(symbol, &pos);
6250 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6251 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6258 static expression_t *parse_reference(void)
6260 source_position_t const pos = token.source_position;
6261 entity_t *const entity = parse_qualified_identifier();
6264 if (is_declaration(entity)) {
6265 orig_type = entity->declaration.type;
6266 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6267 orig_type = entity->enum_value.enum_type;
6269 panic("expected declaration or enum value in reference");
6272 /* we always do the auto-type conversions; the & and sizeof parser contains
6273 * code to revert this! */
6274 type_t *type = automatic_type_conversion(orig_type);
6276 expression_kind_t kind = EXPR_REFERENCE;
6277 if (entity->kind == ENTITY_ENUM_VALUE)
6278 kind = EXPR_REFERENCE_ENUM_VALUE;
6280 expression_t *expression = allocate_expression_zero(kind);
6281 expression->base.source_position = pos;
6282 expression->base.type = type;
6283 expression->reference.entity = entity;
6285 /* this declaration is used */
6286 if (is_declaration(entity)) {
6287 entity->declaration.used = true;
6290 if (entity->base.parent_scope != file_scope
6291 && (current_function != NULL
6292 && entity->base.parent_scope->depth < current_function->parameters.depth)
6293 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6294 if (entity->kind == ENTITY_VARIABLE) {
6295 /* access of a variable from an outer function */
6296 entity->variable.address_taken = true;
6297 } else if (entity->kind == ENTITY_PARAMETER) {
6298 entity->parameter.address_taken = true;
6300 current_function->need_closure = true;
6303 check_deprecated(&pos, entity);
6305 if (entity == current_init_decl && !in_type_prop && entity->kind == ENTITY_VARIABLE) {
6306 current_init_decl = NULL;
6307 warningf(WARN_INIT_SELF, &pos, "variable '%#N' is initialized by itself", entity);
6313 static bool semantic_cast(expression_t *cast)
6315 expression_t *expression = cast->unary.value;
6316 type_t *orig_dest_type = cast->base.type;
6317 type_t *orig_type_right = expression->base.type;
6318 type_t const *dst_type = skip_typeref(orig_dest_type);
6319 type_t const *src_type = skip_typeref(orig_type_right);
6320 source_position_t const *pos = &cast->base.source_position;
6322 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6323 if (dst_type == type_void)
6326 /* only integer and pointer can be casted to pointer */
6327 if (is_type_pointer(dst_type) &&
6328 !is_type_pointer(src_type) &&
6329 !is_type_integer(src_type) &&
6330 is_type_valid(src_type)) {
6331 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6335 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6336 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6340 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6341 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6345 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6346 type_t *src = skip_typeref(src_type->pointer.points_to);
6347 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6348 unsigned missing_qualifiers =
6349 src->base.qualifiers & ~dst->base.qualifiers;
6350 if (missing_qualifiers != 0) {
6351 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6357 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6359 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6360 expression->base.source_position = *pos;
6362 parse_initializer_env_t env;
6365 env.must_be_constant = false;
6366 initializer_t *initializer = parse_initializer(&env);
6369 expression->compound_literal.initializer = initializer;
6370 expression->compound_literal.type = type;
6371 expression->base.type = automatic_type_conversion(type);
6377 * Parse a cast expression.
6379 static expression_t *parse_cast(void)
6381 source_position_t const pos = *HERE;
6384 add_anchor_token(')');
6386 type_t *type = parse_typename();
6388 rem_anchor_token(')');
6389 expect(')', end_error);
6391 if (token.type == '{') {
6392 return parse_compound_literal(&pos, type);
6395 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6396 cast->base.source_position = pos;
6398 expression_t *value = parse_subexpression(PREC_CAST);
6399 cast->base.type = type;
6400 cast->unary.value = value;
6402 if (! semantic_cast(cast)) {
6403 /* TODO: record the error in the AST. else it is impossible to detect it */
6408 return create_invalid_expression();
6412 * Parse a statement expression.
6414 static expression_t *parse_statement_expression(void)
6416 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6419 add_anchor_token(')');
6421 statement_t *statement = parse_compound_statement(true);
6422 statement->compound.stmt_expr = true;
6423 expression->statement.statement = statement;
6425 /* find last statement and use its type */
6426 type_t *type = type_void;
6427 const statement_t *stmt = statement->compound.statements;
6429 while (stmt->base.next != NULL)
6430 stmt = stmt->base.next;
6432 if (stmt->kind == STATEMENT_EXPRESSION) {
6433 type = stmt->expression.expression->base.type;
6436 source_position_t const *const pos = &expression->base.source_position;
6437 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6439 expression->base.type = type;
6441 rem_anchor_token(')');
6442 expect(')', end_error);
6449 * Parse a parenthesized expression.
6451 static expression_t *parse_parenthesized_expression(void)
6453 token_t const* const la1 = look_ahead(1);
6454 switch (la1->type) {
6456 /* gcc extension: a statement expression */
6457 return parse_statement_expression();
6460 if (is_typedef_symbol(la1->symbol)) {
6462 return parse_cast();
6467 add_anchor_token(')');
6468 expression_t *result = parse_expression();
6469 result->base.parenthesized = true;
6470 rem_anchor_token(')');
6471 expect(')', end_error);
6477 static expression_t *parse_function_keyword(void)
6481 if (current_function == NULL) {
6482 errorf(HERE, "'__func__' used outside of a function");
6485 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6486 expression->base.type = type_char_ptr;
6487 expression->funcname.kind = FUNCNAME_FUNCTION;
6494 static expression_t *parse_pretty_function_keyword(void)
6496 if (current_function == NULL) {
6497 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6500 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6501 expression->base.type = type_char_ptr;
6502 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6504 eat(T___PRETTY_FUNCTION__);
6509 static expression_t *parse_funcsig_keyword(void)
6511 if (current_function == NULL) {
6512 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6515 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6516 expression->base.type = type_char_ptr;
6517 expression->funcname.kind = FUNCNAME_FUNCSIG;
6524 static expression_t *parse_funcdname_keyword(void)
6526 if (current_function == NULL) {
6527 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6530 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6531 expression->base.type = type_char_ptr;
6532 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6534 eat(T___FUNCDNAME__);
6539 static designator_t *parse_designator(void)
6541 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6542 result->source_position = *HERE;
6544 if (token.type != T_IDENTIFIER) {
6545 parse_error_expected("while parsing member designator",
6546 T_IDENTIFIER, NULL);
6549 result->symbol = token.symbol;
6552 designator_t *last_designator = result;
6555 if (token.type != T_IDENTIFIER) {
6556 parse_error_expected("while parsing member designator",
6557 T_IDENTIFIER, NULL);
6560 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6561 designator->source_position = *HERE;
6562 designator->symbol = token.symbol;
6565 last_designator->next = designator;
6566 last_designator = designator;
6570 add_anchor_token(']');
6571 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6572 designator->source_position = *HERE;
6573 designator->array_index = parse_expression();
6574 rem_anchor_token(']');
6575 expect(']', end_error);
6576 if (designator->array_index == NULL) {
6580 last_designator->next = designator;
6581 last_designator = designator;
6593 * Parse the __builtin_offsetof() expression.
6595 static expression_t *parse_offsetof(void)
6597 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6598 expression->base.type = type_size_t;
6600 eat(T___builtin_offsetof);
6602 expect('(', end_error);
6603 add_anchor_token(',');
6604 type_t *type = parse_typename();
6605 rem_anchor_token(',');
6606 expect(',', end_error);
6607 add_anchor_token(')');
6608 designator_t *designator = parse_designator();
6609 rem_anchor_token(')');
6610 expect(')', end_error);
6612 expression->offsetofe.type = type;
6613 expression->offsetofe.designator = designator;
6616 memset(&path, 0, sizeof(path));
6617 path.top_type = type;
6618 path.path = NEW_ARR_F(type_path_entry_t, 0);
6620 descend_into_subtype(&path);
6622 if (!walk_designator(&path, designator, true)) {
6623 return create_invalid_expression();
6626 DEL_ARR_F(path.path);
6630 return create_invalid_expression();
6634 * Parses a _builtin_va_start() expression.
6636 static expression_t *parse_va_start(void)
6638 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6640 eat(T___builtin_va_start);
6642 expect('(', end_error);
6643 add_anchor_token(',');
6644 expression->va_starte.ap = parse_assignment_expression();
6645 rem_anchor_token(',');
6646 expect(',', end_error);
6647 expression_t *const expr = parse_assignment_expression();
6648 if (expr->kind == EXPR_REFERENCE) {
6649 entity_t *const entity = expr->reference.entity;
6650 if (!current_function->base.type->function.variadic) {
6651 errorf(&expr->base.source_position,
6652 "'va_start' used in non-variadic function");
6653 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6654 entity->base.next != NULL ||
6655 entity->kind != ENTITY_PARAMETER) {
6656 errorf(&expr->base.source_position,
6657 "second argument of 'va_start' must be last parameter of the current function");
6659 expression->va_starte.parameter = &entity->variable;
6661 expect(')', end_error);
6664 expect(')', end_error);
6666 return create_invalid_expression();
6670 * Parses a __builtin_va_arg() expression.
6672 static expression_t *parse_va_arg(void)
6674 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6676 eat(T___builtin_va_arg);
6678 expect('(', end_error);
6680 ap.expression = parse_assignment_expression();
6681 expression->va_arge.ap = ap.expression;
6682 check_call_argument(type_valist, &ap, 1);
6684 expect(',', end_error);
6685 expression->base.type = parse_typename();
6686 expect(')', end_error);
6690 return create_invalid_expression();
6694 * Parses a __builtin_va_copy() expression.
6696 static expression_t *parse_va_copy(void)
6698 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6700 eat(T___builtin_va_copy);
6702 expect('(', end_error);
6703 expression_t *dst = parse_assignment_expression();
6704 assign_error_t error = semantic_assign(type_valist, dst);
6705 report_assign_error(error, type_valist, dst, "call argument 1",
6706 &dst->base.source_position);
6707 expression->va_copye.dst = dst;
6709 expect(',', end_error);
6711 call_argument_t src;
6712 src.expression = parse_assignment_expression();
6713 check_call_argument(type_valist, &src, 2);
6714 expression->va_copye.src = src.expression;
6715 expect(')', end_error);
6719 return create_invalid_expression();
6723 * Parses a __builtin_constant_p() expression.
6725 static expression_t *parse_builtin_constant(void)
6727 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6729 eat(T___builtin_constant_p);
6731 expect('(', end_error);
6732 add_anchor_token(')');
6733 expression->builtin_constant.value = parse_assignment_expression();
6734 rem_anchor_token(')');
6735 expect(')', end_error);
6736 expression->base.type = type_int;
6740 return create_invalid_expression();
6744 * Parses a __builtin_types_compatible_p() expression.
6746 static expression_t *parse_builtin_types_compatible(void)
6748 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6750 eat(T___builtin_types_compatible_p);
6752 expect('(', end_error);
6753 add_anchor_token(')');
6754 add_anchor_token(',');
6755 expression->builtin_types_compatible.left = parse_typename();
6756 rem_anchor_token(',');
6757 expect(',', end_error);
6758 expression->builtin_types_compatible.right = parse_typename();
6759 rem_anchor_token(')');
6760 expect(')', end_error);
6761 expression->base.type = type_int;
6765 return create_invalid_expression();
6769 * Parses a __builtin_is_*() compare expression.
6771 static expression_t *parse_compare_builtin(void)
6773 expression_t *expression;
6775 switch (token.type) {
6776 case T___builtin_isgreater:
6777 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6779 case T___builtin_isgreaterequal:
6780 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6782 case T___builtin_isless:
6783 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6785 case T___builtin_islessequal:
6786 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6788 case T___builtin_islessgreater:
6789 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6791 case T___builtin_isunordered:
6792 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6795 internal_errorf(HERE, "invalid compare builtin found");
6797 expression->base.source_position = *HERE;
6800 expect('(', end_error);
6801 expression->binary.left = parse_assignment_expression();
6802 expect(',', end_error);
6803 expression->binary.right = parse_assignment_expression();
6804 expect(')', end_error);
6806 type_t *const orig_type_left = expression->binary.left->base.type;
6807 type_t *const orig_type_right = expression->binary.right->base.type;
6809 type_t *const type_left = skip_typeref(orig_type_left);
6810 type_t *const type_right = skip_typeref(orig_type_right);
6811 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6812 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6813 type_error_incompatible("invalid operands in comparison",
6814 &expression->base.source_position, orig_type_left, orig_type_right);
6817 semantic_comparison(&expression->binary);
6822 return create_invalid_expression();
6826 * Parses a MS assume() expression.
6828 static expression_t *parse_assume(void)
6830 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6834 expect('(', end_error);
6835 add_anchor_token(')');
6836 expression->unary.value = parse_assignment_expression();
6837 rem_anchor_token(')');
6838 expect(')', end_error);
6840 expression->base.type = type_void;
6843 return create_invalid_expression();
6847 * Return the label for the current symbol or create a new one.
6849 static label_t *get_label(void)
6851 assert(token.type == T_IDENTIFIER);
6852 assert(current_function != NULL);
6854 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6855 /* If we find a local label, we already created the declaration. */
6856 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6857 if (label->base.parent_scope != current_scope) {
6858 assert(label->base.parent_scope->depth < current_scope->depth);
6859 current_function->goto_to_outer = true;
6861 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6862 /* There is no matching label in the same function, so create a new one. */
6863 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6868 return &label->label;
6872 * Parses a GNU && label address expression.
6874 static expression_t *parse_label_address(void)
6876 source_position_t source_position = token.source_position;
6878 if (token.type != T_IDENTIFIER) {
6879 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6880 return create_invalid_expression();
6883 label_t *const label = get_label();
6885 label->address_taken = true;
6887 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6888 expression->base.source_position = source_position;
6890 /* label address is treated as a void pointer */
6891 expression->base.type = type_void_ptr;
6892 expression->label_address.label = label;
6897 * Parse a microsoft __noop expression.
6899 static expression_t *parse_noop_expression(void)
6901 /* the result is a (int)0 */
6902 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6903 literal->base.type = type_int;
6904 literal->literal.value.begin = "__noop";
6905 literal->literal.value.size = 6;
6909 if (token.type == '(') {
6910 /* parse arguments */
6912 add_anchor_token(')');
6913 add_anchor_token(',');
6915 if (token.type != ')') do {
6916 (void)parse_assignment_expression();
6917 } while (next_if(','));
6919 rem_anchor_token(',');
6920 rem_anchor_token(')');
6921 expect(')', end_error);
6928 * Parses a primary expression.
6930 static expression_t *parse_primary_expression(void)
6932 switch (token.type) {
6933 case T_false: return parse_boolean_literal(false);
6934 case T_true: return parse_boolean_literal(true);
6936 case T_INTEGER_OCTAL:
6937 case T_INTEGER_HEXADECIMAL:
6938 case T_FLOATINGPOINT:
6939 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6940 case T_CHARACTER_CONSTANT: return parse_character_constant();
6941 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6942 case T_STRING_LITERAL:
6943 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6944 case T___FUNCTION__:
6945 case T___func__: return parse_function_keyword();
6946 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6947 case T___FUNCSIG__: return parse_funcsig_keyword();
6948 case T___FUNCDNAME__: return parse_funcdname_keyword();
6949 case T___builtin_offsetof: return parse_offsetof();
6950 case T___builtin_va_start: return parse_va_start();
6951 case T___builtin_va_arg: return parse_va_arg();
6952 case T___builtin_va_copy: return parse_va_copy();
6953 case T___builtin_isgreater:
6954 case T___builtin_isgreaterequal:
6955 case T___builtin_isless:
6956 case T___builtin_islessequal:
6957 case T___builtin_islessgreater:
6958 case T___builtin_isunordered: return parse_compare_builtin();
6959 case T___builtin_constant_p: return parse_builtin_constant();
6960 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6961 case T__assume: return parse_assume();
6964 return parse_label_address();
6967 case '(': return parse_parenthesized_expression();
6968 case T___noop: return parse_noop_expression();
6970 /* Gracefully handle type names while parsing expressions. */
6972 return parse_reference();
6974 if (!is_typedef_symbol(token.symbol)) {
6975 return parse_reference();
6979 source_position_t const pos = *HERE;
6980 declaration_specifiers_t specifiers;
6981 parse_declaration_specifiers(&specifiers);
6982 type_t const *const type = parse_abstract_declarator(specifiers.type);
6983 errorf(&pos, "encountered type '%T' while parsing expression", type);
6984 return create_invalid_expression();
6988 errorf(HERE, "unexpected token %K, expected an expression", &token);
6990 return create_invalid_expression();
6993 static expression_t *parse_array_expression(expression_t *left)
6995 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6996 array_access_expression_t *const arr = &expr->array_access;
6999 add_anchor_token(']');
7001 expression_t *const inside = parse_expression();
7003 type_t *const orig_type_left = left->base.type;
7004 type_t *const orig_type_inside = inside->base.type;
7006 type_t *const type_left = skip_typeref(orig_type_left);
7007 type_t *const type_inside = skip_typeref(orig_type_inside);
7013 if (is_type_pointer(type_left)) {
7016 idx_type = type_inside;
7017 res_type = type_left->pointer.points_to;
7019 } else if (is_type_pointer(type_inside)) {
7020 arr->flipped = true;
7023 idx_type = type_left;
7024 res_type = type_inside->pointer.points_to;
7026 res_type = automatic_type_conversion(res_type);
7027 if (!is_type_integer(idx_type)) {
7028 errorf(&idx->base.source_position, "array subscript must have integer type");
7029 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
7030 source_position_t const *const pos = &idx->base.source_position;
7031 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
7034 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7035 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7037 res_type = type_error_type;
7042 arr->array_ref = ref;
7044 arr->base.type = res_type;
7046 rem_anchor_token(']');
7047 expect(']', end_error);
7052 static expression_t *parse_typeprop(expression_kind_t const kind)
7054 expression_t *tp_expression = allocate_expression_zero(kind);
7055 tp_expression->base.type = type_size_t;
7057 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7059 /* we only refer to a type property, mark this case */
7060 bool old = in_type_prop;
7061 in_type_prop = true;
7064 expression_t *expression;
7065 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7066 source_position_t const pos = *HERE;
7068 add_anchor_token(')');
7069 orig_type = parse_typename();
7070 rem_anchor_token(')');
7071 expect(')', end_error);
7073 if (token.type == '{') {
7074 /* It was not sizeof(type) after all. It is sizeof of an expression
7075 * starting with a compound literal */
7076 expression = parse_compound_literal(&pos, orig_type);
7077 goto typeprop_expression;
7080 expression = parse_subexpression(PREC_UNARY);
7082 typeprop_expression:
7083 tp_expression->typeprop.tp_expression = expression;
7085 orig_type = revert_automatic_type_conversion(expression);
7086 expression->base.type = orig_type;
7089 tp_expression->typeprop.type = orig_type;
7090 type_t const* const type = skip_typeref(orig_type);
7091 char const* wrong_type = NULL;
7092 if (is_type_incomplete(type)) {
7093 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7094 wrong_type = "incomplete";
7095 } else if (type->kind == TYPE_FUNCTION) {
7097 /* function types are allowed (and return 1) */
7098 source_position_t const *const pos = &tp_expression->base.source_position;
7099 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7100 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7102 wrong_type = "function";
7105 if (is_type_incomplete(type))
7106 wrong_type = "incomplete";
7108 if (type->kind == TYPE_BITFIELD)
7109 wrong_type = "bitfield";
7111 if (wrong_type != NULL) {
7112 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7113 errorf(&tp_expression->base.source_position,
7114 "operand of %s expression must not be of %s type '%T'",
7115 what, wrong_type, orig_type);
7120 return tp_expression;
7123 static expression_t *parse_sizeof(void)
7125 return parse_typeprop(EXPR_SIZEOF);
7128 static expression_t *parse_alignof(void)
7130 return parse_typeprop(EXPR_ALIGNOF);
7133 static expression_t *parse_select_expression(expression_t *addr)
7135 assert(token.type == '.' || token.type == T_MINUSGREATER);
7136 bool select_left_arrow = (token.type == T_MINUSGREATER);
7137 source_position_t const pos = *HERE;
7140 if (token.type != T_IDENTIFIER) {
7141 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7142 return create_invalid_expression();
7144 symbol_t *symbol = token.symbol;
7147 type_t *const orig_type = addr->base.type;
7148 type_t *const type = skip_typeref(orig_type);
7151 bool saw_error = false;
7152 if (is_type_pointer(type)) {
7153 if (!select_left_arrow) {
7155 "request for member '%Y' in something not a struct or union, but '%T'",
7159 type_left = skip_typeref(type->pointer.points_to);
7161 if (select_left_arrow && is_type_valid(type)) {
7162 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7168 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7169 type_left->kind != TYPE_COMPOUND_UNION) {
7171 if (is_type_valid(type_left) && !saw_error) {
7173 "request for member '%Y' in something not a struct or union, but '%T'",
7176 return create_invalid_expression();
7179 compound_t *compound = type_left->compound.compound;
7180 if (!compound->complete) {
7181 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7183 return create_invalid_expression();
7186 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7187 expression_t *result =
7188 find_create_select(&pos, addr, qualifiers, compound, symbol);
7190 if (result == NULL) {
7191 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7192 return create_invalid_expression();
7198 static void check_call_argument(type_t *expected_type,
7199 call_argument_t *argument, unsigned pos)
7201 type_t *expected_type_skip = skip_typeref(expected_type);
7202 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7203 expression_t *arg_expr = argument->expression;
7204 type_t *arg_type = skip_typeref(arg_expr->base.type);
7206 /* handle transparent union gnu extension */
7207 if (is_type_union(expected_type_skip)
7208 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7209 compound_t *union_decl = expected_type_skip->compound.compound;
7210 type_t *best_type = NULL;
7211 entity_t *entry = union_decl->members.entities;
7212 for ( ; entry != NULL; entry = entry->base.next) {
7213 assert(is_declaration(entry));
7214 type_t *decl_type = entry->declaration.type;
7215 error = semantic_assign(decl_type, arg_expr);
7216 if (error == ASSIGN_ERROR_INCOMPATIBLE
7217 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7220 if (error == ASSIGN_SUCCESS) {
7221 best_type = decl_type;
7222 } else if (best_type == NULL) {
7223 best_type = decl_type;
7227 if (best_type != NULL) {
7228 expected_type = best_type;
7232 error = semantic_assign(expected_type, arg_expr);
7233 argument->expression = create_implicit_cast(arg_expr, expected_type);
7235 if (error != ASSIGN_SUCCESS) {
7236 /* report exact scope in error messages (like "in argument 3") */
7238 snprintf(buf, sizeof(buf), "call argument %u", pos);
7239 report_assign_error(error, expected_type, arg_expr, buf,
7240 &arg_expr->base.source_position);
7242 type_t *const promoted_type = get_default_promoted_type(arg_type);
7243 if (!types_compatible(expected_type_skip, promoted_type) &&
7244 !types_compatible(expected_type_skip, type_void_ptr) &&
7245 !types_compatible(type_void_ptr, promoted_type)) {
7246 /* Deliberately show the skipped types in this warning */
7247 source_position_t const *const apos = &arg_expr->base.source_position;
7248 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7254 * Handle the semantic restrictions of builtin calls
7256 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7257 switch (call->function->reference.entity->function.btk) {
7258 case bk_gnu_builtin_return_address:
7259 case bk_gnu_builtin_frame_address: {
7260 /* argument must be constant */
7261 call_argument_t *argument = call->arguments;
7263 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7264 errorf(&call->base.source_position,
7265 "argument of '%Y' must be a constant expression",
7266 call->function->reference.entity->base.symbol);
7270 case bk_gnu_builtin_object_size:
7271 if (call->arguments == NULL)
7274 call_argument_t *arg = call->arguments->next;
7275 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7276 errorf(&call->base.source_position,
7277 "second argument of '%Y' must be a constant expression",
7278 call->function->reference.entity->base.symbol);
7281 case bk_gnu_builtin_prefetch:
7282 /* second and third argument must be constant if existent */
7283 if (call->arguments == NULL)
7285 call_argument_t *rw = call->arguments->next;
7286 call_argument_t *locality = NULL;
7289 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7290 errorf(&call->base.source_position,
7291 "second argument of '%Y' must be a constant expression",
7292 call->function->reference.entity->base.symbol);
7294 locality = rw->next;
7296 if (locality != NULL) {
7297 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7298 errorf(&call->base.source_position,
7299 "third argument of '%Y' must be a constant expression",
7300 call->function->reference.entity->base.symbol);
7302 locality = rw->next;
7311 * Parse a call expression, ie. expression '( ... )'.
7313 * @param expression the function address
7315 static expression_t *parse_call_expression(expression_t *expression)
7317 expression_t *result = allocate_expression_zero(EXPR_CALL);
7318 call_expression_t *call = &result->call;
7319 call->function = expression;
7321 type_t *const orig_type = expression->base.type;
7322 type_t *const type = skip_typeref(orig_type);
7324 function_type_t *function_type = NULL;
7325 if (is_type_pointer(type)) {
7326 type_t *const to_type = skip_typeref(type->pointer.points_to);
7328 if (is_type_function(to_type)) {
7329 function_type = &to_type->function;
7330 call->base.type = function_type->return_type;
7334 if (function_type == NULL && is_type_valid(type)) {
7336 "called object '%E' (type '%T') is not a pointer to a function",
7337 expression, orig_type);
7340 /* parse arguments */
7342 add_anchor_token(')');
7343 add_anchor_token(',');
7345 if (token.type != ')') {
7346 call_argument_t **anchor = &call->arguments;
7348 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7349 argument->expression = parse_assignment_expression();
7352 anchor = &argument->next;
7353 } while (next_if(','));
7355 rem_anchor_token(',');
7356 rem_anchor_token(')');
7357 expect(')', end_error);
7359 if (function_type == NULL)
7362 /* check type and count of call arguments */
7363 function_parameter_t *parameter = function_type->parameters;
7364 call_argument_t *argument = call->arguments;
7365 if (!function_type->unspecified_parameters) {
7366 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7367 parameter = parameter->next, argument = argument->next) {
7368 check_call_argument(parameter->type, argument, ++pos);
7371 if (parameter != NULL) {
7372 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7373 } else if (argument != NULL && !function_type->variadic) {
7374 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7378 /* do default promotion for other arguments */
7379 for (; argument != NULL; argument = argument->next) {
7380 type_t *argument_type = argument->expression->base.type;
7381 if (!is_type_object(skip_typeref(argument_type))) {
7382 errorf(&argument->expression->base.source_position,
7383 "call argument '%E' must not be void", argument->expression);
7386 argument_type = get_default_promoted_type(argument_type);
7388 argument->expression
7389 = create_implicit_cast(argument->expression, argument_type);
7394 if (is_type_compound(skip_typeref(function_type->return_type))) {
7395 source_position_t const *const pos = &expression->base.source_position;
7396 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7399 if (expression->kind == EXPR_REFERENCE) {
7400 reference_expression_t *reference = &expression->reference;
7401 if (reference->entity->kind == ENTITY_FUNCTION &&
7402 reference->entity->function.btk != bk_none)
7403 handle_builtin_argument_restrictions(call);
7410 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7412 static bool same_compound_type(const type_t *type1, const type_t *type2)
7415 is_type_compound(type1) &&
7416 type1->kind == type2->kind &&
7417 type1->compound.compound == type2->compound.compound;
7420 static expression_t const *get_reference_address(expression_t const *expr)
7422 bool regular_take_address = true;
7424 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7425 expr = expr->unary.value;
7427 regular_take_address = false;
7430 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7433 expr = expr->unary.value;
7436 if (expr->kind != EXPR_REFERENCE)
7439 /* special case for functions which are automatically converted to a
7440 * pointer to function without an extra TAKE_ADDRESS operation */
7441 if (!regular_take_address &&
7442 expr->reference.entity->kind != ENTITY_FUNCTION) {
7449 static void warn_reference_address_as_bool(expression_t const* expr)
7451 expr = get_reference_address(expr);
7453 source_position_t const *const pos = &expr->base.source_position;
7454 entity_t const *const ent = expr->reference.entity;
7455 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7459 static void warn_assignment_in_condition(const expression_t *const expr)
7461 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7463 if (expr->base.parenthesized)
7465 source_position_t const *const pos = &expr->base.source_position;
7466 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7469 static void semantic_condition(expression_t const *const expr,
7470 char const *const context)
7472 type_t *const type = skip_typeref(expr->base.type);
7473 if (is_type_scalar(type)) {
7474 warn_reference_address_as_bool(expr);
7475 warn_assignment_in_condition(expr);
7476 } else if (is_type_valid(type)) {
7477 errorf(&expr->base.source_position,
7478 "%s must have scalar type", context);
7483 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7485 * @param expression the conditional expression
7487 static expression_t *parse_conditional_expression(expression_t *expression)
7489 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7491 conditional_expression_t *conditional = &result->conditional;
7492 conditional->condition = expression;
7495 add_anchor_token(':');
7497 /* §6.5.15:2 The first operand shall have scalar type. */
7498 semantic_condition(expression, "condition of conditional operator");
7500 expression_t *true_expression = expression;
7501 bool gnu_cond = false;
7502 if (GNU_MODE && token.type == ':') {
7505 true_expression = parse_expression();
7507 rem_anchor_token(':');
7508 expect(':', end_error);
7510 expression_t *false_expression =
7511 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7513 type_t *const orig_true_type = true_expression->base.type;
7514 type_t *const orig_false_type = false_expression->base.type;
7515 type_t *const true_type = skip_typeref(orig_true_type);
7516 type_t *const false_type = skip_typeref(orig_false_type);
7519 source_position_t const *const pos = &conditional->base.source_position;
7520 type_t *result_type;
7521 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7522 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7523 /* ISO/IEC 14882:1998(E) §5.16:2 */
7524 if (true_expression->kind == EXPR_UNARY_THROW) {
7525 result_type = false_type;
7526 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7527 result_type = true_type;
7529 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7530 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7531 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7533 result_type = type_void;
7535 } else if (is_type_arithmetic(true_type)
7536 && is_type_arithmetic(false_type)) {
7537 result_type = semantic_arithmetic(true_type, false_type);
7538 } else if (same_compound_type(true_type, false_type)) {
7539 /* just take 1 of the 2 types */
7540 result_type = true_type;
7541 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7542 type_t *pointer_type;
7544 expression_t *other_expression;
7545 if (is_type_pointer(true_type) &&
7546 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7547 pointer_type = true_type;
7548 other_type = false_type;
7549 other_expression = false_expression;
7551 pointer_type = false_type;
7552 other_type = true_type;
7553 other_expression = true_expression;
7556 if (is_null_pointer_constant(other_expression)) {
7557 result_type = pointer_type;
7558 } else if (is_type_pointer(other_type)) {
7559 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7560 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7563 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7564 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7566 } else if (types_compatible(get_unqualified_type(to1),
7567 get_unqualified_type(to2))) {
7570 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7574 type_t *const type =
7575 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7576 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7577 } else if (is_type_integer(other_type)) {
7578 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7579 result_type = pointer_type;
7581 goto types_incompatible;
7585 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7586 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7588 result_type = type_error_type;
7591 conditional->true_expression
7592 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7593 conditional->false_expression
7594 = create_implicit_cast(false_expression, result_type);
7595 conditional->base.type = result_type;
7600 * Parse an extension expression.
7602 static expression_t *parse_extension(void)
7605 expression_t *expression = parse_subexpression(PREC_UNARY);
7611 * Parse a __builtin_classify_type() expression.
7613 static expression_t *parse_builtin_classify_type(void)
7615 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7616 result->base.type = type_int;
7618 eat(T___builtin_classify_type);
7620 expect('(', end_error);
7621 add_anchor_token(')');
7622 expression_t *expression = parse_expression();
7623 rem_anchor_token(')');
7624 expect(')', end_error);
7625 result->classify_type.type_expression = expression;
7629 return create_invalid_expression();
7633 * Parse a delete expression
7634 * ISO/IEC 14882:1998(E) §5.3.5
7636 static expression_t *parse_delete(void)
7638 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7639 result->base.type = type_void;
7644 result->kind = EXPR_UNARY_DELETE_ARRAY;
7645 expect(']', end_error);
7649 expression_t *const value = parse_subexpression(PREC_CAST);
7650 result->unary.value = value;
7652 type_t *const type = skip_typeref(value->base.type);
7653 if (!is_type_pointer(type)) {
7654 if (is_type_valid(type)) {
7655 errorf(&value->base.source_position,
7656 "operand of delete must have pointer type");
7658 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7659 source_position_t const *const pos = &value->base.source_position;
7660 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7667 * Parse a throw expression
7668 * ISO/IEC 14882:1998(E) §15:1
7670 static expression_t *parse_throw(void)
7672 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7673 result->base.type = type_void;
7677 expression_t *value = NULL;
7678 switch (token.type) {
7680 value = parse_assignment_expression();
7681 /* ISO/IEC 14882:1998(E) §15.1:3 */
7682 type_t *const orig_type = value->base.type;
7683 type_t *const type = skip_typeref(orig_type);
7684 if (is_type_incomplete(type)) {
7685 errorf(&value->base.source_position,
7686 "cannot throw object of incomplete type '%T'", orig_type);
7687 } else if (is_type_pointer(type)) {
7688 type_t *const points_to = skip_typeref(type->pointer.points_to);
7689 if (is_type_incomplete(points_to) &&
7690 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7691 errorf(&value->base.source_position,
7692 "cannot throw pointer to incomplete type '%T'", orig_type);
7700 result->unary.value = value;
7705 static bool check_pointer_arithmetic(const source_position_t *source_position,
7706 type_t *pointer_type,
7707 type_t *orig_pointer_type)
7709 type_t *points_to = pointer_type->pointer.points_to;
7710 points_to = skip_typeref(points_to);
7712 if (is_type_incomplete(points_to)) {
7713 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7714 errorf(source_position,
7715 "arithmetic with pointer to incomplete type '%T' not allowed",
7719 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7721 } else if (is_type_function(points_to)) {
7723 errorf(source_position,
7724 "arithmetic with pointer to function type '%T' not allowed",
7728 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7734 static bool is_lvalue(const expression_t *expression)
7736 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7737 switch (expression->kind) {
7738 case EXPR_ARRAY_ACCESS:
7739 case EXPR_COMPOUND_LITERAL:
7740 case EXPR_REFERENCE:
7742 case EXPR_UNARY_DEREFERENCE:
7746 type_t *type = skip_typeref(expression->base.type);
7748 /* ISO/IEC 14882:1998(E) §3.10:3 */
7749 is_type_reference(type) ||
7750 /* Claim it is an lvalue, if the type is invalid. There was a parse
7751 * error before, which maybe prevented properly recognizing it as
7753 !is_type_valid(type);
7758 static void semantic_incdec(unary_expression_t *expression)
7760 type_t *const orig_type = expression->value->base.type;
7761 type_t *const type = skip_typeref(orig_type);
7762 if (is_type_pointer(type)) {
7763 if (!check_pointer_arithmetic(&expression->base.source_position,
7767 } else if (!is_type_real(type) && is_type_valid(type)) {
7768 /* TODO: improve error message */
7769 errorf(&expression->base.source_position,
7770 "operation needs an arithmetic or pointer type");
7773 if (!is_lvalue(expression->value)) {
7774 /* TODO: improve error message */
7775 errorf(&expression->base.source_position, "lvalue required as operand");
7777 expression->base.type = orig_type;
7780 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7782 type_t *const orig_type = expression->value->base.type;
7783 type_t *const type = skip_typeref(orig_type);
7784 if (!is_type_arithmetic(type)) {
7785 if (is_type_valid(type)) {
7786 /* TODO: improve error message */
7787 errorf(&expression->base.source_position,
7788 "operation needs an arithmetic type");
7793 expression->base.type = orig_type;
7796 static void semantic_unexpr_plus(unary_expression_t *expression)
7798 semantic_unexpr_arithmetic(expression);
7799 source_position_t const *const pos = &expression->base.source_position;
7800 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7803 static void semantic_not(unary_expression_t *expression)
7805 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7806 semantic_condition(expression->value, "operand of !");
7807 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7810 static void semantic_unexpr_integer(unary_expression_t *expression)
7812 type_t *const orig_type = expression->value->base.type;
7813 type_t *const type = skip_typeref(orig_type);
7814 if (!is_type_integer(type)) {
7815 if (is_type_valid(type)) {
7816 errorf(&expression->base.source_position,
7817 "operand of ~ must be of integer type");
7822 expression->base.type = orig_type;
7825 static void semantic_dereference(unary_expression_t *expression)
7827 type_t *const orig_type = expression->value->base.type;
7828 type_t *const type = skip_typeref(orig_type);
7829 if (!is_type_pointer(type)) {
7830 if (is_type_valid(type)) {
7831 errorf(&expression->base.source_position,
7832 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7837 type_t *result_type = type->pointer.points_to;
7838 result_type = automatic_type_conversion(result_type);
7839 expression->base.type = result_type;
7843 * Record that an address is taken (expression represents an lvalue).
7845 * @param expression the expression
7846 * @param may_be_register if true, the expression might be an register
7848 static void set_address_taken(expression_t *expression, bool may_be_register)
7850 if (expression->kind != EXPR_REFERENCE)
7853 entity_t *const entity = expression->reference.entity;
7855 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7858 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7859 && !may_be_register) {
7860 source_position_t const *const pos = &expression->base.source_position;
7861 errorf(pos, "address of register '%N' requested", entity);
7864 if (entity->kind == ENTITY_VARIABLE) {
7865 entity->variable.address_taken = true;
7867 assert(entity->kind == ENTITY_PARAMETER);
7868 entity->parameter.address_taken = true;
7873 * Check the semantic of the address taken expression.
7875 static void semantic_take_addr(unary_expression_t *expression)
7877 expression_t *value = expression->value;
7878 value->base.type = revert_automatic_type_conversion(value);
7880 type_t *orig_type = value->base.type;
7881 type_t *type = skip_typeref(orig_type);
7882 if (!is_type_valid(type))
7886 if (!is_lvalue(value)) {
7887 errorf(&expression->base.source_position, "'&' requires an lvalue");
7889 if (type->kind == TYPE_BITFIELD) {
7890 errorf(&expression->base.source_position,
7891 "'&' not allowed on object with bitfield type '%T'",
7895 set_address_taken(value, false);
7897 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7900 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7901 static expression_t *parse_##unexpression_type(void) \
7903 expression_t *unary_expression \
7904 = allocate_expression_zero(unexpression_type); \
7906 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7908 sfunc(&unary_expression->unary); \
7910 return unary_expression; \
7913 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7914 semantic_unexpr_arithmetic)
7915 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7916 semantic_unexpr_plus)
7917 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7919 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7920 semantic_dereference)
7921 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7923 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7924 semantic_unexpr_integer)
7925 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7927 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7930 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7932 static expression_t *parse_##unexpression_type(expression_t *left) \
7934 expression_t *unary_expression \
7935 = allocate_expression_zero(unexpression_type); \
7937 unary_expression->unary.value = left; \
7939 sfunc(&unary_expression->unary); \
7941 return unary_expression; \
7944 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7945 EXPR_UNARY_POSTFIX_INCREMENT,
7947 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7948 EXPR_UNARY_POSTFIX_DECREMENT,
7951 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7953 /* TODO: handle complex + imaginary types */
7955 type_left = get_unqualified_type(type_left);
7956 type_right = get_unqualified_type(type_right);
7958 /* §6.3.1.8 Usual arithmetic conversions */
7959 if (type_left == type_long_double || type_right == type_long_double) {
7960 return type_long_double;
7961 } else if (type_left == type_double || type_right == type_double) {
7963 } else if (type_left == type_float || type_right == type_float) {
7967 type_left = promote_integer(type_left);
7968 type_right = promote_integer(type_right);
7970 if (type_left == type_right)
7973 bool const signed_left = is_type_signed(type_left);
7974 bool const signed_right = is_type_signed(type_right);
7975 int const rank_left = get_rank(type_left);
7976 int const rank_right = get_rank(type_right);
7978 if (signed_left == signed_right)
7979 return rank_left >= rank_right ? type_left : type_right;
7988 u_rank = rank_right;
7989 u_type = type_right;
7991 s_rank = rank_right;
7992 s_type = type_right;
7997 if (u_rank >= s_rank)
8000 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8002 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8003 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8007 case ATOMIC_TYPE_INT: return type_unsigned_int;
8008 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8009 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8011 default: panic("invalid atomic type");
8016 * Check the semantic restrictions for a binary expression.
8018 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8020 expression_t *const left = expression->left;
8021 expression_t *const right = expression->right;
8022 type_t *const orig_type_left = left->base.type;
8023 type_t *const orig_type_right = right->base.type;
8024 type_t *const type_left = skip_typeref(orig_type_left);
8025 type_t *const type_right = skip_typeref(orig_type_right);
8027 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8028 /* TODO: improve error message */
8029 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8030 errorf(&expression->base.source_position,
8031 "operation needs arithmetic types");
8036 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8037 expression->left = create_implicit_cast(left, arithmetic_type);
8038 expression->right = create_implicit_cast(right, arithmetic_type);
8039 expression->base.type = arithmetic_type;
8042 static void semantic_binexpr_integer(binary_expression_t *const expression)
8044 expression_t *const left = expression->left;
8045 expression_t *const right = expression->right;
8046 type_t *const orig_type_left = left->base.type;
8047 type_t *const orig_type_right = right->base.type;
8048 type_t *const type_left = skip_typeref(orig_type_left);
8049 type_t *const type_right = skip_typeref(orig_type_right);
8051 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8052 /* TODO: improve error message */
8053 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8054 errorf(&expression->base.source_position,
8055 "operation needs integer types");
8060 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8061 expression->left = create_implicit_cast(left, result_type);
8062 expression->right = create_implicit_cast(right, result_type);
8063 expression->base.type = result_type;
8066 static void warn_div_by_zero(binary_expression_t const *const expression)
8068 if (!is_type_integer(expression->base.type))
8071 expression_t const *const right = expression->right;
8072 /* The type of the right operand can be different for /= */
8073 if (is_type_integer(right->base.type) &&
8074 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8075 !fold_constant_to_bool(right)) {
8076 source_position_t const *const pos = &expression->base.source_position;
8077 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8082 * Check the semantic restrictions for a div/mod expression.
8084 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8086 semantic_binexpr_arithmetic(expression);
8087 warn_div_by_zero(expression);
8090 static void warn_addsub_in_shift(const expression_t *const expr)
8092 if (expr->base.parenthesized)
8096 switch (expr->kind) {
8097 case EXPR_BINARY_ADD: op = '+'; break;
8098 case EXPR_BINARY_SUB: op = '-'; break;
8102 source_position_t const *const pos = &expr->base.source_position;
8103 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8106 static bool semantic_shift(binary_expression_t *expression)
8108 expression_t *const left = expression->left;
8109 expression_t *const right = expression->right;
8110 type_t *const orig_type_left = left->base.type;
8111 type_t *const orig_type_right = right->base.type;
8112 type_t * type_left = skip_typeref(orig_type_left);
8113 type_t * type_right = skip_typeref(orig_type_right);
8115 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8116 /* TODO: improve error message */
8117 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8118 errorf(&expression->base.source_position,
8119 "operands of shift operation must have integer types");
8124 type_left = promote_integer(type_left);
8126 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8127 source_position_t const *const pos = &right->base.source_position;
8128 long const count = fold_constant_to_int(right);
8130 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8131 } else if ((unsigned long)count >=
8132 get_atomic_type_size(type_left->atomic.akind) * 8) {
8133 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8137 type_right = promote_integer(type_right);
8138 expression->right = create_implicit_cast(right, type_right);
8143 static void semantic_shift_op(binary_expression_t *expression)
8145 expression_t *const left = expression->left;
8146 expression_t *const right = expression->right;
8148 if (!semantic_shift(expression))
8151 warn_addsub_in_shift(left);
8152 warn_addsub_in_shift(right);
8154 type_t *const orig_type_left = left->base.type;
8155 type_t * type_left = skip_typeref(orig_type_left);
8157 type_left = promote_integer(type_left);
8158 expression->left = create_implicit_cast(left, type_left);
8159 expression->base.type = type_left;
8162 static void semantic_add(binary_expression_t *expression)
8164 expression_t *const left = expression->left;
8165 expression_t *const right = expression->right;
8166 type_t *const orig_type_left = left->base.type;
8167 type_t *const orig_type_right = right->base.type;
8168 type_t *const type_left = skip_typeref(orig_type_left);
8169 type_t *const type_right = skip_typeref(orig_type_right);
8172 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8173 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8174 expression->left = create_implicit_cast(left, arithmetic_type);
8175 expression->right = create_implicit_cast(right, arithmetic_type);
8176 expression->base.type = arithmetic_type;
8177 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8178 check_pointer_arithmetic(&expression->base.source_position,
8179 type_left, orig_type_left);
8180 expression->base.type = type_left;
8181 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8182 check_pointer_arithmetic(&expression->base.source_position,
8183 type_right, orig_type_right);
8184 expression->base.type = type_right;
8185 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8186 errorf(&expression->base.source_position,
8187 "invalid operands to binary + ('%T', '%T')",
8188 orig_type_left, orig_type_right);
8192 static void semantic_sub(binary_expression_t *expression)
8194 expression_t *const left = expression->left;
8195 expression_t *const right = expression->right;
8196 type_t *const orig_type_left = left->base.type;
8197 type_t *const orig_type_right = right->base.type;
8198 type_t *const type_left = skip_typeref(orig_type_left);
8199 type_t *const type_right = skip_typeref(orig_type_right);
8200 source_position_t const *const pos = &expression->base.source_position;
8203 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8204 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8205 expression->left = create_implicit_cast(left, arithmetic_type);
8206 expression->right = create_implicit_cast(right, arithmetic_type);
8207 expression->base.type = arithmetic_type;
8208 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8209 check_pointer_arithmetic(&expression->base.source_position,
8210 type_left, orig_type_left);
8211 expression->base.type = type_left;
8212 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8213 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8214 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8215 if (!types_compatible(unqual_left, unqual_right)) {
8217 "subtracting pointers to incompatible types '%T' and '%T'",
8218 orig_type_left, orig_type_right);
8219 } else if (!is_type_object(unqual_left)) {
8220 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8221 errorf(pos, "subtracting pointers to non-object types '%T'",
8224 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8227 expression->base.type = type_ptrdiff_t;
8228 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8229 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8230 orig_type_left, orig_type_right);
8234 static void warn_string_literal_address(expression_t const* expr)
8236 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8237 expr = expr->unary.value;
8238 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8240 expr = expr->unary.value;
8243 if (expr->kind == EXPR_STRING_LITERAL
8244 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8245 source_position_t const *const pos = &expr->base.source_position;
8246 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8250 static bool maybe_negative(expression_t const *const expr)
8252 switch (is_constant_expression(expr)) {
8253 case EXPR_CLASS_ERROR: return false;
8254 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8255 default: return true;
8259 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8261 warn_string_literal_address(expr);
8263 expression_t const* const ref = get_reference_address(expr);
8264 if (ref != NULL && is_null_pointer_constant(other)) {
8265 entity_t const *const ent = ref->reference.entity;
8266 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8269 if (!expr->base.parenthesized) {
8270 switch (expr->base.kind) {
8271 case EXPR_BINARY_LESS:
8272 case EXPR_BINARY_GREATER:
8273 case EXPR_BINARY_LESSEQUAL:
8274 case EXPR_BINARY_GREATEREQUAL:
8275 case EXPR_BINARY_NOTEQUAL:
8276 case EXPR_BINARY_EQUAL:
8277 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8286 * Check the semantics of comparison expressions.
8288 * @param expression The expression to check.
8290 static void semantic_comparison(binary_expression_t *expression)
8292 source_position_t const *const pos = &expression->base.source_position;
8293 expression_t *const left = expression->left;
8294 expression_t *const right = expression->right;
8296 warn_comparison(pos, left, right);
8297 warn_comparison(pos, right, left);
8299 type_t *orig_type_left = left->base.type;
8300 type_t *orig_type_right = right->base.type;
8301 type_t *type_left = skip_typeref(orig_type_left);
8302 type_t *type_right = skip_typeref(orig_type_right);
8304 /* TODO non-arithmetic types */
8305 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8306 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8308 /* test for signed vs unsigned compares */
8309 if (is_type_integer(arithmetic_type)) {
8310 bool const signed_left = is_type_signed(type_left);
8311 bool const signed_right = is_type_signed(type_right);
8312 if (signed_left != signed_right) {
8313 /* FIXME long long needs better const folding magic */
8314 /* TODO check whether constant value can be represented by other type */
8315 if ((signed_left && maybe_negative(left)) ||
8316 (signed_right && maybe_negative(right))) {
8317 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8322 expression->left = create_implicit_cast(left, arithmetic_type);
8323 expression->right = create_implicit_cast(right, arithmetic_type);
8324 expression->base.type = arithmetic_type;
8325 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8326 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8327 is_type_float(arithmetic_type)) {
8328 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8330 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8331 /* TODO check compatibility */
8332 } else if (is_type_pointer(type_left)) {
8333 expression->right = create_implicit_cast(right, type_left);
8334 } else if (is_type_pointer(type_right)) {
8335 expression->left = create_implicit_cast(left, type_right);
8336 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8337 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8339 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8343 * Checks if a compound type has constant fields.
8345 static bool has_const_fields(const compound_type_t *type)
8347 compound_t *compound = type->compound;
8348 entity_t *entry = compound->members.entities;
8350 for (; entry != NULL; entry = entry->base.next) {
8351 if (!is_declaration(entry))
8354 const type_t *decl_type = skip_typeref(entry->declaration.type);
8355 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8362 static bool is_valid_assignment_lhs(expression_t const* const left)
8364 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8365 type_t *const type_left = skip_typeref(orig_type_left);
8367 if (!is_lvalue(left)) {
8368 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8373 if (left->kind == EXPR_REFERENCE
8374 && left->reference.entity->kind == ENTITY_FUNCTION) {
8375 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8379 if (is_type_array(type_left)) {
8380 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8383 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8384 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8388 if (is_type_incomplete(type_left)) {
8389 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8390 left, orig_type_left);
8393 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8394 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8395 left, orig_type_left);
8402 static void semantic_arithmetic_assign(binary_expression_t *expression)
8404 expression_t *left = expression->left;
8405 expression_t *right = expression->right;
8406 type_t *orig_type_left = left->base.type;
8407 type_t *orig_type_right = right->base.type;
8409 if (!is_valid_assignment_lhs(left))
8412 type_t *type_left = skip_typeref(orig_type_left);
8413 type_t *type_right = skip_typeref(orig_type_right);
8415 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8416 /* TODO: improve error message */
8417 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8418 errorf(&expression->base.source_position,
8419 "operation needs arithmetic types");
8424 /* combined instructions are tricky. We can't create an implicit cast on
8425 * the left side, because we need the uncasted form for the store.
8426 * The ast2firm pass has to know that left_type must be right_type
8427 * for the arithmetic operation and create a cast by itself */
8428 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8429 expression->right = create_implicit_cast(right, arithmetic_type);
8430 expression->base.type = type_left;
8433 static void semantic_divmod_assign(binary_expression_t *expression)
8435 semantic_arithmetic_assign(expression);
8436 warn_div_by_zero(expression);
8439 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8441 expression_t *const left = expression->left;
8442 expression_t *const right = expression->right;
8443 type_t *const orig_type_left = left->base.type;
8444 type_t *const orig_type_right = right->base.type;
8445 type_t *const type_left = skip_typeref(orig_type_left);
8446 type_t *const type_right = skip_typeref(orig_type_right);
8448 if (!is_valid_assignment_lhs(left))
8451 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8452 /* combined instructions are tricky. We can't create an implicit cast on
8453 * the left side, because we need the uncasted form for the store.
8454 * The ast2firm pass has to know that left_type must be right_type
8455 * for the arithmetic operation and create a cast by itself */
8456 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8457 expression->right = create_implicit_cast(right, arithmetic_type);
8458 expression->base.type = type_left;
8459 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8460 check_pointer_arithmetic(&expression->base.source_position,
8461 type_left, orig_type_left);
8462 expression->base.type = type_left;
8463 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8464 errorf(&expression->base.source_position,
8465 "incompatible types '%T' and '%T' in assignment",
8466 orig_type_left, orig_type_right);
8470 static void semantic_integer_assign(binary_expression_t *expression)
8472 expression_t *left = expression->left;
8473 expression_t *right = expression->right;
8474 type_t *orig_type_left = left->base.type;
8475 type_t *orig_type_right = right->base.type;
8477 if (!is_valid_assignment_lhs(left))
8480 type_t *type_left = skip_typeref(orig_type_left);
8481 type_t *type_right = skip_typeref(orig_type_right);
8483 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8484 /* TODO: improve error message */
8485 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8486 errorf(&expression->base.source_position,
8487 "operation needs integer types");
8492 /* combined instructions are tricky. We can't create an implicit cast on
8493 * the left side, because we need the uncasted form for the store.
8494 * The ast2firm pass has to know that left_type must be right_type
8495 * for the arithmetic operation and create a cast by itself */
8496 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8497 expression->right = create_implicit_cast(right, arithmetic_type);
8498 expression->base.type = type_left;
8501 static void semantic_shift_assign(binary_expression_t *expression)
8503 expression_t *left = expression->left;
8505 if (!is_valid_assignment_lhs(left))
8508 if (!semantic_shift(expression))
8511 expression->base.type = skip_typeref(left->base.type);
8514 static void warn_logical_and_within_or(const expression_t *const expr)
8516 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8518 if (expr->base.parenthesized)
8520 source_position_t const *const pos = &expr->base.source_position;
8521 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8525 * Check the semantic restrictions of a logical expression.
8527 static void semantic_logical_op(binary_expression_t *expression)
8529 /* §6.5.13:2 Each of the operands shall have scalar type.
8530 * §6.5.14:2 Each of the operands shall have scalar type. */
8531 semantic_condition(expression->left, "left operand of logical operator");
8532 semantic_condition(expression->right, "right operand of logical operator");
8533 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8534 warn_logical_and_within_or(expression->left);
8535 warn_logical_and_within_or(expression->right);
8537 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8541 * Check the semantic restrictions of a binary assign expression.
8543 static void semantic_binexpr_assign(binary_expression_t *expression)
8545 expression_t *left = expression->left;
8546 type_t *orig_type_left = left->base.type;
8548 if (!is_valid_assignment_lhs(left))
8551 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8552 report_assign_error(error, orig_type_left, expression->right,
8553 "assignment", &left->base.source_position);
8554 expression->right = create_implicit_cast(expression->right, orig_type_left);
8555 expression->base.type = orig_type_left;
8559 * Determine if the outermost operation (or parts thereof) of the given
8560 * expression has no effect in order to generate a warning about this fact.
8561 * Therefore in some cases this only examines some of the operands of the
8562 * expression (see comments in the function and examples below).
8564 * f() + 23; // warning, because + has no effect
8565 * x || f(); // no warning, because x controls execution of f()
8566 * x ? y : f(); // warning, because y has no effect
8567 * (void)x; // no warning to be able to suppress the warning
8568 * This function can NOT be used for an "expression has definitely no effect"-
8570 static bool expression_has_effect(const expression_t *const expr)
8572 switch (expr->kind) {
8573 case EXPR_UNKNOWN: break;
8574 case EXPR_INVALID: return true; /* do NOT warn */
8575 case EXPR_REFERENCE: return false;
8576 case EXPR_REFERENCE_ENUM_VALUE: return false;
8577 case EXPR_LABEL_ADDRESS: return false;
8579 /* suppress the warning for microsoft __noop operations */
8580 case EXPR_LITERAL_MS_NOOP: return true;
8581 case EXPR_LITERAL_BOOLEAN:
8582 case EXPR_LITERAL_CHARACTER:
8583 case EXPR_LITERAL_WIDE_CHARACTER:
8584 case EXPR_LITERAL_INTEGER:
8585 case EXPR_LITERAL_INTEGER_OCTAL:
8586 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8587 case EXPR_LITERAL_FLOATINGPOINT:
8588 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8589 case EXPR_STRING_LITERAL: return false;
8590 case EXPR_WIDE_STRING_LITERAL: return false;
8593 const call_expression_t *const call = &expr->call;
8594 if (call->function->kind != EXPR_REFERENCE)
8597 switch (call->function->reference.entity->function.btk) {
8598 /* FIXME: which builtins have no effect? */
8599 default: return true;
8603 /* Generate the warning if either the left or right hand side of a
8604 * conditional expression has no effect */
8605 case EXPR_CONDITIONAL: {
8606 conditional_expression_t const *const cond = &expr->conditional;
8607 expression_t const *const t = cond->true_expression;
8609 (t == NULL || expression_has_effect(t)) &&
8610 expression_has_effect(cond->false_expression);
8613 case EXPR_SELECT: return false;
8614 case EXPR_ARRAY_ACCESS: return false;
8615 case EXPR_SIZEOF: return false;
8616 case EXPR_CLASSIFY_TYPE: return false;
8617 case EXPR_ALIGNOF: return false;
8619 case EXPR_FUNCNAME: return false;
8620 case EXPR_BUILTIN_CONSTANT_P: return false;
8621 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8622 case EXPR_OFFSETOF: return false;
8623 case EXPR_VA_START: return true;
8624 case EXPR_VA_ARG: return true;
8625 case EXPR_VA_COPY: return true;
8626 case EXPR_STATEMENT: return true; // TODO
8627 case EXPR_COMPOUND_LITERAL: return false;
8629 case EXPR_UNARY_NEGATE: return false;
8630 case EXPR_UNARY_PLUS: return false;
8631 case EXPR_UNARY_BITWISE_NEGATE: return false;
8632 case EXPR_UNARY_NOT: return false;
8633 case EXPR_UNARY_DEREFERENCE: return false;
8634 case EXPR_UNARY_TAKE_ADDRESS: return false;
8635 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8636 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8637 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8638 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8640 /* Treat void casts as if they have an effect in order to being able to
8641 * suppress the warning */
8642 case EXPR_UNARY_CAST: {
8643 type_t *const type = skip_typeref(expr->base.type);
8644 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8647 case EXPR_UNARY_CAST_IMPLICIT: return true;
8648 case EXPR_UNARY_ASSUME: return true;
8649 case EXPR_UNARY_DELETE: return true;
8650 case EXPR_UNARY_DELETE_ARRAY: return true;
8651 case EXPR_UNARY_THROW: return true;
8653 case EXPR_BINARY_ADD: return false;
8654 case EXPR_BINARY_SUB: return false;
8655 case EXPR_BINARY_MUL: return false;
8656 case EXPR_BINARY_DIV: return false;
8657 case EXPR_BINARY_MOD: return false;
8658 case EXPR_BINARY_EQUAL: return false;
8659 case EXPR_BINARY_NOTEQUAL: return false;
8660 case EXPR_BINARY_LESS: return false;
8661 case EXPR_BINARY_LESSEQUAL: return false;
8662 case EXPR_BINARY_GREATER: return false;
8663 case EXPR_BINARY_GREATEREQUAL: return false;
8664 case EXPR_BINARY_BITWISE_AND: return false;
8665 case EXPR_BINARY_BITWISE_OR: return false;
8666 case EXPR_BINARY_BITWISE_XOR: return false;
8667 case EXPR_BINARY_SHIFTLEFT: return false;
8668 case EXPR_BINARY_SHIFTRIGHT: return false;
8669 case EXPR_BINARY_ASSIGN: return true;
8670 case EXPR_BINARY_MUL_ASSIGN: return true;
8671 case EXPR_BINARY_DIV_ASSIGN: return true;
8672 case EXPR_BINARY_MOD_ASSIGN: return true;
8673 case EXPR_BINARY_ADD_ASSIGN: return true;
8674 case EXPR_BINARY_SUB_ASSIGN: return true;
8675 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8676 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8677 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8678 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8679 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8681 /* Only examine the right hand side of && and ||, because the left hand
8682 * side already has the effect of controlling the execution of the right
8684 case EXPR_BINARY_LOGICAL_AND:
8685 case EXPR_BINARY_LOGICAL_OR:
8686 /* Only examine the right hand side of a comma expression, because the left
8687 * hand side has a separate warning */
8688 case EXPR_BINARY_COMMA:
8689 return expression_has_effect(expr->binary.right);
8691 case EXPR_BINARY_ISGREATER: return false;
8692 case EXPR_BINARY_ISGREATEREQUAL: return false;
8693 case EXPR_BINARY_ISLESS: return false;
8694 case EXPR_BINARY_ISLESSEQUAL: return false;
8695 case EXPR_BINARY_ISLESSGREATER: return false;
8696 case EXPR_BINARY_ISUNORDERED: return false;
8699 internal_errorf(HERE, "unexpected expression");
8702 static void semantic_comma(binary_expression_t *expression)
8704 const expression_t *const left = expression->left;
8705 if (!expression_has_effect(left)) {
8706 source_position_t const *const pos = &left->base.source_position;
8707 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8709 expression->base.type = expression->right->base.type;
8713 * @param prec_r precedence of the right operand
8715 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8716 static expression_t *parse_##binexpression_type(expression_t *left) \
8718 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8719 binexpr->binary.left = left; \
8722 expression_t *right = parse_subexpression(prec_r); \
8724 binexpr->binary.right = right; \
8725 sfunc(&binexpr->binary); \
8730 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8731 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8732 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8733 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8734 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8735 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8736 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8737 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8738 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8739 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8740 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8741 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8742 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8743 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8744 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8745 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8746 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8747 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8748 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8749 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8750 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8751 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8752 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8753 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8754 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8755 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8756 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8757 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8758 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8759 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8762 static expression_t *parse_subexpression(precedence_t precedence)
8764 if (token.type < 0) {
8765 return expected_expression_error();
8768 expression_parser_function_t *parser
8769 = &expression_parsers[token.type];
8772 if (parser->parser != NULL) {
8773 left = parser->parser();
8775 left = parse_primary_expression();
8777 assert(left != NULL);
8780 if (token.type < 0) {
8781 return expected_expression_error();
8784 parser = &expression_parsers[token.type];
8785 if (parser->infix_parser == NULL)
8787 if (parser->infix_precedence < precedence)
8790 left = parser->infix_parser(left);
8792 assert(left != NULL);
8793 assert(left->kind != EXPR_UNKNOWN);
8800 * Parse an expression.
8802 static expression_t *parse_expression(void)
8804 return parse_subexpression(PREC_EXPRESSION);
8808 * Register a parser for a prefix-like operator.
8810 * @param parser the parser function
8811 * @param token_type the token type of the prefix token
8813 static void register_expression_parser(parse_expression_function parser,
8816 expression_parser_function_t *entry = &expression_parsers[token_type];
8818 if (entry->parser != NULL) {
8819 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8820 panic("trying to register multiple expression parsers for a token");
8822 entry->parser = parser;
8826 * Register a parser for an infix operator with given precedence.
8828 * @param parser the parser function
8829 * @param token_type the token type of the infix operator
8830 * @param precedence the precedence of the operator
8832 static void register_infix_parser(parse_expression_infix_function parser,
8833 int token_type, precedence_t precedence)
8835 expression_parser_function_t *entry = &expression_parsers[token_type];
8837 if (entry->infix_parser != NULL) {
8838 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8839 panic("trying to register multiple infix expression parsers for a "
8842 entry->infix_parser = parser;
8843 entry->infix_precedence = precedence;
8847 * Initialize the expression parsers.
8849 static void init_expression_parsers(void)
8851 memset(&expression_parsers, 0, sizeof(expression_parsers));
8853 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8854 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8855 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8856 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8857 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8858 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8859 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8860 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8861 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8862 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8863 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8864 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8865 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8866 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8867 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8868 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8869 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8870 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8871 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8872 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8873 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8874 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8875 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8876 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8877 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8878 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8879 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8880 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8881 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8882 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8883 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8884 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8885 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8886 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8887 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8888 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8889 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8891 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8892 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8893 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8894 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8895 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8896 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8897 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8898 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8899 register_expression_parser(parse_sizeof, T_sizeof);
8900 register_expression_parser(parse_alignof, T___alignof__);
8901 register_expression_parser(parse_extension, T___extension__);
8902 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8903 register_expression_parser(parse_delete, T_delete);
8904 register_expression_parser(parse_throw, T_throw);
8908 * Parse a asm statement arguments specification.
8910 static asm_argument_t *parse_asm_arguments(bool is_out)
8912 asm_argument_t *result = NULL;
8913 asm_argument_t **anchor = &result;
8915 while (token.type == T_STRING_LITERAL || token.type == '[') {
8916 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8917 memset(argument, 0, sizeof(argument[0]));
8920 if (token.type != T_IDENTIFIER) {
8921 parse_error_expected("while parsing asm argument",
8922 T_IDENTIFIER, NULL);
8925 argument->symbol = token.symbol;
8927 expect(']', end_error);
8930 argument->constraints = parse_string_literals();
8931 expect('(', end_error);
8932 add_anchor_token(')');
8933 expression_t *expression = parse_expression();
8934 rem_anchor_token(')');
8936 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8937 * change size or type representation (e.g. int -> long is ok, but
8938 * int -> float is not) */
8939 if (expression->kind == EXPR_UNARY_CAST) {
8940 type_t *const type = expression->base.type;
8941 type_kind_t const kind = type->kind;
8942 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8945 if (kind == TYPE_ATOMIC) {
8946 atomic_type_kind_t const akind = type->atomic.akind;
8947 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8948 size = get_atomic_type_size(akind);
8950 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8951 size = get_atomic_type_size(get_intptr_kind());
8955 expression_t *const value = expression->unary.value;
8956 type_t *const value_type = value->base.type;
8957 type_kind_t const value_kind = value_type->kind;
8959 unsigned value_flags;
8960 unsigned value_size;
8961 if (value_kind == TYPE_ATOMIC) {
8962 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8963 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8964 value_size = get_atomic_type_size(value_akind);
8965 } else if (value_kind == TYPE_POINTER) {
8966 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8967 value_size = get_atomic_type_size(get_intptr_kind());
8972 if (value_flags != flags || value_size != size)
8976 } while (expression->kind == EXPR_UNARY_CAST);
8980 if (!is_lvalue(expression)) {
8981 errorf(&expression->base.source_position,
8982 "asm output argument is not an lvalue");
8985 if (argument->constraints.begin[0] == '=')
8986 determine_lhs_ent(expression, NULL);
8988 mark_vars_read(expression, NULL);
8990 mark_vars_read(expression, NULL);
8992 argument->expression = expression;
8993 expect(')', end_error);
8995 set_address_taken(expression, true);
8998 anchor = &argument->next;
9010 * Parse a asm statement clobber specification.
9012 static asm_clobber_t *parse_asm_clobbers(void)
9014 asm_clobber_t *result = NULL;
9015 asm_clobber_t **anchor = &result;
9017 while (token.type == T_STRING_LITERAL) {
9018 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9019 clobber->clobber = parse_string_literals();
9022 anchor = &clobber->next;
9032 * Parse an asm statement.
9034 static statement_t *parse_asm_statement(void)
9036 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9037 asm_statement_t *asm_statement = &statement->asms;
9041 if (next_if(T_volatile))
9042 asm_statement->is_volatile = true;
9044 expect('(', end_error);
9045 add_anchor_token(')');
9046 if (token.type != T_STRING_LITERAL) {
9047 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9050 asm_statement->asm_text = parse_string_literals();
9052 add_anchor_token(':');
9053 if (!next_if(':')) {
9054 rem_anchor_token(':');
9058 asm_statement->outputs = parse_asm_arguments(true);
9059 if (!next_if(':')) {
9060 rem_anchor_token(':');
9064 asm_statement->inputs = parse_asm_arguments(false);
9065 if (!next_if(':')) {
9066 rem_anchor_token(':');
9069 rem_anchor_token(':');
9071 asm_statement->clobbers = parse_asm_clobbers();
9074 rem_anchor_token(')');
9075 expect(')', end_error);
9076 expect(';', end_error);
9078 if (asm_statement->outputs == NULL) {
9079 /* GCC: An 'asm' instruction without any output operands will be treated
9080 * identically to a volatile 'asm' instruction. */
9081 asm_statement->is_volatile = true;
9086 return create_invalid_statement();
9089 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9091 statement_t *inner_stmt;
9092 switch (token.type) {
9094 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9095 inner_stmt = create_invalid_statement();
9099 if (label->kind == STATEMENT_LABEL) {
9100 /* Eat an empty statement here, to avoid the warning about an empty
9101 * statement after a label. label:; is commonly used to have a label
9102 * before a closing brace. */
9103 inner_stmt = create_empty_statement();
9110 inner_stmt = parse_statement();
9111 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9112 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9113 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9114 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9122 * Parse a case statement.
9124 static statement_t *parse_case_statement(void)
9126 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9127 source_position_t *const pos = &statement->base.source_position;
9131 expression_t *const expression = parse_expression();
9132 statement->case_label.expression = expression;
9133 expression_classification_t const expr_class = is_constant_expression(expression);
9134 if (expr_class != EXPR_CLASS_CONSTANT) {
9135 if (expr_class != EXPR_CLASS_ERROR) {
9136 errorf(pos, "case label does not reduce to an integer constant");
9138 statement->case_label.is_bad = true;
9140 long const val = fold_constant_to_int(expression);
9141 statement->case_label.first_case = val;
9142 statement->case_label.last_case = val;
9146 if (next_if(T_DOTDOTDOT)) {
9147 expression_t *const end_range = parse_expression();
9148 statement->case_label.end_range = end_range;
9149 expression_classification_t const end_class = is_constant_expression(end_range);
9150 if (end_class != EXPR_CLASS_CONSTANT) {
9151 if (end_class != EXPR_CLASS_ERROR) {
9152 errorf(pos, "case range does not reduce to an integer constant");
9154 statement->case_label.is_bad = true;
9156 long const val = fold_constant_to_int(end_range);
9157 statement->case_label.last_case = val;
9159 if (val < statement->case_label.first_case) {
9160 statement->case_label.is_empty_range = true;
9161 warningf(WARN_OTHER, pos, "empty range specified");
9167 PUSH_PARENT(statement);
9169 expect(':', end_error);
9172 if (current_switch != NULL) {
9173 if (! statement->case_label.is_bad) {
9174 /* Check for duplicate case values */
9175 case_label_statement_t *c = &statement->case_label;
9176 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9177 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9180 if (c->last_case < l->first_case || c->first_case > l->last_case)
9183 errorf(pos, "duplicate case value (previously used %P)",
9184 &l->base.source_position);
9188 /* link all cases into the switch statement */
9189 if (current_switch->last_case == NULL) {
9190 current_switch->first_case = &statement->case_label;
9192 current_switch->last_case->next = &statement->case_label;
9194 current_switch->last_case = &statement->case_label;
9196 errorf(pos, "case label not within a switch statement");
9199 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9206 * Parse a default statement.
9208 static statement_t *parse_default_statement(void)
9210 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9214 PUSH_PARENT(statement);
9216 expect(':', end_error);
9219 if (current_switch != NULL) {
9220 const case_label_statement_t *def_label = current_switch->default_label;
9221 if (def_label != NULL) {
9222 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9224 current_switch->default_label = &statement->case_label;
9226 /* link all cases into the switch statement */
9227 if (current_switch->last_case == NULL) {
9228 current_switch->first_case = &statement->case_label;
9230 current_switch->last_case->next = &statement->case_label;
9232 current_switch->last_case = &statement->case_label;
9235 errorf(&statement->base.source_position,
9236 "'default' label not within a switch statement");
9239 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9246 * Parse a label statement.
9248 static statement_t *parse_label_statement(void)
9250 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9251 label_t *const label = get_label();
9252 statement->label.label = label;
9254 PUSH_PARENT(statement);
9256 /* if statement is already set then the label is defined twice,
9257 * otherwise it was just mentioned in a goto/local label declaration so far
9259 source_position_t const* const pos = &statement->base.source_position;
9260 if (label->statement != NULL) {
9261 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9263 label->base.source_position = *pos;
9264 label->statement = statement;
9269 statement->label.statement = parse_label_inner_statement(statement, "label");
9271 /* remember the labels in a list for later checking */
9272 *label_anchor = &statement->label;
9273 label_anchor = &statement->label.next;
9279 static statement_t *parse_inner_statement(void)
9281 statement_t *const stmt = parse_statement();
9282 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9283 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9284 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9285 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9291 * Parse an if statement.
9293 static statement_t *parse_if(void)
9295 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9299 PUSH_PARENT(statement);
9301 add_anchor_token('{');
9303 expect('(', end_error);
9304 add_anchor_token(')');
9305 expression_t *const expr = parse_expression();
9306 statement->ifs.condition = expr;
9307 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9309 semantic_condition(expr, "condition of 'if'-statment");
9310 mark_vars_read(expr, NULL);
9311 rem_anchor_token(')');
9312 expect(')', end_error);
9315 rem_anchor_token('{');
9317 add_anchor_token(T_else);
9318 statement_t *const true_stmt = parse_inner_statement();
9319 statement->ifs.true_statement = true_stmt;
9320 rem_anchor_token(T_else);
9322 if (next_if(T_else)) {
9323 statement->ifs.false_statement = parse_inner_statement();
9324 } else if (true_stmt->kind == STATEMENT_IF &&
9325 true_stmt->ifs.false_statement != NULL) {
9326 source_position_t const *const pos = &true_stmt->base.source_position;
9327 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9335 * Check that all enums are handled in a switch.
9337 * @param statement the switch statement to check
9339 static void check_enum_cases(const switch_statement_t *statement)
9341 if (!is_warn_on(WARN_SWITCH_ENUM))
9343 const type_t *type = skip_typeref(statement->expression->base.type);
9344 if (! is_type_enum(type))
9346 const enum_type_t *enumt = &type->enumt;
9348 /* if we have a default, no warnings */
9349 if (statement->default_label != NULL)
9352 /* FIXME: calculation of value should be done while parsing */
9353 /* TODO: quadratic algorithm here. Change to an n log n one */
9354 long last_value = -1;
9355 const entity_t *entry = enumt->enume->base.next;
9356 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9357 entry = entry->base.next) {
9358 const expression_t *expression = entry->enum_value.value;
9359 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9361 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9362 if (l->expression == NULL)
9364 if (l->first_case <= value && value <= l->last_case) {
9370 source_position_t const *const pos = &statement->base.source_position;
9371 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9378 * Parse a switch statement.
9380 static statement_t *parse_switch(void)
9382 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9386 PUSH_PARENT(statement);
9388 expect('(', end_error);
9389 add_anchor_token(')');
9390 expression_t *const expr = parse_expression();
9391 mark_vars_read(expr, NULL);
9392 type_t * type = skip_typeref(expr->base.type);
9393 if (is_type_integer(type)) {
9394 type = promote_integer(type);
9395 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9396 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9398 } else if (is_type_valid(type)) {
9399 errorf(&expr->base.source_position,
9400 "switch quantity is not an integer, but '%T'", type);
9401 type = type_error_type;
9403 statement->switchs.expression = create_implicit_cast(expr, type);
9404 expect(')', end_error);
9405 rem_anchor_token(')');
9407 switch_statement_t *rem = current_switch;
9408 current_switch = &statement->switchs;
9409 statement->switchs.body = parse_inner_statement();
9410 current_switch = rem;
9412 if (statement->switchs.default_label == NULL) {
9413 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9415 check_enum_cases(&statement->switchs);
9421 return create_invalid_statement();
9424 static statement_t *parse_loop_body(statement_t *const loop)
9426 statement_t *const rem = current_loop;
9427 current_loop = loop;
9429 statement_t *const body = parse_inner_statement();
9436 * Parse a while statement.
9438 static statement_t *parse_while(void)
9440 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9444 PUSH_PARENT(statement);
9446 expect('(', end_error);
9447 add_anchor_token(')');
9448 expression_t *const cond = parse_expression();
9449 statement->whiles.condition = cond;
9450 /* §6.8.5:2 The controlling expression of an iteration statement shall
9451 * have scalar type. */
9452 semantic_condition(cond, "condition of 'while'-statement");
9453 mark_vars_read(cond, NULL);
9454 rem_anchor_token(')');
9455 expect(')', end_error);
9457 statement->whiles.body = parse_loop_body(statement);
9463 return create_invalid_statement();
9467 * Parse a do statement.
9469 static statement_t *parse_do(void)
9471 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9475 PUSH_PARENT(statement);
9477 add_anchor_token(T_while);
9478 statement->do_while.body = parse_loop_body(statement);
9479 rem_anchor_token(T_while);
9481 expect(T_while, end_error);
9482 expect('(', end_error);
9483 add_anchor_token(')');
9484 expression_t *const cond = parse_expression();
9485 statement->do_while.condition = cond;
9486 /* §6.8.5:2 The controlling expression of an iteration statement shall
9487 * have scalar type. */
9488 semantic_condition(cond, "condition of 'do-while'-statement");
9489 mark_vars_read(cond, NULL);
9490 rem_anchor_token(')');
9491 expect(')', end_error);
9492 expect(';', end_error);
9498 return create_invalid_statement();
9502 * Parse a for statement.
9504 static statement_t *parse_for(void)
9506 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9510 expect('(', end_error1);
9511 add_anchor_token(')');
9513 PUSH_PARENT(statement);
9514 PUSH_SCOPE(&statement->fors.scope);
9519 } else if (is_declaration_specifier(&token)) {
9520 parse_declaration(record_entity, DECL_FLAGS_NONE);
9522 add_anchor_token(';');
9523 expression_t *const init = parse_expression();
9524 statement->fors.initialisation = init;
9525 mark_vars_read(init, ENT_ANY);
9526 if (!expression_has_effect(init)) {
9527 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9529 rem_anchor_token(';');
9530 expect(';', end_error2);
9535 if (token.type != ';') {
9536 add_anchor_token(';');
9537 expression_t *const cond = parse_expression();
9538 statement->fors.condition = cond;
9539 /* §6.8.5:2 The controlling expression of an iteration statement
9540 * shall have scalar type. */
9541 semantic_condition(cond, "condition of 'for'-statement");
9542 mark_vars_read(cond, NULL);
9543 rem_anchor_token(';');
9545 expect(';', end_error2);
9546 if (token.type != ')') {
9547 expression_t *const step = parse_expression();
9548 statement->fors.step = step;
9549 mark_vars_read(step, ENT_ANY);
9550 if (!expression_has_effect(step)) {
9551 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9554 expect(')', end_error2);
9555 rem_anchor_token(')');
9556 statement->fors.body = parse_loop_body(statement);
9564 rem_anchor_token(')');
9569 return create_invalid_statement();
9573 * Parse a goto statement.
9575 static statement_t *parse_goto(void)
9577 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9580 if (GNU_MODE && next_if('*')) {
9581 expression_t *expression = parse_expression();
9582 mark_vars_read(expression, NULL);
9584 /* Argh: although documentation says the expression must be of type void*,
9585 * gcc accepts anything that can be casted into void* without error */
9586 type_t *type = expression->base.type;
9588 if (type != type_error_type) {
9589 if (!is_type_pointer(type) && !is_type_integer(type)) {
9590 errorf(&expression->base.source_position,
9591 "cannot convert to a pointer type");
9592 } else if (type != type_void_ptr) {
9593 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9595 expression = create_implicit_cast(expression, type_void_ptr);
9598 statement->gotos.expression = expression;
9599 } else if (token.type == T_IDENTIFIER) {
9600 label_t *const label = get_label();
9602 statement->gotos.label = label;
9605 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9607 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9609 return create_invalid_statement();
9612 /* remember the goto's in a list for later checking */
9613 *goto_anchor = &statement->gotos;
9614 goto_anchor = &statement->gotos.next;
9616 expect(';', end_error);
9623 * Parse a continue statement.
9625 static statement_t *parse_continue(void)
9627 if (current_loop == NULL) {
9628 errorf(HERE, "continue statement not within loop");
9631 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9634 expect(';', end_error);
9641 * Parse a break statement.
9643 static statement_t *parse_break(void)
9645 if (current_switch == NULL && current_loop == NULL) {
9646 errorf(HERE, "break statement not within loop or switch");
9649 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9652 expect(';', end_error);
9659 * Parse a __leave statement.
9661 static statement_t *parse_leave_statement(void)
9663 if (current_try == NULL) {
9664 errorf(HERE, "__leave statement not within __try");
9667 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9670 expect(';', end_error);
9677 * Check if a given entity represents a local variable.
9679 static bool is_local_variable(const entity_t *entity)
9681 if (entity->kind != ENTITY_VARIABLE)
9684 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9685 case STORAGE_CLASS_AUTO:
9686 case STORAGE_CLASS_REGISTER: {
9687 const type_t *type = skip_typeref(entity->declaration.type);
9688 if (is_type_function(type)) {
9700 * Check if a given expression represents a local variable.
9702 static bool expression_is_local_variable(const expression_t *expression)
9704 if (expression->base.kind != EXPR_REFERENCE) {
9707 const entity_t *entity = expression->reference.entity;
9708 return is_local_variable(entity);
9712 * Check if a given expression represents a local variable and
9713 * return its declaration then, else return NULL.
9715 entity_t *expression_is_variable(const expression_t *expression)
9717 if (expression->base.kind != EXPR_REFERENCE) {
9720 entity_t *entity = expression->reference.entity;
9721 if (entity->kind != ENTITY_VARIABLE)
9728 * Parse a return statement.
9730 static statement_t *parse_return(void)
9732 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9735 expression_t *return_value = NULL;
9736 if (token.type != ';') {
9737 return_value = parse_expression();
9738 mark_vars_read(return_value, NULL);
9741 const type_t *const func_type = skip_typeref(current_function->base.type);
9742 assert(is_type_function(func_type));
9743 type_t *const return_type = skip_typeref(func_type->function.return_type);
9745 source_position_t const *const pos = &statement->base.source_position;
9746 if (return_value != NULL) {
9747 type_t *return_value_type = skip_typeref(return_value->base.type);
9749 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9750 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9751 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9752 /* Only warn in C mode, because GCC does the same */
9753 if (c_mode & _CXX || strict_mode) {
9755 "'return' with a value, in function returning 'void'");
9757 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9759 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9760 /* Only warn in C mode, because GCC does the same */
9763 "'return' with expression in function returning 'void'");
9765 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9769 assign_error_t error = semantic_assign(return_type, return_value);
9770 report_assign_error(error, return_type, return_value, "'return'",
9773 return_value = create_implicit_cast(return_value, return_type);
9774 /* check for returning address of a local var */
9775 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9776 const expression_t *expression = return_value->unary.value;
9777 if (expression_is_local_variable(expression)) {
9778 warningf(WARN_OTHER, pos, "function returns address of local variable");
9781 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9782 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9783 if (c_mode & _CXX || strict_mode) {
9785 "'return' without value, in function returning non-void");
9787 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9790 statement->returns.value = return_value;
9792 expect(';', end_error);
9799 * Parse a declaration statement.
9801 static statement_t *parse_declaration_statement(void)
9803 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9805 entity_t *before = current_scope->last_entity;
9807 parse_external_declaration();
9809 parse_declaration(record_entity, DECL_FLAGS_NONE);
9812 declaration_statement_t *const decl = &statement->declaration;
9813 entity_t *const begin =
9814 before != NULL ? before->base.next : current_scope->entities;
9815 decl->declarations_begin = begin;
9816 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9822 * Parse an expression statement, ie. expr ';'.
9824 static statement_t *parse_expression_statement(void)
9826 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9828 expression_t *const expr = parse_expression();
9829 statement->expression.expression = expr;
9830 mark_vars_read(expr, ENT_ANY);
9832 expect(';', end_error);
9839 * Parse a microsoft __try { } __finally { } or
9840 * __try{ } __except() { }
9842 static statement_t *parse_ms_try_statment(void)
9844 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9847 PUSH_PARENT(statement);
9849 ms_try_statement_t *rem = current_try;
9850 current_try = &statement->ms_try;
9851 statement->ms_try.try_statement = parse_compound_statement(false);
9856 if (next_if(T___except)) {
9857 expect('(', end_error);
9858 add_anchor_token(')');
9859 expression_t *const expr = parse_expression();
9860 mark_vars_read(expr, NULL);
9861 type_t * type = skip_typeref(expr->base.type);
9862 if (is_type_integer(type)) {
9863 type = promote_integer(type);
9864 } else if (is_type_valid(type)) {
9865 errorf(&expr->base.source_position,
9866 "__expect expression is not an integer, but '%T'", type);
9867 type = type_error_type;
9869 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9870 rem_anchor_token(')');
9871 expect(')', end_error);
9872 statement->ms_try.final_statement = parse_compound_statement(false);
9873 } else if (next_if(T__finally)) {
9874 statement->ms_try.final_statement = parse_compound_statement(false);
9876 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9877 return create_invalid_statement();
9881 return create_invalid_statement();
9884 static statement_t *parse_empty_statement(void)
9886 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9887 statement_t *const statement = create_empty_statement();
9892 static statement_t *parse_local_label_declaration(void)
9894 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9898 entity_t *begin = NULL;
9899 entity_t *end = NULL;
9900 entity_t **anchor = &begin;
9902 if (token.type != T_IDENTIFIER) {
9903 parse_error_expected("while parsing local label declaration",
9904 T_IDENTIFIER, NULL);
9907 symbol_t *symbol = token.symbol;
9908 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9909 if (entity != NULL && entity->base.parent_scope == current_scope) {
9910 source_position_t const *const ppos = &entity->base.source_position;
9911 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9913 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9914 entity->base.parent_scope = current_scope;
9915 entity->base.source_position = token.source_position;
9918 anchor = &entity->base.next;
9921 environment_push(entity);
9924 } while (next_if(','));
9925 expect(';', end_error);
9927 statement->declaration.declarations_begin = begin;
9928 statement->declaration.declarations_end = end;
9932 static void parse_namespace_definition(void)
9936 entity_t *entity = NULL;
9937 symbol_t *symbol = NULL;
9939 if (token.type == T_IDENTIFIER) {
9940 symbol = token.symbol;
9943 entity = get_entity(symbol, NAMESPACE_NORMAL);
9945 && entity->kind != ENTITY_NAMESPACE
9946 && entity->base.parent_scope == current_scope) {
9947 if (is_entity_valid(entity)) {
9948 error_redefined_as_different_kind(&token.source_position,
9949 entity, ENTITY_NAMESPACE);
9955 if (entity == NULL) {
9956 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9957 entity->base.source_position = token.source_position;
9958 entity->base.parent_scope = current_scope;
9961 if (token.type == '=') {
9962 /* TODO: parse namespace alias */
9963 panic("namespace alias definition not supported yet");
9966 environment_push(entity);
9967 append_entity(current_scope, entity);
9969 PUSH_SCOPE(&entity->namespacee.members);
9971 entity_t *old_current_entity = current_entity;
9972 current_entity = entity;
9974 expect('{', end_error);
9976 expect('}', end_error);
9979 assert(current_entity == entity);
9980 current_entity = old_current_entity;
9985 * Parse a statement.
9986 * There's also parse_statement() which additionally checks for
9987 * "statement has no effect" warnings
9989 static statement_t *intern_parse_statement(void)
9991 statement_t *statement = NULL;
9993 /* declaration or statement */
9994 add_anchor_token(';');
9995 switch (token.type) {
9996 case T_IDENTIFIER: {
9997 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9998 if (la1_type == ':') {
9999 statement = parse_label_statement();
10000 } else if (is_typedef_symbol(token.symbol)) {
10001 statement = parse_declaration_statement();
10003 /* it's an identifier, the grammar says this must be an
10004 * expression statement. However it is common that users mistype
10005 * declaration types, so we guess a bit here to improve robustness
10006 * for incorrect programs */
10007 switch (la1_type) {
10010 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10012 statement = parse_expression_statement();
10016 statement = parse_declaration_statement();
10024 case T___extension__: {
10025 /* This can be a prefix to a declaration or an expression statement.
10026 * We simply eat it now and parse the rest with tail recursion. */
10028 statement = intern_parse_statement();
10034 statement = parse_declaration_statement();
10038 statement = parse_local_label_declaration();
10041 case ';': statement = parse_empty_statement(); break;
10042 case '{': statement = parse_compound_statement(false); break;
10043 case T___leave: statement = parse_leave_statement(); break;
10044 case T___try: statement = parse_ms_try_statment(); break;
10045 case T_asm: statement = parse_asm_statement(); break;
10046 case T_break: statement = parse_break(); break;
10047 case T_case: statement = parse_case_statement(); break;
10048 case T_continue: statement = parse_continue(); break;
10049 case T_default: statement = parse_default_statement(); break;
10050 case T_do: statement = parse_do(); break;
10051 case T_for: statement = parse_for(); break;
10052 case T_goto: statement = parse_goto(); break;
10053 case T_if: statement = parse_if(); break;
10054 case T_return: statement = parse_return(); break;
10055 case T_switch: statement = parse_switch(); break;
10056 case T_while: statement = parse_while(); break;
10059 statement = parse_expression_statement();
10063 errorf(HERE, "unexpected token %K while parsing statement", &token);
10064 statement = create_invalid_statement();
10069 rem_anchor_token(';');
10071 assert(statement != NULL
10072 && statement->base.source_position.input_name != NULL);
10078 * parse a statement and emits "statement has no effect" warning if needed
10079 * (This is really a wrapper around intern_parse_statement with check for 1
10080 * single warning. It is needed, because for statement expressions we have
10081 * to avoid the warning on the last statement)
10083 static statement_t *parse_statement(void)
10085 statement_t *statement = intern_parse_statement();
10087 if (statement->kind == STATEMENT_EXPRESSION) {
10088 expression_t *expression = statement->expression.expression;
10089 if (!expression_has_effect(expression)) {
10090 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10098 * Parse a compound statement.
10100 static statement_t *parse_compound_statement(bool inside_expression_statement)
10102 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10104 PUSH_PARENT(statement);
10105 PUSH_SCOPE(&statement->compound.scope);
10108 add_anchor_token('}');
10109 /* tokens, which can start a statement */
10110 /* TODO MS, __builtin_FOO */
10111 add_anchor_token('!');
10112 add_anchor_token('&');
10113 add_anchor_token('(');
10114 add_anchor_token('*');
10115 add_anchor_token('+');
10116 add_anchor_token('-');
10117 add_anchor_token('{');
10118 add_anchor_token('~');
10119 add_anchor_token(T_CHARACTER_CONSTANT);
10120 add_anchor_token(T_COLONCOLON);
10121 add_anchor_token(T_FLOATINGPOINT);
10122 add_anchor_token(T_IDENTIFIER);
10123 add_anchor_token(T_INTEGER);
10124 add_anchor_token(T_MINUSMINUS);
10125 add_anchor_token(T_PLUSPLUS);
10126 add_anchor_token(T_STRING_LITERAL);
10127 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10128 add_anchor_token(T_WIDE_STRING_LITERAL);
10129 add_anchor_token(T__Bool);
10130 add_anchor_token(T__Complex);
10131 add_anchor_token(T__Imaginary);
10132 add_anchor_token(T___FUNCTION__);
10133 add_anchor_token(T___PRETTY_FUNCTION__);
10134 add_anchor_token(T___alignof__);
10135 add_anchor_token(T___attribute__);
10136 add_anchor_token(T___builtin_va_start);
10137 add_anchor_token(T___extension__);
10138 add_anchor_token(T___func__);
10139 add_anchor_token(T___imag__);
10140 add_anchor_token(T___label__);
10141 add_anchor_token(T___real__);
10142 add_anchor_token(T___thread);
10143 add_anchor_token(T_asm);
10144 add_anchor_token(T_auto);
10145 add_anchor_token(T_bool);
10146 add_anchor_token(T_break);
10147 add_anchor_token(T_case);
10148 add_anchor_token(T_char);
10149 add_anchor_token(T_class);
10150 add_anchor_token(T_const);
10151 add_anchor_token(T_const_cast);
10152 add_anchor_token(T_continue);
10153 add_anchor_token(T_default);
10154 add_anchor_token(T_delete);
10155 add_anchor_token(T_double);
10156 add_anchor_token(T_do);
10157 add_anchor_token(T_dynamic_cast);
10158 add_anchor_token(T_enum);
10159 add_anchor_token(T_extern);
10160 add_anchor_token(T_false);
10161 add_anchor_token(T_float);
10162 add_anchor_token(T_for);
10163 add_anchor_token(T_goto);
10164 add_anchor_token(T_if);
10165 add_anchor_token(T_inline);
10166 add_anchor_token(T_int);
10167 add_anchor_token(T_long);
10168 add_anchor_token(T_new);
10169 add_anchor_token(T_operator);
10170 add_anchor_token(T_register);
10171 add_anchor_token(T_reinterpret_cast);
10172 add_anchor_token(T_restrict);
10173 add_anchor_token(T_return);
10174 add_anchor_token(T_short);
10175 add_anchor_token(T_signed);
10176 add_anchor_token(T_sizeof);
10177 add_anchor_token(T_static);
10178 add_anchor_token(T_static_cast);
10179 add_anchor_token(T_struct);
10180 add_anchor_token(T_switch);
10181 add_anchor_token(T_template);
10182 add_anchor_token(T_this);
10183 add_anchor_token(T_throw);
10184 add_anchor_token(T_true);
10185 add_anchor_token(T_try);
10186 add_anchor_token(T_typedef);
10187 add_anchor_token(T_typeid);
10188 add_anchor_token(T_typename);
10189 add_anchor_token(T_typeof);
10190 add_anchor_token(T_union);
10191 add_anchor_token(T_unsigned);
10192 add_anchor_token(T_using);
10193 add_anchor_token(T_void);
10194 add_anchor_token(T_volatile);
10195 add_anchor_token(T_wchar_t);
10196 add_anchor_token(T_while);
10198 statement_t **anchor = &statement->compound.statements;
10199 bool only_decls_so_far = true;
10200 while (token.type != '}') {
10201 if (token.type == T_EOF) {
10202 errorf(&statement->base.source_position,
10203 "EOF while parsing compound statement");
10206 statement_t *sub_statement = intern_parse_statement();
10207 if (is_invalid_statement(sub_statement)) {
10208 /* an error occurred. if we are at an anchor, return */
10214 if (sub_statement->kind != STATEMENT_DECLARATION) {
10215 only_decls_so_far = false;
10216 } else if (!only_decls_so_far) {
10217 source_position_t const *const pos = &sub_statement->base.source_position;
10218 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10221 *anchor = sub_statement;
10223 while (sub_statement->base.next != NULL)
10224 sub_statement = sub_statement->base.next;
10226 anchor = &sub_statement->base.next;
10230 /* look over all statements again to produce no effect warnings */
10231 if (is_warn_on(WARN_UNUSED_VALUE)) {
10232 statement_t *sub_statement = statement->compound.statements;
10233 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10234 if (sub_statement->kind != STATEMENT_EXPRESSION)
10236 /* don't emit a warning for the last expression in an expression
10237 * statement as it has always an effect */
10238 if (inside_expression_statement && sub_statement->base.next == NULL)
10241 expression_t *expression = sub_statement->expression.expression;
10242 if (!expression_has_effect(expression)) {
10243 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10249 rem_anchor_token(T_while);
10250 rem_anchor_token(T_wchar_t);
10251 rem_anchor_token(T_volatile);
10252 rem_anchor_token(T_void);
10253 rem_anchor_token(T_using);
10254 rem_anchor_token(T_unsigned);
10255 rem_anchor_token(T_union);
10256 rem_anchor_token(T_typeof);
10257 rem_anchor_token(T_typename);
10258 rem_anchor_token(T_typeid);
10259 rem_anchor_token(T_typedef);
10260 rem_anchor_token(T_try);
10261 rem_anchor_token(T_true);
10262 rem_anchor_token(T_throw);
10263 rem_anchor_token(T_this);
10264 rem_anchor_token(T_template);
10265 rem_anchor_token(T_switch);
10266 rem_anchor_token(T_struct);
10267 rem_anchor_token(T_static_cast);
10268 rem_anchor_token(T_static);
10269 rem_anchor_token(T_sizeof);
10270 rem_anchor_token(T_signed);
10271 rem_anchor_token(T_short);
10272 rem_anchor_token(T_return);
10273 rem_anchor_token(T_restrict);
10274 rem_anchor_token(T_reinterpret_cast);
10275 rem_anchor_token(T_register);
10276 rem_anchor_token(T_operator);
10277 rem_anchor_token(T_new);
10278 rem_anchor_token(T_long);
10279 rem_anchor_token(T_int);
10280 rem_anchor_token(T_inline);
10281 rem_anchor_token(T_if);
10282 rem_anchor_token(T_goto);
10283 rem_anchor_token(T_for);
10284 rem_anchor_token(T_float);
10285 rem_anchor_token(T_false);
10286 rem_anchor_token(T_extern);
10287 rem_anchor_token(T_enum);
10288 rem_anchor_token(T_dynamic_cast);
10289 rem_anchor_token(T_do);
10290 rem_anchor_token(T_double);
10291 rem_anchor_token(T_delete);
10292 rem_anchor_token(T_default);
10293 rem_anchor_token(T_continue);
10294 rem_anchor_token(T_const_cast);
10295 rem_anchor_token(T_const);
10296 rem_anchor_token(T_class);
10297 rem_anchor_token(T_char);
10298 rem_anchor_token(T_case);
10299 rem_anchor_token(T_break);
10300 rem_anchor_token(T_bool);
10301 rem_anchor_token(T_auto);
10302 rem_anchor_token(T_asm);
10303 rem_anchor_token(T___thread);
10304 rem_anchor_token(T___real__);
10305 rem_anchor_token(T___label__);
10306 rem_anchor_token(T___imag__);
10307 rem_anchor_token(T___func__);
10308 rem_anchor_token(T___extension__);
10309 rem_anchor_token(T___builtin_va_start);
10310 rem_anchor_token(T___attribute__);
10311 rem_anchor_token(T___alignof__);
10312 rem_anchor_token(T___PRETTY_FUNCTION__);
10313 rem_anchor_token(T___FUNCTION__);
10314 rem_anchor_token(T__Imaginary);
10315 rem_anchor_token(T__Complex);
10316 rem_anchor_token(T__Bool);
10317 rem_anchor_token(T_WIDE_STRING_LITERAL);
10318 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10319 rem_anchor_token(T_STRING_LITERAL);
10320 rem_anchor_token(T_PLUSPLUS);
10321 rem_anchor_token(T_MINUSMINUS);
10322 rem_anchor_token(T_INTEGER);
10323 rem_anchor_token(T_IDENTIFIER);
10324 rem_anchor_token(T_FLOATINGPOINT);
10325 rem_anchor_token(T_COLONCOLON);
10326 rem_anchor_token(T_CHARACTER_CONSTANT);
10327 rem_anchor_token('~');
10328 rem_anchor_token('{');
10329 rem_anchor_token('-');
10330 rem_anchor_token('+');
10331 rem_anchor_token('*');
10332 rem_anchor_token('(');
10333 rem_anchor_token('&');
10334 rem_anchor_token('!');
10335 rem_anchor_token('}');
10343 * Check for unused global static functions and variables
10345 static void check_unused_globals(void)
10347 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10350 for (const entity_t *entity = file_scope->entities; entity != NULL;
10351 entity = entity->base.next) {
10352 if (!is_declaration(entity))
10355 const declaration_t *declaration = &entity->declaration;
10356 if (declaration->used ||
10357 declaration->modifiers & DM_UNUSED ||
10358 declaration->modifiers & DM_USED ||
10359 declaration->storage_class != STORAGE_CLASS_STATIC)
10364 if (entity->kind == ENTITY_FUNCTION) {
10365 /* inhibit warning for static inline functions */
10366 if (entity->function.is_inline)
10369 why = WARN_UNUSED_FUNCTION;
10370 s = entity->function.statement != NULL ? "defined" : "declared";
10372 why = WARN_UNUSED_VARIABLE;
10376 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10380 static void parse_global_asm(void)
10382 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10385 expect('(', end_error);
10387 statement->asms.asm_text = parse_string_literals();
10388 statement->base.next = unit->global_asm;
10389 unit->global_asm = statement;
10391 expect(')', end_error);
10392 expect(';', end_error);
10397 static void parse_linkage_specification(void)
10401 source_position_t const pos = *HERE;
10402 char const *const linkage = parse_string_literals().begin;
10404 linkage_kind_t old_linkage = current_linkage;
10405 linkage_kind_t new_linkage;
10406 if (strcmp(linkage, "C") == 0) {
10407 new_linkage = LINKAGE_C;
10408 } else if (strcmp(linkage, "C++") == 0) {
10409 new_linkage = LINKAGE_CXX;
10411 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10412 new_linkage = LINKAGE_INVALID;
10414 current_linkage = new_linkage;
10416 if (next_if('{')) {
10418 expect('}', end_error);
10424 assert(current_linkage == new_linkage);
10425 current_linkage = old_linkage;
10428 static void parse_external(void)
10430 switch (token.type) {
10432 if (look_ahead(1)->type == T_STRING_LITERAL) {
10433 parse_linkage_specification();
10435 DECLARATION_START_NO_EXTERN
10437 case T___extension__:
10438 /* tokens below are for implicit int */
10439 case '&': /* & x; -> int& x; (and error later, because C++ has no
10441 case '*': /* * x; -> int* x; */
10442 case '(':; /* (x); -> int (x); */
10444 parse_external_declaration();
10450 parse_global_asm();
10454 parse_namespace_definition();
10458 if (!strict_mode) {
10459 warningf(WARN_OTHER, HERE, "stray ';' outside of function");
10466 errorf(HERE, "stray %K outside of function", &token);
10467 if (token.type == '(' || token.type == '{' || token.type == '[')
10468 eat_until_matching_token(token.type);
10474 static void parse_externals(void)
10476 add_anchor_token('}');
10477 add_anchor_token(T_EOF);
10480 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10481 unsigned char token_anchor_copy[T_LAST_TOKEN];
10482 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10485 while (token.type != T_EOF && token.type != '}') {
10487 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10488 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10490 /* the anchor set and its copy differs */
10491 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10494 if (in_gcc_extension) {
10495 /* an gcc extension scope was not closed */
10496 internal_errorf(HERE, "Leaked __extension__");
10503 rem_anchor_token(T_EOF);
10504 rem_anchor_token('}');
10508 * Parse a translation unit.
10510 static void parse_translation_unit(void)
10512 add_anchor_token(T_EOF);
10517 if (token.type == T_EOF)
10520 errorf(HERE, "stray %K outside of function", &token);
10521 if (token.type == '(' || token.type == '{' || token.type == '[')
10522 eat_until_matching_token(token.type);
10527 void set_default_visibility(elf_visibility_tag_t visibility)
10529 default_visibility = visibility;
10535 * @return the translation unit or NULL if errors occurred.
10537 void start_parsing(void)
10539 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10540 label_stack = NEW_ARR_F(stack_entry_t, 0);
10541 diagnostic_count = 0;
10545 print_to_file(stderr);
10547 assert(unit == NULL);
10548 unit = allocate_ast_zero(sizeof(unit[0]));
10550 assert(file_scope == NULL);
10551 file_scope = &unit->scope;
10553 assert(current_scope == NULL);
10554 scope_push(&unit->scope);
10556 create_gnu_builtins();
10558 create_microsoft_intrinsics();
10561 translation_unit_t *finish_parsing(void)
10563 assert(current_scope == &unit->scope);
10566 assert(file_scope == &unit->scope);
10567 check_unused_globals();
10570 DEL_ARR_F(environment_stack);
10571 DEL_ARR_F(label_stack);
10573 translation_unit_t *result = unit;
10578 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10579 * are given length one. */
10580 static void complete_incomplete_arrays(void)
10582 size_t n = ARR_LEN(incomplete_arrays);
10583 for (size_t i = 0; i != n; ++i) {
10584 declaration_t *const decl = incomplete_arrays[i];
10585 type_t *const type = skip_typeref(decl->type);
10587 if (!is_type_incomplete(type))
10590 source_position_t const *const pos = &decl->base.source_position;
10591 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10593 type_t *const new_type = duplicate_type(type);
10594 new_type->array.size_constant = true;
10595 new_type->array.has_implicit_size = true;
10596 new_type->array.size = 1;
10598 type_t *const result = identify_new_type(new_type);
10600 decl->type = result;
10604 void prepare_main_collect2(entity_t *entity)
10606 // create call to __main
10607 symbol_t *symbol = symbol_table_insert("__main");
10608 entity_t *subsubmain_ent
10609 = create_implicit_function(symbol, &builtin_source_position);
10611 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10612 type_t *ftype = subsubmain_ent->declaration.type;
10613 ref->base.source_position = builtin_source_position;
10614 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10615 ref->reference.entity = subsubmain_ent;
10617 expression_t *call = allocate_expression_zero(EXPR_CALL);
10618 call->base.source_position = builtin_source_position;
10619 call->base.type = type_void;
10620 call->call.function = ref;
10622 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10623 expr_statement->base.source_position = builtin_source_position;
10624 expr_statement->expression.expression = call;
10626 statement_t *statement = entity->function.statement;
10627 assert(statement->kind == STATEMENT_COMPOUND);
10628 compound_statement_t *compounds = &statement->compound;
10630 expr_statement->base.next = compounds->statements;
10631 compounds->statements = expr_statement;
10636 lookahead_bufpos = 0;
10637 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10640 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10641 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10642 parse_translation_unit();
10643 complete_incomplete_arrays();
10644 DEL_ARR_F(incomplete_arrays);
10645 incomplete_arrays = NULL;
10649 * Initialize the parser.
10651 void init_parser(void)
10653 sym_anonymous = symbol_table_insert("<anonymous>");
10655 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10657 init_expression_parsers();
10658 obstack_init(&temp_obst);
10662 * Terminate the parser.
10664 void exit_parser(void)
10666 obstack_free(&temp_obst, NULL);