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_IDENTIFIER: {
5787 declaration_specifiers_t specifiers;
5788 parse_declaration_specifiers(&specifiers);
5789 parse_compound_declarators(compound, &specifiers);
5794 rem_anchor_token('}');
5795 expect('}', end_error);
5798 compound->complete = true;
5804 static type_t *parse_typename(void)
5806 declaration_specifiers_t specifiers;
5807 parse_declaration_specifiers(&specifiers);
5808 if (specifiers.storage_class != STORAGE_CLASS_NONE
5809 || specifiers.thread_local) {
5810 /* TODO: improve error message, user does probably not know what a
5811 * storage class is...
5813 errorf(&specifiers.source_position, "typename must not have a storage class");
5816 type_t *result = parse_abstract_declarator(specifiers.type);
5824 typedef expression_t* (*parse_expression_function)(void);
5825 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5827 typedef struct expression_parser_function_t expression_parser_function_t;
5828 struct expression_parser_function_t {
5829 parse_expression_function parser;
5830 precedence_t infix_precedence;
5831 parse_expression_infix_function infix_parser;
5834 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5837 * Prints an error message if an expression was expected but not read
5839 static expression_t *expected_expression_error(void)
5841 /* skip the error message if the error token was read */
5842 if (token.type != T_ERROR) {
5843 errorf(HERE, "expected expression, got token %K", &token);
5847 return create_invalid_expression();
5850 static type_t *get_string_type(void)
5852 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5855 static type_t *get_wide_string_type(void)
5857 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5861 * Parse a string constant.
5863 static expression_t *parse_string_literal(void)
5865 source_position_t begin = token.source_position;
5866 string_t res = token.literal;
5867 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5870 while (token.type == T_STRING_LITERAL
5871 || token.type == T_WIDE_STRING_LITERAL) {
5872 warn_string_concat(&token.source_position);
5873 res = concat_strings(&res, &token.literal);
5875 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5878 expression_t *literal;
5880 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5881 literal->base.type = get_wide_string_type();
5883 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5884 literal->base.type = get_string_type();
5886 literal->base.source_position = begin;
5887 literal->literal.value = res;
5893 * Parse a boolean constant.
5895 static expression_t *parse_boolean_literal(bool value)
5897 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5898 literal->base.type = type_bool;
5899 literal->literal.value.begin = value ? "true" : "false";
5900 literal->literal.value.size = value ? 4 : 5;
5906 static void warn_traditional_suffix(void)
5908 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%Y' suffix", token.symbol);
5911 static void check_integer_suffix(void)
5913 symbol_t *suffix = token.symbol;
5917 bool not_traditional = false;
5918 const char *c = suffix->string;
5919 if (*c == 'l' || *c == 'L') {
5922 not_traditional = true;
5924 if (*c == 'u' || *c == 'U') {
5927 } else if (*c == 'u' || *c == 'U') {
5928 not_traditional = true;
5931 } else if (*c == 'u' || *c == 'U') {
5932 not_traditional = true;
5934 if (*c == 'l' || *c == 'L') {
5942 errorf(&token.source_position,
5943 "invalid suffix '%s' on integer constant", suffix->string);
5944 } else if (not_traditional) {
5945 warn_traditional_suffix();
5949 static type_t *check_floatingpoint_suffix(void)
5951 symbol_t *suffix = token.symbol;
5952 type_t *type = type_double;
5956 bool not_traditional = false;
5957 const char *c = suffix->string;
5958 if (*c == 'f' || *c == 'F') {
5961 } else if (*c == 'l' || *c == 'L') {
5963 type = type_long_double;
5966 errorf(&token.source_position,
5967 "invalid suffix '%s' on floatingpoint constant", suffix->string);
5968 } else if (not_traditional) {
5969 warn_traditional_suffix();
5976 * Parse an integer constant.
5978 static expression_t *parse_number_literal(void)
5980 expression_kind_t kind;
5983 switch (token.type) {
5985 kind = EXPR_LITERAL_INTEGER;
5986 check_integer_suffix();
5989 case T_INTEGER_OCTAL:
5990 kind = EXPR_LITERAL_INTEGER_OCTAL;
5991 check_integer_suffix();
5994 case T_INTEGER_HEXADECIMAL:
5995 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5996 check_integer_suffix();
5999 case T_FLOATINGPOINT:
6000 kind = EXPR_LITERAL_FLOATINGPOINT;
6001 type = check_floatingpoint_suffix();
6003 case T_FLOATINGPOINT_HEXADECIMAL:
6004 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6005 type = check_floatingpoint_suffix();
6008 panic("unexpected token type in parse_number_literal");
6011 expression_t *literal = allocate_expression_zero(kind);
6012 literal->base.type = type;
6013 literal->literal.value = token.literal;
6014 literal->literal.suffix = token.symbol;
6017 /* integer type depends on the size of the number and the size
6018 * representable by the types. The backend/codegeneration has to determine
6021 determine_literal_type(&literal->literal);
6026 * Parse a character constant.
6028 static expression_t *parse_character_constant(void)
6030 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6031 literal->base.type = c_mode & _CXX ? type_char : type_int;
6032 literal->literal.value = token.literal;
6034 size_t len = literal->literal.value.size;
6036 if (!GNU_MODE && !(c_mode & _C99)) {
6037 errorf(HERE, "more than 1 character in character constant");
6039 literal->base.type = type_int;
6040 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6049 * Parse a wide character constant.
6051 static expression_t *parse_wide_character_constant(void)
6053 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6054 literal->base.type = type_int;
6055 literal->literal.value = token.literal;
6057 size_t len = wstrlen(&literal->literal.value);
6059 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6066 static entity_t *create_implicit_function(symbol_t *symbol,
6067 const source_position_t *source_position)
6069 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6070 ntype->function.return_type = type_int;
6071 ntype->function.unspecified_parameters = true;
6072 ntype->function.linkage = LINKAGE_C;
6073 type_t *type = identify_new_type(ntype);
6075 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6076 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6077 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6078 entity->declaration.type = type;
6079 entity->declaration.implicit = true;
6080 entity->base.source_position = *source_position;
6082 if (current_scope != NULL)
6083 record_entity(entity, false);
6089 * Performs automatic type cast as described in §6.3.2.1.
6091 * @param orig_type the original type
6093 static type_t *automatic_type_conversion(type_t *orig_type)
6095 type_t *type = skip_typeref(orig_type);
6096 if (is_type_array(type)) {
6097 array_type_t *array_type = &type->array;
6098 type_t *element_type = array_type->element_type;
6099 unsigned qualifiers = array_type->base.qualifiers;
6101 return make_pointer_type(element_type, qualifiers);
6104 if (is_type_function(type)) {
6105 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6112 * reverts the automatic casts of array to pointer types and function
6113 * to function-pointer types as defined §6.3.2.1
6115 type_t *revert_automatic_type_conversion(const expression_t *expression)
6117 switch (expression->kind) {
6118 case EXPR_REFERENCE: {
6119 entity_t *entity = expression->reference.entity;
6120 if (is_declaration(entity)) {
6121 return entity->declaration.type;
6122 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6123 return entity->enum_value.enum_type;
6125 panic("no declaration or enum in reference");
6130 entity_t *entity = expression->select.compound_entry;
6131 assert(is_declaration(entity));
6132 type_t *type = entity->declaration.type;
6133 return get_qualified_type(type,
6134 expression->base.type->base.qualifiers);
6137 case EXPR_UNARY_DEREFERENCE: {
6138 const expression_t *const value = expression->unary.value;
6139 type_t *const type = skip_typeref(value->base.type);
6140 if (!is_type_pointer(type))
6141 return type_error_type;
6142 return type->pointer.points_to;
6145 case EXPR_ARRAY_ACCESS: {
6146 const expression_t *array_ref = expression->array_access.array_ref;
6147 type_t *type_left = skip_typeref(array_ref->base.type);
6148 if (!is_type_pointer(type_left))
6149 return type_error_type;
6150 return type_left->pointer.points_to;
6153 case EXPR_STRING_LITERAL: {
6154 size_t size = expression->string_literal.value.size;
6155 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6158 case EXPR_WIDE_STRING_LITERAL: {
6159 size_t size = wstrlen(&expression->string_literal.value);
6160 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6163 case EXPR_COMPOUND_LITERAL:
6164 return expression->compound_literal.type;
6169 return expression->base.type;
6173 * Find an entity matching a symbol in a scope.
6174 * Uses current scope if scope is NULL
6176 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6177 namespace_tag_t namespc)
6179 if (scope == NULL) {
6180 return get_entity(symbol, namespc);
6183 /* we should optimize here, if scope grows above a certain size we should
6184 construct a hashmap here... */
6185 entity_t *entity = scope->entities;
6186 for ( ; entity != NULL; entity = entity->base.next) {
6187 if (entity->base.symbol == symbol
6188 && (namespace_tag_t)entity->base.namespc == namespc)
6195 static entity_t *parse_qualified_identifier(void)
6197 /* namespace containing the symbol */
6199 source_position_t pos;
6200 const scope_t *lookup_scope = NULL;
6202 if (next_if(T_COLONCOLON))
6203 lookup_scope = &unit->scope;
6207 if (token.type != T_IDENTIFIER) {
6208 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6209 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6211 symbol = token.symbol;
6216 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6218 if (!next_if(T_COLONCOLON))
6221 switch (entity->kind) {
6222 case ENTITY_NAMESPACE:
6223 lookup_scope = &entity->namespacee.members;
6228 lookup_scope = &entity->compound.members;
6231 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6232 symbol, get_entity_kind_name(entity->kind));
6234 /* skip further qualifications */
6235 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6237 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6241 if (entity == NULL) {
6242 if (!strict_mode && token.type == '(') {
6243 /* an implicitly declared function */
6244 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6245 entity = create_implicit_function(symbol, &pos);
6247 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6248 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6255 static expression_t *parse_reference(void)
6257 source_position_t const pos = token.source_position;
6258 entity_t *const entity = parse_qualified_identifier();
6261 if (is_declaration(entity)) {
6262 orig_type = entity->declaration.type;
6263 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6264 orig_type = entity->enum_value.enum_type;
6266 panic("expected declaration or enum value in reference");
6269 /* we always do the auto-type conversions; the & and sizeof parser contains
6270 * code to revert this! */
6271 type_t *type = automatic_type_conversion(orig_type);
6273 expression_kind_t kind = EXPR_REFERENCE;
6274 if (entity->kind == ENTITY_ENUM_VALUE)
6275 kind = EXPR_REFERENCE_ENUM_VALUE;
6277 expression_t *expression = allocate_expression_zero(kind);
6278 expression->base.source_position = pos;
6279 expression->base.type = type;
6280 expression->reference.entity = entity;
6282 /* this declaration is used */
6283 if (is_declaration(entity)) {
6284 entity->declaration.used = true;
6287 if (entity->base.parent_scope != file_scope
6288 && (current_function != NULL
6289 && entity->base.parent_scope->depth < current_function->parameters.depth)
6290 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6291 if (entity->kind == ENTITY_VARIABLE) {
6292 /* access of a variable from an outer function */
6293 entity->variable.address_taken = true;
6294 } else if (entity->kind == ENTITY_PARAMETER) {
6295 entity->parameter.address_taken = true;
6297 current_function->need_closure = true;
6300 check_deprecated(&pos, entity);
6302 if (entity == current_init_decl && !in_type_prop && entity->kind == ENTITY_VARIABLE) {
6303 current_init_decl = NULL;
6304 warningf(WARN_INIT_SELF, &pos, "variable '%#N' is initialized by itself", entity);
6310 static bool semantic_cast(expression_t *cast)
6312 expression_t *expression = cast->unary.value;
6313 type_t *orig_dest_type = cast->base.type;
6314 type_t *orig_type_right = expression->base.type;
6315 type_t const *dst_type = skip_typeref(orig_dest_type);
6316 type_t const *src_type = skip_typeref(orig_type_right);
6317 source_position_t const *pos = &cast->base.source_position;
6319 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6320 if (dst_type == type_void)
6323 /* only integer and pointer can be casted to pointer */
6324 if (is_type_pointer(dst_type) &&
6325 !is_type_pointer(src_type) &&
6326 !is_type_integer(src_type) &&
6327 is_type_valid(src_type)) {
6328 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6332 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6333 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6337 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6338 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6342 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6343 type_t *src = skip_typeref(src_type->pointer.points_to);
6344 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6345 unsigned missing_qualifiers =
6346 src->base.qualifiers & ~dst->base.qualifiers;
6347 if (missing_qualifiers != 0) {
6348 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6354 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6356 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6357 expression->base.source_position = *pos;
6359 parse_initializer_env_t env;
6362 env.must_be_constant = false;
6363 initializer_t *initializer = parse_initializer(&env);
6366 expression->compound_literal.initializer = initializer;
6367 expression->compound_literal.type = type;
6368 expression->base.type = automatic_type_conversion(type);
6374 * Parse a cast expression.
6376 static expression_t *parse_cast(void)
6378 source_position_t const pos = *HERE;
6381 add_anchor_token(')');
6383 type_t *type = parse_typename();
6385 rem_anchor_token(')');
6386 expect(')', end_error);
6388 if (token.type == '{') {
6389 return parse_compound_literal(&pos, type);
6392 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6393 cast->base.source_position = pos;
6395 expression_t *value = parse_subexpression(PREC_CAST);
6396 cast->base.type = type;
6397 cast->unary.value = value;
6399 if (! semantic_cast(cast)) {
6400 /* TODO: record the error in the AST. else it is impossible to detect it */
6405 return create_invalid_expression();
6409 * Parse a statement expression.
6411 static expression_t *parse_statement_expression(void)
6413 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6416 add_anchor_token(')');
6418 statement_t *statement = parse_compound_statement(true);
6419 statement->compound.stmt_expr = true;
6420 expression->statement.statement = statement;
6422 /* find last statement and use its type */
6423 type_t *type = type_void;
6424 const statement_t *stmt = statement->compound.statements;
6426 while (stmt->base.next != NULL)
6427 stmt = stmt->base.next;
6429 if (stmt->kind == STATEMENT_EXPRESSION) {
6430 type = stmt->expression.expression->base.type;
6433 source_position_t const *const pos = &expression->base.source_position;
6434 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6436 expression->base.type = type;
6438 rem_anchor_token(')');
6439 expect(')', end_error);
6446 * Parse a parenthesized expression.
6448 static expression_t *parse_parenthesized_expression(void)
6450 token_t const* const la1 = look_ahead(1);
6451 switch (la1->type) {
6453 /* gcc extension: a statement expression */
6454 return parse_statement_expression();
6457 if (is_typedef_symbol(la1->symbol)) {
6459 return parse_cast();
6464 add_anchor_token(')');
6465 expression_t *result = parse_expression();
6466 result->base.parenthesized = true;
6467 rem_anchor_token(')');
6468 expect(')', end_error);
6474 static expression_t *parse_function_keyword(void)
6478 if (current_function == NULL) {
6479 errorf(HERE, "'__func__' used outside of a function");
6482 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6483 expression->base.type = type_char_ptr;
6484 expression->funcname.kind = FUNCNAME_FUNCTION;
6491 static expression_t *parse_pretty_function_keyword(void)
6493 if (current_function == NULL) {
6494 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6497 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6498 expression->base.type = type_char_ptr;
6499 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6501 eat(T___PRETTY_FUNCTION__);
6506 static expression_t *parse_funcsig_keyword(void)
6508 if (current_function == NULL) {
6509 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6512 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6513 expression->base.type = type_char_ptr;
6514 expression->funcname.kind = FUNCNAME_FUNCSIG;
6521 static expression_t *parse_funcdname_keyword(void)
6523 if (current_function == NULL) {
6524 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6527 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6528 expression->base.type = type_char_ptr;
6529 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6531 eat(T___FUNCDNAME__);
6536 static designator_t *parse_designator(void)
6538 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6539 result->source_position = *HERE;
6541 if (token.type != T_IDENTIFIER) {
6542 parse_error_expected("while parsing member designator",
6543 T_IDENTIFIER, NULL);
6546 result->symbol = token.symbol;
6549 designator_t *last_designator = result;
6552 if (token.type != T_IDENTIFIER) {
6553 parse_error_expected("while parsing member designator",
6554 T_IDENTIFIER, NULL);
6557 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6558 designator->source_position = *HERE;
6559 designator->symbol = token.symbol;
6562 last_designator->next = designator;
6563 last_designator = designator;
6567 add_anchor_token(']');
6568 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6569 designator->source_position = *HERE;
6570 designator->array_index = parse_expression();
6571 rem_anchor_token(']');
6572 expect(']', end_error);
6573 if (designator->array_index == NULL) {
6577 last_designator->next = designator;
6578 last_designator = designator;
6590 * Parse the __builtin_offsetof() expression.
6592 static expression_t *parse_offsetof(void)
6594 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6595 expression->base.type = type_size_t;
6597 eat(T___builtin_offsetof);
6599 expect('(', end_error);
6600 add_anchor_token(',');
6601 type_t *type = parse_typename();
6602 rem_anchor_token(',');
6603 expect(',', end_error);
6604 add_anchor_token(')');
6605 designator_t *designator = parse_designator();
6606 rem_anchor_token(')');
6607 expect(')', end_error);
6609 expression->offsetofe.type = type;
6610 expression->offsetofe.designator = designator;
6613 memset(&path, 0, sizeof(path));
6614 path.top_type = type;
6615 path.path = NEW_ARR_F(type_path_entry_t, 0);
6617 descend_into_subtype(&path);
6619 if (!walk_designator(&path, designator, true)) {
6620 return create_invalid_expression();
6623 DEL_ARR_F(path.path);
6627 return create_invalid_expression();
6631 * Parses a _builtin_va_start() expression.
6633 static expression_t *parse_va_start(void)
6635 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6637 eat(T___builtin_va_start);
6639 expect('(', end_error);
6640 add_anchor_token(',');
6641 expression->va_starte.ap = parse_assignment_expression();
6642 rem_anchor_token(',');
6643 expect(',', end_error);
6644 expression_t *const expr = parse_assignment_expression();
6645 if (expr->kind == EXPR_REFERENCE) {
6646 entity_t *const entity = expr->reference.entity;
6647 if (!current_function->base.type->function.variadic) {
6648 errorf(&expr->base.source_position,
6649 "'va_start' used in non-variadic function");
6650 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6651 entity->base.next != NULL ||
6652 entity->kind != ENTITY_PARAMETER) {
6653 errorf(&expr->base.source_position,
6654 "second argument of 'va_start' must be last parameter of the current function");
6656 expression->va_starte.parameter = &entity->variable;
6658 expect(')', end_error);
6661 expect(')', end_error);
6663 return create_invalid_expression();
6667 * Parses a __builtin_va_arg() expression.
6669 static expression_t *parse_va_arg(void)
6671 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6673 eat(T___builtin_va_arg);
6675 expect('(', end_error);
6677 ap.expression = parse_assignment_expression();
6678 expression->va_arge.ap = ap.expression;
6679 check_call_argument(type_valist, &ap, 1);
6681 expect(',', end_error);
6682 expression->base.type = parse_typename();
6683 expect(')', end_error);
6687 return create_invalid_expression();
6691 * Parses a __builtin_va_copy() expression.
6693 static expression_t *parse_va_copy(void)
6695 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6697 eat(T___builtin_va_copy);
6699 expect('(', end_error);
6700 expression_t *dst = parse_assignment_expression();
6701 assign_error_t error = semantic_assign(type_valist, dst);
6702 report_assign_error(error, type_valist, dst, "call argument 1",
6703 &dst->base.source_position);
6704 expression->va_copye.dst = dst;
6706 expect(',', end_error);
6708 call_argument_t src;
6709 src.expression = parse_assignment_expression();
6710 check_call_argument(type_valist, &src, 2);
6711 expression->va_copye.src = src.expression;
6712 expect(')', end_error);
6716 return create_invalid_expression();
6720 * Parses a __builtin_constant_p() expression.
6722 static expression_t *parse_builtin_constant(void)
6724 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6726 eat(T___builtin_constant_p);
6728 expect('(', end_error);
6729 add_anchor_token(')');
6730 expression->builtin_constant.value = parse_assignment_expression();
6731 rem_anchor_token(')');
6732 expect(')', end_error);
6733 expression->base.type = type_int;
6737 return create_invalid_expression();
6741 * Parses a __builtin_types_compatible_p() expression.
6743 static expression_t *parse_builtin_types_compatible(void)
6745 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6747 eat(T___builtin_types_compatible_p);
6749 expect('(', end_error);
6750 add_anchor_token(')');
6751 add_anchor_token(',');
6752 expression->builtin_types_compatible.left = parse_typename();
6753 rem_anchor_token(',');
6754 expect(',', end_error);
6755 expression->builtin_types_compatible.right = parse_typename();
6756 rem_anchor_token(')');
6757 expect(')', end_error);
6758 expression->base.type = type_int;
6762 return create_invalid_expression();
6766 * Parses a __builtin_is_*() compare expression.
6768 static expression_t *parse_compare_builtin(void)
6770 expression_t *expression;
6772 switch (token.type) {
6773 case T___builtin_isgreater:
6774 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6776 case T___builtin_isgreaterequal:
6777 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6779 case T___builtin_isless:
6780 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6782 case T___builtin_islessequal:
6783 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6785 case T___builtin_islessgreater:
6786 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6788 case T___builtin_isunordered:
6789 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6792 internal_errorf(HERE, "invalid compare builtin found");
6794 expression->base.source_position = *HERE;
6797 expect('(', end_error);
6798 expression->binary.left = parse_assignment_expression();
6799 expect(',', end_error);
6800 expression->binary.right = parse_assignment_expression();
6801 expect(')', end_error);
6803 type_t *const orig_type_left = expression->binary.left->base.type;
6804 type_t *const orig_type_right = expression->binary.right->base.type;
6806 type_t *const type_left = skip_typeref(orig_type_left);
6807 type_t *const type_right = skip_typeref(orig_type_right);
6808 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6809 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6810 type_error_incompatible("invalid operands in comparison",
6811 &expression->base.source_position, orig_type_left, orig_type_right);
6814 semantic_comparison(&expression->binary);
6819 return create_invalid_expression();
6823 * Parses a MS assume() expression.
6825 static expression_t *parse_assume(void)
6827 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6831 expect('(', end_error);
6832 add_anchor_token(')');
6833 expression->unary.value = parse_assignment_expression();
6834 rem_anchor_token(')');
6835 expect(')', end_error);
6837 expression->base.type = type_void;
6840 return create_invalid_expression();
6844 * Return the label for the current symbol or create a new one.
6846 static label_t *get_label(void)
6848 assert(token.type == T_IDENTIFIER);
6849 assert(current_function != NULL);
6851 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6852 /* If we find a local label, we already created the declaration. */
6853 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6854 if (label->base.parent_scope != current_scope) {
6855 assert(label->base.parent_scope->depth < current_scope->depth);
6856 current_function->goto_to_outer = true;
6858 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6859 /* There is no matching label in the same function, so create a new one. */
6860 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6865 return &label->label;
6869 * Parses a GNU && label address expression.
6871 static expression_t *parse_label_address(void)
6873 source_position_t source_position = token.source_position;
6875 if (token.type != T_IDENTIFIER) {
6876 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6877 return create_invalid_expression();
6880 label_t *const label = get_label();
6882 label->address_taken = true;
6884 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6885 expression->base.source_position = source_position;
6887 /* label address is treated as a void pointer */
6888 expression->base.type = type_void_ptr;
6889 expression->label_address.label = label;
6894 * Parse a microsoft __noop expression.
6896 static expression_t *parse_noop_expression(void)
6898 /* the result is a (int)0 */
6899 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6900 literal->base.type = type_int;
6901 literal->literal.value.begin = "__noop";
6902 literal->literal.value.size = 6;
6906 if (token.type == '(') {
6907 /* parse arguments */
6909 add_anchor_token(')');
6910 add_anchor_token(',');
6912 if (token.type != ')') do {
6913 (void)parse_assignment_expression();
6914 } while (next_if(','));
6916 rem_anchor_token(',');
6917 rem_anchor_token(')');
6918 expect(')', end_error);
6925 * Parses a primary expression.
6927 static expression_t *parse_primary_expression(void)
6929 switch (token.type) {
6930 case T_false: return parse_boolean_literal(false);
6931 case T_true: return parse_boolean_literal(true);
6933 case T_INTEGER_OCTAL:
6934 case T_INTEGER_HEXADECIMAL:
6935 case T_FLOATINGPOINT:
6936 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6937 case T_CHARACTER_CONSTANT: return parse_character_constant();
6938 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6939 case T_STRING_LITERAL:
6940 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6941 case T___FUNCTION__:
6942 case T___func__: return parse_function_keyword();
6943 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6944 case T___FUNCSIG__: return parse_funcsig_keyword();
6945 case T___FUNCDNAME__: return parse_funcdname_keyword();
6946 case T___builtin_offsetof: return parse_offsetof();
6947 case T___builtin_va_start: return parse_va_start();
6948 case T___builtin_va_arg: return parse_va_arg();
6949 case T___builtin_va_copy: return parse_va_copy();
6950 case T___builtin_isgreater:
6951 case T___builtin_isgreaterequal:
6952 case T___builtin_isless:
6953 case T___builtin_islessequal:
6954 case T___builtin_islessgreater:
6955 case T___builtin_isunordered: return parse_compare_builtin();
6956 case T___builtin_constant_p: return parse_builtin_constant();
6957 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6958 case T__assume: return parse_assume();
6961 return parse_label_address();
6964 case '(': return parse_parenthesized_expression();
6965 case T___noop: return parse_noop_expression();
6967 /* Gracefully handle type names while parsing expressions. */
6969 return parse_reference();
6971 if (!is_typedef_symbol(token.symbol)) {
6972 return parse_reference();
6976 source_position_t const pos = *HERE;
6977 declaration_specifiers_t specifiers;
6978 parse_declaration_specifiers(&specifiers);
6979 type_t const *const type = parse_abstract_declarator(specifiers.type);
6980 errorf(&pos, "encountered type '%T' while parsing expression", type);
6981 return create_invalid_expression();
6985 errorf(HERE, "unexpected token %K, expected an expression", &token);
6987 return create_invalid_expression();
6990 static expression_t *parse_array_expression(expression_t *left)
6992 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6993 array_access_expression_t *const arr = &expr->array_access;
6996 add_anchor_token(']');
6998 expression_t *const inside = parse_expression();
7000 type_t *const orig_type_left = left->base.type;
7001 type_t *const orig_type_inside = inside->base.type;
7003 type_t *const type_left = skip_typeref(orig_type_left);
7004 type_t *const type_inside = skip_typeref(orig_type_inside);
7010 if (is_type_pointer(type_left)) {
7013 idx_type = type_inside;
7014 res_type = type_left->pointer.points_to;
7016 } else if (is_type_pointer(type_inside)) {
7017 arr->flipped = true;
7020 idx_type = type_left;
7021 res_type = type_inside->pointer.points_to;
7023 res_type = automatic_type_conversion(res_type);
7024 if (!is_type_integer(idx_type)) {
7025 errorf(&idx->base.source_position, "array subscript must have integer type");
7026 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
7027 source_position_t const *const pos = &idx->base.source_position;
7028 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
7031 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7032 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7034 res_type = type_error_type;
7039 arr->array_ref = ref;
7041 arr->base.type = res_type;
7043 rem_anchor_token(']');
7044 expect(']', end_error);
7049 static expression_t *parse_typeprop(expression_kind_t const kind)
7051 expression_t *tp_expression = allocate_expression_zero(kind);
7052 tp_expression->base.type = type_size_t;
7054 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7056 /* we only refer to a type property, mark this case */
7057 bool old = in_type_prop;
7058 in_type_prop = true;
7061 expression_t *expression;
7062 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7063 source_position_t const pos = *HERE;
7065 add_anchor_token(')');
7066 orig_type = parse_typename();
7067 rem_anchor_token(')');
7068 expect(')', end_error);
7070 if (token.type == '{') {
7071 /* It was not sizeof(type) after all. It is sizeof of an expression
7072 * starting with a compound literal */
7073 expression = parse_compound_literal(&pos, orig_type);
7074 goto typeprop_expression;
7077 expression = parse_subexpression(PREC_UNARY);
7079 typeprop_expression:
7080 tp_expression->typeprop.tp_expression = expression;
7082 orig_type = revert_automatic_type_conversion(expression);
7083 expression->base.type = orig_type;
7086 tp_expression->typeprop.type = orig_type;
7087 type_t const* const type = skip_typeref(orig_type);
7088 char const* wrong_type = NULL;
7089 if (is_type_incomplete(type)) {
7090 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7091 wrong_type = "incomplete";
7092 } else if (type->kind == TYPE_FUNCTION) {
7094 /* function types are allowed (and return 1) */
7095 source_position_t const *const pos = &tp_expression->base.source_position;
7096 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7097 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7099 wrong_type = "function";
7102 if (is_type_incomplete(type))
7103 wrong_type = "incomplete";
7105 if (type->kind == TYPE_BITFIELD)
7106 wrong_type = "bitfield";
7108 if (wrong_type != NULL) {
7109 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7110 errorf(&tp_expression->base.source_position,
7111 "operand of %s expression must not be of %s type '%T'",
7112 what, wrong_type, orig_type);
7117 return tp_expression;
7120 static expression_t *parse_sizeof(void)
7122 return parse_typeprop(EXPR_SIZEOF);
7125 static expression_t *parse_alignof(void)
7127 return parse_typeprop(EXPR_ALIGNOF);
7130 static expression_t *parse_select_expression(expression_t *addr)
7132 assert(token.type == '.' || token.type == T_MINUSGREATER);
7133 bool select_left_arrow = (token.type == T_MINUSGREATER);
7134 source_position_t const pos = *HERE;
7137 if (token.type != T_IDENTIFIER) {
7138 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7139 return create_invalid_expression();
7141 symbol_t *symbol = token.symbol;
7144 type_t *const orig_type = addr->base.type;
7145 type_t *const type = skip_typeref(orig_type);
7148 bool saw_error = false;
7149 if (is_type_pointer(type)) {
7150 if (!select_left_arrow) {
7152 "request for member '%Y' in something not a struct or union, but '%T'",
7156 type_left = skip_typeref(type->pointer.points_to);
7158 if (select_left_arrow && is_type_valid(type)) {
7159 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7165 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7166 type_left->kind != TYPE_COMPOUND_UNION) {
7168 if (is_type_valid(type_left) && !saw_error) {
7170 "request for member '%Y' in something not a struct or union, but '%T'",
7173 return create_invalid_expression();
7176 compound_t *compound = type_left->compound.compound;
7177 if (!compound->complete) {
7178 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7180 return create_invalid_expression();
7183 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7184 expression_t *result =
7185 find_create_select(&pos, addr, qualifiers, compound, symbol);
7187 if (result == NULL) {
7188 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7189 return create_invalid_expression();
7195 static void check_call_argument(type_t *expected_type,
7196 call_argument_t *argument, unsigned pos)
7198 type_t *expected_type_skip = skip_typeref(expected_type);
7199 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7200 expression_t *arg_expr = argument->expression;
7201 type_t *arg_type = skip_typeref(arg_expr->base.type);
7203 /* handle transparent union gnu extension */
7204 if (is_type_union(expected_type_skip)
7205 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7206 compound_t *union_decl = expected_type_skip->compound.compound;
7207 type_t *best_type = NULL;
7208 entity_t *entry = union_decl->members.entities;
7209 for ( ; entry != NULL; entry = entry->base.next) {
7210 assert(is_declaration(entry));
7211 type_t *decl_type = entry->declaration.type;
7212 error = semantic_assign(decl_type, arg_expr);
7213 if (error == ASSIGN_ERROR_INCOMPATIBLE
7214 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7217 if (error == ASSIGN_SUCCESS) {
7218 best_type = decl_type;
7219 } else if (best_type == NULL) {
7220 best_type = decl_type;
7224 if (best_type != NULL) {
7225 expected_type = best_type;
7229 error = semantic_assign(expected_type, arg_expr);
7230 argument->expression = create_implicit_cast(arg_expr, expected_type);
7232 if (error != ASSIGN_SUCCESS) {
7233 /* report exact scope in error messages (like "in argument 3") */
7235 snprintf(buf, sizeof(buf), "call argument %u", pos);
7236 report_assign_error(error, expected_type, arg_expr, buf,
7237 &arg_expr->base.source_position);
7239 type_t *const promoted_type = get_default_promoted_type(arg_type);
7240 if (!types_compatible(expected_type_skip, promoted_type) &&
7241 !types_compatible(expected_type_skip, type_void_ptr) &&
7242 !types_compatible(type_void_ptr, promoted_type)) {
7243 /* Deliberately show the skipped types in this warning */
7244 source_position_t const *const apos = &arg_expr->base.source_position;
7245 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7251 * Handle the semantic restrictions of builtin calls
7253 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7254 switch (call->function->reference.entity->function.btk) {
7255 case bk_gnu_builtin_return_address:
7256 case bk_gnu_builtin_frame_address: {
7257 /* argument must be constant */
7258 call_argument_t *argument = call->arguments;
7260 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7261 errorf(&call->base.source_position,
7262 "argument of '%Y' must be a constant expression",
7263 call->function->reference.entity->base.symbol);
7267 case bk_gnu_builtin_object_size:
7268 if (call->arguments == NULL)
7271 call_argument_t *arg = call->arguments->next;
7272 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7273 errorf(&call->base.source_position,
7274 "second argument of '%Y' must be a constant expression",
7275 call->function->reference.entity->base.symbol);
7278 case bk_gnu_builtin_prefetch:
7279 /* second and third argument must be constant if existent */
7280 if (call->arguments == NULL)
7282 call_argument_t *rw = call->arguments->next;
7283 call_argument_t *locality = NULL;
7286 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7287 errorf(&call->base.source_position,
7288 "second argument of '%Y' must be a constant expression",
7289 call->function->reference.entity->base.symbol);
7291 locality = rw->next;
7293 if (locality != NULL) {
7294 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7295 errorf(&call->base.source_position,
7296 "third argument of '%Y' must be a constant expression",
7297 call->function->reference.entity->base.symbol);
7299 locality = rw->next;
7308 * Parse a call expression, ie. expression '( ... )'.
7310 * @param expression the function address
7312 static expression_t *parse_call_expression(expression_t *expression)
7314 expression_t *result = allocate_expression_zero(EXPR_CALL);
7315 call_expression_t *call = &result->call;
7316 call->function = expression;
7318 type_t *const orig_type = expression->base.type;
7319 type_t *const type = skip_typeref(orig_type);
7321 function_type_t *function_type = NULL;
7322 if (is_type_pointer(type)) {
7323 type_t *const to_type = skip_typeref(type->pointer.points_to);
7325 if (is_type_function(to_type)) {
7326 function_type = &to_type->function;
7327 call->base.type = function_type->return_type;
7331 if (function_type == NULL && is_type_valid(type)) {
7333 "called object '%E' (type '%T') is not a pointer to a function",
7334 expression, orig_type);
7337 /* parse arguments */
7339 add_anchor_token(')');
7340 add_anchor_token(',');
7342 if (token.type != ')') {
7343 call_argument_t **anchor = &call->arguments;
7345 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7346 argument->expression = parse_assignment_expression();
7349 anchor = &argument->next;
7350 } while (next_if(','));
7352 rem_anchor_token(',');
7353 rem_anchor_token(')');
7354 expect(')', end_error);
7356 if (function_type == NULL)
7359 /* check type and count of call arguments */
7360 function_parameter_t *parameter = function_type->parameters;
7361 call_argument_t *argument = call->arguments;
7362 if (!function_type->unspecified_parameters) {
7363 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7364 parameter = parameter->next, argument = argument->next) {
7365 check_call_argument(parameter->type, argument, ++pos);
7368 if (parameter != NULL) {
7369 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7370 } else if (argument != NULL && !function_type->variadic) {
7371 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7375 /* do default promotion for other arguments */
7376 for (; argument != NULL; argument = argument->next) {
7377 type_t *argument_type = argument->expression->base.type;
7378 if (!is_type_object(skip_typeref(argument_type))) {
7379 errorf(&argument->expression->base.source_position,
7380 "call argument '%E' must not be void", argument->expression);
7383 argument_type = get_default_promoted_type(argument_type);
7385 argument->expression
7386 = create_implicit_cast(argument->expression, argument_type);
7391 if (is_type_compound(skip_typeref(function_type->return_type))) {
7392 source_position_t const *const pos = &expression->base.source_position;
7393 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7396 if (expression->kind == EXPR_REFERENCE) {
7397 reference_expression_t *reference = &expression->reference;
7398 if (reference->entity->kind == ENTITY_FUNCTION &&
7399 reference->entity->function.btk != bk_none)
7400 handle_builtin_argument_restrictions(call);
7407 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7409 static bool same_compound_type(const type_t *type1, const type_t *type2)
7412 is_type_compound(type1) &&
7413 type1->kind == type2->kind &&
7414 type1->compound.compound == type2->compound.compound;
7417 static expression_t const *get_reference_address(expression_t const *expr)
7419 bool regular_take_address = true;
7421 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7422 expr = expr->unary.value;
7424 regular_take_address = false;
7427 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7430 expr = expr->unary.value;
7433 if (expr->kind != EXPR_REFERENCE)
7436 /* special case for functions which are automatically converted to a
7437 * pointer to function without an extra TAKE_ADDRESS operation */
7438 if (!regular_take_address &&
7439 expr->reference.entity->kind != ENTITY_FUNCTION) {
7446 static void warn_reference_address_as_bool(expression_t const* expr)
7448 expr = get_reference_address(expr);
7450 source_position_t const *const pos = &expr->base.source_position;
7451 entity_t const *const ent = expr->reference.entity;
7452 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7456 static void warn_assignment_in_condition(const expression_t *const expr)
7458 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7460 if (expr->base.parenthesized)
7462 source_position_t const *const pos = &expr->base.source_position;
7463 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7466 static void semantic_condition(expression_t const *const expr,
7467 char const *const context)
7469 type_t *const type = skip_typeref(expr->base.type);
7470 if (is_type_scalar(type)) {
7471 warn_reference_address_as_bool(expr);
7472 warn_assignment_in_condition(expr);
7473 } else if (is_type_valid(type)) {
7474 errorf(&expr->base.source_position,
7475 "%s must have scalar type", context);
7480 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7482 * @param expression the conditional expression
7484 static expression_t *parse_conditional_expression(expression_t *expression)
7486 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7488 conditional_expression_t *conditional = &result->conditional;
7489 conditional->condition = expression;
7492 add_anchor_token(':');
7494 /* §6.5.15:2 The first operand shall have scalar type. */
7495 semantic_condition(expression, "condition of conditional operator");
7497 expression_t *true_expression = expression;
7498 bool gnu_cond = false;
7499 if (GNU_MODE && token.type == ':') {
7502 true_expression = parse_expression();
7504 rem_anchor_token(':');
7505 expect(':', end_error);
7507 expression_t *false_expression =
7508 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7510 type_t *const orig_true_type = true_expression->base.type;
7511 type_t *const orig_false_type = false_expression->base.type;
7512 type_t *const true_type = skip_typeref(orig_true_type);
7513 type_t *const false_type = skip_typeref(orig_false_type);
7516 source_position_t const *const pos = &conditional->base.source_position;
7517 type_t *result_type;
7518 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7519 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7520 /* ISO/IEC 14882:1998(E) §5.16:2 */
7521 if (true_expression->kind == EXPR_UNARY_THROW) {
7522 result_type = false_type;
7523 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7524 result_type = true_type;
7526 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7527 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7528 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7530 result_type = type_void;
7532 } else if (is_type_arithmetic(true_type)
7533 && is_type_arithmetic(false_type)) {
7534 result_type = semantic_arithmetic(true_type, false_type);
7535 } else if (same_compound_type(true_type, false_type)) {
7536 /* just take 1 of the 2 types */
7537 result_type = true_type;
7538 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7539 type_t *pointer_type;
7541 expression_t *other_expression;
7542 if (is_type_pointer(true_type) &&
7543 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7544 pointer_type = true_type;
7545 other_type = false_type;
7546 other_expression = false_expression;
7548 pointer_type = false_type;
7549 other_type = true_type;
7550 other_expression = true_expression;
7553 if (is_null_pointer_constant(other_expression)) {
7554 result_type = pointer_type;
7555 } else if (is_type_pointer(other_type)) {
7556 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7557 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7560 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7561 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7563 } else if (types_compatible(get_unqualified_type(to1),
7564 get_unqualified_type(to2))) {
7567 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7571 type_t *const type =
7572 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7573 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7574 } else if (is_type_integer(other_type)) {
7575 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7576 result_type = pointer_type;
7578 goto types_incompatible;
7582 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7583 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7585 result_type = type_error_type;
7588 conditional->true_expression
7589 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7590 conditional->false_expression
7591 = create_implicit_cast(false_expression, result_type);
7592 conditional->base.type = result_type;
7597 * Parse an extension expression.
7599 static expression_t *parse_extension(void)
7602 expression_t *expression = parse_subexpression(PREC_UNARY);
7608 * Parse a __builtin_classify_type() expression.
7610 static expression_t *parse_builtin_classify_type(void)
7612 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7613 result->base.type = type_int;
7615 eat(T___builtin_classify_type);
7617 expect('(', end_error);
7618 add_anchor_token(')');
7619 expression_t *expression = parse_expression();
7620 rem_anchor_token(')');
7621 expect(')', end_error);
7622 result->classify_type.type_expression = expression;
7626 return create_invalid_expression();
7630 * Parse a delete expression
7631 * ISO/IEC 14882:1998(E) §5.3.5
7633 static expression_t *parse_delete(void)
7635 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7636 result->base.type = type_void;
7641 result->kind = EXPR_UNARY_DELETE_ARRAY;
7642 expect(']', end_error);
7646 expression_t *const value = parse_subexpression(PREC_CAST);
7647 result->unary.value = value;
7649 type_t *const type = skip_typeref(value->base.type);
7650 if (!is_type_pointer(type)) {
7651 if (is_type_valid(type)) {
7652 errorf(&value->base.source_position,
7653 "operand of delete must have pointer type");
7655 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7656 source_position_t const *const pos = &value->base.source_position;
7657 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7664 * Parse a throw expression
7665 * ISO/IEC 14882:1998(E) §15:1
7667 static expression_t *parse_throw(void)
7669 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7670 result->base.type = type_void;
7674 expression_t *value = NULL;
7675 switch (token.type) {
7677 value = parse_assignment_expression();
7678 /* ISO/IEC 14882:1998(E) §15.1:3 */
7679 type_t *const orig_type = value->base.type;
7680 type_t *const type = skip_typeref(orig_type);
7681 if (is_type_incomplete(type)) {
7682 errorf(&value->base.source_position,
7683 "cannot throw object of incomplete type '%T'", orig_type);
7684 } else if (is_type_pointer(type)) {
7685 type_t *const points_to = skip_typeref(type->pointer.points_to);
7686 if (is_type_incomplete(points_to) &&
7687 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7688 errorf(&value->base.source_position,
7689 "cannot throw pointer to incomplete type '%T'", orig_type);
7697 result->unary.value = value;
7702 static bool check_pointer_arithmetic(const source_position_t *source_position,
7703 type_t *pointer_type,
7704 type_t *orig_pointer_type)
7706 type_t *points_to = pointer_type->pointer.points_to;
7707 points_to = skip_typeref(points_to);
7709 if (is_type_incomplete(points_to)) {
7710 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7711 errorf(source_position,
7712 "arithmetic with pointer to incomplete type '%T' not allowed",
7716 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7718 } else if (is_type_function(points_to)) {
7720 errorf(source_position,
7721 "arithmetic with pointer to function type '%T' not allowed",
7725 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7731 static bool is_lvalue(const expression_t *expression)
7733 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7734 switch (expression->kind) {
7735 case EXPR_ARRAY_ACCESS:
7736 case EXPR_COMPOUND_LITERAL:
7737 case EXPR_REFERENCE:
7739 case EXPR_UNARY_DEREFERENCE:
7743 type_t *type = skip_typeref(expression->base.type);
7745 /* ISO/IEC 14882:1998(E) §3.10:3 */
7746 is_type_reference(type) ||
7747 /* Claim it is an lvalue, if the type is invalid. There was a parse
7748 * error before, which maybe prevented properly recognizing it as
7750 !is_type_valid(type);
7755 static void semantic_incdec(unary_expression_t *expression)
7757 type_t *const orig_type = expression->value->base.type;
7758 type_t *const type = skip_typeref(orig_type);
7759 if (is_type_pointer(type)) {
7760 if (!check_pointer_arithmetic(&expression->base.source_position,
7764 } else if (!is_type_real(type) && is_type_valid(type)) {
7765 /* TODO: improve error message */
7766 errorf(&expression->base.source_position,
7767 "operation needs an arithmetic or pointer type");
7770 if (!is_lvalue(expression->value)) {
7771 /* TODO: improve error message */
7772 errorf(&expression->base.source_position, "lvalue required as operand");
7774 expression->base.type = orig_type;
7777 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7779 type_t *const orig_type = expression->value->base.type;
7780 type_t *const type = skip_typeref(orig_type);
7781 if (!is_type_arithmetic(type)) {
7782 if (is_type_valid(type)) {
7783 /* TODO: improve error message */
7784 errorf(&expression->base.source_position,
7785 "operation needs an arithmetic type");
7790 expression->base.type = orig_type;
7793 static void semantic_unexpr_plus(unary_expression_t *expression)
7795 semantic_unexpr_arithmetic(expression);
7796 source_position_t const *const pos = &expression->base.source_position;
7797 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7800 static void semantic_not(unary_expression_t *expression)
7802 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7803 semantic_condition(expression->value, "operand of !");
7804 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7807 static void semantic_unexpr_integer(unary_expression_t *expression)
7809 type_t *const orig_type = expression->value->base.type;
7810 type_t *const type = skip_typeref(orig_type);
7811 if (!is_type_integer(type)) {
7812 if (is_type_valid(type)) {
7813 errorf(&expression->base.source_position,
7814 "operand of ~ must be of integer type");
7819 expression->base.type = orig_type;
7822 static void semantic_dereference(unary_expression_t *expression)
7824 type_t *const orig_type = expression->value->base.type;
7825 type_t *const type = skip_typeref(orig_type);
7826 if (!is_type_pointer(type)) {
7827 if (is_type_valid(type)) {
7828 errorf(&expression->base.source_position,
7829 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7834 type_t *result_type = type->pointer.points_to;
7835 result_type = automatic_type_conversion(result_type);
7836 expression->base.type = result_type;
7840 * Record that an address is taken (expression represents an lvalue).
7842 * @param expression the expression
7843 * @param may_be_register if true, the expression might be an register
7845 static void set_address_taken(expression_t *expression, bool may_be_register)
7847 if (expression->kind != EXPR_REFERENCE)
7850 entity_t *const entity = expression->reference.entity;
7852 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7855 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7856 && !may_be_register) {
7857 source_position_t const *const pos = &expression->base.source_position;
7858 errorf(pos, "address of register '%N' requested", entity);
7861 if (entity->kind == ENTITY_VARIABLE) {
7862 entity->variable.address_taken = true;
7864 assert(entity->kind == ENTITY_PARAMETER);
7865 entity->parameter.address_taken = true;
7870 * Check the semantic of the address taken expression.
7872 static void semantic_take_addr(unary_expression_t *expression)
7874 expression_t *value = expression->value;
7875 value->base.type = revert_automatic_type_conversion(value);
7877 type_t *orig_type = value->base.type;
7878 type_t *type = skip_typeref(orig_type);
7879 if (!is_type_valid(type))
7883 if (!is_lvalue(value)) {
7884 errorf(&expression->base.source_position, "'&' requires an lvalue");
7886 if (type->kind == TYPE_BITFIELD) {
7887 errorf(&expression->base.source_position,
7888 "'&' not allowed on object with bitfield type '%T'",
7892 set_address_taken(value, false);
7894 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7897 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7898 static expression_t *parse_##unexpression_type(void) \
7900 expression_t *unary_expression \
7901 = allocate_expression_zero(unexpression_type); \
7903 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7905 sfunc(&unary_expression->unary); \
7907 return unary_expression; \
7910 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7911 semantic_unexpr_arithmetic)
7912 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7913 semantic_unexpr_plus)
7914 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7916 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7917 semantic_dereference)
7918 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7920 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7921 semantic_unexpr_integer)
7922 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7924 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7927 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7929 static expression_t *parse_##unexpression_type(expression_t *left) \
7931 expression_t *unary_expression \
7932 = allocate_expression_zero(unexpression_type); \
7934 unary_expression->unary.value = left; \
7936 sfunc(&unary_expression->unary); \
7938 return unary_expression; \
7941 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7942 EXPR_UNARY_POSTFIX_INCREMENT,
7944 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7945 EXPR_UNARY_POSTFIX_DECREMENT,
7948 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7950 /* TODO: handle complex + imaginary types */
7952 type_left = get_unqualified_type(type_left);
7953 type_right = get_unqualified_type(type_right);
7955 /* §6.3.1.8 Usual arithmetic conversions */
7956 if (type_left == type_long_double || type_right == type_long_double) {
7957 return type_long_double;
7958 } else if (type_left == type_double || type_right == type_double) {
7960 } else if (type_left == type_float || type_right == type_float) {
7964 type_left = promote_integer(type_left);
7965 type_right = promote_integer(type_right);
7967 if (type_left == type_right)
7970 bool const signed_left = is_type_signed(type_left);
7971 bool const signed_right = is_type_signed(type_right);
7972 int const rank_left = get_rank(type_left);
7973 int const rank_right = get_rank(type_right);
7975 if (signed_left == signed_right)
7976 return rank_left >= rank_right ? type_left : type_right;
7985 u_rank = rank_right;
7986 u_type = type_right;
7988 s_rank = rank_right;
7989 s_type = type_right;
7994 if (u_rank >= s_rank)
7997 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7999 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8000 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8004 case ATOMIC_TYPE_INT: return type_unsigned_int;
8005 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8006 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8008 default: panic("invalid atomic type");
8013 * Check the semantic restrictions for a binary expression.
8015 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8017 expression_t *const left = expression->left;
8018 expression_t *const right = expression->right;
8019 type_t *const orig_type_left = left->base.type;
8020 type_t *const orig_type_right = right->base.type;
8021 type_t *const type_left = skip_typeref(orig_type_left);
8022 type_t *const type_right = skip_typeref(orig_type_right);
8024 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8025 /* TODO: improve error message */
8026 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8027 errorf(&expression->base.source_position,
8028 "operation needs arithmetic types");
8033 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8034 expression->left = create_implicit_cast(left, arithmetic_type);
8035 expression->right = create_implicit_cast(right, arithmetic_type);
8036 expression->base.type = arithmetic_type;
8039 static void semantic_binexpr_integer(binary_expression_t *const expression)
8041 expression_t *const left = expression->left;
8042 expression_t *const right = expression->right;
8043 type_t *const orig_type_left = left->base.type;
8044 type_t *const orig_type_right = right->base.type;
8045 type_t *const type_left = skip_typeref(orig_type_left);
8046 type_t *const type_right = skip_typeref(orig_type_right);
8048 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8049 /* TODO: improve error message */
8050 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8051 errorf(&expression->base.source_position,
8052 "operation needs integer types");
8057 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8058 expression->left = create_implicit_cast(left, result_type);
8059 expression->right = create_implicit_cast(right, result_type);
8060 expression->base.type = result_type;
8063 static void warn_div_by_zero(binary_expression_t const *const expression)
8065 if (!is_type_integer(expression->base.type))
8068 expression_t const *const right = expression->right;
8069 /* The type of the right operand can be different for /= */
8070 if (is_type_integer(right->base.type) &&
8071 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8072 !fold_constant_to_bool(right)) {
8073 source_position_t const *const pos = &expression->base.source_position;
8074 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8079 * Check the semantic restrictions for a div/mod expression.
8081 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8083 semantic_binexpr_arithmetic(expression);
8084 warn_div_by_zero(expression);
8087 static void warn_addsub_in_shift(const expression_t *const expr)
8089 if (expr->base.parenthesized)
8093 switch (expr->kind) {
8094 case EXPR_BINARY_ADD: op = '+'; break;
8095 case EXPR_BINARY_SUB: op = '-'; break;
8099 source_position_t const *const pos = &expr->base.source_position;
8100 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8103 static bool semantic_shift(binary_expression_t *expression)
8105 expression_t *const left = expression->left;
8106 expression_t *const right = expression->right;
8107 type_t *const orig_type_left = left->base.type;
8108 type_t *const orig_type_right = right->base.type;
8109 type_t * type_left = skip_typeref(orig_type_left);
8110 type_t * type_right = skip_typeref(orig_type_right);
8112 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8113 /* TODO: improve error message */
8114 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8115 errorf(&expression->base.source_position,
8116 "operands of shift operation must have integer types");
8121 type_left = promote_integer(type_left);
8123 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8124 source_position_t const *const pos = &right->base.source_position;
8125 long const count = fold_constant_to_int(right);
8127 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8128 } else if ((unsigned long)count >=
8129 get_atomic_type_size(type_left->atomic.akind) * 8) {
8130 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8134 type_right = promote_integer(type_right);
8135 expression->right = create_implicit_cast(right, type_right);
8140 static void semantic_shift_op(binary_expression_t *expression)
8142 expression_t *const left = expression->left;
8143 expression_t *const right = expression->right;
8145 if (!semantic_shift(expression))
8148 warn_addsub_in_shift(left);
8149 warn_addsub_in_shift(right);
8151 type_t *const orig_type_left = left->base.type;
8152 type_t * type_left = skip_typeref(orig_type_left);
8154 type_left = promote_integer(type_left);
8155 expression->left = create_implicit_cast(left, type_left);
8156 expression->base.type = type_left;
8159 static void semantic_add(binary_expression_t *expression)
8161 expression_t *const left = expression->left;
8162 expression_t *const right = expression->right;
8163 type_t *const orig_type_left = left->base.type;
8164 type_t *const orig_type_right = right->base.type;
8165 type_t *const type_left = skip_typeref(orig_type_left);
8166 type_t *const type_right = skip_typeref(orig_type_right);
8169 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8170 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8171 expression->left = create_implicit_cast(left, arithmetic_type);
8172 expression->right = create_implicit_cast(right, arithmetic_type);
8173 expression->base.type = arithmetic_type;
8174 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8175 check_pointer_arithmetic(&expression->base.source_position,
8176 type_left, orig_type_left);
8177 expression->base.type = type_left;
8178 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8179 check_pointer_arithmetic(&expression->base.source_position,
8180 type_right, orig_type_right);
8181 expression->base.type = type_right;
8182 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8183 errorf(&expression->base.source_position,
8184 "invalid operands to binary + ('%T', '%T')",
8185 orig_type_left, orig_type_right);
8189 static void semantic_sub(binary_expression_t *expression)
8191 expression_t *const left = expression->left;
8192 expression_t *const right = expression->right;
8193 type_t *const orig_type_left = left->base.type;
8194 type_t *const orig_type_right = right->base.type;
8195 type_t *const type_left = skip_typeref(orig_type_left);
8196 type_t *const type_right = skip_typeref(orig_type_right);
8197 source_position_t const *const pos = &expression->base.source_position;
8200 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8201 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8202 expression->left = create_implicit_cast(left, arithmetic_type);
8203 expression->right = create_implicit_cast(right, arithmetic_type);
8204 expression->base.type = arithmetic_type;
8205 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8206 check_pointer_arithmetic(&expression->base.source_position,
8207 type_left, orig_type_left);
8208 expression->base.type = type_left;
8209 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8210 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8211 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8212 if (!types_compatible(unqual_left, unqual_right)) {
8214 "subtracting pointers to incompatible types '%T' and '%T'",
8215 orig_type_left, orig_type_right);
8216 } else if (!is_type_object(unqual_left)) {
8217 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8218 errorf(pos, "subtracting pointers to non-object types '%T'",
8221 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8224 expression->base.type = type_ptrdiff_t;
8225 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8226 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8227 orig_type_left, orig_type_right);
8231 static void warn_string_literal_address(expression_t const* expr)
8233 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8234 expr = expr->unary.value;
8235 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8237 expr = expr->unary.value;
8240 if (expr->kind == EXPR_STRING_LITERAL
8241 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8242 source_position_t const *const pos = &expr->base.source_position;
8243 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8247 static bool maybe_negative(expression_t const *const expr)
8249 switch (is_constant_expression(expr)) {
8250 case EXPR_CLASS_ERROR: return false;
8251 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8252 default: return true;
8256 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8258 warn_string_literal_address(expr);
8260 expression_t const* const ref = get_reference_address(expr);
8261 if (ref != NULL && is_null_pointer_constant(other)) {
8262 entity_t const *const ent = ref->reference.entity;
8263 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8266 if (!expr->base.parenthesized) {
8267 switch (expr->base.kind) {
8268 case EXPR_BINARY_LESS:
8269 case EXPR_BINARY_GREATER:
8270 case EXPR_BINARY_LESSEQUAL:
8271 case EXPR_BINARY_GREATEREQUAL:
8272 case EXPR_BINARY_NOTEQUAL:
8273 case EXPR_BINARY_EQUAL:
8274 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8283 * Check the semantics of comparison expressions.
8285 * @param expression The expression to check.
8287 static void semantic_comparison(binary_expression_t *expression)
8289 source_position_t const *const pos = &expression->base.source_position;
8290 expression_t *const left = expression->left;
8291 expression_t *const right = expression->right;
8293 warn_comparison(pos, left, right);
8294 warn_comparison(pos, right, left);
8296 type_t *orig_type_left = left->base.type;
8297 type_t *orig_type_right = right->base.type;
8298 type_t *type_left = skip_typeref(orig_type_left);
8299 type_t *type_right = skip_typeref(orig_type_right);
8301 /* TODO non-arithmetic types */
8302 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8303 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8305 /* test for signed vs unsigned compares */
8306 if (is_type_integer(arithmetic_type)) {
8307 bool const signed_left = is_type_signed(type_left);
8308 bool const signed_right = is_type_signed(type_right);
8309 if (signed_left != signed_right) {
8310 /* FIXME long long needs better const folding magic */
8311 /* TODO check whether constant value can be represented by other type */
8312 if ((signed_left && maybe_negative(left)) ||
8313 (signed_right && maybe_negative(right))) {
8314 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8319 expression->left = create_implicit_cast(left, arithmetic_type);
8320 expression->right = create_implicit_cast(right, arithmetic_type);
8321 expression->base.type = arithmetic_type;
8322 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8323 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8324 is_type_float(arithmetic_type)) {
8325 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8327 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8328 /* TODO check compatibility */
8329 } else if (is_type_pointer(type_left)) {
8330 expression->right = create_implicit_cast(right, type_left);
8331 } else if (is_type_pointer(type_right)) {
8332 expression->left = create_implicit_cast(left, type_right);
8333 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8334 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8336 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8340 * Checks if a compound type has constant fields.
8342 static bool has_const_fields(const compound_type_t *type)
8344 compound_t *compound = type->compound;
8345 entity_t *entry = compound->members.entities;
8347 for (; entry != NULL; entry = entry->base.next) {
8348 if (!is_declaration(entry))
8351 const type_t *decl_type = skip_typeref(entry->declaration.type);
8352 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8359 static bool is_valid_assignment_lhs(expression_t const* const left)
8361 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8362 type_t *const type_left = skip_typeref(orig_type_left);
8364 if (!is_lvalue(left)) {
8365 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8370 if (left->kind == EXPR_REFERENCE
8371 && left->reference.entity->kind == ENTITY_FUNCTION) {
8372 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8376 if (is_type_array(type_left)) {
8377 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8380 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8381 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8385 if (is_type_incomplete(type_left)) {
8386 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8387 left, orig_type_left);
8390 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8391 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8392 left, orig_type_left);
8399 static void semantic_arithmetic_assign(binary_expression_t *expression)
8401 expression_t *left = expression->left;
8402 expression_t *right = expression->right;
8403 type_t *orig_type_left = left->base.type;
8404 type_t *orig_type_right = right->base.type;
8406 if (!is_valid_assignment_lhs(left))
8409 type_t *type_left = skip_typeref(orig_type_left);
8410 type_t *type_right = skip_typeref(orig_type_right);
8412 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8413 /* TODO: improve error message */
8414 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8415 errorf(&expression->base.source_position,
8416 "operation needs arithmetic types");
8421 /* combined instructions are tricky. We can't create an implicit cast on
8422 * the left side, because we need the uncasted form for the store.
8423 * The ast2firm pass has to know that left_type must be right_type
8424 * for the arithmetic operation and create a cast by itself */
8425 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8426 expression->right = create_implicit_cast(right, arithmetic_type);
8427 expression->base.type = type_left;
8430 static void semantic_divmod_assign(binary_expression_t *expression)
8432 semantic_arithmetic_assign(expression);
8433 warn_div_by_zero(expression);
8436 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8438 expression_t *const left = expression->left;
8439 expression_t *const right = expression->right;
8440 type_t *const orig_type_left = left->base.type;
8441 type_t *const orig_type_right = right->base.type;
8442 type_t *const type_left = skip_typeref(orig_type_left);
8443 type_t *const type_right = skip_typeref(orig_type_right);
8445 if (!is_valid_assignment_lhs(left))
8448 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8449 /* combined instructions are tricky. We can't create an implicit cast on
8450 * the left side, because we need the uncasted form for the store.
8451 * The ast2firm pass has to know that left_type must be right_type
8452 * for the arithmetic operation and create a cast by itself */
8453 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8454 expression->right = create_implicit_cast(right, arithmetic_type);
8455 expression->base.type = type_left;
8456 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8457 check_pointer_arithmetic(&expression->base.source_position,
8458 type_left, orig_type_left);
8459 expression->base.type = type_left;
8460 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8461 errorf(&expression->base.source_position,
8462 "incompatible types '%T' and '%T' in assignment",
8463 orig_type_left, orig_type_right);
8467 static void semantic_integer_assign(binary_expression_t *expression)
8469 expression_t *left = expression->left;
8470 expression_t *right = expression->right;
8471 type_t *orig_type_left = left->base.type;
8472 type_t *orig_type_right = right->base.type;
8474 if (!is_valid_assignment_lhs(left))
8477 type_t *type_left = skip_typeref(orig_type_left);
8478 type_t *type_right = skip_typeref(orig_type_right);
8480 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8481 /* TODO: improve error message */
8482 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8483 errorf(&expression->base.source_position,
8484 "operation needs integer types");
8489 /* combined instructions are tricky. We can't create an implicit cast on
8490 * the left side, because we need the uncasted form for the store.
8491 * The ast2firm pass has to know that left_type must be right_type
8492 * for the arithmetic operation and create a cast by itself */
8493 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8494 expression->right = create_implicit_cast(right, arithmetic_type);
8495 expression->base.type = type_left;
8498 static void semantic_shift_assign(binary_expression_t *expression)
8500 expression_t *left = expression->left;
8502 if (!is_valid_assignment_lhs(left))
8505 if (!semantic_shift(expression))
8508 expression->base.type = skip_typeref(left->base.type);
8511 static void warn_logical_and_within_or(const expression_t *const expr)
8513 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8515 if (expr->base.parenthesized)
8517 source_position_t const *const pos = &expr->base.source_position;
8518 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8522 * Check the semantic restrictions of a logical expression.
8524 static void semantic_logical_op(binary_expression_t *expression)
8526 /* §6.5.13:2 Each of the operands shall have scalar type.
8527 * §6.5.14:2 Each of the operands shall have scalar type. */
8528 semantic_condition(expression->left, "left operand of logical operator");
8529 semantic_condition(expression->right, "right operand of logical operator");
8530 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8531 warn_logical_and_within_or(expression->left);
8532 warn_logical_and_within_or(expression->right);
8534 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8538 * Check the semantic restrictions of a binary assign expression.
8540 static void semantic_binexpr_assign(binary_expression_t *expression)
8542 expression_t *left = expression->left;
8543 type_t *orig_type_left = left->base.type;
8545 if (!is_valid_assignment_lhs(left))
8548 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8549 report_assign_error(error, orig_type_left, expression->right,
8550 "assignment", &left->base.source_position);
8551 expression->right = create_implicit_cast(expression->right, orig_type_left);
8552 expression->base.type = orig_type_left;
8556 * Determine if the outermost operation (or parts thereof) of the given
8557 * expression has no effect in order to generate a warning about this fact.
8558 * Therefore in some cases this only examines some of the operands of the
8559 * expression (see comments in the function and examples below).
8561 * f() + 23; // warning, because + has no effect
8562 * x || f(); // no warning, because x controls execution of f()
8563 * x ? y : f(); // warning, because y has no effect
8564 * (void)x; // no warning to be able to suppress the warning
8565 * This function can NOT be used for an "expression has definitely no effect"-
8567 static bool expression_has_effect(const expression_t *const expr)
8569 switch (expr->kind) {
8570 case EXPR_UNKNOWN: break;
8571 case EXPR_INVALID: return true; /* do NOT warn */
8572 case EXPR_REFERENCE: return false;
8573 case EXPR_REFERENCE_ENUM_VALUE: return false;
8574 case EXPR_LABEL_ADDRESS: return false;
8576 /* suppress the warning for microsoft __noop operations */
8577 case EXPR_LITERAL_MS_NOOP: return true;
8578 case EXPR_LITERAL_BOOLEAN:
8579 case EXPR_LITERAL_CHARACTER:
8580 case EXPR_LITERAL_WIDE_CHARACTER:
8581 case EXPR_LITERAL_INTEGER:
8582 case EXPR_LITERAL_INTEGER_OCTAL:
8583 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8584 case EXPR_LITERAL_FLOATINGPOINT:
8585 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8586 case EXPR_STRING_LITERAL: return false;
8587 case EXPR_WIDE_STRING_LITERAL: return false;
8590 const call_expression_t *const call = &expr->call;
8591 if (call->function->kind != EXPR_REFERENCE)
8594 switch (call->function->reference.entity->function.btk) {
8595 /* FIXME: which builtins have no effect? */
8596 default: return true;
8600 /* Generate the warning if either the left or right hand side of a
8601 * conditional expression has no effect */
8602 case EXPR_CONDITIONAL: {
8603 conditional_expression_t const *const cond = &expr->conditional;
8604 expression_t const *const t = cond->true_expression;
8606 (t == NULL || expression_has_effect(t)) &&
8607 expression_has_effect(cond->false_expression);
8610 case EXPR_SELECT: return false;
8611 case EXPR_ARRAY_ACCESS: return false;
8612 case EXPR_SIZEOF: return false;
8613 case EXPR_CLASSIFY_TYPE: return false;
8614 case EXPR_ALIGNOF: return false;
8616 case EXPR_FUNCNAME: return false;
8617 case EXPR_BUILTIN_CONSTANT_P: return false;
8618 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8619 case EXPR_OFFSETOF: return false;
8620 case EXPR_VA_START: return true;
8621 case EXPR_VA_ARG: return true;
8622 case EXPR_VA_COPY: return true;
8623 case EXPR_STATEMENT: return true; // TODO
8624 case EXPR_COMPOUND_LITERAL: return false;
8626 case EXPR_UNARY_NEGATE: return false;
8627 case EXPR_UNARY_PLUS: return false;
8628 case EXPR_UNARY_BITWISE_NEGATE: return false;
8629 case EXPR_UNARY_NOT: return false;
8630 case EXPR_UNARY_DEREFERENCE: return false;
8631 case EXPR_UNARY_TAKE_ADDRESS: return false;
8632 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8633 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8634 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8635 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8637 /* Treat void casts as if they have an effect in order to being able to
8638 * suppress the warning */
8639 case EXPR_UNARY_CAST: {
8640 type_t *const type = skip_typeref(expr->base.type);
8641 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8644 case EXPR_UNARY_CAST_IMPLICIT: return true;
8645 case EXPR_UNARY_ASSUME: return true;
8646 case EXPR_UNARY_DELETE: return true;
8647 case EXPR_UNARY_DELETE_ARRAY: return true;
8648 case EXPR_UNARY_THROW: return true;
8650 case EXPR_BINARY_ADD: return false;
8651 case EXPR_BINARY_SUB: return false;
8652 case EXPR_BINARY_MUL: return false;
8653 case EXPR_BINARY_DIV: return false;
8654 case EXPR_BINARY_MOD: return false;
8655 case EXPR_BINARY_EQUAL: return false;
8656 case EXPR_BINARY_NOTEQUAL: return false;
8657 case EXPR_BINARY_LESS: return false;
8658 case EXPR_BINARY_LESSEQUAL: return false;
8659 case EXPR_BINARY_GREATER: return false;
8660 case EXPR_BINARY_GREATEREQUAL: return false;
8661 case EXPR_BINARY_BITWISE_AND: return false;
8662 case EXPR_BINARY_BITWISE_OR: return false;
8663 case EXPR_BINARY_BITWISE_XOR: return false;
8664 case EXPR_BINARY_SHIFTLEFT: return false;
8665 case EXPR_BINARY_SHIFTRIGHT: return false;
8666 case EXPR_BINARY_ASSIGN: return true;
8667 case EXPR_BINARY_MUL_ASSIGN: return true;
8668 case EXPR_BINARY_DIV_ASSIGN: return true;
8669 case EXPR_BINARY_MOD_ASSIGN: return true;
8670 case EXPR_BINARY_ADD_ASSIGN: return true;
8671 case EXPR_BINARY_SUB_ASSIGN: return true;
8672 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8673 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8674 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8675 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8676 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8678 /* Only examine the right hand side of && and ||, because the left hand
8679 * side already has the effect of controlling the execution of the right
8681 case EXPR_BINARY_LOGICAL_AND:
8682 case EXPR_BINARY_LOGICAL_OR:
8683 /* Only examine the right hand side of a comma expression, because the left
8684 * hand side has a separate warning */
8685 case EXPR_BINARY_COMMA:
8686 return expression_has_effect(expr->binary.right);
8688 case EXPR_BINARY_ISGREATER: return false;
8689 case EXPR_BINARY_ISGREATEREQUAL: return false;
8690 case EXPR_BINARY_ISLESS: return false;
8691 case EXPR_BINARY_ISLESSEQUAL: return false;
8692 case EXPR_BINARY_ISLESSGREATER: return false;
8693 case EXPR_BINARY_ISUNORDERED: return false;
8696 internal_errorf(HERE, "unexpected expression");
8699 static void semantic_comma(binary_expression_t *expression)
8701 const expression_t *const left = expression->left;
8702 if (!expression_has_effect(left)) {
8703 source_position_t const *const pos = &left->base.source_position;
8704 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8706 expression->base.type = expression->right->base.type;
8710 * @param prec_r precedence of the right operand
8712 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8713 static expression_t *parse_##binexpression_type(expression_t *left) \
8715 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8716 binexpr->binary.left = left; \
8719 expression_t *right = parse_subexpression(prec_r); \
8721 binexpr->binary.right = right; \
8722 sfunc(&binexpr->binary); \
8727 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8728 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8729 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8730 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8731 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8732 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8733 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8734 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8735 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8736 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8737 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8738 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8739 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8740 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8741 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8742 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8743 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8744 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8745 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8746 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8747 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8748 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8749 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8750 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8751 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8752 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8753 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8754 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8755 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8756 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8759 static expression_t *parse_subexpression(precedence_t precedence)
8761 if (token.type < 0) {
8762 return expected_expression_error();
8765 expression_parser_function_t *parser
8766 = &expression_parsers[token.type];
8769 if (parser->parser != NULL) {
8770 left = parser->parser();
8772 left = parse_primary_expression();
8774 assert(left != NULL);
8777 if (token.type < 0) {
8778 return expected_expression_error();
8781 parser = &expression_parsers[token.type];
8782 if (parser->infix_parser == NULL)
8784 if (parser->infix_precedence < precedence)
8787 left = parser->infix_parser(left);
8789 assert(left != NULL);
8790 assert(left->kind != EXPR_UNKNOWN);
8797 * Parse an expression.
8799 static expression_t *parse_expression(void)
8801 return parse_subexpression(PREC_EXPRESSION);
8805 * Register a parser for a prefix-like operator.
8807 * @param parser the parser function
8808 * @param token_type the token type of the prefix token
8810 static void register_expression_parser(parse_expression_function parser,
8813 expression_parser_function_t *entry = &expression_parsers[token_type];
8815 if (entry->parser != NULL) {
8816 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8817 panic("trying to register multiple expression parsers for a token");
8819 entry->parser = parser;
8823 * Register a parser for an infix operator with given precedence.
8825 * @param parser the parser function
8826 * @param token_type the token type of the infix operator
8827 * @param precedence the precedence of the operator
8829 static void register_infix_parser(parse_expression_infix_function parser,
8830 int token_type, precedence_t precedence)
8832 expression_parser_function_t *entry = &expression_parsers[token_type];
8834 if (entry->infix_parser != NULL) {
8835 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8836 panic("trying to register multiple infix expression parsers for a "
8839 entry->infix_parser = parser;
8840 entry->infix_precedence = precedence;
8844 * Initialize the expression parsers.
8846 static void init_expression_parsers(void)
8848 memset(&expression_parsers, 0, sizeof(expression_parsers));
8850 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8851 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8852 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8853 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8854 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8855 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8856 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8857 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8858 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8859 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8860 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8861 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8862 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8863 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8864 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8865 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8866 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8867 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8868 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8869 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8870 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8871 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8872 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8873 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8874 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8875 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8876 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8877 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8878 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8879 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8880 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8881 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8882 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8883 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8884 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8885 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8886 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8888 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8889 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8890 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8891 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8892 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8893 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8894 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8895 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8896 register_expression_parser(parse_sizeof, T_sizeof);
8897 register_expression_parser(parse_alignof, T___alignof__);
8898 register_expression_parser(parse_extension, T___extension__);
8899 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8900 register_expression_parser(parse_delete, T_delete);
8901 register_expression_parser(parse_throw, T_throw);
8905 * Parse a asm statement arguments specification.
8907 static asm_argument_t *parse_asm_arguments(bool is_out)
8909 asm_argument_t *result = NULL;
8910 asm_argument_t **anchor = &result;
8912 while (token.type == T_STRING_LITERAL || token.type == '[') {
8913 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8914 memset(argument, 0, sizeof(argument[0]));
8917 if (token.type != T_IDENTIFIER) {
8918 parse_error_expected("while parsing asm argument",
8919 T_IDENTIFIER, NULL);
8922 argument->symbol = token.symbol;
8924 expect(']', end_error);
8927 argument->constraints = parse_string_literals();
8928 expect('(', end_error);
8929 add_anchor_token(')');
8930 expression_t *expression = parse_expression();
8931 rem_anchor_token(')');
8933 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8934 * change size or type representation (e.g. int -> long is ok, but
8935 * int -> float is not) */
8936 if (expression->kind == EXPR_UNARY_CAST) {
8937 type_t *const type = expression->base.type;
8938 type_kind_t const kind = type->kind;
8939 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8942 if (kind == TYPE_ATOMIC) {
8943 atomic_type_kind_t const akind = type->atomic.akind;
8944 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8945 size = get_atomic_type_size(akind);
8947 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8948 size = get_atomic_type_size(get_intptr_kind());
8952 expression_t *const value = expression->unary.value;
8953 type_t *const value_type = value->base.type;
8954 type_kind_t const value_kind = value_type->kind;
8956 unsigned value_flags;
8957 unsigned value_size;
8958 if (value_kind == TYPE_ATOMIC) {
8959 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8960 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8961 value_size = get_atomic_type_size(value_akind);
8962 } else if (value_kind == TYPE_POINTER) {
8963 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8964 value_size = get_atomic_type_size(get_intptr_kind());
8969 if (value_flags != flags || value_size != size)
8973 } while (expression->kind == EXPR_UNARY_CAST);
8977 if (!is_lvalue(expression)) {
8978 errorf(&expression->base.source_position,
8979 "asm output argument is not an lvalue");
8982 if (argument->constraints.begin[0] == '=')
8983 determine_lhs_ent(expression, NULL);
8985 mark_vars_read(expression, NULL);
8987 mark_vars_read(expression, NULL);
8989 argument->expression = expression;
8990 expect(')', end_error);
8992 set_address_taken(expression, true);
8995 anchor = &argument->next;
9007 * Parse a asm statement clobber specification.
9009 static asm_clobber_t *parse_asm_clobbers(void)
9011 asm_clobber_t *result = NULL;
9012 asm_clobber_t **anchor = &result;
9014 while (token.type == T_STRING_LITERAL) {
9015 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9016 clobber->clobber = parse_string_literals();
9019 anchor = &clobber->next;
9029 * Parse an asm statement.
9031 static statement_t *parse_asm_statement(void)
9033 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9034 asm_statement_t *asm_statement = &statement->asms;
9038 if (next_if(T_volatile))
9039 asm_statement->is_volatile = true;
9041 expect('(', end_error);
9042 add_anchor_token(')');
9043 if (token.type != T_STRING_LITERAL) {
9044 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9047 asm_statement->asm_text = parse_string_literals();
9049 add_anchor_token(':');
9050 if (!next_if(':')) {
9051 rem_anchor_token(':');
9055 asm_statement->outputs = parse_asm_arguments(true);
9056 if (!next_if(':')) {
9057 rem_anchor_token(':');
9061 asm_statement->inputs = parse_asm_arguments(false);
9062 if (!next_if(':')) {
9063 rem_anchor_token(':');
9066 rem_anchor_token(':');
9068 asm_statement->clobbers = parse_asm_clobbers();
9071 rem_anchor_token(')');
9072 expect(')', end_error);
9073 expect(';', end_error);
9075 if (asm_statement->outputs == NULL) {
9076 /* GCC: An 'asm' instruction without any output operands will be treated
9077 * identically to a volatile 'asm' instruction. */
9078 asm_statement->is_volatile = true;
9083 return create_invalid_statement();
9086 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9088 statement_t *inner_stmt;
9089 switch (token.type) {
9091 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9092 inner_stmt = create_invalid_statement();
9096 if (label->kind == STATEMENT_LABEL) {
9097 /* Eat an empty statement here, to avoid the warning about an empty
9098 * statement after a label. label:; is commonly used to have a label
9099 * before a closing brace. */
9100 inner_stmt = create_empty_statement();
9107 inner_stmt = parse_statement();
9108 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9109 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9110 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9111 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9119 * Parse a case statement.
9121 static statement_t *parse_case_statement(void)
9123 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9124 source_position_t *const pos = &statement->base.source_position;
9128 expression_t *const expression = parse_expression();
9129 statement->case_label.expression = expression;
9130 expression_classification_t const expr_class = is_constant_expression(expression);
9131 if (expr_class != EXPR_CLASS_CONSTANT) {
9132 if (expr_class != EXPR_CLASS_ERROR) {
9133 errorf(pos, "case label does not reduce to an integer constant");
9135 statement->case_label.is_bad = true;
9137 long const val = fold_constant_to_int(expression);
9138 statement->case_label.first_case = val;
9139 statement->case_label.last_case = val;
9143 if (next_if(T_DOTDOTDOT)) {
9144 expression_t *const end_range = parse_expression();
9145 statement->case_label.end_range = end_range;
9146 expression_classification_t const end_class = is_constant_expression(end_range);
9147 if (end_class != EXPR_CLASS_CONSTANT) {
9148 if (end_class != EXPR_CLASS_ERROR) {
9149 errorf(pos, "case range does not reduce to an integer constant");
9151 statement->case_label.is_bad = true;
9153 long const val = fold_constant_to_int(end_range);
9154 statement->case_label.last_case = val;
9156 if (val < statement->case_label.first_case) {
9157 statement->case_label.is_empty_range = true;
9158 warningf(WARN_OTHER, pos, "empty range specified");
9164 PUSH_PARENT(statement);
9166 expect(':', end_error);
9169 if (current_switch != NULL) {
9170 if (! statement->case_label.is_bad) {
9171 /* Check for duplicate case values */
9172 case_label_statement_t *c = &statement->case_label;
9173 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9174 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9177 if (c->last_case < l->first_case || c->first_case > l->last_case)
9180 errorf(pos, "duplicate case value (previously used %P)",
9181 &l->base.source_position);
9185 /* link all cases into the switch statement */
9186 if (current_switch->last_case == NULL) {
9187 current_switch->first_case = &statement->case_label;
9189 current_switch->last_case->next = &statement->case_label;
9191 current_switch->last_case = &statement->case_label;
9193 errorf(pos, "case label not within a switch statement");
9196 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9203 * Parse a default statement.
9205 static statement_t *parse_default_statement(void)
9207 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9211 PUSH_PARENT(statement);
9213 expect(':', end_error);
9216 if (current_switch != NULL) {
9217 const case_label_statement_t *def_label = current_switch->default_label;
9218 if (def_label != NULL) {
9219 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9221 current_switch->default_label = &statement->case_label;
9223 /* link all cases into the switch statement */
9224 if (current_switch->last_case == NULL) {
9225 current_switch->first_case = &statement->case_label;
9227 current_switch->last_case->next = &statement->case_label;
9229 current_switch->last_case = &statement->case_label;
9232 errorf(&statement->base.source_position,
9233 "'default' label not within a switch statement");
9236 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9243 * Parse a label statement.
9245 static statement_t *parse_label_statement(void)
9247 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9248 label_t *const label = get_label();
9249 statement->label.label = label;
9251 PUSH_PARENT(statement);
9253 /* if statement is already set then the label is defined twice,
9254 * otherwise it was just mentioned in a goto/local label declaration so far
9256 source_position_t const* const pos = &statement->base.source_position;
9257 if (label->statement != NULL) {
9258 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9260 label->base.source_position = *pos;
9261 label->statement = statement;
9266 statement->label.statement = parse_label_inner_statement(statement, "label");
9268 /* remember the labels in a list for later checking */
9269 *label_anchor = &statement->label;
9270 label_anchor = &statement->label.next;
9276 static statement_t *parse_inner_statement(void)
9278 statement_t *const stmt = parse_statement();
9279 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9280 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9281 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9282 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9288 * Parse an if statement.
9290 static statement_t *parse_if(void)
9292 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9296 PUSH_PARENT(statement);
9298 add_anchor_token('{');
9300 expect('(', end_error);
9301 add_anchor_token(')');
9302 expression_t *const expr = parse_expression();
9303 statement->ifs.condition = expr;
9304 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9306 semantic_condition(expr, "condition of 'if'-statment");
9307 mark_vars_read(expr, NULL);
9308 rem_anchor_token(')');
9309 expect(')', end_error);
9312 rem_anchor_token('{');
9314 add_anchor_token(T_else);
9315 statement_t *const true_stmt = parse_inner_statement();
9316 statement->ifs.true_statement = true_stmt;
9317 rem_anchor_token(T_else);
9319 if (next_if(T_else)) {
9320 statement->ifs.false_statement = parse_inner_statement();
9321 } else if (true_stmt->kind == STATEMENT_IF &&
9322 true_stmt->ifs.false_statement != NULL) {
9323 source_position_t const *const pos = &true_stmt->base.source_position;
9324 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9332 * Check that all enums are handled in a switch.
9334 * @param statement the switch statement to check
9336 static void check_enum_cases(const switch_statement_t *statement)
9338 if (!is_warn_on(WARN_SWITCH_ENUM))
9340 const type_t *type = skip_typeref(statement->expression->base.type);
9341 if (! is_type_enum(type))
9343 const enum_type_t *enumt = &type->enumt;
9345 /* if we have a default, no warnings */
9346 if (statement->default_label != NULL)
9349 /* FIXME: calculation of value should be done while parsing */
9350 /* TODO: quadratic algorithm here. Change to an n log n one */
9351 long last_value = -1;
9352 const entity_t *entry = enumt->enume->base.next;
9353 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9354 entry = entry->base.next) {
9355 const expression_t *expression = entry->enum_value.value;
9356 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9358 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9359 if (l->expression == NULL)
9361 if (l->first_case <= value && value <= l->last_case) {
9367 source_position_t const *const pos = &statement->base.source_position;
9368 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9375 * Parse a switch statement.
9377 static statement_t *parse_switch(void)
9379 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9383 PUSH_PARENT(statement);
9385 expect('(', end_error);
9386 add_anchor_token(')');
9387 expression_t *const expr = parse_expression();
9388 mark_vars_read(expr, NULL);
9389 type_t * type = skip_typeref(expr->base.type);
9390 if (is_type_integer(type)) {
9391 type = promote_integer(type);
9392 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9393 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9395 } else if (is_type_valid(type)) {
9396 errorf(&expr->base.source_position,
9397 "switch quantity is not an integer, but '%T'", type);
9398 type = type_error_type;
9400 statement->switchs.expression = create_implicit_cast(expr, type);
9401 expect(')', end_error);
9402 rem_anchor_token(')');
9404 switch_statement_t *rem = current_switch;
9405 current_switch = &statement->switchs;
9406 statement->switchs.body = parse_inner_statement();
9407 current_switch = rem;
9409 if (statement->switchs.default_label == NULL) {
9410 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9412 check_enum_cases(&statement->switchs);
9418 return create_invalid_statement();
9421 static statement_t *parse_loop_body(statement_t *const loop)
9423 statement_t *const rem = current_loop;
9424 current_loop = loop;
9426 statement_t *const body = parse_inner_statement();
9433 * Parse a while statement.
9435 static statement_t *parse_while(void)
9437 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9441 PUSH_PARENT(statement);
9443 expect('(', end_error);
9444 add_anchor_token(')');
9445 expression_t *const cond = parse_expression();
9446 statement->whiles.condition = cond;
9447 /* §6.8.5:2 The controlling expression of an iteration statement shall
9448 * have scalar type. */
9449 semantic_condition(cond, "condition of 'while'-statement");
9450 mark_vars_read(cond, NULL);
9451 rem_anchor_token(')');
9452 expect(')', end_error);
9454 statement->whiles.body = parse_loop_body(statement);
9460 return create_invalid_statement();
9464 * Parse a do statement.
9466 static statement_t *parse_do(void)
9468 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9472 PUSH_PARENT(statement);
9474 add_anchor_token(T_while);
9475 statement->do_while.body = parse_loop_body(statement);
9476 rem_anchor_token(T_while);
9478 expect(T_while, end_error);
9479 expect('(', end_error);
9480 add_anchor_token(')');
9481 expression_t *const cond = parse_expression();
9482 statement->do_while.condition = cond;
9483 /* §6.8.5:2 The controlling expression of an iteration statement shall
9484 * have scalar type. */
9485 semantic_condition(cond, "condition of 'do-while'-statement");
9486 mark_vars_read(cond, NULL);
9487 rem_anchor_token(')');
9488 expect(')', end_error);
9489 expect(';', end_error);
9495 return create_invalid_statement();
9499 * Parse a for statement.
9501 static statement_t *parse_for(void)
9503 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9507 expect('(', end_error1);
9508 add_anchor_token(')');
9510 PUSH_PARENT(statement);
9511 PUSH_SCOPE(&statement->fors.scope);
9516 } else if (is_declaration_specifier(&token)) {
9517 parse_declaration(record_entity, DECL_FLAGS_NONE);
9519 add_anchor_token(';');
9520 expression_t *const init = parse_expression();
9521 statement->fors.initialisation = init;
9522 mark_vars_read(init, ENT_ANY);
9523 if (!expression_has_effect(init)) {
9524 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9526 rem_anchor_token(';');
9527 expect(';', end_error2);
9532 if (token.type != ';') {
9533 add_anchor_token(';');
9534 expression_t *const cond = parse_expression();
9535 statement->fors.condition = cond;
9536 /* §6.8.5:2 The controlling expression of an iteration statement
9537 * shall have scalar type. */
9538 semantic_condition(cond, "condition of 'for'-statement");
9539 mark_vars_read(cond, NULL);
9540 rem_anchor_token(';');
9542 expect(';', end_error2);
9543 if (token.type != ')') {
9544 expression_t *const step = parse_expression();
9545 statement->fors.step = step;
9546 mark_vars_read(step, ENT_ANY);
9547 if (!expression_has_effect(step)) {
9548 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9551 expect(')', end_error2);
9552 rem_anchor_token(')');
9553 statement->fors.body = parse_loop_body(statement);
9561 rem_anchor_token(')');
9566 return create_invalid_statement();
9570 * Parse a goto statement.
9572 static statement_t *parse_goto(void)
9574 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9577 if (GNU_MODE && next_if('*')) {
9578 expression_t *expression = parse_expression();
9579 mark_vars_read(expression, NULL);
9581 /* Argh: although documentation says the expression must be of type void*,
9582 * gcc accepts anything that can be casted into void* without error */
9583 type_t *type = expression->base.type;
9585 if (type != type_error_type) {
9586 if (!is_type_pointer(type) && !is_type_integer(type)) {
9587 errorf(&expression->base.source_position,
9588 "cannot convert to a pointer type");
9589 } else if (type != type_void_ptr) {
9590 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9592 expression = create_implicit_cast(expression, type_void_ptr);
9595 statement->gotos.expression = expression;
9596 } else if (token.type == T_IDENTIFIER) {
9597 label_t *const label = get_label();
9599 statement->gotos.label = label;
9602 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9604 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9606 return create_invalid_statement();
9609 /* remember the goto's in a list for later checking */
9610 *goto_anchor = &statement->gotos;
9611 goto_anchor = &statement->gotos.next;
9613 expect(';', end_error);
9620 * Parse a continue statement.
9622 static statement_t *parse_continue(void)
9624 if (current_loop == NULL) {
9625 errorf(HERE, "continue statement not within loop");
9628 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9631 expect(';', end_error);
9638 * Parse a break statement.
9640 static statement_t *parse_break(void)
9642 if (current_switch == NULL && current_loop == NULL) {
9643 errorf(HERE, "break statement not within loop or switch");
9646 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9649 expect(';', end_error);
9656 * Parse a __leave statement.
9658 static statement_t *parse_leave_statement(void)
9660 if (current_try == NULL) {
9661 errorf(HERE, "__leave statement not within __try");
9664 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9667 expect(';', end_error);
9674 * Check if a given entity represents a local variable.
9676 static bool is_local_variable(const entity_t *entity)
9678 if (entity->kind != ENTITY_VARIABLE)
9681 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9682 case STORAGE_CLASS_AUTO:
9683 case STORAGE_CLASS_REGISTER: {
9684 const type_t *type = skip_typeref(entity->declaration.type);
9685 if (is_type_function(type)) {
9697 * Check if a given expression represents a local variable.
9699 static bool expression_is_local_variable(const expression_t *expression)
9701 if (expression->base.kind != EXPR_REFERENCE) {
9704 const entity_t *entity = expression->reference.entity;
9705 return is_local_variable(entity);
9709 * Check if a given expression represents a local variable and
9710 * return its declaration then, else return NULL.
9712 entity_t *expression_is_variable(const expression_t *expression)
9714 if (expression->base.kind != EXPR_REFERENCE) {
9717 entity_t *entity = expression->reference.entity;
9718 if (entity->kind != ENTITY_VARIABLE)
9725 * Parse a return statement.
9727 static statement_t *parse_return(void)
9729 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9732 expression_t *return_value = NULL;
9733 if (token.type != ';') {
9734 return_value = parse_expression();
9735 mark_vars_read(return_value, NULL);
9738 const type_t *const func_type = skip_typeref(current_function->base.type);
9739 assert(is_type_function(func_type));
9740 type_t *const return_type = skip_typeref(func_type->function.return_type);
9742 source_position_t const *const pos = &statement->base.source_position;
9743 if (return_value != NULL) {
9744 type_t *return_value_type = skip_typeref(return_value->base.type);
9746 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9747 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9748 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9749 /* Only warn in C mode, because GCC does the same */
9750 if (c_mode & _CXX || strict_mode) {
9752 "'return' with a value, in function returning 'void'");
9754 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9756 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9757 /* Only warn in C mode, because GCC does the same */
9760 "'return' with expression in function returning 'void'");
9762 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9766 assign_error_t error = semantic_assign(return_type, return_value);
9767 report_assign_error(error, return_type, return_value, "'return'",
9770 return_value = create_implicit_cast(return_value, return_type);
9771 /* check for returning address of a local var */
9772 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9773 const expression_t *expression = return_value->unary.value;
9774 if (expression_is_local_variable(expression)) {
9775 warningf(WARN_OTHER, pos, "function returns address of local variable");
9778 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9779 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9780 if (c_mode & _CXX || strict_mode) {
9782 "'return' without value, in function returning non-void");
9784 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9787 statement->returns.value = return_value;
9789 expect(';', end_error);
9796 * Parse a declaration statement.
9798 static statement_t *parse_declaration_statement(void)
9800 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9802 entity_t *before = current_scope->last_entity;
9804 parse_external_declaration();
9806 parse_declaration(record_entity, DECL_FLAGS_NONE);
9809 declaration_statement_t *const decl = &statement->declaration;
9810 entity_t *const begin =
9811 before != NULL ? before->base.next : current_scope->entities;
9812 decl->declarations_begin = begin;
9813 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9819 * Parse an expression statement, ie. expr ';'.
9821 static statement_t *parse_expression_statement(void)
9823 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9825 expression_t *const expr = parse_expression();
9826 statement->expression.expression = expr;
9827 mark_vars_read(expr, ENT_ANY);
9829 expect(';', end_error);
9836 * Parse a microsoft __try { } __finally { } or
9837 * __try{ } __except() { }
9839 static statement_t *parse_ms_try_statment(void)
9841 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9844 PUSH_PARENT(statement);
9846 ms_try_statement_t *rem = current_try;
9847 current_try = &statement->ms_try;
9848 statement->ms_try.try_statement = parse_compound_statement(false);
9853 if (next_if(T___except)) {
9854 expect('(', end_error);
9855 add_anchor_token(')');
9856 expression_t *const expr = parse_expression();
9857 mark_vars_read(expr, NULL);
9858 type_t * type = skip_typeref(expr->base.type);
9859 if (is_type_integer(type)) {
9860 type = promote_integer(type);
9861 } else if (is_type_valid(type)) {
9862 errorf(&expr->base.source_position,
9863 "__expect expression is not an integer, but '%T'", type);
9864 type = type_error_type;
9866 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9867 rem_anchor_token(')');
9868 expect(')', end_error);
9869 statement->ms_try.final_statement = parse_compound_statement(false);
9870 } else if (next_if(T__finally)) {
9871 statement->ms_try.final_statement = parse_compound_statement(false);
9873 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9874 return create_invalid_statement();
9878 return create_invalid_statement();
9881 static statement_t *parse_empty_statement(void)
9883 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9884 statement_t *const statement = create_empty_statement();
9889 static statement_t *parse_local_label_declaration(void)
9891 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9895 entity_t *begin = NULL;
9896 entity_t *end = NULL;
9897 entity_t **anchor = &begin;
9899 if (token.type != T_IDENTIFIER) {
9900 parse_error_expected("while parsing local label declaration",
9901 T_IDENTIFIER, NULL);
9904 symbol_t *symbol = token.symbol;
9905 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9906 if (entity != NULL && entity->base.parent_scope == current_scope) {
9907 source_position_t const *const ppos = &entity->base.source_position;
9908 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9910 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9911 entity->base.parent_scope = current_scope;
9912 entity->base.source_position = token.source_position;
9915 anchor = &entity->base.next;
9918 environment_push(entity);
9921 } while (next_if(','));
9922 expect(';', end_error);
9924 statement->declaration.declarations_begin = begin;
9925 statement->declaration.declarations_end = end;
9929 static void parse_namespace_definition(void)
9933 entity_t *entity = NULL;
9934 symbol_t *symbol = NULL;
9936 if (token.type == T_IDENTIFIER) {
9937 symbol = token.symbol;
9940 entity = get_entity(symbol, NAMESPACE_NORMAL);
9942 && entity->kind != ENTITY_NAMESPACE
9943 && entity->base.parent_scope == current_scope) {
9944 if (is_entity_valid(entity)) {
9945 error_redefined_as_different_kind(&token.source_position,
9946 entity, ENTITY_NAMESPACE);
9952 if (entity == NULL) {
9953 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9954 entity->base.source_position = token.source_position;
9955 entity->base.parent_scope = current_scope;
9958 if (token.type == '=') {
9959 /* TODO: parse namespace alias */
9960 panic("namespace alias definition not supported yet");
9963 environment_push(entity);
9964 append_entity(current_scope, entity);
9966 PUSH_SCOPE(&entity->namespacee.members);
9968 entity_t *old_current_entity = current_entity;
9969 current_entity = entity;
9971 expect('{', end_error);
9973 expect('}', end_error);
9976 assert(current_entity == entity);
9977 current_entity = old_current_entity;
9982 * Parse a statement.
9983 * There's also parse_statement() which additionally checks for
9984 * "statement has no effect" warnings
9986 static statement_t *intern_parse_statement(void)
9988 statement_t *statement = NULL;
9990 /* declaration or statement */
9991 add_anchor_token(';');
9992 switch (token.type) {
9993 case T_IDENTIFIER: {
9994 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9995 if (la1_type == ':') {
9996 statement = parse_label_statement();
9997 } else if (is_typedef_symbol(token.symbol)) {
9998 statement = parse_declaration_statement();
10000 /* it's an identifier, the grammar says this must be an
10001 * expression statement. However it is common that users mistype
10002 * declaration types, so we guess a bit here to improve robustness
10003 * for incorrect programs */
10004 switch (la1_type) {
10007 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10009 statement = parse_expression_statement();
10013 statement = parse_declaration_statement();
10021 case T___extension__: {
10022 /* This can be a prefix to a declaration or an expression statement.
10023 * We simply eat it now and parse the rest with tail recursion. */
10025 statement = intern_parse_statement();
10031 statement = parse_declaration_statement();
10035 statement = parse_local_label_declaration();
10038 case ';': statement = parse_empty_statement(); break;
10039 case '{': statement = parse_compound_statement(false); break;
10040 case T___leave: statement = parse_leave_statement(); break;
10041 case T___try: statement = parse_ms_try_statment(); break;
10042 case T_asm: statement = parse_asm_statement(); break;
10043 case T_break: statement = parse_break(); break;
10044 case T_case: statement = parse_case_statement(); break;
10045 case T_continue: statement = parse_continue(); break;
10046 case T_default: statement = parse_default_statement(); break;
10047 case T_do: statement = parse_do(); break;
10048 case T_for: statement = parse_for(); break;
10049 case T_goto: statement = parse_goto(); break;
10050 case T_if: statement = parse_if(); break;
10051 case T_return: statement = parse_return(); break;
10052 case T_switch: statement = parse_switch(); break;
10053 case T_while: statement = parse_while(); break;
10056 statement = parse_expression_statement();
10060 errorf(HERE, "unexpected token %K while parsing statement", &token);
10061 statement = create_invalid_statement();
10066 rem_anchor_token(';');
10068 assert(statement != NULL
10069 && statement->base.source_position.input_name != NULL);
10075 * parse a statement and emits "statement has no effect" warning if needed
10076 * (This is really a wrapper around intern_parse_statement with check for 1
10077 * single warning. It is needed, because for statement expressions we have
10078 * to avoid the warning on the last statement)
10080 static statement_t *parse_statement(void)
10082 statement_t *statement = intern_parse_statement();
10084 if (statement->kind == STATEMENT_EXPRESSION) {
10085 expression_t *expression = statement->expression.expression;
10086 if (!expression_has_effect(expression)) {
10087 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10095 * Parse a compound statement.
10097 static statement_t *parse_compound_statement(bool inside_expression_statement)
10099 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10101 PUSH_PARENT(statement);
10102 PUSH_SCOPE(&statement->compound.scope);
10105 add_anchor_token('}');
10106 /* tokens, which can start a statement */
10107 /* TODO MS, __builtin_FOO */
10108 add_anchor_token('!');
10109 add_anchor_token('&');
10110 add_anchor_token('(');
10111 add_anchor_token('*');
10112 add_anchor_token('+');
10113 add_anchor_token('-');
10114 add_anchor_token('{');
10115 add_anchor_token('~');
10116 add_anchor_token(T_CHARACTER_CONSTANT);
10117 add_anchor_token(T_COLONCOLON);
10118 add_anchor_token(T_FLOATINGPOINT);
10119 add_anchor_token(T_IDENTIFIER);
10120 add_anchor_token(T_INTEGER);
10121 add_anchor_token(T_MINUSMINUS);
10122 add_anchor_token(T_PLUSPLUS);
10123 add_anchor_token(T_STRING_LITERAL);
10124 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10125 add_anchor_token(T_WIDE_STRING_LITERAL);
10126 add_anchor_token(T__Bool);
10127 add_anchor_token(T__Complex);
10128 add_anchor_token(T__Imaginary);
10129 add_anchor_token(T___FUNCTION__);
10130 add_anchor_token(T___PRETTY_FUNCTION__);
10131 add_anchor_token(T___alignof__);
10132 add_anchor_token(T___attribute__);
10133 add_anchor_token(T___builtin_va_start);
10134 add_anchor_token(T___extension__);
10135 add_anchor_token(T___func__);
10136 add_anchor_token(T___imag__);
10137 add_anchor_token(T___label__);
10138 add_anchor_token(T___real__);
10139 add_anchor_token(T___thread);
10140 add_anchor_token(T_asm);
10141 add_anchor_token(T_auto);
10142 add_anchor_token(T_bool);
10143 add_anchor_token(T_break);
10144 add_anchor_token(T_case);
10145 add_anchor_token(T_char);
10146 add_anchor_token(T_class);
10147 add_anchor_token(T_const);
10148 add_anchor_token(T_const_cast);
10149 add_anchor_token(T_continue);
10150 add_anchor_token(T_default);
10151 add_anchor_token(T_delete);
10152 add_anchor_token(T_double);
10153 add_anchor_token(T_do);
10154 add_anchor_token(T_dynamic_cast);
10155 add_anchor_token(T_enum);
10156 add_anchor_token(T_extern);
10157 add_anchor_token(T_false);
10158 add_anchor_token(T_float);
10159 add_anchor_token(T_for);
10160 add_anchor_token(T_goto);
10161 add_anchor_token(T_if);
10162 add_anchor_token(T_inline);
10163 add_anchor_token(T_int);
10164 add_anchor_token(T_long);
10165 add_anchor_token(T_new);
10166 add_anchor_token(T_operator);
10167 add_anchor_token(T_register);
10168 add_anchor_token(T_reinterpret_cast);
10169 add_anchor_token(T_restrict);
10170 add_anchor_token(T_return);
10171 add_anchor_token(T_short);
10172 add_anchor_token(T_signed);
10173 add_anchor_token(T_sizeof);
10174 add_anchor_token(T_static);
10175 add_anchor_token(T_static_cast);
10176 add_anchor_token(T_struct);
10177 add_anchor_token(T_switch);
10178 add_anchor_token(T_template);
10179 add_anchor_token(T_this);
10180 add_anchor_token(T_throw);
10181 add_anchor_token(T_true);
10182 add_anchor_token(T_try);
10183 add_anchor_token(T_typedef);
10184 add_anchor_token(T_typeid);
10185 add_anchor_token(T_typename);
10186 add_anchor_token(T_typeof);
10187 add_anchor_token(T_union);
10188 add_anchor_token(T_unsigned);
10189 add_anchor_token(T_using);
10190 add_anchor_token(T_void);
10191 add_anchor_token(T_volatile);
10192 add_anchor_token(T_wchar_t);
10193 add_anchor_token(T_while);
10195 statement_t **anchor = &statement->compound.statements;
10196 bool only_decls_so_far = true;
10197 while (token.type != '}') {
10198 if (token.type == T_EOF) {
10199 errorf(&statement->base.source_position,
10200 "EOF while parsing compound statement");
10203 statement_t *sub_statement = intern_parse_statement();
10204 if (is_invalid_statement(sub_statement)) {
10205 /* an error occurred. if we are at an anchor, return */
10211 if (sub_statement->kind != STATEMENT_DECLARATION) {
10212 only_decls_so_far = false;
10213 } else if (!only_decls_so_far) {
10214 source_position_t const *const pos = &sub_statement->base.source_position;
10215 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10218 *anchor = sub_statement;
10220 while (sub_statement->base.next != NULL)
10221 sub_statement = sub_statement->base.next;
10223 anchor = &sub_statement->base.next;
10227 /* look over all statements again to produce no effect warnings */
10228 if (is_warn_on(WARN_UNUSED_VALUE)) {
10229 statement_t *sub_statement = statement->compound.statements;
10230 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10231 if (sub_statement->kind != STATEMENT_EXPRESSION)
10233 /* don't emit a warning for the last expression in an expression
10234 * statement as it has always an effect */
10235 if (inside_expression_statement && sub_statement->base.next == NULL)
10238 expression_t *expression = sub_statement->expression.expression;
10239 if (!expression_has_effect(expression)) {
10240 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10246 rem_anchor_token(T_while);
10247 rem_anchor_token(T_wchar_t);
10248 rem_anchor_token(T_volatile);
10249 rem_anchor_token(T_void);
10250 rem_anchor_token(T_using);
10251 rem_anchor_token(T_unsigned);
10252 rem_anchor_token(T_union);
10253 rem_anchor_token(T_typeof);
10254 rem_anchor_token(T_typename);
10255 rem_anchor_token(T_typeid);
10256 rem_anchor_token(T_typedef);
10257 rem_anchor_token(T_try);
10258 rem_anchor_token(T_true);
10259 rem_anchor_token(T_throw);
10260 rem_anchor_token(T_this);
10261 rem_anchor_token(T_template);
10262 rem_anchor_token(T_switch);
10263 rem_anchor_token(T_struct);
10264 rem_anchor_token(T_static_cast);
10265 rem_anchor_token(T_static);
10266 rem_anchor_token(T_sizeof);
10267 rem_anchor_token(T_signed);
10268 rem_anchor_token(T_short);
10269 rem_anchor_token(T_return);
10270 rem_anchor_token(T_restrict);
10271 rem_anchor_token(T_reinterpret_cast);
10272 rem_anchor_token(T_register);
10273 rem_anchor_token(T_operator);
10274 rem_anchor_token(T_new);
10275 rem_anchor_token(T_long);
10276 rem_anchor_token(T_int);
10277 rem_anchor_token(T_inline);
10278 rem_anchor_token(T_if);
10279 rem_anchor_token(T_goto);
10280 rem_anchor_token(T_for);
10281 rem_anchor_token(T_float);
10282 rem_anchor_token(T_false);
10283 rem_anchor_token(T_extern);
10284 rem_anchor_token(T_enum);
10285 rem_anchor_token(T_dynamic_cast);
10286 rem_anchor_token(T_do);
10287 rem_anchor_token(T_double);
10288 rem_anchor_token(T_delete);
10289 rem_anchor_token(T_default);
10290 rem_anchor_token(T_continue);
10291 rem_anchor_token(T_const_cast);
10292 rem_anchor_token(T_const);
10293 rem_anchor_token(T_class);
10294 rem_anchor_token(T_char);
10295 rem_anchor_token(T_case);
10296 rem_anchor_token(T_break);
10297 rem_anchor_token(T_bool);
10298 rem_anchor_token(T_auto);
10299 rem_anchor_token(T_asm);
10300 rem_anchor_token(T___thread);
10301 rem_anchor_token(T___real__);
10302 rem_anchor_token(T___label__);
10303 rem_anchor_token(T___imag__);
10304 rem_anchor_token(T___func__);
10305 rem_anchor_token(T___extension__);
10306 rem_anchor_token(T___builtin_va_start);
10307 rem_anchor_token(T___attribute__);
10308 rem_anchor_token(T___alignof__);
10309 rem_anchor_token(T___PRETTY_FUNCTION__);
10310 rem_anchor_token(T___FUNCTION__);
10311 rem_anchor_token(T__Imaginary);
10312 rem_anchor_token(T__Complex);
10313 rem_anchor_token(T__Bool);
10314 rem_anchor_token(T_WIDE_STRING_LITERAL);
10315 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10316 rem_anchor_token(T_STRING_LITERAL);
10317 rem_anchor_token(T_PLUSPLUS);
10318 rem_anchor_token(T_MINUSMINUS);
10319 rem_anchor_token(T_INTEGER);
10320 rem_anchor_token(T_IDENTIFIER);
10321 rem_anchor_token(T_FLOATINGPOINT);
10322 rem_anchor_token(T_COLONCOLON);
10323 rem_anchor_token(T_CHARACTER_CONSTANT);
10324 rem_anchor_token('~');
10325 rem_anchor_token('{');
10326 rem_anchor_token('-');
10327 rem_anchor_token('+');
10328 rem_anchor_token('*');
10329 rem_anchor_token('(');
10330 rem_anchor_token('&');
10331 rem_anchor_token('!');
10332 rem_anchor_token('}');
10340 * Check for unused global static functions and variables
10342 static void check_unused_globals(void)
10344 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10347 for (const entity_t *entity = file_scope->entities; entity != NULL;
10348 entity = entity->base.next) {
10349 if (!is_declaration(entity))
10352 const declaration_t *declaration = &entity->declaration;
10353 if (declaration->used ||
10354 declaration->modifiers & DM_UNUSED ||
10355 declaration->modifiers & DM_USED ||
10356 declaration->storage_class != STORAGE_CLASS_STATIC)
10361 if (entity->kind == ENTITY_FUNCTION) {
10362 /* inhibit warning for static inline functions */
10363 if (entity->function.is_inline)
10366 why = WARN_UNUSED_FUNCTION;
10367 s = entity->function.statement != NULL ? "defined" : "declared";
10369 why = WARN_UNUSED_VARIABLE;
10373 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10377 static void parse_global_asm(void)
10379 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10382 expect('(', end_error);
10384 statement->asms.asm_text = parse_string_literals();
10385 statement->base.next = unit->global_asm;
10386 unit->global_asm = statement;
10388 expect(')', end_error);
10389 expect(';', end_error);
10394 static void parse_linkage_specification(void)
10398 source_position_t const pos = *HERE;
10399 char const *const linkage = parse_string_literals().begin;
10401 linkage_kind_t old_linkage = current_linkage;
10402 linkage_kind_t new_linkage;
10403 if (strcmp(linkage, "C") == 0) {
10404 new_linkage = LINKAGE_C;
10405 } else if (strcmp(linkage, "C++") == 0) {
10406 new_linkage = LINKAGE_CXX;
10408 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10409 new_linkage = LINKAGE_INVALID;
10411 current_linkage = new_linkage;
10413 if (next_if('{')) {
10415 expect('}', end_error);
10421 assert(current_linkage == new_linkage);
10422 current_linkage = old_linkage;
10425 static void parse_external(void)
10427 switch (token.type) {
10429 if (look_ahead(1)->type == T_STRING_LITERAL) {
10430 parse_linkage_specification();
10432 DECLARATION_START_NO_EXTERN
10434 case T___extension__:
10435 /* tokens below are for implicit int */
10436 case '&': /* & x; -> int& x; (and error later, because C++ has no
10438 case '*': /* * x; -> int* x; */
10439 case '(':; /* (x); -> int (x); */
10441 parse_external_declaration();
10447 parse_global_asm();
10451 parse_namespace_definition();
10455 if (!strict_mode) {
10456 warningf(WARN_OTHER, HERE, "stray ';' outside of function");
10463 errorf(HERE, "stray %K outside of function", &token);
10464 if (token.type == '(' || token.type == '{' || token.type == '[')
10465 eat_until_matching_token(token.type);
10471 static void parse_externals(void)
10473 add_anchor_token('}');
10474 add_anchor_token(T_EOF);
10477 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10478 unsigned char token_anchor_copy[T_LAST_TOKEN];
10479 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10482 while (token.type != T_EOF && token.type != '}') {
10484 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10485 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10487 /* the anchor set and its copy differs */
10488 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10491 if (in_gcc_extension) {
10492 /* an gcc extension scope was not closed */
10493 internal_errorf(HERE, "Leaked __extension__");
10500 rem_anchor_token(T_EOF);
10501 rem_anchor_token('}');
10505 * Parse a translation unit.
10507 static void parse_translation_unit(void)
10509 add_anchor_token(T_EOF);
10514 if (token.type == T_EOF)
10517 errorf(HERE, "stray %K outside of function", &token);
10518 if (token.type == '(' || token.type == '{' || token.type == '[')
10519 eat_until_matching_token(token.type);
10524 void set_default_visibility(elf_visibility_tag_t visibility)
10526 default_visibility = visibility;
10532 * @return the translation unit or NULL if errors occurred.
10534 void start_parsing(void)
10536 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10537 label_stack = NEW_ARR_F(stack_entry_t, 0);
10538 diagnostic_count = 0;
10542 print_to_file(stderr);
10544 assert(unit == NULL);
10545 unit = allocate_ast_zero(sizeof(unit[0]));
10547 assert(file_scope == NULL);
10548 file_scope = &unit->scope;
10550 assert(current_scope == NULL);
10551 scope_push(&unit->scope);
10553 create_gnu_builtins();
10555 create_microsoft_intrinsics();
10558 translation_unit_t *finish_parsing(void)
10560 assert(current_scope == &unit->scope);
10563 assert(file_scope == &unit->scope);
10564 check_unused_globals();
10567 DEL_ARR_F(environment_stack);
10568 DEL_ARR_F(label_stack);
10570 translation_unit_t *result = unit;
10575 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10576 * are given length one. */
10577 static void complete_incomplete_arrays(void)
10579 size_t n = ARR_LEN(incomplete_arrays);
10580 for (size_t i = 0; i != n; ++i) {
10581 declaration_t *const decl = incomplete_arrays[i];
10582 type_t *const type = skip_typeref(decl->type);
10584 if (!is_type_incomplete(type))
10587 source_position_t const *const pos = &decl->base.source_position;
10588 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10590 type_t *const new_type = duplicate_type(type);
10591 new_type->array.size_constant = true;
10592 new_type->array.has_implicit_size = true;
10593 new_type->array.size = 1;
10595 type_t *const result = identify_new_type(new_type);
10597 decl->type = result;
10601 void prepare_main_collect2(entity_t *entity)
10603 // create call to __main
10604 symbol_t *symbol = symbol_table_insert("__main");
10605 entity_t *subsubmain_ent
10606 = create_implicit_function(symbol, &builtin_source_position);
10608 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10609 type_t *ftype = subsubmain_ent->declaration.type;
10610 ref->base.source_position = builtin_source_position;
10611 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10612 ref->reference.entity = subsubmain_ent;
10614 expression_t *call = allocate_expression_zero(EXPR_CALL);
10615 call->base.source_position = builtin_source_position;
10616 call->base.type = type_void;
10617 call->call.function = ref;
10619 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10620 expr_statement->base.source_position = builtin_source_position;
10621 expr_statement->expression.expression = call;
10623 statement_t *statement = entity->function.statement;
10624 assert(statement->kind == STATEMENT_COMPOUND);
10625 compound_statement_t *compounds = &statement->compound;
10627 expr_statement->base.next = compounds->statements;
10628 compounds->statements = expr_statement;
10633 lookahead_bufpos = 0;
10634 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10637 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10638 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10639 parse_translation_unit();
10640 complete_incomplete_arrays();
10641 DEL_ARR_F(incomplete_arrays);
10642 incomplete_arrays = NULL;
10646 * Initialize the parser.
10648 void init_parser(void)
10650 sym_anonymous = symbol_table_insert("<anonymous>");
10652 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10654 init_expression_parsers();
10655 obstack_init(&temp_obst);
10659 * Terminate the parser.
10661 void exit_parser(void)
10663 obstack_free(&temp_obst, NULL);