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
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = 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;
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 an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_PARENT(stmt) \
113 statement_t *const new_parent = (stmt); \
114 statement_t *const old_parent = current_parent; \
115 ((void)(current_parent = new_parent))
116 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
118 #define PUSH_SCOPE(scope) \
119 size_t const top = environment_top(); \
120 scope_t *const new_scope = (scope); \
121 scope_t *const old_scope = scope_push(new_scope)
122 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
124 #define PUSH_EXTENSION() \
126 bool const old_gcc_extension = in_gcc_extension; \
127 while (next_if(T___extension__)) { \
128 in_gcc_extension = true; \
131 #define POP_EXTENSION() \
132 ((void)(in_gcc_extension = old_gcc_extension))
134 /** special symbol used for anonymous entities. */
135 static symbol_t *sym_anonymous = NULL;
137 /** The token anchor set */
138 static unsigned short token_anchor_set[T_LAST_TOKEN];
140 /** The current source position. */
141 #define HERE (&token.base.source_position)
143 /** true if we are in GCC mode. */
144 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
146 static statement_t *parse_compound_statement(bool inside_expression_statement);
147 static statement_t *parse_statement(void);
149 static expression_t *parse_subexpression(precedence_t);
150 static expression_t *parse_expression(void);
151 static type_t *parse_typename(void);
152 static void parse_externals(void);
153 static void parse_external(void);
155 static void parse_compound_type_entries(compound_t *compound_declaration);
157 static void check_call_argument(type_t *expected_type,
158 call_argument_t *argument, unsigned pos);
160 typedef enum declarator_flags_t {
162 DECL_MAY_BE_ABSTRACT = 1U << 0,
163 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
164 DECL_IS_PARAMETER = 1U << 2
165 } declarator_flags_t;
167 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
168 declarator_flags_t flags);
170 static void semantic_comparison(binary_expression_t *expression);
172 #define STORAGE_CLASSES \
173 STORAGE_CLASSES_NO_EXTERN \
176 #define STORAGE_CLASSES_NO_EXTERN \
183 #define TYPE_QUALIFIERS \
188 case T__forceinline: \
189 case T___attribute__:
191 #define COMPLEX_SPECIFIERS \
193 #define IMAGINARY_SPECIFIERS \
196 #define TYPE_SPECIFIERS \
198 case T___builtin_va_list: \
223 #define DECLARATION_START \
228 #define DECLARATION_START_NO_EXTERN \
229 STORAGE_CLASSES_NO_EXTERN \
233 #define EXPRESSION_START \
242 case T_CHARACTER_CONSTANT: \
243 case T_FLOATINGPOINT: \
244 case T_FLOATINGPOINT_HEXADECIMAL: \
246 case T_INTEGER_HEXADECIMAL: \
247 case T_INTEGER_OCTAL: \
250 case T_STRING_LITERAL: \
251 case T_WIDE_CHARACTER_CONSTANT: \
252 case T_WIDE_STRING_LITERAL: \
253 case T___FUNCDNAME__: \
254 case T___FUNCSIG__: \
255 case T___FUNCTION__: \
256 case T___PRETTY_FUNCTION__: \
257 case T___alignof__: \
258 case T___builtin_classify_type: \
259 case T___builtin_constant_p: \
260 case T___builtin_isgreater: \
261 case T___builtin_isgreaterequal: \
262 case T___builtin_isless: \
263 case T___builtin_islessequal: \
264 case T___builtin_islessgreater: \
265 case T___builtin_isunordered: \
266 case T___builtin_offsetof: \
267 case T___builtin_va_arg: \
268 case T___builtin_va_copy: \
269 case T___builtin_va_start: \
280 * Returns the size of a statement node.
282 * @param kind the statement kind
284 static size_t get_statement_struct_size(statement_kind_t kind)
286 static const size_t sizes[] = {
287 [STATEMENT_ERROR] = sizeof(statement_base_t),
288 [STATEMENT_EMPTY] = sizeof(statement_base_t),
289 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
290 [STATEMENT_RETURN] = sizeof(return_statement_t),
291 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
292 [STATEMENT_IF] = sizeof(if_statement_t),
293 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
294 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
295 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
296 [STATEMENT_BREAK] = sizeof(statement_base_t),
297 [STATEMENT_GOTO] = sizeof(goto_statement_t),
298 [STATEMENT_LABEL] = sizeof(label_statement_t),
299 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
300 [STATEMENT_WHILE] = sizeof(while_statement_t),
301 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
302 [STATEMENT_FOR] = sizeof(for_statement_t),
303 [STATEMENT_ASM] = sizeof(asm_statement_t),
304 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
305 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
307 assert((size_t)kind < lengthof(sizes));
308 assert(sizes[kind] != 0);
313 * Returns the size of an expression node.
315 * @param kind the expression kind
317 static size_t get_expression_struct_size(expression_kind_t kind)
319 static const size_t sizes[] = {
320 [EXPR_ERROR] = sizeof(expression_base_t),
321 [EXPR_REFERENCE] = sizeof(reference_expression_t),
322 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
323 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
324 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
327 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
331 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
332 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
333 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
334 [EXPR_CALL] = sizeof(call_expression_t),
335 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
336 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
337 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
338 [EXPR_SELECT] = sizeof(select_expression_t),
339 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
340 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
341 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
342 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
343 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
344 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
345 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
346 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
347 [EXPR_VA_START] = sizeof(va_start_expression_t),
348 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
349 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
350 [EXPR_STATEMENT] = sizeof(statement_expression_t),
351 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
353 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
354 return sizes[EXPR_UNARY_FIRST];
356 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
357 return sizes[EXPR_BINARY_FIRST];
359 assert((size_t)kind < lengthof(sizes));
360 assert(sizes[kind] != 0);
365 * Allocate a statement node of given kind and initialize all
366 * fields with zero. Sets its source position to the position
367 * of the current token.
369 static statement_t *allocate_statement_zero(statement_kind_t kind)
371 size_t size = get_statement_struct_size(kind);
372 statement_t *res = allocate_ast_zero(size);
374 res->base.kind = kind;
375 res->base.parent = current_parent;
376 res->base.source_position = token.base.source_position;
381 * Allocate an expression node of given kind and initialize all
384 * @param kind the kind of the expression to allocate
386 static expression_t *allocate_expression_zero(expression_kind_t kind)
388 size_t size = get_expression_struct_size(kind);
389 expression_t *res = allocate_ast_zero(size);
391 res->base.kind = kind;
392 res->base.type = type_error_type;
393 res->base.source_position = token.base.source_position;
398 * Creates a new invalid expression at the source position
399 * of the current token.
401 static expression_t *create_error_expression(void)
403 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
404 expression->base.type = type_error_type;
409 * Creates a new invalid statement.
411 static statement_t *create_error_statement(void)
413 return allocate_statement_zero(STATEMENT_ERROR);
417 * Allocate a new empty statement.
419 static statement_t *create_empty_statement(void)
421 return allocate_statement_zero(STATEMENT_EMPTY);
425 * Returns the size of an initializer node.
427 * @param kind the initializer kind
429 static size_t get_initializer_size(initializer_kind_t kind)
431 static const size_t sizes[] = {
432 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
433 [INITIALIZER_STRING] = sizeof(initializer_string_t),
434 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
435 [INITIALIZER_LIST] = sizeof(initializer_list_t),
436 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
438 assert((size_t)kind < lengthof(sizes));
439 assert(sizes[kind] != 0);
444 * Allocate an initializer node of given kind and initialize all
447 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
449 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
456 * Returns the index of the top element of the environment stack.
458 static size_t environment_top(void)
460 return ARR_LEN(environment_stack);
464 * Returns the index of the top element of the global label stack.
466 static size_t label_top(void)
468 return ARR_LEN(label_stack);
472 * Return the next token.
474 static inline void next_token(void)
476 token = lookahead_buffer[lookahead_bufpos];
477 lookahead_buffer[lookahead_bufpos] = lexer_token;
480 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
483 print_token(stderr, &token);
484 fprintf(stderr, "\n");
488 static inline bool next_if(int const type)
490 if (token.kind == type) {
499 * Return the next token with a given lookahead.
501 static inline const token_t *look_ahead(size_t num)
503 assert(0 < num && num <= MAX_LOOKAHEAD);
504 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
505 return &lookahead_buffer[pos];
509 * Adds a token type to the token type anchor set (a multi-set).
511 static void add_anchor_token(int token_kind)
513 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
514 ++token_anchor_set[token_kind];
518 * Set the number of tokens types of the given type
519 * to zero and return the old count.
521 static int save_and_reset_anchor_state(int token_kind)
523 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
524 int count = token_anchor_set[token_kind];
525 token_anchor_set[token_kind] = 0;
530 * Restore the number of token types to the given count.
532 static void restore_anchor_state(int token_kind, int count)
534 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
535 token_anchor_set[token_kind] = count;
539 * Remove a token type from the token type anchor set (a multi-set).
541 static void rem_anchor_token(int token_kind)
543 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
544 assert(token_anchor_set[token_kind] != 0);
545 --token_anchor_set[token_kind];
549 * Return true if the token type of the current token is
552 static bool at_anchor(void)
556 return token_anchor_set[token.kind];
560 * Eat tokens until a matching token type is found.
562 static void eat_until_matching_token(int type)
566 case '(': end_token = ')'; break;
567 case '{': end_token = '}'; break;
568 case '[': end_token = ']'; break;
569 default: end_token = type; break;
572 unsigned parenthesis_count = 0;
573 unsigned brace_count = 0;
574 unsigned bracket_count = 0;
575 while (token.kind != end_token ||
576 parenthesis_count != 0 ||
578 bracket_count != 0) {
579 switch (token.kind) {
581 case '(': ++parenthesis_count; break;
582 case '{': ++brace_count; break;
583 case '[': ++bracket_count; break;
586 if (parenthesis_count > 0)
596 if (bracket_count > 0)
599 if (token.kind == end_token &&
600 parenthesis_count == 0 &&
614 * Eat input tokens until an anchor is found.
616 static void eat_until_anchor(void)
618 while (token_anchor_set[token.kind] == 0) {
619 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
620 eat_until_matching_token(token.kind);
626 * Eat a whole block from input tokens.
628 static void eat_block(void)
630 eat_until_matching_token('{');
634 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
637 * Report a parse error because an expected token was not found.
640 #if defined __GNUC__ && __GNUC__ >= 4
641 __attribute__((sentinel))
643 void parse_error_expected(const char *message, ...)
645 if (message != NULL) {
646 errorf(HERE, "%s", message);
649 va_start(ap, message);
650 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
655 * Report an incompatible type.
657 static void type_error_incompatible(const char *msg,
658 const source_position_t *source_position, type_t *type1, type_t *type2)
660 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
665 * Expect the current token is the expected token.
666 * If not, generate an error, eat the current statement,
667 * and goto the error_label label.
669 #define expect(expected, error_label) \
671 if (UNLIKELY(token.kind != (expected))) { \
672 parse_error_expected(NULL, (expected), NULL); \
673 add_anchor_token(expected); \
674 eat_until_anchor(); \
675 rem_anchor_token(expected); \
676 if (token.kind != (expected)) \
683 * Push a given scope on the scope stack and make it the
686 static scope_t *scope_push(scope_t *new_scope)
688 if (current_scope != NULL) {
689 new_scope->depth = current_scope->depth + 1;
692 scope_t *old_scope = current_scope;
693 current_scope = new_scope;
698 * Pop the current scope from the scope stack.
700 static void scope_pop(scope_t *old_scope)
702 current_scope = old_scope;
706 * Search an entity by its symbol in a given namespace.
708 static entity_t *get_entity(const symbol_t *const symbol,
709 namespace_tag_t namespc)
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 != 0);
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 atomic_type_kind_t get_akind(const type_t *type)
859 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
860 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
861 return type->atomic.akind;
865 * §6.3.1.1:2 Do integer promotion for a given type.
867 * @param type the type to promote
868 * @return the promoted type
870 static type_t *promote_integer(type_t *type)
872 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
879 * Check if a given expression represents a null pointer constant.
881 * @param expression the expression to check
883 static bool is_null_pointer_constant(const expression_t *expression)
885 /* skip void* cast */
886 if (expression->kind == EXPR_UNARY_CAST) {
887 type_t *const type = skip_typeref(expression->base.type);
888 if (types_compatible(type, type_void_ptr))
889 expression = expression->unary.value;
892 type_t *const type = skip_typeref(expression->base.type);
893 if (!is_type_integer(type))
895 switch (is_constant_expression(expression)) {
896 case EXPR_CLASS_ERROR: return true;
897 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
898 default: return false;
903 * Create an implicit cast expression.
905 * @param expression the expression to cast
906 * @param dest_type the destination type
908 static expression_t *create_implicit_cast(expression_t *expression,
911 type_t *const source_type = expression->base.type;
913 if (source_type == dest_type)
916 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
917 cast->unary.value = expression;
918 cast->base.type = dest_type;
919 cast->base.implicit = true;
924 typedef enum assign_error_t {
926 ASSIGN_ERROR_INCOMPATIBLE,
927 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
928 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
929 ASSIGN_WARNING_POINTER_FROM_INT,
930 ASSIGN_WARNING_INT_FROM_POINTER
933 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)
935 type_t *const orig_type_right = right->base.type;
936 type_t *const type_left = skip_typeref(orig_type_left);
937 type_t *const type_right = skip_typeref(orig_type_right);
942 case ASSIGN_ERROR_INCOMPATIBLE:
943 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
946 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
947 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
948 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
950 /* the left type has all qualifiers from the right type */
951 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
952 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);
956 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
957 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
960 case ASSIGN_WARNING_POINTER_FROM_INT:
961 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
964 case ASSIGN_WARNING_INT_FROM_POINTER:
965 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
969 panic("invalid error value");
973 /** Implements the rules from §6.5.16.1 */
974 static assign_error_t semantic_assign(type_t *orig_type_left,
975 const expression_t *const right)
977 type_t *const orig_type_right = right->base.type;
978 type_t *const type_left = skip_typeref(orig_type_left);
979 type_t *const type_right = skip_typeref(orig_type_right);
981 if (is_type_pointer(type_left)) {
982 if (is_null_pointer_constant(right)) {
983 return ASSIGN_SUCCESS;
984 } else if (is_type_pointer(type_right)) {
985 type_t *points_to_left
986 = skip_typeref(type_left->pointer.points_to);
987 type_t *points_to_right
988 = skip_typeref(type_right->pointer.points_to);
989 assign_error_t res = ASSIGN_SUCCESS;
991 /* the left type has all qualifiers from the right type */
992 unsigned missing_qualifiers
993 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
994 if (missing_qualifiers != 0) {
995 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
998 points_to_left = get_unqualified_type(points_to_left);
999 points_to_right = get_unqualified_type(points_to_right);
1001 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1004 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1005 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1006 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1009 if (!types_compatible(points_to_left, points_to_right)) {
1010 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1014 } else if (is_type_integer(type_right)) {
1015 return ASSIGN_WARNING_POINTER_FROM_INT;
1017 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1018 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1019 && is_type_pointer(type_right))) {
1020 return ASSIGN_SUCCESS;
1021 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1022 type_t *const unqual_type_left = get_unqualified_type(type_left);
1023 type_t *const unqual_type_right = get_unqualified_type(type_right);
1024 if (types_compatible(unqual_type_left, unqual_type_right)) {
1025 return ASSIGN_SUCCESS;
1027 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1028 return ASSIGN_WARNING_INT_FROM_POINTER;
1031 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1032 return ASSIGN_SUCCESS;
1034 return ASSIGN_ERROR_INCOMPATIBLE;
1037 static expression_t *parse_constant_expression(void)
1039 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1041 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1042 errorf(&result->base.source_position,
1043 "expression '%E' is not constant", result);
1049 static expression_t *parse_assignment_expression(void)
1051 return parse_subexpression(PREC_ASSIGNMENT);
1054 static void warn_string_concat(const source_position_t *pos)
1056 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1059 static string_t parse_string_literals(void)
1061 assert(token.kind == T_STRING_LITERAL);
1062 string_t result = token.string.string;
1066 while (token.kind == T_STRING_LITERAL) {
1067 warn_string_concat(&token.base.source_position);
1068 result = concat_strings(&result, &token.string.string);
1075 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1077 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1078 attribute->kind = kind;
1079 attribute->source_position = *HERE;
1084 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1087 * __attribute__ ( ( attribute-list ) )
1091 * attribute_list , attrib
1096 * any-word ( identifier )
1097 * any-word ( identifier , nonempty-expr-list )
1098 * any-word ( expr-list )
1100 * where the "identifier" must not be declared as a type, and
1101 * "any-word" may be any identifier (including one declared as a
1102 * type), a reserved word storage class specifier, type specifier or
1103 * type qualifier. ??? This still leaves out most reserved keywords
1104 * (following the old parser), shouldn't we include them, and why not
1105 * allow identifiers declared as types to start the arguments?
1107 * Matze: this all looks confusing and little systematic, so we're even less
1108 * strict and parse any list of things which are identifiers or
1109 * (assignment-)expressions.
1111 static attribute_argument_t *parse_attribute_arguments(void)
1113 attribute_argument_t *first = NULL;
1114 attribute_argument_t **anchor = &first;
1115 if (token.kind != ')') do {
1116 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1118 /* is it an identifier */
1119 if (token.kind == T_IDENTIFIER
1120 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1121 symbol_t *symbol = token.identifier.symbol;
1122 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1123 argument->v.symbol = symbol;
1126 /* must be an expression */
1127 expression_t *expression = parse_assignment_expression();
1129 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1130 argument->v.expression = expression;
1133 /* append argument */
1135 anchor = &argument->next;
1136 } while (next_if(','));
1137 expect(')', end_error);
1146 static attribute_t *parse_attribute_asm(void)
1148 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1151 expect('(', end_error);
1152 attribute->a.arguments = parse_attribute_arguments();
1159 static symbol_t *get_symbol_from_token(void)
1161 switch(token.kind) {
1163 return token.identifier.symbol;
1192 /* maybe we need more tokens ... add them on demand */
1193 return get_token_kind_symbol(token.kind);
1199 static attribute_t *parse_attribute_gnu_single(void)
1201 /* parse "any-word" */
1202 symbol_t *symbol = get_symbol_from_token();
1203 if (symbol == NULL) {
1204 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1208 attribute_kind_t kind;
1209 char const *const name = symbol->string;
1210 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1211 if (kind > ATTRIBUTE_GNU_LAST) {
1212 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1213 /* TODO: we should still save the attribute in the list... */
1214 kind = ATTRIBUTE_UNKNOWN;
1218 const char *attribute_name = get_attribute_name(kind);
1219 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1223 attribute_t *attribute = allocate_attribute_zero(kind);
1226 /* parse arguments */
1228 attribute->a.arguments = parse_attribute_arguments();
1233 static attribute_t *parse_attribute_gnu(void)
1235 attribute_t *first = NULL;
1236 attribute_t **anchor = &first;
1238 eat(T___attribute__);
1239 expect('(', end_error);
1240 expect('(', end_error);
1242 if (token.kind != ')') do {
1243 attribute_t *attribute = parse_attribute_gnu_single();
1244 if (attribute == NULL)
1247 *anchor = attribute;
1248 anchor = &attribute->next;
1249 } while (next_if(','));
1250 expect(')', end_error);
1251 expect(')', end_error);
1257 /** Parse attributes. */
1258 static attribute_t *parse_attributes(attribute_t *first)
1260 attribute_t **anchor = &first;
1262 while (*anchor != NULL)
1263 anchor = &(*anchor)->next;
1265 attribute_t *attribute;
1266 switch (token.kind) {
1267 case T___attribute__:
1268 attribute = parse_attribute_gnu();
1269 if (attribute == NULL)
1274 attribute = parse_attribute_asm();
1278 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1283 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1287 case T__forceinline:
1288 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1289 eat(T__forceinline);
1293 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1298 /* TODO record modifier */
1299 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1300 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1308 *anchor = attribute;
1309 anchor = &attribute->next;
1313 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1315 static entity_t *determine_lhs_ent(expression_t *const expr,
1318 switch (expr->kind) {
1319 case EXPR_REFERENCE: {
1320 entity_t *const entity = expr->reference.entity;
1321 /* we should only find variables as lvalues... */
1322 if (entity->base.kind != ENTITY_VARIABLE
1323 && entity->base.kind != ENTITY_PARAMETER)
1329 case EXPR_ARRAY_ACCESS: {
1330 expression_t *const ref = expr->array_access.array_ref;
1331 entity_t * ent = NULL;
1332 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1333 ent = determine_lhs_ent(ref, lhs_ent);
1336 mark_vars_read(ref, lhs_ent);
1338 mark_vars_read(expr->array_access.index, lhs_ent);
1343 mark_vars_read(expr->select.compound, lhs_ent);
1344 if (is_type_compound(skip_typeref(expr->base.type)))
1345 return determine_lhs_ent(expr->select.compound, lhs_ent);
1349 case EXPR_UNARY_DEREFERENCE: {
1350 expression_t *const val = expr->unary.value;
1351 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1353 return determine_lhs_ent(val->unary.value, lhs_ent);
1355 mark_vars_read(val, NULL);
1361 mark_vars_read(expr, NULL);
1366 #define ENT_ANY ((entity_t*)-1)
1369 * Mark declarations, which are read. This is used to detect variables, which
1373 * x is not marked as "read", because it is only read to calculate its own new
1377 * x and y are not detected as "not read", because multiple variables are
1380 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1382 switch (expr->kind) {
1383 case EXPR_REFERENCE: {
1384 entity_t *const entity = expr->reference.entity;
1385 if (entity->kind != ENTITY_VARIABLE
1386 && entity->kind != ENTITY_PARAMETER)
1389 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1390 if (entity->kind == ENTITY_VARIABLE) {
1391 entity->variable.read = true;
1393 entity->parameter.read = true;
1400 // TODO respect pure/const
1401 mark_vars_read(expr->call.function, NULL);
1402 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1403 mark_vars_read(arg->expression, NULL);
1407 case EXPR_CONDITIONAL:
1408 // TODO lhs_decl should depend on whether true/false have an effect
1409 mark_vars_read(expr->conditional.condition, NULL);
1410 if (expr->conditional.true_expression != NULL)
1411 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1412 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1416 if (lhs_ent == ENT_ANY
1417 && !is_type_compound(skip_typeref(expr->base.type)))
1419 mark_vars_read(expr->select.compound, lhs_ent);
1422 case EXPR_ARRAY_ACCESS: {
1423 mark_vars_read(expr->array_access.index, lhs_ent);
1424 expression_t *const ref = expr->array_access.array_ref;
1425 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1426 if (lhs_ent == ENT_ANY)
1429 mark_vars_read(ref, lhs_ent);
1434 mark_vars_read(expr->va_arge.ap, lhs_ent);
1438 mark_vars_read(expr->va_copye.src, lhs_ent);
1441 case EXPR_UNARY_CAST:
1442 /* Special case: Use void cast to mark a variable as "read" */
1443 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1448 case EXPR_UNARY_THROW:
1449 if (expr->unary.value == NULL)
1452 case EXPR_UNARY_DEREFERENCE:
1453 case EXPR_UNARY_DELETE:
1454 case EXPR_UNARY_DELETE_ARRAY:
1455 if (lhs_ent == ENT_ANY)
1459 case EXPR_UNARY_NEGATE:
1460 case EXPR_UNARY_PLUS:
1461 case EXPR_UNARY_BITWISE_NEGATE:
1462 case EXPR_UNARY_NOT:
1463 case EXPR_UNARY_TAKE_ADDRESS:
1464 case EXPR_UNARY_POSTFIX_INCREMENT:
1465 case EXPR_UNARY_POSTFIX_DECREMENT:
1466 case EXPR_UNARY_PREFIX_INCREMENT:
1467 case EXPR_UNARY_PREFIX_DECREMENT:
1468 case EXPR_UNARY_ASSUME:
1470 mark_vars_read(expr->unary.value, lhs_ent);
1473 case EXPR_BINARY_ADD:
1474 case EXPR_BINARY_SUB:
1475 case EXPR_BINARY_MUL:
1476 case EXPR_BINARY_DIV:
1477 case EXPR_BINARY_MOD:
1478 case EXPR_BINARY_EQUAL:
1479 case EXPR_BINARY_NOTEQUAL:
1480 case EXPR_BINARY_LESS:
1481 case EXPR_BINARY_LESSEQUAL:
1482 case EXPR_BINARY_GREATER:
1483 case EXPR_BINARY_GREATEREQUAL:
1484 case EXPR_BINARY_BITWISE_AND:
1485 case EXPR_BINARY_BITWISE_OR:
1486 case EXPR_BINARY_BITWISE_XOR:
1487 case EXPR_BINARY_LOGICAL_AND:
1488 case EXPR_BINARY_LOGICAL_OR:
1489 case EXPR_BINARY_SHIFTLEFT:
1490 case EXPR_BINARY_SHIFTRIGHT:
1491 case EXPR_BINARY_COMMA:
1492 case EXPR_BINARY_ISGREATER:
1493 case EXPR_BINARY_ISGREATEREQUAL:
1494 case EXPR_BINARY_ISLESS:
1495 case EXPR_BINARY_ISLESSEQUAL:
1496 case EXPR_BINARY_ISLESSGREATER:
1497 case EXPR_BINARY_ISUNORDERED:
1498 mark_vars_read(expr->binary.left, lhs_ent);
1499 mark_vars_read(expr->binary.right, lhs_ent);
1502 case EXPR_BINARY_ASSIGN:
1503 case EXPR_BINARY_MUL_ASSIGN:
1504 case EXPR_BINARY_DIV_ASSIGN:
1505 case EXPR_BINARY_MOD_ASSIGN:
1506 case EXPR_BINARY_ADD_ASSIGN:
1507 case EXPR_BINARY_SUB_ASSIGN:
1508 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1509 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1510 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1511 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1512 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1513 if (lhs_ent == ENT_ANY)
1515 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1516 mark_vars_read(expr->binary.right, lhs_ent);
1521 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1526 case EXPR_STRING_LITERAL:
1527 case EXPR_WIDE_STRING_LITERAL:
1528 case EXPR_COMPOUND_LITERAL: // TODO init?
1530 case EXPR_CLASSIFY_TYPE:
1533 case EXPR_BUILTIN_CONSTANT_P:
1534 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1536 case EXPR_STATEMENT: // TODO
1537 case EXPR_LABEL_ADDRESS:
1538 case EXPR_REFERENCE_ENUM_VALUE:
1542 panic("unhandled expression");
1545 static designator_t *parse_designation(void)
1547 designator_t *result = NULL;
1548 designator_t **anchor = &result;
1551 designator_t *designator;
1552 switch (token.kind) {
1554 designator = allocate_ast_zero(sizeof(designator[0]));
1555 designator->source_position = token.base.source_position;
1557 add_anchor_token(']');
1558 designator->array_index = parse_constant_expression();
1559 rem_anchor_token(']');
1560 expect(']', end_error);
1563 designator = allocate_ast_zero(sizeof(designator[0]));
1564 designator->source_position = token.base.source_position;
1566 if (token.kind != T_IDENTIFIER) {
1567 parse_error_expected("while parsing designator",
1568 T_IDENTIFIER, NULL);
1571 designator->symbol = token.identifier.symbol;
1575 expect('=', end_error);
1579 assert(designator != NULL);
1580 *anchor = designator;
1581 anchor = &designator->next;
1587 static initializer_t *initializer_from_string(array_type_t *const type,
1588 const string_t *const string)
1590 /* TODO: check len vs. size of array type */
1593 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1594 initializer->string.string = *string;
1599 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1600 const string_t *const string)
1602 /* TODO: check len vs. size of array type */
1605 initializer_t *const initializer =
1606 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1607 initializer->wide_string.string = *string;
1613 * Build an initializer from a given expression.
1615 static initializer_t *initializer_from_expression(type_t *orig_type,
1616 expression_t *expression)
1618 /* TODO check that expression is a constant expression */
1620 /* §6.7.8.14/15 char array may be initialized by string literals */
1621 type_t *type = skip_typeref(orig_type);
1622 type_t *expr_type_orig = expression->base.type;
1623 type_t *expr_type = skip_typeref(expr_type_orig);
1625 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1626 array_type_t *const array_type = &type->array;
1627 type_t *const element_type = skip_typeref(array_type->element_type);
1629 if (element_type->kind == TYPE_ATOMIC) {
1630 atomic_type_kind_t akind = element_type->atomic.akind;
1631 switch (expression->kind) {
1632 case EXPR_STRING_LITERAL:
1633 if (akind == ATOMIC_TYPE_CHAR
1634 || akind == ATOMIC_TYPE_SCHAR
1635 || akind == ATOMIC_TYPE_UCHAR) {
1636 return initializer_from_string(array_type,
1637 &expression->string_literal.value);
1641 case EXPR_WIDE_STRING_LITERAL: {
1642 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1643 if (get_unqualified_type(element_type) == bare_wchar_type) {
1644 return initializer_from_wide_string(array_type,
1645 &expression->string_literal.value);
1656 assign_error_t error = semantic_assign(type, expression);
1657 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1659 report_assign_error(error, type, expression, "initializer",
1660 &expression->base.source_position);
1662 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1663 result->value.value = create_implicit_cast(expression, type);
1669 * Checks if a given expression can be used as a constant initializer.
1671 static bool is_initializer_constant(const expression_t *expression)
1673 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1674 is_linker_constant(expression) != EXPR_CLASS_VARIABLE;
1678 * Parses an scalar initializer.
1680 * §6.7.8.11; eat {} without warning
1682 static initializer_t *parse_scalar_initializer(type_t *type,
1683 bool must_be_constant)
1685 /* there might be extra {} hierarchies */
1687 if (token.kind == '{') {
1688 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1692 } while (token.kind == '{');
1695 expression_t *expression = parse_assignment_expression();
1696 mark_vars_read(expression, NULL);
1697 if (must_be_constant && !is_initializer_constant(expression)) {
1698 errorf(&expression->base.source_position,
1699 "initialisation expression '%E' is not constant",
1703 initializer_t *initializer = initializer_from_expression(type, expression);
1705 if (initializer == NULL) {
1706 errorf(&expression->base.source_position,
1707 "expression '%E' (type '%T') doesn't match expected type '%T'",
1708 expression, expression->base.type, type);
1713 bool additional_warning_displayed = false;
1714 while (braces > 0) {
1716 if (token.kind != '}') {
1717 if (!additional_warning_displayed) {
1718 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1719 additional_warning_displayed = true;
1730 * An entry in the type path.
1732 typedef struct type_path_entry_t type_path_entry_t;
1733 struct type_path_entry_t {
1734 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1736 size_t index; /**< For array types: the current index. */
1737 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1742 * A type path expression a position inside compound or array types.
1744 typedef struct type_path_t type_path_t;
1745 struct type_path_t {
1746 type_path_entry_t *path; /**< An flexible array containing the current path. */
1747 type_t *top_type; /**< type of the element the path points */
1748 size_t max_index; /**< largest index in outermost array */
1752 * Prints a type path for debugging.
1754 static __attribute__((unused)) void debug_print_type_path(
1755 const type_path_t *path)
1757 size_t len = ARR_LEN(path->path);
1759 for (size_t i = 0; i < len; ++i) {
1760 const type_path_entry_t *entry = & path->path[i];
1762 type_t *type = skip_typeref(entry->type);
1763 if (is_type_compound(type)) {
1764 /* in gcc mode structs can have no members */
1765 if (entry->v.compound_entry == NULL) {
1769 fprintf(stderr, ".%s",
1770 entry->v.compound_entry->base.symbol->string);
1771 } else if (is_type_array(type)) {
1772 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1774 fprintf(stderr, "-INVALID-");
1777 if (path->top_type != NULL) {
1778 fprintf(stderr, " (");
1779 print_type(path->top_type);
1780 fprintf(stderr, ")");
1785 * Return the top type path entry, ie. in a path
1786 * (type).a.b returns the b.
1788 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1790 size_t len = ARR_LEN(path->path);
1792 return &path->path[len-1];
1796 * Enlarge the type path by an (empty) element.
1798 static type_path_entry_t *append_to_type_path(type_path_t *path)
1800 size_t len = ARR_LEN(path->path);
1801 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1803 type_path_entry_t *result = & path->path[len];
1804 memset(result, 0, sizeof(result[0]));
1809 * Descending into a sub-type. Enter the scope of the current top_type.
1811 static void descend_into_subtype(type_path_t *path)
1813 type_t *orig_top_type = path->top_type;
1814 type_t *top_type = skip_typeref(orig_top_type);
1816 type_path_entry_t *top = append_to_type_path(path);
1817 top->type = top_type;
1819 if (is_type_compound(top_type)) {
1820 compound_t *const compound = top_type->compound.compound;
1821 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1823 if (entry != NULL) {
1824 top->v.compound_entry = &entry->declaration;
1825 path->top_type = entry->declaration.type;
1827 path->top_type = NULL;
1829 } else if (is_type_array(top_type)) {
1831 path->top_type = top_type->array.element_type;
1833 assert(!is_type_valid(top_type));
1838 * Pop an entry from the given type path, ie. returning from
1839 * (type).a.b to (type).a
1841 static void ascend_from_subtype(type_path_t *path)
1843 type_path_entry_t *top = get_type_path_top(path);
1845 path->top_type = top->type;
1847 size_t len = ARR_LEN(path->path);
1848 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1852 * Pop entries from the given type path until the given
1853 * path level is reached.
1855 static void ascend_to(type_path_t *path, size_t top_path_level)
1857 size_t len = ARR_LEN(path->path);
1859 while (len > top_path_level) {
1860 ascend_from_subtype(path);
1861 len = ARR_LEN(path->path);
1865 static bool walk_designator(type_path_t *path, const designator_t *designator,
1866 bool used_in_offsetof)
1868 for (; designator != NULL; designator = designator->next) {
1869 type_path_entry_t *top = get_type_path_top(path);
1870 type_t *orig_type = top->type;
1872 type_t *type = skip_typeref(orig_type);
1874 if (designator->symbol != NULL) {
1875 symbol_t *symbol = designator->symbol;
1876 if (!is_type_compound(type)) {
1877 if (is_type_valid(type)) {
1878 errorf(&designator->source_position,
1879 "'.%Y' designator used for non-compound type '%T'",
1883 top->type = type_error_type;
1884 top->v.compound_entry = NULL;
1885 orig_type = type_error_type;
1887 compound_t *compound = type->compound.compound;
1888 entity_t *iter = compound->members.entities;
1889 for (; iter != NULL; iter = iter->base.next) {
1890 if (iter->base.symbol == symbol) {
1895 errorf(&designator->source_position,
1896 "'%T' has no member named '%Y'", orig_type, symbol);
1899 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1900 if (used_in_offsetof && iter->compound_member.bitfield) {
1901 errorf(&designator->source_position,
1902 "offsetof designator '%Y' must not specify bitfield",
1907 top->type = orig_type;
1908 top->v.compound_entry = &iter->declaration;
1909 orig_type = iter->declaration.type;
1912 expression_t *array_index = designator->array_index;
1913 assert(designator->array_index != NULL);
1915 if (!is_type_array(type)) {
1916 if (is_type_valid(type)) {
1917 errorf(&designator->source_position,
1918 "[%E] designator used for non-array type '%T'",
1919 array_index, orig_type);
1924 long index = fold_constant_to_int(array_index);
1925 if (!used_in_offsetof) {
1927 errorf(&designator->source_position,
1928 "array index [%E] must be positive", array_index);
1929 } else if (type->array.size_constant) {
1930 long array_size = type->array.size;
1931 if (index >= array_size) {
1932 errorf(&designator->source_position,
1933 "designator [%E] (%d) exceeds array size %d",
1934 array_index, index, array_size);
1939 top->type = orig_type;
1940 top->v.index = (size_t) index;
1941 orig_type = type->array.element_type;
1943 path->top_type = orig_type;
1945 if (designator->next != NULL) {
1946 descend_into_subtype(path);
1952 static void advance_current_object(type_path_t *path, size_t top_path_level)
1954 type_path_entry_t *top = get_type_path_top(path);
1956 type_t *type = skip_typeref(top->type);
1957 if (is_type_union(type)) {
1958 /* in unions only the first element is initialized */
1959 top->v.compound_entry = NULL;
1960 } else if (is_type_struct(type)) {
1961 declaration_t *entry = top->v.compound_entry;
1963 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1964 if (next_entity != NULL) {
1965 assert(is_declaration(next_entity));
1966 entry = &next_entity->declaration;
1971 top->v.compound_entry = entry;
1972 if (entry != NULL) {
1973 path->top_type = entry->type;
1976 } else if (is_type_array(type)) {
1977 assert(is_type_array(type));
1981 if (!type->array.size_constant || top->v.index < type->array.size) {
1985 assert(!is_type_valid(type));
1989 /* we're past the last member of the current sub-aggregate, try if we
1990 * can ascend in the type hierarchy and continue with another subobject */
1991 size_t len = ARR_LEN(path->path);
1993 if (len > top_path_level) {
1994 ascend_from_subtype(path);
1995 advance_current_object(path, top_path_level);
1997 path->top_type = NULL;
2002 * skip any {...} blocks until a closing bracket is reached.
2004 static void skip_initializers(void)
2008 while (token.kind != '}') {
2009 if (token.kind == T_EOF)
2011 if (token.kind == '{') {
2019 static initializer_t *create_empty_initializer(void)
2021 static initializer_t empty_initializer
2022 = { .list = { { INITIALIZER_LIST }, 0 } };
2023 return &empty_initializer;
2027 * Parse a part of an initialiser for a struct or union,
2029 static initializer_t *parse_sub_initializer(type_path_t *path,
2030 type_t *outer_type, size_t top_path_level,
2031 parse_initializer_env_t *env)
2033 if (token.kind == '}') {
2034 /* empty initializer */
2035 return create_empty_initializer();
2038 type_t *orig_type = path->top_type;
2039 type_t *type = NULL;
2041 if (orig_type == NULL) {
2042 /* We are initializing an empty compound. */
2044 type = skip_typeref(orig_type);
2047 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2050 designator_t *designator = NULL;
2051 if (token.kind == '.' || token.kind == '[') {
2052 designator = parse_designation();
2053 goto finish_designator;
2054 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2055 /* GNU-style designator ("identifier: value") */
2056 designator = allocate_ast_zero(sizeof(designator[0]));
2057 designator->source_position = token.base.source_position;
2058 designator->symbol = token.identifier.symbol;
2063 /* reset path to toplevel, evaluate designator from there */
2064 ascend_to(path, top_path_level);
2065 if (!walk_designator(path, designator, false)) {
2066 /* can't continue after designation error */
2070 initializer_t *designator_initializer
2071 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2072 designator_initializer->designator.designator = designator;
2073 ARR_APP1(initializer_t*, initializers, designator_initializer);
2075 orig_type = path->top_type;
2076 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2081 if (token.kind == '{') {
2082 if (type != NULL && is_type_scalar(type)) {
2083 sub = parse_scalar_initializer(type, env->must_be_constant);
2086 if (env->entity != NULL) {
2088 "extra brace group at end of initializer for '%Y'",
2089 env->entity->base.symbol);
2091 errorf(HERE, "extra brace group at end of initializer");
2096 descend_into_subtype(path);
2099 add_anchor_token('}');
2100 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2102 rem_anchor_token('}');
2105 ascend_from_subtype(path);
2106 expect('}', end_error);
2108 expect('}', end_error);
2109 goto error_parse_next;
2113 /* must be an expression */
2114 expression_t *expression = parse_assignment_expression();
2115 mark_vars_read(expression, NULL);
2117 if (env->must_be_constant && !is_initializer_constant(expression)) {
2118 errorf(&expression->base.source_position,
2119 "Initialisation expression '%E' is not constant",
2124 /* we are already outside, ... */
2125 if (outer_type == NULL)
2126 goto error_parse_next;
2127 type_t *const outer_type_skip = skip_typeref(outer_type);
2128 if (is_type_compound(outer_type_skip) &&
2129 !outer_type_skip->compound.compound->complete) {
2130 goto error_parse_next;
2133 source_position_t const* const pos = &expression->base.source_position;
2134 if (env->entity != NULL) {
2135 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2137 warningf(WARN_OTHER, pos, "excess elements in initializer");
2139 goto error_parse_next;
2142 /* handle { "string" } special case */
2143 if ((expression->kind == EXPR_STRING_LITERAL
2144 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2145 && outer_type != NULL) {
2146 sub = initializer_from_expression(outer_type, expression);
2149 if (token.kind != '}') {
2150 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2152 /* TODO: eat , ... */
2157 /* descend into subtypes until expression matches type */
2159 orig_type = path->top_type;
2160 type = skip_typeref(orig_type);
2162 sub = initializer_from_expression(orig_type, expression);
2166 if (!is_type_valid(type)) {
2169 if (is_type_scalar(type)) {
2170 errorf(&expression->base.source_position,
2171 "expression '%E' doesn't match expected type '%T'",
2172 expression, orig_type);
2176 descend_into_subtype(path);
2180 /* update largest index of top array */
2181 const type_path_entry_t *first = &path->path[0];
2182 type_t *first_type = first->type;
2183 first_type = skip_typeref(first_type);
2184 if (is_type_array(first_type)) {
2185 size_t index = first->v.index;
2186 if (index > path->max_index)
2187 path->max_index = index;
2190 /* append to initializers list */
2191 ARR_APP1(initializer_t*, initializers, sub);
2194 if (token.kind == '}') {
2197 expect(',', end_error);
2198 if (token.kind == '}') {
2203 /* advance to the next declaration if we are not at the end */
2204 advance_current_object(path, top_path_level);
2205 orig_type = path->top_type;
2206 if (orig_type != NULL)
2207 type = skip_typeref(orig_type);
2213 size_t len = ARR_LEN(initializers);
2214 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2215 initializer_t *result = allocate_ast_zero(size);
2216 result->kind = INITIALIZER_LIST;
2217 result->list.len = len;
2218 memcpy(&result->list.initializers, initializers,
2219 len * sizeof(initializers[0]));
2221 DEL_ARR_F(initializers);
2222 ascend_to(path, top_path_level+1);
2227 skip_initializers();
2228 DEL_ARR_F(initializers);
2229 ascend_to(path, top_path_level+1);
2233 static expression_t *make_size_literal(size_t value)
2235 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2236 literal->base.type = type_size_t;
2239 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2240 literal->literal.value = make_string(buf);
2246 * Parses an initializer. Parsers either a compound literal
2247 * (env->declaration == NULL) or an initializer of a declaration.
2249 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2251 type_t *type = skip_typeref(env->type);
2252 size_t max_index = 0;
2253 initializer_t *result;
2255 if (is_type_scalar(type)) {
2256 result = parse_scalar_initializer(type, env->must_be_constant);
2257 } else if (token.kind == '{') {
2261 memset(&path, 0, sizeof(path));
2262 path.top_type = env->type;
2263 path.path = NEW_ARR_F(type_path_entry_t, 0);
2265 descend_into_subtype(&path);
2267 add_anchor_token('}');
2268 result = parse_sub_initializer(&path, env->type, 1, env);
2269 rem_anchor_token('}');
2271 max_index = path.max_index;
2272 DEL_ARR_F(path.path);
2274 expect('}', end_error);
2277 /* parse_scalar_initializer() also works in this case: we simply
2278 * have an expression without {} around it */
2279 result = parse_scalar_initializer(type, env->must_be_constant);
2282 /* §6.7.8:22 array initializers for arrays with unknown size determine
2283 * the array type size */
2284 if (is_type_array(type) && type->array.size_expression == NULL
2285 && result != NULL) {
2287 switch (result->kind) {
2288 case INITIALIZER_LIST:
2289 assert(max_index != 0xdeadbeaf);
2290 size = max_index + 1;
2293 case INITIALIZER_STRING:
2294 size = result->string.string.size;
2297 case INITIALIZER_WIDE_STRING:
2298 size = result->wide_string.string.size;
2301 case INITIALIZER_DESIGNATOR:
2302 case INITIALIZER_VALUE:
2303 /* can happen for parse errors */
2308 internal_errorf(HERE, "invalid initializer type");
2311 type_t *new_type = duplicate_type(type);
2313 new_type->array.size_expression = make_size_literal(size);
2314 new_type->array.size_constant = true;
2315 new_type->array.has_implicit_size = true;
2316 new_type->array.size = size;
2317 env->type = new_type;
2323 static void append_entity(scope_t *scope, entity_t *entity)
2325 if (scope->last_entity != NULL) {
2326 scope->last_entity->base.next = entity;
2328 scope->entities = entity;
2330 entity->base.parent_entity = current_entity;
2331 scope->last_entity = entity;
2335 static compound_t *parse_compound_type_specifier(bool is_struct)
2337 source_position_t const pos = *HERE;
2338 eat(is_struct ? T_struct : T_union);
2340 symbol_t *symbol = NULL;
2341 entity_t *entity = NULL;
2342 attribute_t *attributes = NULL;
2344 if (token.kind == T___attribute__) {
2345 attributes = parse_attributes(NULL);
2348 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2349 if (token.kind == T_IDENTIFIER) {
2350 /* the compound has a name, check if we have seen it already */
2351 symbol = token.identifier.symbol;
2352 entity = get_tag(symbol, kind);
2355 if (entity != NULL) {
2356 if (entity->base.parent_scope != current_scope &&
2357 (token.kind == '{' || token.kind == ';')) {
2358 /* we're in an inner scope and have a definition. Shadow
2359 * existing definition in outer scope */
2361 } else if (entity->compound.complete && token.kind == '{') {
2362 source_position_t const *const ppos = &entity->base.source_position;
2363 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2364 /* clear members in the hope to avoid further errors */
2365 entity->compound.members.entities = NULL;
2368 } else if (token.kind != '{') {
2369 char const *const msg =
2370 is_struct ? "while parsing struct type specifier" :
2371 "while parsing union type specifier";
2372 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2377 if (entity == NULL) {
2378 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2379 entity->compound.alignment = 1;
2380 entity->base.source_position = pos;
2381 entity->base.parent_scope = current_scope;
2382 if (symbol != NULL) {
2383 environment_push(entity);
2385 append_entity(current_scope, entity);
2388 if (token.kind == '{') {
2389 parse_compound_type_entries(&entity->compound);
2391 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2392 if (symbol == NULL) {
2393 assert(anonymous_entity == NULL);
2394 anonymous_entity = entity;
2398 if (attributes != NULL) {
2399 handle_entity_attributes(attributes, entity);
2402 return &entity->compound;
2405 static void parse_enum_entries(type_t *const enum_type)
2409 if (token.kind == '}') {
2410 errorf(HERE, "empty enum not allowed");
2415 add_anchor_token('}');
2417 if (token.kind != T_IDENTIFIER) {
2418 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2420 rem_anchor_token('}');
2424 symbol_t *symbol = token.identifier.symbol;
2425 entity_t *const entity
2426 = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol);
2427 entity->enum_value.enum_type = enum_type;
2428 entity->base.source_position = token.base.source_position;
2432 expression_t *value = parse_constant_expression();
2434 value = create_implicit_cast(value, enum_type);
2435 entity->enum_value.value = value;
2440 record_entity(entity, false);
2441 } while (next_if(',') && token.kind != '}');
2442 rem_anchor_token('}');
2444 expect('}', end_error);
2450 static type_t *parse_enum_specifier(void)
2452 source_position_t const pos = *HERE;
2457 switch (token.kind) {
2459 symbol = token.identifier.symbol;
2460 entity = get_tag(symbol, ENTITY_ENUM);
2463 if (entity != NULL) {
2464 if (entity->base.parent_scope != current_scope &&
2465 (token.kind == '{' || token.kind == ';')) {
2466 /* we're in an inner scope and have a definition. Shadow
2467 * existing definition in outer scope */
2469 } else if (entity->enume.complete && token.kind == '{') {
2470 source_position_t const *const ppos = &entity->base.source_position;
2471 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2482 parse_error_expected("while parsing enum type specifier",
2483 T_IDENTIFIER, '{', NULL);
2487 if (entity == NULL) {
2488 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2489 entity->base.source_position = pos;
2490 entity->base.parent_scope = current_scope;
2493 type_t *const type = allocate_type_zero(TYPE_ENUM);
2494 type->enumt.enume = &entity->enume;
2495 type->enumt.base.akind = ATOMIC_TYPE_INT;
2497 if (token.kind == '{') {
2498 if (symbol != NULL) {
2499 environment_push(entity);
2501 append_entity(current_scope, entity);
2502 entity->enume.complete = true;
2504 parse_enum_entries(type);
2505 parse_attributes(NULL);
2507 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2508 if (symbol == NULL) {
2509 assert(anonymous_entity == NULL);
2510 anonymous_entity = entity;
2512 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2513 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2520 * if a symbol is a typedef to another type, return true
2522 static bool is_typedef_symbol(symbol_t *symbol)
2524 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2525 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2528 static type_t *parse_typeof(void)
2534 expect('(', end_error);
2535 add_anchor_token(')');
2537 expression_t *expression = NULL;
2539 switch (token.kind) {
2541 if (is_typedef_symbol(token.identifier.symbol)) {
2543 type = parse_typename();
2546 expression = parse_expression();
2547 type = revert_automatic_type_conversion(expression);
2552 rem_anchor_token(')');
2553 expect(')', end_error);
2555 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2556 typeof_type->typeoft.expression = expression;
2557 typeof_type->typeoft.typeof_type = type;
2564 typedef enum specifiers_t {
2565 SPECIFIER_SIGNED = 1 << 0,
2566 SPECIFIER_UNSIGNED = 1 << 1,
2567 SPECIFIER_LONG = 1 << 2,
2568 SPECIFIER_INT = 1 << 3,
2569 SPECIFIER_DOUBLE = 1 << 4,
2570 SPECIFIER_CHAR = 1 << 5,
2571 SPECIFIER_WCHAR_T = 1 << 6,
2572 SPECIFIER_SHORT = 1 << 7,
2573 SPECIFIER_LONG_LONG = 1 << 8,
2574 SPECIFIER_FLOAT = 1 << 9,
2575 SPECIFIER_BOOL = 1 << 10,
2576 SPECIFIER_VOID = 1 << 11,
2577 SPECIFIER_INT8 = 1 << 12,
2578 SPECIFIER_INT16 = 1 << 13,
2579 SPECIFIER_INT32 = 1 << 14,
2580 SPECIFIER_INT64 = 1 << 15,
2581 SPECIFIER_INT128 = 1 << 16,
2582 SPECIFIER_COMPLEX = 1 << 17,
2583 SPECIFIER_IMAGINARY = 1 << 18,
2586 static type_t *get_typedef_type(symbol_t *symbol)
2588 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2589 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2592 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2593 type->typedeft.typedefe = &entity->typedefe;
2598 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2600 expect('(', end_error);
2602 attribute_property_argument_t *property
2603 = allocate_ast_zero(sizeof(*property));
2606 if (token.kind != T_IDENTIFIER) {
2607 parse_error_expected("while parsing property declspec",
2608 T_IDENTIFIER, NULL);
2613 symbol_t *symbol = token.identifier.symbol;
2614 if (streq(symbol->string, "put")) {
2615 prop = &property->put_symbol;
2616 } else if (streq(symbol->string, "get")) {
2617 prop = &property->get_symbol;
2619 errorf(HERE, "expected put or get in property declspec");
2623 expect('=', end_error);
2624 if (token.kind != T_IDENTIFIER) {
2625 parse_error_expected("while parsing property declspec",
2626 T_IDENTIFIER, NULL);
2630 *prop = token.identifier.symbol;
2632 } while (next_if(','));
2634 attribute->a.property = property;
2636 expect(')', end_error);
2642 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2644 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2645 if (next_if(T_restrict)) {
2646 kind = ATTRIBUTE_MS_RESTRICT;
2647 } else if (token.kind == T_IDENTIFIER) {
2648 const char *name = token.identifier.symbol->string;
2649 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2651 const char *attribute_name = get_attribute_name(k);
2652 if (attribute_name != NULL && streq(attribute_name, name)) {
2658 if (kind == ATTRIBUTE_UNKNOWN) {
2659 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2662 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2666 attribute_t *attribute = allocate_attribute_zero(kind);
2669 if (kind == ATTRIBUTE_MS_PROPERTY) {
2670 return parse_attribute_ms_property(attribute);
2673 /* parse arguments */
2675 attribute->a.arguments = parse_attribute_arguments();
2680 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2684 expect('(', end_error);
2689 add_anchor_token(')');
2691 attribute_t **anchor = &first;
2693 while (*anchor != NULL)
2694 anchor = &(*anchor)->next;
2696 attribute_t *attribute
2697 = parse_microsoft_extended_decl_modifier_single();
2698 if (attribute == NULL)
2701 *anchor = attribute;
2702 anchor = &attribute->next;
2703 } while (next_if(','));
2705 rem_anchor_token(')');
2706 expect(')', end_error);
2710 rem_anchor_token(')');
2714 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2716 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2717 entity->base.source_position = *HERE;
2718 if (is_declaration(entity)) {
2719 entity->declaration.type = type_error_type;
2720 entity->declaration.implicit = true;
2721 } else if (kind == ENTITY_TYPEDEF) {
2722 entity->typedefe.type = type_error_type;
2723 entity->typedefe.builtin = true;
2725 if (kind != ENTITY_COMPOUND_MEMBER)
2726 record_entity(entity, false);
2730 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2732 type_t *type = NULL;
2733 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2734 unsigned type_specifiers = 0;
2735 bool newtype = false;
2736 bool saw_error = false;
2738 memset(specifiers, 0, sizeof(*specifiers));
2739 specifiers->source_position = token.base.source_position;
2742 specifiers->attributes = parse_attributes(specifiers->attributes);
2744 switch (token.kind) {
2746 #define MATCH_STORAGE_CLASS(token, class) \
2748 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2749 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2751 specifiers->storage_class = class; \
2752 if (specifiers->thread_local) \
2753 goto check_thread_storage_class; \
2757 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2758 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2759 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2760 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2761 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2764 specifiers->attributes
2765 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2769 if (specifiers->thread_local) {
2770 errorf(HERE, "duplicate '__thread'");
2772 specifiers->thread_local = true;
2773 check_thread_storage_class:
2774 switch (specifiers->storage_class) {
2775 case STORAGE_CLASS_EXTERN:
2776 case STORAGE_CLASS_NONE:
2777 case STORAGE_CLASS_STATIC:
2781 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2782 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2783 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2784 wrong_thread_storage_class:
2785 errorf(HERE, "'__thread' used with '%s'", wrong);
2792 /* type qualifiers */
2793 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2795 qualifiers |= qualifier; \
2799 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2800 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2801 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2802 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2803 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2804 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2805 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2806 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2808 /* type specifiers */
2809 #define MATCH_SPECIFIER(token, specifier, name) \
2811 if (type_specifiers & specifier) { \
2812 errorf(HERE, "multiple " name " type specifiers given"); \
2814 type_specifiers |= specifier; \
2819 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2820 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2821 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2822 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2823 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2824 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2825 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2826 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2827 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2828 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2829 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2830 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2831 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2832 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2833 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2834 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2835 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2836 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2840 specifiers->is_inline = true;
2844 case T__forceinline:
2846 specifiers->modifiers |= DM_FORCEINLINE;
2851 if (type_specifiers & SPECIFIER_LONG_LONG) {
2852 errorf(HERE, "too many long type specifiers given");
2853 } else if (type_specifiers & SPECIFIER_LONG) {
2854 type_specifiers |= SPECIFIER_LONG_LONG;
2856 type_specifiers |= SPECIFIER_LONG;
2861 #define CHECK_DOUBLE_TYPE() \
2862 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2865 CHECK_DOUBLE_TYPE();
2866 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2868 type->compound.compound = parse_compound_type_specifier(true);
2871 CHECK_DOUBLE_TYPE();
2872 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2873 type->compound.compound = parse_compound_type_specifier(false);
2876 CHECK_DOUBLE_TYPE();
2877 type = parse_enum_specifier();
2880 CHECK_DOUBLE_TYPE();
2881 type = parse_typeof();
2883 case T___builtin_va_list:
2884 CHECK_DOUBLE_TYPE();
2885 type = duplicate_type(type_valist);
2889 case T_IDENTIFIER: {
2890 /* only parse identifier if we haven't found a type yet */
2891 if (type != NULL || type_specifiers != 0) {
2892 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2893 * declaration, so it doesn't generate errors about expecting '(' or
2895 switch (look_ahead(1)->kind) {
2902 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2906 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2911 goto finish_specifiers;
2915 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2916 if (typedef_type == NULL) {
2917 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2918 * declaration, so it doesn't generate 'implicit int' followed by more
2919 * errors later on. */
2920 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2926 errorf(HERE, "%K does not name a type", &token);
2928 symbol_t *symbol = token.identifier.symbol;
2930 = create_error_entity(symbol, ENTITY_TYPEDEF);
2932 type = allocate_type_zero(TYPE_TYPEDEF);
2933 type->typedeft.typedefe = &entity->typedefe;
2941 goto finish_specifiers;
2946 type = typedef_type;
2950 /* function specifier */
2952 goto finish_specifiers;
2957 specifiers->attributes = parse_attributes(specifiers->attributes);
2959 if (type == NULL || (saw_error && type_specifiers != 0)) {
2960 atomic_type_kind_t atomic_type;
2962 /* match valid basic types */
2963 switch (type_specifiers) {
2964 case SPECIFIER_VOID:
2965 atomic_type = ATOMIC_TYPE_VOID;
2967 case SPECIFIER_WCHAR_T:
2968 atomic_type = ATOMIC_TYPE_WCHAR_T;
2970 case SPECIFIER_CHAR:
2971 atomic_type = ATOMIC_TYPE_CHAR;
2973 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2974 atomic_type = ATOMIC_TYPE_SCHAR;
2976 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2977 atomic_type = ATOMIC_TYPE_UCHAR;
2979 case SPECIFIER_SHORT:
2980 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2981 case SPECIFIER_SHORT | SPECIFIER_INT:
2982 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2983 atomic_type = ATOMIC_TYPE_SHORT;
2985 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2986 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2987 atomic_type = ATOMIC_TYPE_USHORT;
2990 case SPECIFIER_SIGNED:
2991 case SPECIFIER_SIGNED | SPECIFIER_INT:
2992 atomic_type = ATOMIC_TYPE_INT;
2994 case SPECIFIER_UNSIGNED:
2995 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2996 atomic_type = ATOMIC_TYPE_UINT;
2998 case SPECIFIER_LONG:
2999 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3000 case SPECIFIER_LONG | SPECIFIER_INT:
3001 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3002 atomic_type = ATOMIC_TYPE_LONG;
3004 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3005 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3006 atomic_type = ATOMIC_TYPE_ULONG;
3009 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3010 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3011 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3012 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3014 atomic_type = ATOMIC_TYPE_LONGLONG;
3015 goto warn_about_long_long;
3017 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3018 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3020 atomic_type = ATOMIC_TYPE_ULONGLONG;
3021 warn_about_long_long:
3022 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3025 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3026 atomic_type = unsigned_int8_type_kind;
3029 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3030 atomic_type = unsigned_int16_type_kind;
3033 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3034 atomic_type = unsigned_int32_type_kind;
3037 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3038 atomic_type = unsigned_int64_type_kind;
3041 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3042 atomic_type = unsigned_int128_type_kind;
3045 case SPECIFIER_INT8:
3046 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3047 atomic_type = int8_type_kind;
3050 case SPECIFIER_INT16:
3051 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3052 atomic_type = int16_type_kind;
3055 case SPECIFIER_INT32:
3056 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3057 atomic_type = int32_type_kind;
3060 case SPECIFIER_INT64:
3061 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3062 atomic_type = int64_type_kind;
3065 case SPECIFIER_INT128:
3066 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3067 atomic_type = int128_type_kind;
3070 case SPECIFIER_FLOAT:
3071 atomic_type = ATOMIC_TYPE_FLOAT;
3073 case SPECIFIER_DOUBLE:
3074 atomic_type = ATOMIC_TYPE_DOUBLE;
3076 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3077 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3079 case SPECIFIER_BOOL:
3080 atomic_type = ATOMIC_TYPE_BOOL;
3082 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3083 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3084 atomic_type = ATOMIC_TYPE_FLOAT;
3086 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3087 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3088 atomic_type = ATOMIC_TYPE_DOUBLE;
3090 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3091 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3092 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3095 /* invalid specifier combination, give an error message */
3096 source_position_t const* const pos = &specifiers->source_position;
3097 if (type_specifiers == 0) {
3099 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3100 if (!(c_mode & _CXX) && !strict_mode) {
3101 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3102 atomic_type = ATOMIC_TYPE_INT;
3105 errorf(pos, "no type specifiers given in declaration");
3108 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3109 (type_specifiers & SPECIFIER_UNSIGNED)) {
3110 errorf(pos, "signed and unsigned specifiers given");
3111 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3112 errorf(pos, "only integer types can be signed or unsigned");
3114 errorf(pos, "multiple datatypes in declaration");
3120 if (type_specifiers & SPECIFIER_COMPLEX) {
3121 type = allocate_type_zero(TYPE_COMPLEX);
3122 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3123 type = allocate_type_zero(TYPE_IMAGINARY);
3125 type = allocate_type_zero(TYPE_ATOMIC);
3127 type->atomic.akind = atomic_type;
3129 } else if (type_specifiers != 0) {
3130 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3133 /* FIXME: check type qualifiers here */
3134 type->base.qualifiers = qualifiers;
3137 type = identify_new_type(type);
3139 type = typehash_insert(type);
3142 if (specifiers->attributes != NULL)
3143 type = handle_type_attributes(specifiers->attributes, type);
3144 specifiers->type = type;
3148 specifiers->type = type_error_type;
3151 static type_qualifiers_t parse_type_qualifiers(void)
3153 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3156 switch (token.kind) {
3157 /* type qualifiers */
3158 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3159 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3160 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3161 /* microsoft extended type modifiers */
3162 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3163 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3164 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3165 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3166 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3175 * Parses an K&R identifier list
3177 static void parse_identifier_list(scope_t *scope)
3179 assert(token.kind == T_IDENTIFIER);
3181 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol);
3182 entity->base.source_position = token.base.source_position;
3183 /* a K&R parameter has no type, yet */
3187 append_entity(scope, entity);
3188 } while (next_if(',') && token.kind == T_IDENTIFIER);
3191 static entity_t *parse_parameter(void)
3193 declaration_specifiers_t specifiers;
3194 parse_declaration_specifiers(&specifiers);
3196 entity_t *entity = parse_declarator(&specifiers,
3197 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3198 anonymous_entity = NULL;
3202 static void semantic_parameter_incomplete(const entity_t *entity)
3204 assert(entity->kind == ENTITY_PARAMETER);
3206 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3207 * list in a function declarator that is part of a
3208 * definition of that function shall not have
3209 * incomplete type. */
3210 type_t *type = skip_typeref(entity->declaration.type);
3211 if (is_type_incomplete(type)) {
3212 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3216 static bool has_parameters(void)
3218 /* func(void) is not a parameter */
3219 if (token.kind == T_IDENTIFIER) {
3220 entity_t const *const entity
3221 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3224 if (entity->kind != ENTITY_TYPEDEF)
3226 if (skip_typeref(entity->typedefe.type) != type_void)
3228 } else if (token.kind != T_void) {
3231 if (look_ahead(1)->kind != ')')
3238 * Parses function type parameters (and optionally creates variable_t entities
3239 * for them in a scope)
3241 static void parse_parameters(function_type_t *type, scope_t *scope)
3244 add_anchor_token(')');
3245 int saved_comma_state = save_and_reset_anchor_state(',');
3247 if (token.kind == T_IDENTIFIER
3248 && !is_typedef_symbol(token.identifier.symbol)) {
3249 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3250 if (la1_type == ',' || la1_type == ')') {
3251 type->kr_style_parameters = true;
3252 parse_identifier_list(scope);
3253 goto parameters_finished;
3257 if (token.kind == ')') {
3258 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3259 if (!(c_mode & _CXX))
3260 type->unspecified_parameters = true;
3261 } else if (has_parameters()) {
3262 function_parameter_t **anchor = &type->parameters;
3264 switch (token.kind) {
3267 type->variadic = true;
3268 goto parameters_finished;
3273 entity_t *entity = parse_parameter();
3274 if (entity->kind == ENTITY_TYPEDEF) {
3275 errorf(&entity->base.source_position,
3276 "typedef not allowed as function parameter");
3279 assert(is_declaration(entity));
3281 semantic_parameter_incomplete(entity);
3283 function_parameter_t *const parameter =
3284 allocate_parameter(entity->declaration.type);
3286 if (scope != NULL) {
3287 append_entity(scope, entity);
3290 *anchor = parameter;
3291 anchor = ¶meter->next;
3296 goto parameters_finished;
3298 } while (next_if(','));
3301 parameters_finished:
3302 rem_anchor_token(')');
3303 expect(')', end_error);
3306 restore_anchor_state(',', saved_comma_state);
3309 typedef enum construct_type_kind_t {
3310 CONSTRUCT_POINTER = 1,
3311 CONSTRUCT_REFERENCE,
3314 } construct_type_kind_t;
3316 typedef union construct_type_t construct_type_t;
3318 typedef struct construct_type_base_t {
3319 construct_type_kind_t kind;
3320 source_position_t pos;
3321 construct_type_t *next;
3322 } construct_type_base_t;
3324 typedef struct parsed_pointer_t {
3325 construct_type_base_t base;
3326 type_qualifiers_t type_qualifiers;
3327 variable_t *base_variable; /**< MS __based extension. */
3330 typedef struct parsed_reference_t {
3331 construct_type_base_t base;
3332 } parsed_reference_t;
3334 typedef struct construct_function_type_t {
3335 construct_type_base_t base;
3336 type_t *function_type;
3337 } construct_function_type_t;
3339 typedef struct parsed_array_t {
3340 construct_type_base_t base;
3341 type_qualifiers_t type_qualifiers;
3347 union construct_type_t {
3348 construct_type_kind_t kind;
3349 construct_type_base_t base;
3350 parsed_pointer_t pointer;
3351 parsed_reference_t reference;
3352 construct_function_type_t function;
3353 parsed_array_t array;
3356 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3358 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3359 memset(cons, 0, size);
3361 cons->base.pos = *HERE;
3366 static construct_type_t *parse_pointer_declarator(void)
3368 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3370 cons->pointer.type_qualifiers = parse_type_qualifiers();
3371 //cons->pointer.base_variable = base_variable;
3376 /* ISO/IEC 14882:1998(E) §8.3.2 */
3377 static construct_type_t *parse_reference_declarator(void)
3379 if (!(c_mode & _CXX))
3380 errorf(HERE, "references are only available for C++");
3382 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3389 static construct_type_t *parse_array_declarator(void)
3391 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3392 parsed_array_t *const array = &cons->array;
3395 add_anchor_token(']');
3397 bool is_static = next_if(T_static);
3399 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3402 is_static = next_if(T_static);
3404 array->type_qualifiers = type_qualifiers;
3405 array->is_static = is_static;
3407 expression_t *size = NULL;
3408 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3409 array->is_variable = true;
3411 } else if (token.kind != ']') {
3412 size = parse_assignment_expression();
3414 /* §6.7.5.2:1 Array size must have integer type */
3415 type_t *const orig_type = size->base.type;
3416 type_t *const type = skip_typeref(orig_type);
3417 if (!is_type_integer(type) && is_type_valid(type)) {
3418 errorf(&size->base.source_position,
3419 "array size '%E' must have integer type but has type '%T'",
3424 mark_vars_read(size, NULL);
3427 if (is_static && size == NULL)
3428 errorf(&array->base.pos, "static array parameters require a size");
3430 rem_anchor_token(']');
3431 expect(']', end_error);
3438 static construct_type_t *parse_function_declarator(scope_t *scope)
3440 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3442 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3443 function_type_t *ftype = &type->function;
3445 ftype->linkage = current_linkage;
3446 ftype->calling_convention = CC_DEFAULT;
3448 parse_parameters(ftype, scope);
3450 cons->function.function_type = type;
3455 typedef struct parse_declarator_env_t {
3456 bool may_be_abstract : 1;
3457 bool must_be_abstract : 1;
3458 decl_modifiers_t modifiers;
3460 source_position_t source_position;
3462 attribute_t *attributes;
3463 } parse_declarator_env_t;
3466 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3468 /* construct a single linked list of construct_type_t's which describe
3469 * how to construct the final declarator type */
3470 construct_type_t *first = NULL;
3471 construct_type_t **anchor = &first;
3473 env->attributes = parse_attributes(env->attributes);
3476 construct_type_t *type;
3477 //variable_t *based = NULL; /* MS __based extension */
3478 switch (token.kind) {
3480 type = parse_reference_declarator();
3484 panic("based not supported anymore");
3489 type = parse_pointer_declarator();
3493 goto ptr_operator_end;
3497 anchor = &type->base.next;
3499 /* TODO: find out if this is correct */
3500 env->attributes = parse_attributes(env->attributes);
3504 construct_type_t *inner_types = NULL;
3506 switch (token.kind) {
3508 if (env->must_be_abstract) {
3509 errorf(HERE, "no identifier expected in typename");
3511 env->symbol = token.identifier.symbol;
3512 env->source_position = token.base.source_position;
3518 /* Parenthesized declarator or function declarator? */
3519 token_t const *const la1 = look_ahead(1);
3520 switch (la1->kind) {
3522 if (is_typedef_symbol(la1->identifier.symbol)) {
3524 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3525 * interpreted as ``function with no parameter specification'', rather
3526 * than redundant parentheses around the omitted identifier. */
3528 /* Function declarator. */
3529 if (!env->may_be_abstract) {
3530 errorf(HERE, "function declarator must have a name");
3537 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3538 /* Paranthesized declarator. */
3540 add_anchor_token(')');
3541 inner_types = parse_inner_declarator(env);
3542 if (inner_types != NULL) {
3543 /* All later declarators only modify the return type */
3544 env->must_be_abstract = true;
3546 rem_anchor_token(')');
3547 expect(')', end_error);
3555 if (env->may_be_abstract)
3557 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3562 construct_type_t **const p = anchor;
3565 construct_type_t *type;
3566 switch (token.kind) {
3568 scope_t *scope = NULL;
3569 if (!env->must_be_abstract) {
3570 scope = &env->parameters;
3573 type = parse_function_declarator(scope);
3577 type = parse_array_declarator();
3580 goto declarator_finished;
3583 /* insert in the middle of the list (at p) */
3584 type->base.next = *p;
3587 anchor = &type->base.next;
3590 declarator_finished:
3591 /* append inner_types at the end of the list, we don't to set anchor anymore
3592 * as it's not needed anymore */
3593 *anchor = inner_types;
3600 static type_t *construct_declarator_type(construct_type_t *construct_list,
3603 construct_type_t *iter = construct_list;
3604 for (; iter != NULL; iter = iter->base.next) {
3605 source_position_t const* const pos = &iter->base.pos;
3606 switch (iter->kind) {
3607 case CONSTRUCT_FUNCTION: {
3608 construct_function_type_t *function = &iter->function;
3609 type_t *function_type = function->function_type;
3611 function_type->function.return_type = type;
3613 type_t *skipped_return_type = skip_typeref(type);
3615 if (is_type_function(skipped_return_type)) {
3616 errorf(pos, "function returning function is not allowed");
3617 } else if (is_type_array(skipped_return_type)) {
3618 errorf(pos, "function returning array is not allowed");
3620 if (skipped_return_type->base.qualifiers != 0) {
3621 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3625 /* The function type was constructed earlier. Freeing it here will
3626 * destroy other types. */
3627 type = typehash_insert(function_type);
3631 case CONSTRUCT_POINTER: {
3632 if (is_type_reference(skip_typeref(type)))
3633 errorf(pos, "cannot declare a pointer to reference");
3635 parsed_pointer_t *pointer = &iter->pointer;
3636 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3640 case CONSTRUCT_REFERENCE:
3641 if (is_type_reference(skip_typeref(type)))
3642 errorf(pos, "cannot declare a reference to reference");
3644 type = make_reference_type(type);
3647 case CONSTRUCT_ARRAY: {
3648 if (is_type_reference(skip_typeref(type)))
3649 errorf(pos, "cannot declare an array of references");
3651 parsed_array_t *array = &iter->array;
3652 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3654 expression_t *size_expression = array->size;
3655 if (size_expression != NULL) {
3657 = create_implicit_cast(size_expression, type_size_t);
3660 array_type->base.qualifiers = array->type_qualifiers;
3661 array_type->array.element_type = type;
3662 array_type->array.is_static = array->is_static;
3663 array_type->array.is_variable = array->is_variable;
3664 array_type->array.size_expression = size_expression;
3666 if (size_expression != NULL) {
3667 switch (is_constant_expression(size_expression)) {
3668 case EXPR_CLASS_CONSTANT: {
3669 long const size = fold_constant_to_int(size_expression);
3670 array_type->array.size = size;
3671 array_type->array.size_constant = true;
3672 /* §6.7.5.2:1 If the expression is a constant expression,
3673 * it shall have a value greater than zero. */
3675 errorf(&size_expression->base.source_position,
3676 "size of array must be greater than zero");
3677 } else if (size == 0 && !GNU_MODE) {
3678 errorf(&size_expression->base.source_position,
3679 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3684 case EXPR_CLASS_VARIABLE:
3685 array_type->array.is_vla = true;
3688 case EXPR_CLASS_ERROR:
3693 type_t *skipped_type = skip_typeref(type);
3695 if (is_type_incomplete(skipped_type)) {
3696 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3697 } else if (is_type_function(skipped_type)) {
3698 errorf(pos, "array of functions is not allowed");
3700 type = identify_new_type(array_type);
3704 internal_errorf(pos, "invalid type construction found");
3710 static type_t *automatic_type_conversion(type_t *orig_type);
3712 static type_t *semantic_parameter(const source_position_t *pos,
3714 const declaration_specifiers_t *specifiers,
3715 entity_t const *const param)
3717 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3718 * shall be adjusted to ``qualified pointer to type'',
3720 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3721 * type'' shall be adjusted to ``pointer to function
3722 * returning type'', as in 6.3.2.1. */
3723 type = automatic_type_conversion(type);
3725 if (specifiers->is_inline && is_type_valid(type)) {
3726 errorf(pos, "'%N' declared 'inline'", param);
3729 /* §6.9.1:6 The declarations in the declaration list shall contain
3730 * no storage-class specifier other than register and no
3731 * initializations. */
3732 if (specifiers->thread_local || (
3733 specifiers->storage_class != STORAGE_CLASS_NONE &&
3734 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3736 errorf(pos, "invalid storage class for '%N'", param);
3739 /* delay test for incomplete type, because we might have (void)
3740 * which is legal but incomplete... */
3745 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3746 declarator_flags_t flags)
3748 parse_declarator_env_t env;
3749 memset(&env, 0, sizeof(env));
3750 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3752 construct_type_t *construct_type = parse_inner_declarator(&env);
3754 construct_declarator_type(construct_type, specifiers->type);
3755 type_t *type = skip_typeref(orig_type);
3757 if (construct_type != NULL) {
3758 obstack_free(&temp_obst, construct_type);
3761 attribute_t *attributes = parse_attributes(env.attributes);
3762 /* append (shared) specifier attribute behind attributes of this
3764 attribute_t **anchor = &attributes;
3765 while (*anchor != NULL)
3766 anchor = &(*anchor)->next;
3767 *anchor = specifiers->attributes;
3770 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3771 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3772 entity->base.source_position = env.source_position;
3773 entity->typedefe.type = orig_type;
3775 if (anonymous_entity != NULL) {
3776 if (is_type_compound(type)) {
3777 assert(anonymous_entity->compound.alias == NULL);
3778 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3779 anonymous_entity->kind == ENTITY_UNION);
3780 anonymous_entity->compound.alias = entity;
3781 anonymous_entity = NULL;
3782 } else if (is_type_enum(type)) {
3783 assert(anonymous_entity->enume.alias == NULL);
3784 assert(anonymous_entity->kind == ENTITY_ENUM);
3785 anonymous_entity->enume.alias = entity;
3786 anonymous_entity = NULL;
3790 /* create a declaration type entity */
3791 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3792 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3794 if (env.symbol != NULL) {
3795 if (specifiers->is_inline && is_type_valid(type)) {
3796 errorf(&env.source_position,
3797 "compound member '%Y' declared 'inline'", env.symbol);
3800 if (specifiers->thread_local ||
3801 specifiers->storage_class != STORAGE_CLASS_NONE) {
3802 errorf(&env.source_position,
3803 "compound member '%Y' must have no storage class",
3807 } else if (flags & DECL_IS_PARAMETER) {
3808 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3809 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3810 } else if (is_type_function(type)) {
3811 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3812 entity->function.is_inline = specifiers->is_inline;
3813 entity->function.elf_visibility = default_visibility;
3814 entity->function.parameters = env.parameters;
3816 if (env.symbol != NULL) {
3817 /* this needs fixes for C++ */
3818 bool in_function_scope = current_function != NULL;
3820 if (specifiers->thread_local || (
3821 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3822 specifiers->storage_class != STORAGE_CLASS_NONE &&
3823 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3825 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3829 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3830 entity->variable.elf_visibility = default_visibility;
3831 entity->variable.thread_local = specifiers->thread_local;
3833 if (env.symbol != NULL) {
3834 if (specifiers->is_inline && is_type_valid(type)) {
3835 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3838 bool invalid_storage_class = false;
3839 if (current_scope == file_scope) {
3840 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3841 specifiers->storage_class != STORAGE_CLASS_NONE &&
3842 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3843 invalid_storage_class = true;
3846 if (specifiers->thread_local &&
3847 specifiers->storage_class == STORAGE_CLASS_NONE) {
3848 invalid_storage_class = true;
3851 if (invalid_storage_class) {
3852 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3857 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3858 entity->declaration.type = orig_type;
3859 entity->declaration.alignment = get_type_alignment(orig_type);
3860 entity->declaration.modifiers = env.modifiers;
3861 entity->declaration.attributes = attributes;
3863 storage_class_t storage_class = specifiers->storage_class;
3864 entity->declaration.declared_storage_class = storage_class;
3866 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3867 storage_class = STORAGE_CLASS_AUTO;
3868 entity->declaration.storage_class = storage_class;
3871 if (attributes != NULL) {
3872 handle_entity_attributes(attributes, entity);
3875 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3876 adapt_special_functions(&entity->function);
3882 static type_t *parse_abstract_declarator(type_t *base_type)
3884 parse_declarator_env_t env;
3885 memset(&env, 0, sizeof(env));
3886 env.may_be_abstract = true;
3887 env.must_be_abstract = true;
3889 construct_type_t *construct_type = parse_inner_declarator(&env);
3891 type_t *result = construct_declarator_type(construct_type, base_type);
3892 if (construct_type != NULL) {
3893 obstack_free(&temp_obst, construct_type);
3895 result = handle_type_attributes(env.attributes, result);
3901 * Check if the declaration of main is suspicious. main should be a
3902 * function with external linkage, returning int, taking either zero
3903 * arguments, two, or three arguments of appropriate types, ie.
3905 * int main([ int argc, char **argv [, char **env ] ]).
3907 * @param decl the declaration to check
3908 * @param type the function type of the declaration
3910 static void check_main(const entity_t *entity)
3912 const source_position_t *pos = &entity->base.source_position;
3913 if (entity->kind != ENTITY_FUNCTION) {
3914 warningf(WARN_MAIN, pos, "'main' is not a function");
3918 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3919 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3922 type_t *type = skip_typeref(entity->declaration.type);
3923 assert(is_type_function(type));
3925 function_type_t const *const func_type = &type->function;
3926 type_t *const ret_type = func_type->return_type;
3927 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3928 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3930 const function_parameter_t *parm = func_type->parameters;
3932 type_t *const first_type = skip_typeref(parm->type);
3933 type_t *const first_type_unqual = get_unqualified_type(first_type);
3934 if (!types_compatible(first_type_unqual, type_int)) {
3935 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3939 type_t *const second_type = skip_typeref(parm->type);
3940 type_t *const second_type_unqual
3941 = get_unqualified_type(second_type);
3942 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3943 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3947 type_t *const third_type = skip_typeref(parm->type);
3948 type_t *const third_type_unqual
3949 = get_unqualified_type(third_type);
3950 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3951 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3955 goto warn_arg_count;
3959 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3965 * Check if a symbol is the equal to "main".
3967 static bool is_sym_main(const symbol_t *const sym)
3969 return streq(sym->string, "main");
3972 static void error_redefined_as_different_kind(const source_position_t *pos,
3973 const entity_t *old, entity_kind_t new_kind)
3975 char const *const what = get_entity_kind_name(new_kind);
3976 source_position_t const *const ppos = &old->base.source_position;
3977 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3980 static bool is_entity_valid(entity_t *const ent)
3982 if (is_declaration(ent)) {
3983 return is_type_valid(skip_typeref(ent->declaration.type));
3984 } else if (ent->kind == ENTITY_TYPEDEF) {
3985 return is_type_valid(skip_typeref(ent->typedefe.type));
3990 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3992 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3993 if (attributes_equal(tattr, attr))
4000 * test wether new_list contains any attributes not included in old_list
4002 static bool has_new_attributes(const attribute_t *old_list,
4003 const attribute_t *new_list)
4005 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4006 if (!contains_attribute(old_list, attr))
4013 * Merge in attributes from an attribute list (probably from a previous
4014 * declaration with the same name). Warning: destroys the old structure
4015 * of the attribute list - don't reuse attributes after this call.
4017 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4020 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4022 if (contains_attribute(decl->attributes, attr))
4025 /* move attribute to new declarations attributes list */
4026 attr->next = decl->attributes;
4027 decl->attributes = attr;
4032 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4033 * for various problems that occur for multiple definitions
4035 entity_t *record_entity(entity_t *entity, const bool is_definition)
4037 const symbol_t *const symbol = entity->base.symbol;
4038 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4039 const source_position_t *pos = &entity->base.source_position;
4041 /* can happen in error cases */
4045 entity_t *const previous_entity = get_entity(symbol, namespc);
4046 /* pushing the same entity twice will break the stack structure */
4047 assert(previous_entity != entity);
4049 if (entity->kind == ENTITY_FUNCTION) {
4050 type_t *const orig_type = entity->declaration.type;
4051 type_t *const type = skip_typeref(orig_type);
4053 assert(is_type_function(type));
4054 if (type->function.unspecified_parameters &&
4055 previous_entity == NULL &&
4056 !entity->declaration.implicit) {
4057 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4060 if (current_scope == file_scope && is_sym_main(symbol)) {
4065 if (is_declaration(entity) &&
4066 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4067 current_scope != file_scope &&
4068 !entity->declaration.implicit) {
4069 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4072 if (previous_entity != NULL) {
4073 source_position_t const *const ppos = &previous_entity->base.source_position;
4075 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4076 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4077 assert(previous_entity->kind == ENTITY_PARAMETER);
4078 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4082 if (previous_entity->base.parent_scope == current_scope) {
4083 if (previous_entity->kind != entity->kind) {
4084 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4085 error_redefined_as_different_kind(pos, previous_entity,
4090 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4091 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4094 if (previous_entity->kind == ENTITY_TYPEDEF) {
4095 type_t *const type = skip_typeref(entity->typedefe.type);
4096 type_t *const prev_type
4097 = skip_typeref(previous_entity->typedefe.type);
4098 if (c_mode & _CXX) {
4099 /* C++ allows double typedef if they are identical
4100 * (after skipping typedefs) */
4101 if (type == prev_type)
4104 /* GCC extension: redef in system headers is allowed */
4105 if ((pos->is_system_header || ppos->is_system_header) &&
4106 types_compatible(type, prev_type))
4109 errorf(pos, "redefinition of '%N' (declared %P)",
4114 /* at this point we should have only VARIABLES or FUNCTIONS */
4115 assert(is_declaration(previous_entity) && is_declaration(entity));
4117 declaration_t *const prev_decl = &previous_entity->declaration;
4118 declaration_t *const decl = &entity->declaration;
4120 /* can happen for K&R style declarations */
4121 if (prev_decl->type == NULL &&
4122 previous_entity->kind == ENTITY_PARAMETER &&
4123 entity->kind == ENTITY_PARAMETER) {
4124 prev_decl->type = decl->type;
4125 prev_decl->storage_class = decl->storage_class;
4126 prev_decl->declared_storage_class = decl->declared_storage_class;
4127 prev_decl->modifiers = decl->modifiers;
4128 return previous_entity;
4131 type_t *const type = skip_typeref(decl->type);
4132 type_t *const prev_type = skip_typeref(prev_decl->type);
4134 if (!types_compatible(type, prev_type)) {
4135 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4137 unsigned old_storage_class = prev_decl->storage_class;
4139 if (is_definition &&
4141 !(prev_decl->modifiers & DM_USED) &&
4142 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4143 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4146 storage_class_t new_storage_class = decl->storage_class;
4148 /* pretend no storage class means extern for function
4149 * declarations (except if the previous declaration is neither
4150 * none nor extern) */
4151 if (entity->kind == ENTITY_FUNCTION) {
4152 /* the previous declaration could have unspecified parameters or
4153 * be a typedef, so use the new type */
4154 if (prev_type->function.unspecified_parameters || is_definition)
4155 prev_decl->type = type;
4157 switch (old_storage_class) {
4158 case STORAGE_CLASS_NONE:
4159 old_storage_class = STORAGE_CLASS_EXTERN;
4162 case STORAGE_CLASS_EXTERN:
4163 if (is_definition) {
4164 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4165 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4167 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4168 new_storage_class = STORAGE_CLASS_EXTERN;
4175 } else if (is_type_incomplete(prev_type)) {
4176 prev_decl->type = type;
4179 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4180 new_storage_class == STORAGE_CLASS_EXTERN) {
4182 warn_redundant_declaration: ;
4184 = has_new_attributes(prev_decl->attributes,
4186 if (has_new_attrs) {
4187 merge_in_attributes(decl, prev_decl->attributes);
4188 } else if (!is_definition &&
4189 is_type_valid(prev_type) &&
4190 !pos->is_system_header) {
4191 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4193 } else if (current_function == NULL) {
4194 if (old_storage_class != STORAGE_CLASS_STATIC &&
4195 new_storage_class == STORAGE_CLASS_STATIC) {
4196 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4197 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4198 prev_decl->storage_class = STORAGE_CLASS_NONE;
4199 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4201 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4203 goto error_redeclaration;
4204 goto warn_redundant_declaration;
4206 } else if (is_type_valid(prev_type)) {
4207 if (old_storage_class == new_storage_class) {
4208 error_redeclaration:
4209 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4211 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4216 prev_decl->modifiers |= decl->modifiers;
4217 if (entity->kind == ENTITY_FUNCTION) {
4218 previous_entity->function.is_inline |= entity->function.is_inline;
4220 return previous_entity;
4224 if (is_warn_on(why = WARN_SHADOW) ||
4225 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4226 char const *const what = get_entity_kind_name(previous_entity->kind);
4227 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4231 if (entity->kind == ENTITY_FUNCTION) {
4232 if (is_definition &&
4233 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4234 !is_sym_main(symbol)) {
4235 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4236 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4238 goto warn_missing_declaration;
4241 } else if (entity->kind == ENTITY_VARIABLE) {
4242 if (current_scope == file_scope &&
4243 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4244 !entity->declaration.implicit) {
4245 warn_missing_declaration:
4246 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4251 assert(entity->base.parent_scope == NULL);
4252 assert(current_scope != NULL);
4254 entity->base.parent_scope = current_scope;
4255 environment_push(entity);
4256 append_entity(current_scope, entity);
4261 static void parser_error_multiple_definition(entity_t *entity,
4262 const source_position_t *source_position)
4264 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4265 entity->base.symbol, &entity->base.source_position);
4268 static bool is_declaration_specifier(const token_t *token)
4270 switch (token->kind) {
4274 return is_typedef_symbol(token->identifier.symbol);
4281 static void parse_init_declarator_rest(entity_t *entity)
4283 type_t *orig_type = type_error_type;
4285 if (entity->base.kind == ENTITY_TYPEDEF) {
4286 source_position_t const *const pos = &entity->base.source_position;
4287 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4289 assert(is_declaration(entity));
4290 orig_type = entity->declaration.type;
4293 type_t *type = skip_typeref(orig_type);
4295 if (entity->kind == ENTITY_VARIABLE
4296 && entity->variable.initializer != NULL) {
4297 parser_error_multiple_definition(entity, HERE);
4301 declaration_t *const declaration = &entity->declaration;
4302 bool must_be_constant = false;
4303 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4304 entity->base.parent_scope == file_scope) {
4305 must_be_constant = true;
4308 if (is_type_function(type)) {
4309 source_position_t const *const pos = &entity->base.source_position;
4310 errorf(pos, "'%N' is initialized like a variable", entity);
4311 orig_type = type_error_type;
4314 parse_initializer_env_t env;
4315 env.type = orig_type;
4316 env.must_be_constant = must_be_constant;
4317 env.entity = entity;
4319 initializer_t *initializer = parse_initializer(&env);
4321 if (entity->kind == ENTITY_VARIABLE) {
4322 /* §6.7.5:22 array initializers for arrays with unknown size
4323 * determine the array type size */
4324 declaration->type = env.type;
4325 entity->variable.initializer = initializer;
4329 /* parse rest of a declaration without any declarator */
4330 static void parse_anonymous_declaration_rest(
4331 const declaration_specifiers_t *specifiers)
4334 anonymous_entity = NULL;
4336 source_position_t const *const pos = &specifiers->source_position;
4337 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4338 specifiers->thread_local) {
4339 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4342 type_t *type = specifiers->type;
4343 switch (type->kind) {
4344 case TYPE_COMPOUND_STRUCT:
4345 case TYPE_COMPOUND_UNION: {
4346 if (type->compound.compound->base.symbol == NULL) {
4347 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4356 warningf(WARN_OTHER, pos, "empty declaration");
4361 static void check_variable_type_complete(entity_t *ent)
4363 if (ent->kind != ENTITY_VARIABLE)
4366 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4367 * type for the object shall be complete [...] */
4368 declaration_t *decl = &ent->declaration;
4369 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4370 decl->storage_class == STORAGE_CLASS_STATIC)
4373 type_t *const type = skip_typeref(decl->type);
4374 if (!is_type_incomplete(type))
4377 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4378 * are given length one. */
4379 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4380 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4384 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4388 static void parse_declaration_rest(entity_t *ndeclaration,
4389 const declaration_specifiers_t *specifiers,
4390 parsed_declaration_func finished_declaration,
4391 declarator_flags_t flags)
4393 add_anchor_token(';');
4394 add_anchor_token(',');
4396 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4398 if (token.kind == '=') {
4399 parse_init_declarator_rest(entity);
4400 } else if (entity->kind == ENTITY_VARIABLE) {
4401 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4402 * [...] where the extern specifier is explicitly used. */
4403 declaration_t *decl = &entity->declaration;
4404 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4405 type_t *type = decl->type;
4406 if (is_type_reference(skip_typeref(type))) {
4407 source_position_t const *const pos = &entity->base.source_position;
4408 errorf(pos, "reference '%#N' must be initialized", entity);
4413 check_variable_type_complete(entity);
4418 add_anchor_token('=');
4419 ndeclaration = parse_declarator(specifiers, flags);
4420 rem_anchor_token('=');
4422 expect(';', end_error);
4425 anonymous_entity = NULL;
4426 rem_anchor_token(';');
4427 rem_anchor_token(',');
4430 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4432 symbol_t *symbol = entity->base.symbol;
4436 assert(entity->base.namespc == NAMESPACE_NORMAL);
4437 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4438 if (previous_entity == NULL
4439 || previous_entity->base.parent_scope != current_scope) {
4440 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4445 if (is_definition) {
4446 errorf(HERE, "'%N' is initialised", entity);
4449 return record_entity(entity, false);
4452 static void parse_declaration(parsed_declaration_func finished_declaration,
4453 declarator_flags_t flags)
4455 add_anchor_token(';');
4456 declaration_specifiers_t specifiers;
4457 parse_declaration_specifiers(&specifiers);
4458 rem_anchor_token(';');
4460 if (token.kind == ';') {
4461 parse_anonymous_declaration_rest(&specifiers);
4463 entity_t *entity = parse_declarator(&specifiers, flags);
4464 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4469 static type_t *get_default_promoted_type(type_t *orig_type)
4471 type_t *result = orig_type;
4473 type_t *type = skip_typeref(orig_type);
4474 if (is_type_integer(type)) {
4475 result = promote_integer(type);
4476 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4477 result = type_double;
4483 static void parse_kr_declaration_list(entity_t *entity)
4485 if (entity->kind != ENTITY_FUNCTION)
4488 type_t *type = skip_typeref(entity->declaration.type);
4489 assert(is_type_function(type));
4490 if (!type->function.kr_style_parameters)
4493 add_anchor_token('{');
4495 PUSH_SCOPE(&entity->function.parameters);
4497 entity_t *parameter = entity->function.parameters.entities;
4498 for ( ; parameter != NULL; parameter = parameter->base.next) {
4499 assert(parameter->base.parent_scope == NULL);
4500 parameter->base.parent_scope = current_scope;
4501 environment_push(parameter);
4504 /* parse declaration list */
4506 switch (token.kind) {
4508 /* This covers symbols, which are no type, too, and results in
4509 * better error messages. The typical cases are misspelled type
4510 * names and missing includes. */
4512 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4522 /* update function type */
4523 type_t *new_type = duplicate_type(type);
4525 function_parameter_t *parameters = NULL;
4526 function_parameter_t **anchor = ¶meters;
4528 /* did we have an earlier prototype? */
4529 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4530 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4533 function_parameter_t *proto_parameter = NULL;
4534 if (proto_type != NULL) {
4535 type_t *proto_type_type = proto_type->declaration.type;
4536 proto_parameter = proto_type_type->function.parameters;
4537 /* If a K&R function definition has a variadic prototype earlier, then
4538 * make the function definition variadic, too. This should conform to
4539 * §6.7.5.3:15 and §6.9.1:8. */
4540 new_type->function.variadic = proto_type_type->function.variadic;
4542 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4544 new_type->function.unspecified_parameters = true;
4547 bool need_incompatible_warning = false;
4548 parameter = entity->function.parameters.entities;
4549 for (; parameter != NULL; parameter = parameter->base.next,
4551 proto_parameter == NULL ? NULL : proto_parameter->next) {
4552 if (parameter->kind != ENTITY_PARAMETER)
4555 type_t *parameter_type = parameter->declaration.type;
4556 if (parameter_type == NULL) {
4557 source_position_t const* const pos = ¶meter->base.source_position;
4559 errorf(pos, "no type specified for function '%N'", parameter);
4560 parameter_type = type_error_type;
4562 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4563 parameter_type = type_int;
4565 parameter->declaration.type = parameter_type;
4568 semantic_parameter_incomplete(parameter);
4570 /* we need the default promoted types for the function type */
4571 type_t *not_promoted = parameter_type;
4572 parameter_type = get_default_promoted_type(parameter_type);
4574 /* gcc special: if the type of the prototype matches the unpromoted
4575 * type don't promote */
4576 if (!strict_mode && proto_parameter != NULL) {
4577 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4578 type_t *promo_skip = skip_typeref(parameter_type);
4579 type_t *param_skip = skip_typeref(not_promoted);
4580 if (!types_compatible(proto_p_type, promo_skip)
4581 && types_compatible(proto_p_type, param_skip)) {
4583 need_incompatible_warning = true;
4584 parameter_type = not_promoted;
4587 function_parameter_t *const function_parameter
4588 = allocate_parameter(parameter_type);
4590 *anchor = function_parameter;
4591 anchor = &function_parameter->next;
4594 new_type->function.parameters = parameters;
4595 new_type = identify_new_type(new_type);
4597 if (need_incompatible_warning) {
4598 symbol_t const *const sym = entity->base.symbol;
4599 source_position_t const *const pos = &entity->base.source_position;
4600 source_position_t const *const ppos = &proto_type->base.source_position;
4601 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4603 entity->declaration.type = new_type;
4605 rem_anchor_token('{');
4608 static bool first_err = true;
4611 * When called with first_err set, prints the name of the current function,
4614 static void print_in_function(void)
4618 char const *const file = current_function->base.base.source_position.input_name;
4619 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4624 * Check if all labels are defined in the current function.
4625 * Check if all labels are used in the current function.
4627 static void check_labels(void)
4629 for (const goto_statement_t *goto_statement = goto_first;
4630 goto_statement != NULL;
4631 goto_statement = goto_statement->next) {
4632 /* skip computed gotos */
4633 if (goto_statement->expression != NULL)
4636 label_t *label = goto_statement->label;
4637 if (label->base.source_position.input_name == NULL) {
4638 print_in_function();
4639 source_position_t const *const pos = &goto_statement->base.source_position;
4640 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4644 if (is_warn_on(WARN_UNUSED_LABEL)) {
4645 for (const label_statement_t *label_statement = label_first;
4646 label_statement != NULL;
4647 label_statement = label_statement->next) {
4648 label_t *label = label_statement->label;
4650 if (! label->used) {
4651 print_in_function();
4652 source_position_t const *const pos = &label_statement->base.source_position;
4653 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4659 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4661 entity_t const *const end = last != NULL ? last->base.next : NULL;
4662 for (; entity != end; entity = entity->base.next) {
4663 if (!is_declaration(entity))
4666 declaration_t *declaration = &entity->declaration;
4667 if (declaration->implicit)
4670 if (!declaration->used) {
4671 print_in_function();
4672 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4673 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4674 print_in_function();
4675 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4680 static void check_unused_variables(statement_t *const stmt, void *const env)
4684 switch (stmt->kind) {
4685 case STATEMENT_DECLARATION: {
4686 declaration_statement_t const *const decls = &stmt->declaration;
4687 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4692 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4701 * Check declarations of current_function for unused entities.
4703 static void check_declarations(void)
4705 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4706 const scope_t *scope = ¤t_function->parameters;
4708 /* do not issue unused warnings for main */
4709 if (!is_sym_main(current_function->base.base.symbol)) {
4710 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4713 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4714 walk_statements(current_function->statement, check_unused_variables,
4719 static int determine_truth(expression_t const* const cond)
4722 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4723 fold_constant_to_bool(cond) ? 1 :
4727 static void check_reachable(statement_t *);
4728 static bool reaches_end;
4730 static bool expression_returns(expression_t const *const expr)
4732 switch (expr->kind) {
4734 expression_t const *const func = expr->call.function;
4735 if (func->kind == EXPR_REFERENCE) {
4736 entity_t *entity = func->reference.entity;
4737 if (entity->kind == ENTITY_FUNCTION
4738 && entity->declaration.modifiers & DM_NORETURN)
4742 if (!expression_returns(func))
4745 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4746 if (!expression_returns(arg->expression))
4753 case EXPR_REFERENCE:
4754 case EXPR_REFERENCE_ENUM_VALUE:
4756 case EXPR_STRING_LITERAL:
4757 case EXPR_WIDE_STRING_LITERAL:
4758 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4759 case EXPR_LABEL_ADDRESS:
4760 case EXPR_CLASSIFY_TYPE:
4761 case EXPR_SIZEOF: // TODO handle obscure VLA case
4764 case EXPR_BUILTIN_CONSTANT_P:
4765 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4770 case EXPR_STATEMENT: {
4771 bool old_reaches_end = reaches_end;
4772 reaches_end = false;
4773 check_reachable(expr->statement.statement);
4774 bool returns = reaches_end;
4775 reaches_end = old_reaches_end;
4779 case EXPR_CONDITIONAL:
4780 // TODO handle constant expression
4782 if (!expression_returns(expr->conditional.condition))
4785 if (expr->conditional.true_expression != NULL
4786 && expression_returns(expr->conditional.true_expression))
4789 return expression_returns(expr->conditional.false_expression);
4792 return expression_returns(expr->select.compound);
4794 case EXPR_ARRAY_ACCESS:
4796 expression_returns(expr->array_access.array_ref) &&
4797 expression_returns(expr->array_access.index);
4800 return expression_returns(expr->va_starte.ap);
4803 return expression_returns(expr->va_arge.ap);
4806 return expression_returns(expr->va_copye.src);
4808 EXPR_UNARY_CASES_MANDATORY
4809 return expression_returns(expr->unary.value);
4811 case EXPR_UNARY_THROW:
4815 // TODO handle constant lhs of && and ||
4817 expression_returns(expr->binary.left) &&
4818 expression_returns(expr->binary.right);
4821 panic("unhandled expression");
4824 static bool initializer_returns(initializer_t const *const init)
4826 switch (init->kind) {
4827 case INITIALIZER_VALUE:
4828 return expression_returns(init->value.value);
4830 case INITIALIZER_LIST: {
4831 initializer_t * const* i = init->list.initializers;
4832 initializer_t * const* const end = i + init->list.len;
4833 bool returns = true;
4834 for (; i != end; ++i) {
4835 if (!initializer_returns(*i))
4841 case INITIALIZER_STRING:
4842 case INITIALIZER_WIDE_STRING:
4843 case INITIALIZER_DESIGNATOR: // designators have no payload
4846 panic("unhandled initializer");
4849 static bool noreturn_candidate;
4851 static void check_reachable(statement_t *const stmt)
4853 if (stmt->base.reachable)
4855 if (stmt->kind != STATEMENT_DO_WHILE)
4856 stmt->base.reachable = true;
4858 statement_t *last = stmt;
4860 switch (stmt->kind) {
4861 case STATEMENT_ERROR:
4862 case STATEMENT_EMPTY:
4864 next = stmt->base.next;
4867 case STATEMENT_DECLARATION: {
4868 declaration_statement_t const *const decl = &stmt->declaration;
4869 entity_t const * ent = decl->declarations_begin;
4870 entity_t const *const last_decl = decl->declarations_end;
4872 for (;; ent = ent->base.next) {
4873 if (ent->kind == ENTITY_VARIABLE &&
4874 ent->variable.initializer != NULL &&
4875 !initializer_returns(ent->variable.initializer)) {
4878 if (ent == last_decl)
4882 next = stmt->base.next;
4886 case STATEMENT_COMPOUND:
4887 next = stmt->compound.statements;
4889 next = stmt->base.next;
4892 case STATEMENT_RETURN: {
4893 expression_t const *const val = stmt->returns.value;
4894 if (val == NULL || expression_returns(val))
4895 noreturn_candidate = false;
4899 case STATEMENT_IF: {
4900 if_statement_t const *const ifs = &stmt->ifs;
4901 expression_t const *const cond = ifs->condition;
4903 if (!expression_returns(cond))
4906 int const val = determine_truth(cond);
4909 check_reachable(ifs->true_statement);
4914 if (ifs->false_statement != NULL) {
4915 check_reachable(ifs->false_statement);
4919 next = stmt->base.next;
4923 case STATEMENT_SWITCH: {
4924 switch_statement_t const *const switchs = &stmt->switchs;
4925 expression_t const *const expr = switchs->expression;
4927 if (!expression_returns(expr))
4930 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4931 long const val = fold_constant_to_int(expr);
4932 case_label_statement_t * defaults = NULL;
4933 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4934 if (i->expression == NULL) {
4939 if (i->first_case <= val && val <= i->last_case) {
4940 check_reachable((statement_t*)i);
4945 if (defaults != NULL) {
4946 check_reachable((statement_t*)defaults);
4950 bool has_default = false;
4951 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4952 if (i->expression == NULL)
4955 check_reachable((statement_t*)i);
4962 next = stmt->base.next;
4966 case STATEMENT_EXPRESSION: {
4967 /* Check for noreturn function call */
4968 expression_t const *const expr = stmt->expression.expression;
4969 if (!expression_returns(expr))
4972 next = stmt->base.next;
4976 case STATEMENT_CONTINUE:
4977 for (statement_t *parent = stmt;;) {
4978 parent = parent->base.parent;
4979 if (parent == NULL) /* continue not within loop */
4983 switch (parent->kind) {
4984 case STATEMENT_WHILE: goto continue_while;
4985 case STATEMENT_DO_WHILE: goto continue_do_while;
4986 case STATEMENT_FOR: goto continue_for;
4992 case STATEMENT_BREAK:
4993 for (statement_t *parent = stmt;;) {
4994 parent = parent->base.parent;
4995 if (parent == NULL) /* break not within loop/switch */
4998 switch (parent->kind) {
4999 case STATEMENT_SWITCH:
5000 case STATEMENT_WHILE:
5001 case STATEMENT_DO_WHILE:
5004 next = parent->base.next;
5005 goto found_break_parent;
5013 case STATEMENT_GOTO:
5014 if (stmt->gotos.expression) {
5015 if (!expression_returns(stmt->gotos.expression))
5018 statement_t *parent = stmt->base.parent;
5019 if (parent == NULL) /* top level goto */
5023 next = stmt->gotos.label->statement;
5024 if (next == NULL) /* missing label */
5029 case STATEMENT_LABEL:
5030 next = stmt->label.statement;
5033 case STATEMENT_CASE_LABEL:
5034 next = stmt->case_label.statement;
5037 case STATEMENT_WHILE: {
5038 while_statement_t const *const whiles = &stmt->whiles;
5039 expression_t const *const cond = whiles->condition;
5041 if (!expression_returns(cond))
5044 int const val = determine_truth(cond);
5047 check_reachable(whiles->body);
5052 next = stmt->base.next;
5056 case STATEMENT_DO_WHILE:
5057 next = stmt->do_while.body;
5060 case STATEMENT_FOR: {
5061 for_statement_t *const fors = &stmt->fors;
5063 if (fors->condition_reachable)
5065 fors->condition_reachable = true;
5067 expression_t const *const cond = fors->condition;
5072 } else if (expression_returns(cond)) {
5073 val = determine_truth(cond);
5079 check_reachable(fors->body);
5084 next = stmt->base.next;
5088 case STATEMENT_MS_TRY: {
5089 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5090 check_reachable(ms_try->try_statement);
5091 next = ms_try->final_statement;
5095 case STATEMENT_LEAVE: {
5096 statement_t *parent = stmt;
5098 parent = parent->base.parent;
5099 if (parent == NULL) /* __leave not within __try */
5102 if (parent->kind == STATEMENT_MS_TRY) {
5104 next = parent->ms_try.final_statement;
5112 panic("invalid statement kind");
5115 while (next == NULL) {
5116 next = last->base.parent;
5118 noreturn_candidate = false;
5120 type_t *const type = skip_typeref(current_function->base.type);
5121 assert(is_type_function(type));
5122 type_t *const ret = skip_typeref(type->function.return_type);
5123 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5124 is_type_valid(ret) &&
5125 !is_sym_main(current_function->base.base.symbol)) {
5126 source_position_t const *const pos = &stmt->base.source_position;
5127 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5132 switch (next->kind) {
5133 case STATEMENT_ERROR:
5134 case STATEMENT_EMPTY:
5135 case STATEMENT_DECLARATION:
5136 case STATEMENT_EXPRESSION:
5138 case STATEMENT_RETURN:
5139 case STATEMENT_CONTINUE:
5140 case STATEMENT_BREAK:
5141 case STATEMENT_GOTO:
5142 case STATEMENT_LEAVE:
5143 panic("invalid control flow in function");
5145 case STATEMENT_COMPOUND:
5146 if (next->compound.stmt_expr) {
5152 case STATEMENT_SWITCH:
5153 case STATEMENT_LABEL:
5154 case STATEMENT_CASE_LABEL:
5156 next = next->base.next;
5159 case STATEMENT_WHILE: {
5161 if (next->base.reachable)
5163 next->base.reachable = true;
5165 while_statement_t const *const whiles = &next->whiles;
5166 expression_t const *const cond = whiles->condition;
5168 if (!expression_returns(cond))
5171 int const val = determine_truth(cond);
5174 check_reachable(whiles->body);
5180 next = next->base.next;
5184 case STATEMENT_DO_WHILE: {
5186 if (next->base.reachable)
5188 next->base.reachable = true;
5190 do_while_statement_t const *const dw = &next->do_while;
5191 expression_t const *const cond = dw->condition;
5193 if (!expression_returns(cond))
5196 int const val = determine_truth(cond);
5199 check_reachable(dw->body);
5205 next = next->base.next;
5209 case STATEMENT_FOR: {
5211 for_statement_t *const fors = &next->fors;
5213 fors->step_reachable = true;
5215 if (fors->condition_reachable)
5217 fors->condition_reachable = true;
5219 expression_t const *const cond = fors->condition;
5224 } else if (expression_returns(cond)) {
5225 val = determine_truth(cond);
5231 check_reachable(fors->body);
5237 next = next->base.next;
5241 case STATEMENT_MS_TRY:
5243 next = next->ms_try.final_statement;
5248 check_reachable(next);
5251 static void check_unreachable(statement_t* const stmt, void *const env)
5255 switch (stmt->kind) {
5256 case STATEMENT_DO_WHILE:
5257 if (!stmt->base.reachable) {
5258 expression_t const *const cond = stmt->do_while.condition;
5259 if (determine_truth(cond) >= 0) {
5260 source_position_t const *const pos = &cond->base.source_position;
5261 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5266 case STATEMENT_FOR: {
5267 for_statement_t const* const fors = &stmt->fors;
5269 // if init and step are unreachable, cond is unreachable, too
5270 if (!stmt->base.reachable && !fors->step_reachable) {
5271 goto warn_unreachable;
5273 if (!stmt->base.reachable && fors->initialisation != NULL) {
5274 source_position_t const *const pos = &fors->initialisation->base.source_position;
5275 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5278 if (!fors->condition_reachable && fors->condition != NULL) {
5279 source_position_t const *const pos = &fors->condition->base.source_position;
5280 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5283 if (!fors->step_reachable && fors->step != NULL) {
5284 source_position_t const *const pos = &fors->step->base.source_position;
5285 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5291 case STATEMENT_COMPOUND:
5292 if (stmt->compound.statements != NULL)
5294 goto warn_unreachable;
5296 case STATEMENT_DECLARATION: {
5297 /* Only warn if there is at least one declarator with an initializer.
5298 * This typically occurs in switch statements. */
5299 declaration_statement_t const *const decl = &stmt->declaration;
5300 entity_t const * ent = decl->declarations_begin;
5301 entity_t const *const last = decl->declarations_end;
5303 for (;; ent = ent->base.next) {
5304 if (ent->kind == ENTITY_VARIABLE &&
5305 ent->variable.initializer != NULL) {
5306 goto warn_unreachable;
5316 if (!stmt->base.reachable) {
5317 source_position_t const *const pos = &stmt->base.source_position;
5318 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5324 static void parse_external_declaration(void)
5326 /* function-definitions and declarations both start with declaration
5328 add_anchor_token(';');
5329 declaration_specifiers_t specifiers;
5330 parse_declaration_specifiers(&specifiers);
5331 rem_anchor_token(';');
5333 /* must be a declaration */
5334 if (token.kind == ';') {
5335 parse_anonymous_declaration_rest(&specifiers);
5339 add_anchor_token(',');
5340 add_anchor_token('=');
5341 add_anchor_token(';');
5342 add_anchor_token('{');
5344 /* declarator is common to both function-definitions and declarations */
5345 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5347 rem_anchor_token('{');
5348 rem_anchor_token(';');
5349 rem_anchor_token('=');
5350 rem_anchor_token(',');
5352 /* must be a declaration */
5353 switch (token.kind) {
5357 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5362 /* must be a function definition */
5363 parse_kr_declaration_list(ndeclaration);
5365 if (token.kind != '{') {
5366 parse_error_expected("while parsing function definition", '{', NULL);
5367 eat_until_matching_token(';');
5371 assert(is_declaration(ndeclaration));
5372 type_t *const orig_type = ndeclaration->declaration.type;
5373 type_t * type = skip_typeref(orig_type);
5375 if (!is_type_function(type)) {
5376 if (is_type_valid(type)) {
5377 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5383 source_position_t const *const pos = &ndeclaration->base.source_position;
5384 if (is_typeref(orig_type)) {
5386 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5389 if (is_type_compound(skip_typeref(type->function.return_type))) {
5390 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5392 if (type->function.unspecified_parameters) {
5393 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5395 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5398 /* §6.7.5.3:14 a function definition with () means no
5399 * parameters (and not unspecified parameters) */
5400 if (type->function.unspecified_parameters &&
5401 type->function.parameters == NULL) {
5402 type_t *copy = duplicate_type(type);
5403 copy->function.unspecified_parameters = false;
5404 type = identify_new_type(copy);
5406 ndeclaration->declaration.type = type;
5409 entity_t *const entity = record_entity(ndeclaration, true);
5410 assert(entity->kind == ENTITY_FUNCTION);
5411 assert(ndeclaration->kind == ENTITY_FUNCTION);
5413 function_t *const function = &entity->function;
5414 if (ndeclaration != entity) {
5415 function->parameters = ndeclaration->function.parameters;
5417 assert(is_declaration(entity));
5418 type = skip_typeref(entity->declaration.type);
5420 PUSH_SCOPE(&function->parameters);
5422 entity_t *parameter = function->parameters.entities;
5423 for (; parameter != NULL; parameter = parameter->base.next) {
5424 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5425 parameter->base.parent_scope = current_scope;
5427 assert(parameter->base.parent_scope == NULL
5428 || parameter->base.parent_scope == current_scope);
5429 parameter->base.parent_scope = current_scope;
5430 if (parameter->base.symbol == NULL) {
5431 errorf(¶meter->base.source_position, "parameter name omitted");
5434 environment_push(parameter);
5437 if (function->statement != NULL) {
5438 parser_error_multiple_definition(entity, HERE);
5441 /* parse function body */
5442 int label_stack_top = label_top();
5443 function_t *old_current_function = current_function;
5444 entity_t *old_current_entity = current_entity;
5445 current_function = function;
5446 current_entity = entity;
5450 goto_anchor = &goto_first;
5452 label_anchor = &label_first;
5454 statement_t *const body = parse_compound_statement(false);
5455 function->statement = body;
5458 check_declarations();
5459 if (is_warn_on(WARN_RETURN_TYPE) ||
5460 is_warn_on(WARN_UNREACHABLE_CODE) ||
5461 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5462 noreturn_candidate = true;
5463 check_reachable(body);
5464 if (is_warn_on(WARN_UNREACHABLE_CODE))
5465 walk_statements(body, check_unreachable, NULL);
5466 if (noreturn_candidate &&
5467 !(function->base.modifiers & DM_NORETURN)) {
5468 source_position_t const *const pos = &body->base.source_position;
5469 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5474 assert(current_function == function);
5475 assert(current_entity == entity);
5476 current_entity = old_current_entity;
5477 current_function = old_current_function;
5478 label_pop_to(label_stack_top);
5484 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5486 entity_t *iter = compound->members.entities;
5487 for (; iter != NULL; iter = iter->base.next) {
5488 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5491 if (iter->base.symbol == symbol) {
5493 } else if (iter->base.symbol == NULL) {
5494 /* search in anonymous structs and unions */
5495 type_t *type = skip_typeref(iter->declaration.type);
5496 if (is_type_compound(type)) {
5497 if (find_compound_entry(type->compound.compound, symbol)
5508 static void check_deprecated(const source_position_t *source_position,
5509 const entity_t *entity)
5511 if (!is_declaration(entity))
5513 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5516 source_position_t const *const epos = &entity->base.source_position;
5517 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5519 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5521 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5526 static expression_t *create_select(const source_position_t *pos,
5528 type_qualifiers_t qualifiers,
5531 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5533 check_deprecated(pos, entry);
5535 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5536 select->select.compound = addr;
5537 select->select.compound_entry = entry;
5539 type_t *entry_type = entry->declaration.type;
5540 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5542 /* bitfields need special treatment */
5543 if (entry->compound_member.bitfield) {
5544 unsigned bit_size = entry->compound_member.bit_size;
5545 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5546 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5547 res_type = type_int;
5551 /* we always do the auto-type conversions; the & and sizeof parser contains
5552 * code to revert this! */
5553 select->base.type = automatic_type_conversion(res_type);
5560 * Find entry with symbol in compound. Search anonymous structs and unions and
5561 * creates implicit select expressions for them.
5562 * Returns the adress for the innermost compound.
5564 static expression_t *find_create_select(const source_position_t *pos,
5566 type_qualifiers_t qualifiers,
5567 compound_t *compound, symbol_t *symbol)
5569 entity_t *iter = compound->members.entities;
5570 for (; iter != NULL; iter = iter->base.next) {
5571 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5574 symbol_t *iter_symbol = iter->base.symbol;
5575 if (iter_symbol == NULL) {
5576 type_t *type = iter->declaration.type;
5577 if (type->kind != TYPE_COMPOUND_STRUCT
5578 && type->kind != TYPE_COMPOUND_UNION)
5581 compound_t *sub_compound = type->compound.compound;
5583 if (find_compound_entry(sub_compound, symbol) == NULL)
5586 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5587 sub_addr->base.source_position = *pos;
5588 sub_addr->base.implicit = true;
5589 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5593 if (iter_symbol == symbol) {
5594 return create_select(pos, addr, qualifiers, iter);
5601 static void parse_bitfield_member(entity_t *entity)
5605 expression_t *size = parse_constant_expression();
5608 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5609 type_t *type = entity->declaration.type;
5610 if (!is_type_integer(skip_typeref(type))) {
5611 errorf(HERE, "bitfield base type '%T' is not an integer type",
5615 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5616 /* error already reported by parse_constant_expression */
5617 size_long = get_type_size(type) * 8;
5619 size_long = fold_constant_to_int(size);
5621 const symbol_t *symbol = entity->base.symbol;
5622 const symbol_t *user_symbol
5623 = symbol == NULL ? sym_anonymous : symbol;
5624 unsigned bit_size = get_type_size(type) * 8;
5625 if (size_long < 0) {
5626 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5627 } else if (size_long == 0 && symbol != NULL) {
5628 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5629 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5630 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5633 /* hope that people don't invent crazy types with more bits
5634 * than our struct can hold */
5636 (1 << sizeof(entity->compound_member.bit_size)*8));
5640 entity->compound_member.bitfield = true;
5641 entity->compound_member.bit_size = (unsigned char)size_long;
5644 static void parse_compound_declarators(compound_t *compound,
5645 const declaration_specifiers_t *specifiers)
5650 if (token.kind == ':') {
5651 /* anonymous bitfield */
5652 type_t *type = specifiers->type;
5653 entity_t *entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER,
5654 NAMESPACE_NORMAL, NULL);
5655 entity->base.source_position = *HERE;
5656 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5657 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5658 entity->declaration.type = type;
5660 parse_bitfield_member(entity);
5662 attribute_t *attributes = parse_attributes(NULL);
5663 attribute_t **anchor = &attributes;
5664 while (*anchor != NULL)
5665 anchor = &(*anchor)->next;
5666 *anchor = specifiers->attributes;
5667 if (attributes != NULL) {
5668 handle_entity_attributes(attributes, entity);
5670 entity->declaration.attributes = attributes;
5672 append_entity(&compound->members, entity);
5674 entity = parse_declarator(specifiers,
5675 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5676 source_position_t const *const pos = &entity->base.source_position;
5677 if (entity->kind == ENTITY_TYPEDEF) {
5678 errorf(pos, "typedef not allowed as compound member");
5680 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5682 /* make sure we don't define a symbol multiple times */
5683 symbol_t *symbol = entity->base.symbol;
5684 if (symbol != NULL) {
5685 entity_t *prev = find_compound_entry(compound, symbol);
5687 source_position_t const *const ppos = &prev->base.source_position;
5688 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5692 if (token.kind == ':') {
5693 parse_bitfield_member(entity);
5695 attribute_t *attributes = parse_attributes(NULL);
5696 handle_entity_attributes(attributes, entity);
5698 type_t *orig_type = entity->declaration.type;
5699 type_t *type = skip_typeref(orig_type);
5700 if (is_type_function(type)) {
5701 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5702 } else if (is_type_incomplete(type)) {
5703 /* §6.7.2.1:16 flexible array member */
5704 if (!is_type_array(type) ||
5705 token.kind != ';' ||
5706 look_ahead(1)->kind != '}') {
5707 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5708 } else if (compound->members.entities == NULL) {
5709 errorf(pos, "flexible array member in otherwise empty struct");
5714 append_entity(&compound->members, entity);
5717 } while (next_if(','));
5718 expect(';', end_error);
5721 anonymous_entity = NULL;
5724 static void parse_compound_type_entries(compound_t *compound)
5727 add_anchor_token('}');
5730 switch (token.kind) {
5732 case T___extension__:
5733 case T_IDENTIFIER: {
5735 declaration_specifiers_t specifiers;
5736 parse_declaration_specifiers(&specifiers);
5737 parse_compound_declarators(compound, &specifiers);
5743 rem_anchor_token('}');
5744 expect('}', end_error);
5747 compound->complete = true;
5753 static type_t *parse_typename(void)
5755 declaration_specifiers_t specifiers;
5756 parse_declaration_specifiers(&specifiers);
5757 if (specifiers.storage_class != STORAGE_CLASS_NONE
5758 || specifiers.thread_local) {
5759 /* TODO: improve error message, user does probably not know what a
5760 * storage class is...
5762 errorf(&specifiers.source_position, "typename must not have a storage class");
5765 type_t *result = parse_abstract_declarator(specifiers.type);
5773 typedef expression_t* (*parse_expression_function)(void);
5774 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5776 typedef struct expression_parser_function_t expression_parser_function_t;
5777 struct expression_parser_function_t {
5778 parse_expression_function parser;
5779 precedence_t infix_precedence;
5780 parse_expression_infix_function infix_parser;
5783 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5786 * Prints an error message if an expression was expected but not read
5788 static expression_t *expected_expression_error(void)
5790 /* skip the error message if the error token was read */
5791 if (token.kind != T_ERROR) {
5792 errorf(HERE, "expected expression, got token %K", &token);
5796 return create_error_expression();
5799 static type_t *get_string_type(void)
5801 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5804 static type_t *get_wide_string_type(void)
5806 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5810 * Parse a string constant.
5812 static expression_t *parse_string_literal(void)
5814 source_position_t begin = token.base.source_position;
5815 string_t res = token.string.string;
5816 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5819 while (token.kind == T_STRING_LITERAL
5820 || token.kind == T_WIDE_STRING_LITERAL) {
5821 warn_string_concat(&token.base.source_position);
5822 res = concat_strings(&res, &token.string.string);
5824 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5827 expression_t *literal;
5829 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5830 literal->base.type = get_wide_string_type();
5832 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5833 literal->base.type = get_string_type();
5835 literal->base.source_position = begin;
5836 literal->literal.value = res;
5842 * Parse a boolean constant.
5844 static expression_t *parse_boolean_literal(bool value)
5846 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5847 literal->base.type = type_bool;
5848 literal->literal.value.begin = value ? "true" : "false";
5849 literal->literal.value.size = value ? 4 : 5;
5855 static void warn_traditional_suffix(void)
5857 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5858 &token.number.suffix);
5861 static void check_integer_suffix(void)
5863 const string_t *suffix = &token.number.suffix;
5864 if (suffix->size == 0)
5867 bool not_traditional = false;
5868 const char *c = suffix->begin;
5869 if (*c == 'l' || *c == 'L') {
5872 not_traditional = true;
5874 if (*c == 'u' || *c == 'U') {
5877 } else if (*c == 'u' || *c == 'U') {
5878 not_traditional = true;
5881 } else if (*c == 'u' || *c == 'U') {
5882 not_traditional = true;
5884 if (*c == 'l' || *c == 'L') {
5892 errorf(&token.base.source_position,
5893 "invalid suffix '%S' on integer constant", suffix);
5894 } else if (not_traditional) {
5895 warn_traditional_suffix();
5899 static type_t *check_floatingpoint_suffix(void)
5901 const string_t *suffix = &token.number.suffix;
5902 type_t *type = type_double;
5903 if (suffix->size == 0)
5906 bool not_traditional = false;
5907 const char *c = suffix->begin;
5908 if (*c == 'f' || *c == 'F') {
5911 } else if (*c == 'l' || *c == 'L') {
5913 type = type_long_double;
5916 errorf(&token.base.source_position,
5917 "invalid suffix '%S' on floatingpoint constant", suffix);
5918 } else if (not_traditional) {
5919 warn_traditional_suffix();
5926 * Parse an integer constant.
5928 static expression_t *parse_number_literal(void)
5930 expression_kind_t kind;
5933 switch (token.kind) {
5935 kind = EXPR_LITERAL_INTEGER;
5936 check_integer_suffix();
5939 case T_INTEGER_OCTAL:
5940 kind = EXPR_LITERAL_INTEGER_OCTAL;
5941 check_integer_suffix();
5944 case T_INTEGER_HEXADECIMAL:
5945 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5946 check_integer_suffix();
5949 case T_FLOATINGPOINT:
5950 kind = EXPR_LITERAL_FLOATINGPOINT;
5951 type = check_floatingpoint_suffix();
5953 case T_FLOATINGPOINT_HEXADECIMAL:
5954 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5955 type = check_floatingpoint_suffix();
5958 panic("unexpected token type in parse_number_literal");
5961 expression_t *literal = allocate_expression_zero(kind);
5962 literal->base.type = type;
5963 literal->literal.value = token.number.number;
5964 literal->literal.suffix = token.number.suffix;
5967 /* integer type depends on the size of the number and the size
5968 * representable by the types. The backend/codegeneration has to determine
5971 determine_literal_type(&literal->literal);
5976 * Parse a character constant.
5978 static expression_t *parse_character_constant(void)
5980 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5981 literal->base.type = c_mode & _CXX ? type_char : type_int;
5982 literal->literal.value = token.string.string;
5984 size_t len = literal->literal.value.size;
5986 if (!GNU_MODE && !(c_mode & _C99)) {
5987 errorf(HERE, "more than 1 character in character constant");
5989 literal->base.type = type_int;
5990 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5999 * Parse a wide character constant.
6001 static expression_t *parse_wide_character_constant(void)
6003 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6004 literal->base.type = type_int;
6005 literal->literal.value = token.string.string;
6007 size_t len = wstrlen(&literal->literal.value);
6009 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6016 static entity_t *create_implicit_function(symbol_t *symbol,
6017 const source_position_t *source_position)
6019 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6020 ntype->function.return_type = type_int;
6021 ntype->function.unspecified_parameters = true;
6022 ntype->function.linkage = LINKAGE_C;
6023 type_t *type = identify_new_type(ntype);
6025 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6026 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6027 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6028 entity->declaration.type = type;
6029 entity->declaration.implicit = true;
6030 entity->base.source_position = *source_position;
6032 if (current_scope != NULL)
6033 record_entity(entity, false);
6039 * Performs automatic type cast as described in §6.3.2.1.
6041 * @param orig_type the original type
6043 static type_t *automatic_type_conversion(type_t *orig_type)
6045 type_t *type = skip_typeref(orig_type);
6046 if (is_type_array(type)) {
6047 array_type_t *array_type = &type->array;
6048 type_t *element_type = array_type->element_type;
6049 unsigned qualifiers = array_type->base.qualifiers;
6051 return make_pointer_type(element_type, qualifiers);
6054 if (is_type_function(type)) {
6055 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6062 * reverts the automatic casts of array to pointer types and function
6063 * to function-pointer types as defined §6.3.2.1
6065 type_t *revert_automatic_type_conversion(const expression_t *expression)
6067 switch (expression->kind) {
6068 case EXPR_REFERENCE: {
6069 entity_t *entity = expression->reference.entity;
6070 if (is_declaration(entity)) {
6071 return entity->declaration.type;
6072 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6073 return entity->enum_value.enum_type;
6075 panic("no declaration or enum in reference");
6080 entity_t *entity = expression->select.compound_entry;
6081 assert(is_declaration(entity));
6082 type_t *type = entity->declaration.type;
6083 return get_qualified_type(type, expression->base.type->base.qualifiers);
6086 case EXPR_UNARY_DEREFERENCE: {
6087 const expression_t *const value = expression->unary.value;
6088 type_t *const type = skip_typeref(value->base.type);
6089 if (!is_type_pointer(type))
6090 return type_error_type;
6091 return type->pointer.points_to;
6094 case EXPR_ARRAY_ACCESS: {
6095 const expression_t *array_ref = expression->array_access.array_ref;
6096 type_t *type_left = skip_typeref(array_ref->base.type);
6097 if (!is_type_pointer(type_left))
6098 return type_error_type;
6099 return type_left->pointer.points_to;
6102 case EXPR_STRING_LITERAL: {
6103 size_t size = expression->string_literal.value.size;
6104 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6107 case EXPR_WIDE_STRING_LITERAL: {
6108 size_t size = wstrlen(&expression->string_literal.value);
6109 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6112 case EXPR_COMPOUND_LITERAL:
6113 return expression->compound_literal.type;
6118 return expression->base.type;
6122 * Find an entity matching a symbol in a scope.
6123 * Uses current scope if scope is NULL
6125 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6126 namespace_tag_t namespc)
6128 if (scope == NULL) {
6129 return get_entity(symbol, namespc);
6132 /* we should optimize here, if scope grows above a certain size we should
6133 construct a hashmap here... */
6134 entity_t *entity = scope->entities;
6135 for ( ; entity != NULL; entity = entity->base.next) {
6136 if (entity->base.symbol == symbol
6137 && (namespace_tag_t)entity->base.namespc == namespc)
6144 static entity_t *parse_qualified_identifier(void)
6146 /* namespace containing the symbol */
6148 source_position_t pos;
6149 const scope_t *lookup_scope = NULL;
6151 if (next_if(T_COLONCOLON))
6152 lookup_scope = &unit->scope;
6156 if (token.kind != T_IDENTIFIER) {
6157 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6158 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6160 symbol = token.identifier.symbol;
6165 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6167 if (!next_if(T_COLONCOLON))
6170 switch (entity->kind) {
6171 case ENTITY_NAMESPACE:
6172 lookup_scope = &entity->namespacee.members;
6177 lookup_scope = &entity->compound.members;
6180 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6181 symbol, get_entity_kind_name(entity->kind));
6183 /* skip further qualifications */
6184 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6186 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6190 if (entity == NULL) {
6191 if (!strict_mode && token.kind == '(') {
6192 /* an implicitly declared function */
6193 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6194 "implicit declaration of function '%Y'", symbol);
6195 entity = create_implicit_function(symbol, &pos);
6197 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6198 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6205 static expression_t *parse_reference(void)
6207 source_position_t const pos = token.base.source_position;
6208 entity_t *const entity = parse_qualified_identifier();
6211 if (is_declaration(entity)) {
6212 orig_type = entity->declaration.type;
6213 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6214 orig_type = entity->enum_value.enum_type;
6216 panic("expected declaration or enum value in reference");
6219 /* we always do the auto-type conversions; the & and sizeof parser contains
6220 * code to revert this! */
6221 type_t *type = automatic_type_conversion(orig_type);
6223 expression_kind_t kind = EXPR_REFERENCE;
6224 if (entity->kind == ENTITY_ENUM_VALUE)
6225 kind = EXPR_REFERENCE_ENUM_VALUE;
6227 expression_t *expression = allocate_expression_zero(kind);
6228 expression->base.source_position = pos;
6229 expression->base.type = type;
6230 expression->reference.entity = entity;
6232 /* this declaration is used */
6233 if (is_declaration(entity)) {
6234 entity->declaration.used = true;
6237 if (entity->base.parent_scope != file_scope
6238 && (current_function != NULL
6239 && entity->base.parent_scope->depth < current_function->parameters.depth)
6240 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6241 if (entity->kind == ENTITY_VARIABLE) {
6242 /* access of a variable from an outer function */
6243 entity->variable.address_taken = true;
6244 } else if (entity->kind == ENTITY_PARAMETER) {
6245 entity->parameter.address_taken = true;
6247 current_function->need_closure = true;
6250 check_deprecated(&pos, entity);
6255 static bool semantic_cast(expression_t *cast)
6257 expression_t *expression = cast->unary.value;
6258 type_t *orig_dest_type = cast->base.type;
6259 type_t *orig_type_right = expression->base.type;
6260 type_t const *dst_type = skip_typeref(orig_dest_type);
6261 type_t const *src_type = skip_typeref(orig_type_right);
6262 source_position_t const *pos = &cast->base.source_position;
6264 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6265 if (dst_type == type_void)
6268 /* only integer and pointer can be casted to pointer */
6269 if (is_type_pointer(dst_type) &&
6270 !is_type_pointer(src_type) &&
6271 !is_type_integer(src_type) &&
6272 is_type_valid(src_type)) {
6273 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6277 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6278 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6282 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6283 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6287 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6288 type_t *src = skip_typeref(src_type->pointer.points_to);
6289 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6290 unsigned missing_qualifiers =
6291 src->base.qualifiers & ~dst->base.qualifiers;
6292 if (missing_qualifiers != 0) {
6293 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6299 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6301 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6302 expression->base.source_position = *pos;
6304 parse_initializer_env_t env;
6307 env.must_be_constant = false;
6308 initializer_t *initializer = parse_initializer(&env);
6311 expression->compound_literal.initializer = initializer;
6312 expression->compound_literal.type = type;
6313 expression->base.type = automatic_type_conversion(type);
6319 * Parse a cast expression.
6321 static expression_t *parse_cast(void)
6323 source_position_t const pos = *HERE;
6326 add_anchor_token(')');
6328 type_t *type = parse_typename();
6330 rem_anchor_token(')');
6331 expect(')', end_error);
6333 if (token.kind == '{') {
6334 return parse_compound_literal(&pos, type);
6337 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6338 cast->base.source_position = pos;
6340 expression_t *value = parse_subexpression(PREC_CAST);
6341 cast->base.type = type;
6342 cast->unary.value = value;
6344 if (! semantic_cast(cast)) {
6345 /* TODO: record the error in the AST. else it is impossible to detect it */
6350 return create_error_expression();
6354 * Parse a statement expression.
6356 static expression_t *parse_statement_expression(void)
6358 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6361 add_anchor_token(')');
6363 statement_t *statement = parse_compound_statement(true);
6364 statement->compound.stmt_expr = true;
6365 expression->statement.statement = statement;
6367 /* find last statement and use its type */
6368 type_t *type = type_void;
6369 const statement_t *stmt = statement->compound.statements;
6371 while (stmt->base.next != NULL)
6372 stmt = stmt->base.next;
6374 if (stmt->kind == STATEMENT_EXPRESSION) {
6375 type = stmt->expression.expression->base.type;
6378 source_position_t const *const pos = &expression->base.source_position;
6379 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6381 expression->base.type = type;
6383 rem_anchor_token(')');
6384 expect(')', end_error);
6391 * Parse a parenthesized expression.
6393 static expression_t *parse_parenthesized_expression(void)
6395 token_t const* const la1 = look_ahead(1);
6396 switch (la1->kind) {
6398 /* gcc extension: a statement expression */
6399 return parse_statement_expression();
6402 if (is_typedef_symbol(la1->identifier.symbol)) {
6404 return parse_cast();
6409 add_anchor_token(')');
6410 expression_t *result = parse_expression();
6411 result->base.parenthesized = true;
6412 rem_anchor_token(')');
6413 expect(')', end_error);
6419 static expression_t *parse_function_keyword(void)
6423 if (current_function == NULL) {
6424 errorf(HERE, "'__func__' used outside of a function");
6427 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6428 expression->base.type = type_char_ptr;
6429 expression->funcname.kind = FUNCNAME_FUNCTION;
6436 static expression_t *parse_pretty_function_keyword(void)
6438 if (current_function == NULL) {
6439 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6442 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6443 expression->base.type = type_char_ptr;
6444 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6446 eat(T___PRETTY_FUNCTION__);
6451 static expression_t *parse_funcsig_keyword(void)
6453 if (current_function == NULL) {
6454 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6457 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6458 expression->base.type = type_char_ptr;
6459 expression->funcname.kind = FUNCNAME_FUNCSIG;
6466 static expression_t *parse_funcdname_keyword(void)
6468 if (current_function == NULL) {
6469 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6472 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6473 expression->base.type = type_char_ptr;
6474 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6476 eat(T___FUNCDNAME__);
6481 static designator_t *parse_designator(void)
6483 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6484 result->source_position = *HERE;
6486 if (token.kind != T_IDENTIFIER) {
6487 parse_error_expected("while parsing member designator",
6488 T_IDENTIFIER, NULL);
6491 result->symbol = token.identifier.symbol;
6494 designator_t *last_designator = result;
6497 if (token.kind != T_IDENTIFIER) {
6498 parse_error_expected("while parsing member designator",
6499 T_IDENTIFIER, NULL);
6502 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6503 designator->source_position = *HERE;
6504 designator->symbol = token.identifier.symbol;
6507 last_designator->next = designator;
6508 last_designator = designator;
6512 add_anchor_token(']');
6513 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6514 designator->source_position = *HERE;
6515 designator->array_index = parse_expression();
6516 rem_anchor_token(']');
6517 expect(']', end_error);
6518 if (designator->array_index == NULL) {
6522 last_designator->next = designator;
6523 last_designator = designator;
6535 * Parse the __builtin_offsetof() expression.
6537 static expression_t *parse_offsetof(void)
6539 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6540 expression->base.type = type_size_t;
6542 eat(T___builtin_offsetof);
6544 expect('(', end_error);
6545 add_anchor_token(',');
6546 type_t *type = parse_typename();
6547 rem_anchor_token(',');
6548 expect(',', end_error);
6549 add_anchor_token(')');
6550 designator_t *designator = parse_designator();
6551 rem_anchor_token(')');
6552 expect(')', end_error);
6554 expression->offsetofe.type = type;
6555 expression->offsetofe.designator = designator;
6558 memset(&path, 0, sizeof(path));
6559 path.top_type = type;
6560 path.path = NEW_ARR_F(type_path_entry_t, 0);
6562 descend_into_subtype(&path);
6564 if (!walk_designator(&path, designator, true)) {
6565 return create_error_expression();
6568 DEL_ARR_F(path.path);
6572 return create_error_expression();
6576 * Parses a _builtin_va_start() expression.
6578 static expression_t *parse_va_start(void)
6580 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6582 eat(T___builtin_va_start);
6584 expect('(', end_error);
6585 add_anchor_token(',');
6586 expression->va_starte.ap = parse_assignment_expression();
6587 rem_anchor_token(',');
6588 expect(',', end_error);
6589 expression_t *const expr = parse_assignment_expression();
6590 if (expr->kind == EXPR_REFERENCE) {
6591 entity_t *const entity = expr->reference.entity;
6592 if (!current_function->base.type->function.variadic) {
6593 errorf(&expr->base.source_position,
6594 "'va_start' used in non-variadic function");
6595 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6596 entity->base.next != NULL ||
6597 entity->kind != ENTITY_PARAMETER) {
6598 errorf(&expr->base.source_position,
6599 "second argument of 'va_start' must be last parameter of the current function");
6601 expression->va_starte.parameter = &entity->variable;
6603 expect(')', end_error);
6606 expect(')', end_error);
6608 return create_error_expression();
6612 * Parses a __builtin_va_arg() expression.
6614 static expression_t *parse_va_arg(void)
6616 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6618 eat(T___builtin_va_arg);
6620 expect('(', end_error);
6622 ap.expression = parse_assignment_expression();
6623 expression->va_arge.ap = ap.expression;
6624 check_call_argument(type_valist, &ap, 1);
6626 expect(',', end_error);
6627 expression->base.type = parse_typename();
6628 expect(')', end_error);
6632 return create_error_expression();
6636 * Parses a __builtin_va_copy() expression.
6638 static expression_t *parse_va_copy(void)
6640 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6642 eat(T___builtin_va_copy);
6644 expect('(', end_error);
6645 expression_t *dst = parse_assignment_expression();
6646 assign_error_t error = semantic_assign(type_valist, dst);
6647 report_assign_error(error, type_valist, dst, "call argument 1",
6648 &dst->base.source_position);
6649 expression->va_copye.dst = dst;
6651 expect(',', end_error);
6653 call_argument_t src;
6654 src.expression = parse_assignment_expression();
6655 check_call_argument(type_valist, &src, 2);
6656 expression->va_copye.src = src.expression;
6657 expect(')', end_error);
6661 return create_error_expression();
6665 * Parses a __builtin_constant_p() expression.
6667 static expression_t *parse_builtin_constant(void)
6669 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6671 eat(T___builtin_constant_p);
6673 expect('(', end_error);
6674 add_anchor_token(')');
6675 expression->builtin_constant.value = parse_assignment_expression();
6676 rem_anchor_token(')');
6677 expect(')', end_error);
6678 expression->base.type = type_int;
6682 return create_error_expression();
6686 * Parses a __builtin_types_compatible_p() expression.
6688 static expression_t *parse_builtin_types_compatible(void)
6690 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6692 eat(T___builtin_types_compatible_p);
6694 expect('(', end_error);
6695 add_anchor_token(')');
6696 add_anchor_token(',');
6697 expression->builtin_types_compatible.left = parse_typename();
6698 rem_anchor_token(',');
6699 expect(',', end_error);
6700 expression->builtin_types_compatible.right = parse_typename();
6701 rem_anchor_token(')');
6702 expect(')', end_error);
6703 expression->base.type = type_int;
6707 return create_error_expression();
6711 * Parses a __builtin_is_*() compare expression.
6713 static expression_t *parse_compare_builtin(void)
6715 expression_t *expression;
6717 switch (token.kind) {
6718 case T___builtin_isgreater:
6719 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6721 case T___builtin_isgreaterequal:
6722 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6724 case T___builtin_isless:
6725 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6727 case T___builtin_islessequal:
6728 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6730 case T___builtin_islessgreater:
6731 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6733 case T___builtin_isunordered:
6734 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6737 internal_errorf(HERE, "invalid compare builtin found");
6739 expression->base.source_position = *HERE;
6742 expect('(', end_error);
6743 expression->binary.left = parse_assignment_expression();
6744 expect(',', end_error);
6745 expression->binary.right = parse_assignment_expression();
6746 expect(')', end_error);
6748 type_t *const orig_type_left = expression->binary.left->base.type;
6749 type_t *const orig_type_right = expression->binary.right->base.type;
6751 type_t *const type_left = skip_typeref(orig_type_left);
6752 type_t *const type_right = skip_typeref(orig_type_right);
6753 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6754 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6755 type_error_incompatible("invalid operands in comparison",
6756 &expression->base.source_position, orig_type_left, orig_type_right);
6759 semantic_comparison(&expression->binary);
6764 return create_error_expression();
6768 * Parses a MS assume() expression.
6770 static expression_t *parse_assume(void)
6772 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6776 expect('(', end_error);
6777 add_anchor_token(')');
6778 expression->unary.value = parse_assignment_expression();
6779 rem_anchor_token(')');
6780 expect(')', end_error);
6782 expression->base.type = type_void;
6785 return create_error_expression();
6789 * Return the label for the current symbol or create a new one.
6791 static label_t *get_label(void)
6793 assert(token.kind == T_IDENTIFIER);
6794 assert(current_function != NULL);
6796 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6797 /* If we find a local label, we already created the declaration. */
6798 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6799 if (label->base.parent_scope != current_scope) {
6800 assert(label->base.parent_scope->depth < current_scope->depth);
6801 current_function->goto_to_outer = true;
6803 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6804 /* There is no matching label in the same function, so create a new one. */
6805 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol);
6810 return &label->label;
6814 * Parses a GNU && label address expression.
6816 static expression_t *parse_label_address(void)
6818 source_position_t source_position = token.base.source_position;
6820 if (token.kind != T_IDENTIFIER) {
6821 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6822 return create_error_expression();
6825 label_t *const label = get_label();
6827 label->address_taken = true;
6829 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6830 expression->base.source_position = source_position;
6832 /* label address is treated as a void pointer */
6833 expression->base.type = type_void_ptr;
6834 expression->label_address.label = label;
6839 * Parse a microsoft __noop expression.
6841 static expression_t *parse_noop_expression(void)
6843 /* the result is a (int)0 */
6844 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6845 literal->base.type = type_int;
6846 literal->literal.value.begin = "__noop";
6847 literal->literal.value.size = 6;
6851 if (token.kind == '(') {
6852 /* parse arguments */
6854 add_anchor_token(')');
6855 add_anchor_token(',');
6857 if (token.kind != ')') do {
6858 (void)parse_assignment_expression();
6859 } while (next_if(','));
6861 rem_anchor_token(',');
6862 rem_anchor_token(')');
6863 expect(')', end_error);
6870 * Parses a primary expression.
6872 static expression_t *parse_primary_expression(void)
6874 switch (token.kind) {
6875 case T_false: return parse_boolean_literal(false);
6876 case T_true: return parse_boolean_literal(true);
6878 case T_INTEGER_OCTAL:
6879 case T_INTEGER_HEXADECIMAL:
6880 case T_FLOATINGPOINT:
6881 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6882 case T_CHARACTER_CONSTANT: return parse_character_constant();
6883 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6884 case T_STRING_LITERAL:
6885 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6886 case T___FUNCTION__:
6887 case T___func__: return parse_function_keyword();
6888 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6889 case T___FUNCSIG__: return parse_funcsig_keyword();
6890 case T___FUNCDNAME__: return parse_funcdname_keyword();
6891 case T___builtin_offsetof: return parse_offsetof();
6892 case T___builtin_va_start: return parse_va_start();
6893 case T___builtin_va_arg: return parse_va_arg();
6894 case T___builtin_va_copy: return parse_va_copy();
6895 case T___builtin_isgreater:
6896 case T___builtin_isgreaterequal:
6897 case T___builtin_isless:
6898 case T___builtin_islessequal:
6899 case T___builtin_islessgreater:
6900 case T___builtin_isunordered: return parse_compare_builtin();
6901 case T___builtin_constant_p: return parse_builtin_constant();
6902 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6903 case T__assume: return parse_assume();
6906 return parse_label_address();
6909 case '(': return parse_parenthesized_expression();
6910 case T___noop: return parse_noop_expression();
6912 /* Gracefully handle type names while parsing expressions. */
6914 return parse_reference();
6916 if (!is_typedef_symbol(token.identifier.symbol)) {
6917 return parse_reference();
6921 source_position_t const pos = *HERE;
6922 declaration_specifiers_t specifiers;
6923 parse_declaration_specifiers(&specifiers);
6924 type_t const *const type = parse_abstract_declarator(specifiers.type);
6925 errorf(&pos, "encountered type '%T' while parsing expression", type);
6926 return create_error_expression();
6930 errorf(HERE, "unexpected token %K, expected an expression", &token);
6932 return create_error_expression();
6935 static expression_t *parse_array_expression(expression_t *left)
6937 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6938 array_access_expression_t *const arr = &expr->array_access;
6941 add_anchor_token(']');
6943 expression_t *const inside = parse_expression();
6945 type_t *const orig_type_left = left->base.type;
6946 type_t *const orig_type_inside = inside->base.type;
6948 type_t *const type_left = skip_typeref(orig_type_left);
6949 type_t *const type_inside = skip_typeref(orig_type_inside);
6955 if (is_type_pointer(type_left)) {
6958 idx_type = type_inside;
6959 res_type = type_left->pointer.points_to;
6961 } else if (is_type_pointer(type_inside)) {
6962 arr->flipped = true;
6965 idx_type = type_left;
6966 res_type = type_inside->pointer.points_to;
6968 res_type = automatic_type_conversion(res_type);
6969 if (!is_type_integer(idx_type)) {
6970 errorf(&idx->base.source_position, "array subscript must have integer type");
6971 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6972 source_position_t const *const pos = &idx->base.source_position;
6973 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6976 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6977 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6979 res_type = type_error_type;
6984 arr->array_ref = ref;
6986 arr->base.type = res_type;
6988 rem_anchor_token(']');
6989 expect(']', end_error);
6994 static bool is_bitfield(const expression_t *expression)
6996 return expression->kind == EXPR_SELECT
6997 && expression->select.compound_entry->compound_member.bitfield;
7000 static expression_t *parse_typeprop(expression_kind_t const kind)
7002 expression_t *tp_expression = allocate_expression_zero(kind);
7003 tp_expression->base.type = type_size_t;
7005 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7008 expression_t *expression;
7009 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
7010 source_position_t const pos = *HERE;
7012 add_anchor_token(')');
7013 orig_type = parse_typename();
7014 rem_anchor_token(')');
7015 expect(')', end_error);
7017 if (token.kind == '{') {
7018 /* It was not sizeof(type) after all. It is sizeof of an expression
7019 * starting with a compound literal */
7020 expression = parse_compound_literal(&pos, orig_type);
7021 goto typeprop_expression;
7024 expression = parse_subexpression(PREC_UNARY);
7026 typeprop_expression:
7027 if (is_bitfield(expression)) {
7028 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7029 errorf(&tp_expression->base.source_position,
7030 "operand of %s expression must not be a bitfield", what);
7033 tp_expression->typeprop.tp_expression = expression;
7035 orig_type = revert_automatic_type_conversion(expression);
7036 expression->base.type = orig_type;
7039 tp_expression->typeprop.type = orig_type;
7040 type_t const* const type = skip_typeref(orig_type);
7041 char const* wrong_type = NULL;
7042 if (is_type_incomplete(type)) {
7043 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7044 wrong_type = "incomplete";
7045 } else if (type->kind == TYPE_FUNCTION) {
7047 /* function types are allowed (and return 1) */
7048 source_position_t const *const pos = &tp_expression->base.source_position;
7049 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7050 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7052 wrong_type = "function";
7056 if (wrong_type != NULL) {
7057 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7058 errorf(&tp_expression->base.source_position,
7059 "operand of %s expression must not be of %s type '%T'",
7060 what, wrong_type, orig_type);
7064 return tp_expression;
7067 static expression_t *parse_sizeof(void)
7069 return parse_typeprop(EXPR_SIZEOF);
7072 static expression_t *parse_alignof(void)
7074 return parse_typeprop(EXPR_ALIGNOF);
7077 static expression_t *parse_select_expression(expression_t *addr)
7079 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7080 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7081 source_position_t const pos = *HERE;
7084 if (token.kind != T_IDENTIFIER) {
7085 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7086 return create_error_expression();
7088 symbol_t *symbol = token.identifier.symbol;
7091 type_t *const orig_type = addr->base.type;
7092 type_t *const type = skip_typeref(orig_type);
7095 bool saw_error = false;
7096 if (is_type_pointer(type)) {
7097 if (!select_left_arrow) {
7099 "request for member '%Y' in something not a struct or union, but '%T'",
7103 type_left = skip_typeref(type->pointer.points_to);
7105 if (select_left_arrow && is_type_valid(type)) {
7106 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7112 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7113 type_left->kind != TYPE_COMPOUND_UNION) {
7115 if (is_type_valid(type_left) && !saw_error) {
7117 "request for member '%Y' in something not a struct or union, but '%T'",
7120 return create_error_expression();
7123 compound_t *compound = type_left->compound.compound;
7124 if (!compound->complete) {
7125 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7127 return create_error_expression();
7130 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7131 expression_t *result =
7132 find_create_select(&pos, addr, qualifiers, compound, symbol);
7134 if (result == NULL) {
7135 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7136 return create_error_expression();
7142 static void check_call_argument(type_t *expected_type,
7143 call_argument_t *argument, unsigned pos)
7145 type_t *expected_type_skip = skip_typeref(expected_type);
7146 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7147 expression_t *arg_expr = argument->expression;
7148 type_t *arg_type = skip_typeref(arg_expr->base.type);
7150 /* handle transparent union gnu extension */
7151 if (is_type_union(expected_type_skip)
7152 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7153 compound_t *union_decl = expected_type_skip->compound.compound;
7154 type_t *best_type = NULL;
7155 entity_t *entry = union_decl->members.entities;
7156 for ( ; entry != NULL; entry = entry->base.next) {
7157 assert(is_declaration(entry));
7158 type_t *decl_type = entry->declaration.type;
7159 error = semantic_assign(decl_type, arg_expr);
7160 if (error == ASSIGN_ERROR_INCOMPATIBLE
7161 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7164 if (error == ASSIGN_SUCCESS) {
7165 best_type = decl_type;
7166 } else if (best_type == NULL) {
7167 best_type = decl_type;
7171 if (best_type != NULL) {
7172 expected_type = best_type;
7176 error = semantic_assign(expected_type, arg_expr);
7177 argument->expression = create_implicit_cast(arg_expr, expected_type);
7179 if (error != ASSIGN_SUCCESS) {
7180 /* report exact scope in error messages (like "in argument 3") */
7182 snprintf(buf, sizeof(buf), "call argument %u", pos);
7183 report_assign_error(error, expected_type, arg_expr, buf,
7184 &arg_expr->base.source_position);
7186 type_t *const promoted_type = get_default_promoted_type(arg_type);
7187 if (!types_compatible(expected_type_skip, promoted_type) &&
7188 !types_compatible(expected_type_skip, type_void_ptr) &&
7189 !types_compatible(type_void_ptr, promoted_type)) {
7190 /* Deliberately show the skipped types in this warning */
7191 source_position_t const *const apos = &arg_expr->base.source_position;
7192 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7198 * Handle the semantic restrictions of builtin calls
7200 static void handle_builtin_argument_restrictions(call_expression_t *call)
7202 entity_t *entity = call->function->reference.entity;
7203 switch (entity->function.btk) {
7205 switch (entity->function.b.firm_builtin_kind) {
7206 case ir_bk_return_address:
7207 case ir_bk_frame_address: {
7208 /* argument must be constant */
7209 call_argument_t *argument = call->arguments;
7211 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7212 errorf(&call->base.source_position,
7213 "argument of '%Y' must be a constant expression",
7214 call->function->reference.entity->base.symbol);
7218 case ir_bk_prefetch:
7219 /* second and third argument must be constant if existent */
7220 if (call->arguments == NULL)
7222 call_argument_t *rw = call->arguments->next;
7223 call_argument_t *locality = NULL;
7226 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7227 errorf(&call->base.source_position,
7228 "second argument of '%Y' must be a constant expression",
7229 call->function->reference.entity->base.symbol);
7231 locality = rw->next;
7233 if (locality != NULL) {
7234 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7235 errorf(&call->base.source_position,
7236 "third argument of '%Y' must be a constant expression",
7237 call->function->reference.entity->base.symbol);
7239 locality = rw->next;
7246 case BUILTIN_OBJECT_SIZE:
7247 if (call->arguments == NULL)
7250 call_argument_t *arg = call->arguments->next;
7251 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7252 errorf(&call->base.source_position,
7253 "second argument of '%Y' must be a constant expression",
7254 call->function->reference.entity->base.symbol);
7263 * Parse a call expression, ie. expression '( ... )'.
7265 * @param expression the function address
7267 static expression_t *parse_call_expression(expression_t *expression)
7269 expression_t *result = allocate_expression_zero(EXPR_CALL);
7270 call_expression_t *call = &result->call;
7271 call->function = expression;
7273 type_t *const orig_type = expression->base.type;
7274 type_t *const type = skip_typeref(orig_type);
7276 function_type_t *function_type = NULL;
7277 if (is_type_pointer(type)) {
7278 type_t *const to_type = skip_typeref(type->pointer.points_to);
7280 if (is_type_function(to_type)) {
7281 function_type = &to_type->function;
7282 call->base.type = function_type->return_type;
7286 if (function_type == NULL && is_type_valid(type)) {
7288 "called object '%E' (type '%T') is not a pointer to a function",
7289 expression, orig_type);
7292 /* parse arguments */
7294 add_anchor_token(')');
7295 add_anchor_token(',');
7297 if (token.kind != ')') {
7298 call_argument_t **anchor = &call->arguments;
7300 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7301 argument->expression = parse_assignment_expression();
7304 anchor = &argument->next;
7305 } while (next_if(','));
7307 rem_anchor_token(',');
7308 rem_anchor_token(')');
7309 expect(')', end_error);
7311 if (function_type == NULL)
7314 /* check type and count of call arguments */
7315 function_parameter_t *parameter = function_type->parameters;
7316 call_argument_t *argument = call->arguments;
7317 if (!function_type->unspecified_parameters) {
7318 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7319 parameter = parameter->next, argument = argument->next) {
7320 check_call_argument(parameter->type, argument, ++pos);
7323 if (parameter != NULL) {
7324 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7325 } else if (argument != NULL && !function_type->variadic) {
7326 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7330 /* do default promotion for other arguments */
7331 for (; argument != NULL; argument = argument->next) {
7332 type_t *argument_type = argument->expression->base.type;
7333 if (!is_type_object(skip_typeref(argument_type))) {
7334 errorf(&argument->expression->base.source_position,
7335 "call argument '%E' must not be void", argument->expression);
7338 argument_type = get_default_promoted_type(argument_type);
7340 argument->expression
7341 = create_implicit_cast(argument->expression, argument_type);
7346 if (is_type_compound(skip_typeref(function_type->return_type))) {
7347 source_position_t const *const pos = &expression->base.source_position;
7348 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7351 if (expression->kind == EXPR_REFERENCE) {
7352 reference_expression_t *reference = &expression->reference;
7353 if (reference->entity->kind == ENTITY_FUNCTION &&
7354 reference->entity->function.btk != BUILTIN_NONE)
7355 handle_builtin_argument_restrictions(call);
7362 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7364 static bool same_compound_type(const type_t *type1, const type_t *type2)
7367 is_type_compound(type1) &&
7368 type1->kind == type2->kind &&
7369 type1->compound.compound == type2->compound.compound;
7372 static expression_t const *get_reference_address(expression_t const *expr)
7374 bool regular_take_address = true;
7376 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7377 expr = expr->unary.value;
7379 regular_take_address = false;
7382 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7385 expr = expr->unary.value;
7388 if (expr->kind != EXPR_REFERENCE)
7391 /* special case for functions which are automatically converted to a
7392 * pointer to function without an extra TAKE_ADDRESS operation */
7393 if (!regular_take_address &&
7394 expr->reference.entity->kind != ENTITY_FUNCTION) {
7401 static void warn_reference_address_as_bool(expression_t const* expr)
7403 expr = get_reference_address(expr);
7405 source_position_t const *const pos = &expr->base.source_position;
7406 entity_t const *const ent = expr->reference.entity;
7407 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7411 static void warn_assignment_in_condition(const expression_t *const expr)
7413 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7415 if (expr->base.parenthesized)
7417 source_position_t const *const pos = &expr->base.source_position;
7418 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7421 static void semantic_condition(expression_t const *const expr,
7422 char const *const context)
7424 type_t *const type = skip_typeref(expr->base.type);
7425 if (is_type_scalar(type)) {
7426 warn_reference_address_as_bool(expr);
7427 warn_assignment_in_condition(expr);
7428 } else if (is_type_valid(type)) {
7429 errorf(&expr->base.source_position,
7430 "%s must have scalar type", context);
7435 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7437 * @param expression the conditional expression
7439 static expression_t *parse_conditional_expression(expression_t *expression)
7441 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7443 conditional_expression_t *conditional = &result->conditional;
7444 conditional->condition = expression;
7447 add_anchor_token(':');
7449 /* §6.5.15:2 The first operand shall have scalar type. */
7450 semantic_condition(expression, "condition of conditional operator");
7452 expression_t *true_expression = expression;
7453 bool gnu_cond = false;
7454 if (GNU_MODE && token.kind == ':') {
7457 true_expression = parse_expression();
7459 rem_anchor_token(':');
7460 expect(':', end_error);
7462 expression_t *false_expression =
7463 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7465 type_t *const orig_true_type = true_expression->base.type;
7466 type_t *const orig_false_type = false_expression->base.type;
7467 type_t *const true_type = skip_typeref(orig_true_type);
7468 type_t *const false_type = skip_typeref(orig_false_type);
7471 source_position_t const *const pos = &conditional->base.source_position;
7472 type_t *result_type;
7473 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7474 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7475 /* ISO/IEC 14882:1998(E) §5.16:2 */
7476 if (true_expression->kind == EXPR_UNARY_THROW) {
7477 result_type = false_type;
7478 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7479 result_type = true_type;
7481 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7482 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7483 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7485 result_type = type_void;
7487 } else if (is_type_arithmetic(true_type)
7488 && is_type_arithmetic(false_type)) {
7489 result_type = semantic_arithmetic(true_type, false_type);
7490 } else if (same_compound_type(true_type, false_type)) {
7491 /* just take 1 of the 2 types */
7492 result_type = true_type;
7493 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7494 type_t *pointer_type;
7496 expression_t *other_expression;
7497 if (is_type_pointer(true_type) &&
7498 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7499 pointer_type = true_type;
7500 other_type = false_type;
7501 other_expression = false_expression;
7503 pointer_type = false_type;
7504 other_type = true_type;
7505 other_expression = true_expression;
7508 if (is_null_pointer_constant(other_expression)) {
7509 result_type = pointer_type;
7510 } else if (is_type_pointer(other_type)) {
7511 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7512 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7515 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7516 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7518 } else if (types_compatible(get_unqualified_type(to1),
7519 get_unqualified_type(to2))) {
7522 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7526 type_t *const type =
7527 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7528 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7529 } else if (is_type_integer(other_type)) {
7530 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7531 result_type = pointer_type;
7533 goto types_incompatible;
7537 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7538 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7540 result_type = type_error_type;
7543 conditional->true_expression
7544 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7545 conditional->false_expression
7546 = create_implicit_cast(false_expression, result_type);
7547 conditional->base.type = result_type;
7552 * Parse an extension expression.
7554 static expression_t *parse_extension(void)
7557 expression_t *expression = parse_subexpression(PREC_UNARY);
7563 * Parse a __builtin_classify_type() expression.
7565 static expression_t *parse_builtin_classify_type(void)
7567 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7568 result->base.type = type_int;
7570 eat(T___builtin_classify_type);
7572 expect('(', end_error);
7573 add_anchor_token(')');
7574 expression_t *expression = parse_expression();
7575 rem_anchor_token(')');
7576 expect(')', end_error);
7577 result->classify_type.type_expression = expression;
7581 return create_error_expression();
7585 * Parse a delete expression
7586 * ISO/IEC 14882:1998(E) §5.3.5
7588 static expression_t *parse_delete(void)
7590 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7591 result->base.type = type_void;
7596 result->kind = EXPR_UNARY_DELETE_ARRAY;
7597 expect(']', end_error);
7601 expression_t *const value = parse_subexpression(PREC_CAST);
7602 result->unary.value = value;
7604 type_t *const type = skip_typeref(value->base.type);
7605 if (!is_type_pointer(type)) {
7606 if (is_type_valid(type)) {
7607 errorf(&value->base.source_position,
7608 "operand of delete must have pointer type");
7610 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7611 source_position_t const *const pos = &value->base.source_position;
7612 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7619 * Parse a throw expression
7620 * ISO/IEC 14882:1998(E) §15:1
7622 static expression_t *parse_throw(void)
7624 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7625 result->base.type = type_void;
7629 expression_t *value = NULL;
7630 switch (token.kind) {
7632 value = parse_assignment_expression();
7633 /* ISO/IEC 14882:1998(E) §15.1:3 */
7634 type_t *const orig_type = value->base.type;
7635 type_t *const type = skip_typeref(orig_type);
7636 if (is_type_incomplete(type)) {
7637 errorf(&value->base.source_position,
7638 "cannot throw object of incomplete type '%T'", orig_type);
7639 } else if (is_type_pointer(type)) {
7640 type_t *const points_to = skip_typeref(type->pointer.points_to);
7641 if (is_type_incomplete(points_to) &&
7642 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7643 errorf(&value->base.source_position,
7644 "cannot throw pointer to incomplete type '%T'", orig_type);
7652 result->unary.value = value;
7657 static bool check_pointer_arithmetic(const source_position_t *source_position,
7658 type_t *pointer_type,
7659 type_t *orig_pointer_type)
7661 type_t *points_to = pointer_type->pointer.points_to;
7662 points_to = skip_typeref(points_to);
7664 if (is_type_incomplete(points_to)) {
7665 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7666 errorf(source_position,
7667 "arithmetic with pointer to incomplete type '%T' not allowed",
7671 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7673 } else if (is_type_function(points_to)) {
7675 errorf(source_position,
7676 "arithmetic with pointer to function type '%T' not allowed",
7680 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7686 static bool is_lvalue(const expression_t *expression)
7688 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7689 switch (expression->kind) {
7690 case EXPR_ARRAY_ACCESS:
7691 case EXPR_COMPOUND_LITERAL:
7692 case EXPR_REFERENCE:
7694 case EXPR_UNARY_DEREFERENCE:
7698 type_t *type = skip_typeref(expression->base.type);
7700 /* ISO/IEC 14882:1998(E) §3.10:3 */
7701 is_type_reference(type) ||
7702 /* Claim it is an lvalue, if the type is invalid. There was a parse
7703 * error before, which maybe prevented properly recognizing it as
7705 !is_type_valid(type);
7710 static void semantic_incdec(unary_expression_t *expression)
7712 type_t *const orig_type = expression->value->base.type;
7713 type_t *const type = skip_typeref(orig_type);
7714 if (is_type_pointer(type)) {
7715 if (!check_pointer_arithmetic(&expression->base.source_position,
7719 } else if (!is_type_real(type) && is_type_valid(type)) {
7720 /* TODO: improve error message */
7721 errorf(&expression->base.source_position,
7722 "operation needs an arithmetic or pointer type");
7725 if (!is_lvalue(expression->value)) {
7726 /* TODO: improve error message */
7727 errorf(&expression->base.source_position, "lvalue required as operand");
7729 expression->base.type = orig_type;
7732 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7734 type_t *const res_type = promote_integer(type);
7735 expr->base.type = res_type;
7736 expr->value = create_implicit_cast(expr->value, res_type);
7739 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7741 type_t *const orig_type = expression->value->base.type;
7742 type_t *const type = skip_typeref(orig_type);
7743 if (!is_type_arithmetic(type)) {
7744 if (is_type_valid(type)) {
7745 /* TODO: improve error message */
7746 errorf(&expression->base.source_position,
7747 "operation needs an arithmetic type");
7750 } else if (is_type_integer(type)) {
7751 promote_unary_int_expr(expression, type);
7753 expression->base.type = orig_type;
7757 static void semantic_unexpr_plus(unary_expression_t *expression)
7759 semantic_unexpr_arithmetic(expression);
7760 source_position_t const *const pos = &expression->base.source_position;
7761 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7764 static void semantic_not(unary_expression_t *expression)
7766 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7767 semantic_condition(expression->value, "operand of !");
7768 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7771 static void semantic_unexpr_integer(unary_expression_t *expression)
7773 type_t *const orig_type = expression->value->base.type;
7774 type_t *const type = skip_typeref(orig_type);
7775 if (!is_type_integer(type)) {
7776 if (is_type_valid(type)) {
7777 errorf(&expression->base.source_position,
7778 "operand of ~ must be of integer type");
7783 promote_unary_int_expr(expression, type);
7786 static void semantic_dereference(unary_expression_t *expression)
7788 type_t *const orig_type = expression->value->base.type;
7789 type_t *const type = skip_typeref(orig_type);
7790 if (!is_type_pointer(type)) {
7791 if (is_type_valid(type)) {
7792 errorf(&expression->base.source_position,
7793 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7798 type_t *result_type = type->pointer.points_to;
7799 result_type = automatic_type_conversion(result_type);
7800 expression->base.type = result_type;
7804 * Record that an address is taken (expression represents an lvalue).
7806 * @param expression the expression
7807 * @param may_be_register if true, the expression might be an register
7809 static void set_address_taken(expression_t *expression, bool may_be_register)
7811 if (expression->kind != EXPR_REFERENCE)
7814 entity_t *const entity = expression->reference.entity;
7816 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7819 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7820 && !may_be_register) {
7821 source_position_t const *const pos = &expression->base.source_position;
7822 errorf(pos, "address of register '%N' requested", entity);
7825 if (entity->kind == ENTITY_VARIABLE) {
7826 entity->variable.address_taken = true;
7828 assert(entity->kind == ENTITY_PARAMETER);
7829 entity->parameter.address_taken = true;
7834 * Check the semantic of the address taken expression.
7836 static void semantic_take_addr(unary_expression_t *expression)
7838 expression_t *value = expression->value;
7839 value->base.type = revert_automatic_type_conversion(value);
7841 type_t *orig_type = value->base.type;
7842 type_t *type = skip_typeref(orig_type);
7843 if (!is_type_valid(type))
7847 if (!is_lvalue(value)) {
7848 errorf(&expression->base.source_position, "'&' requires an lvalue");
7850 if (is_bitfield(value)) {
7851 errorf(&expression->base.source_position,
7852 "'&' not allowed on bitfield");
7855 set_address_taken(value, false);
7857 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7860 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7861 static expression_t *parse_##unexpression_type(void) \
7863 expression_t *unary_expression \
7864 = allocate_expression_zero(unexpression_type); \
7866 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7868 sfunc(&unary_expression->unary); \
7870 return unary_expression; \
7873 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7874 semantic_unexpr_arithmetic)
7875 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7876 semantic_unexpr_plus)
7877 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7879 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7880 semantic_dereference)
7881 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7883 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7884 semantic_unexpr_integer)
7885 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7887 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7890 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7892 static expression_t *parse_##unexpression_type(expression_t *left) \
7894 expression_t *unary_expression \
7895 = allocate_expression_zero(unexpression_type); \
7897 unary_expression->unary.value = left; \
7899 sfunc(&unary_expression->unary); \
7901 return unary_expression; \
7904 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7905 EXPR_UNARY_POSTFIX_INCREMENT,
7907 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7908 EXPR_UNARY_POSTFIX_DECREMENT,
7911 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7913 /* TODO: handle complex + imaginary types */
7915 type_left = get_unqualified_type(type_left);
7916 type_right = get_unqualified_type(type_right);
7918 /* §6.3.1.8 Usual arithmetic conversions */
7919 if (type_left == type_long_double || type_right == type_long_double) {
7920 return type_long_double;
7921 } else if (type_left == type_double || type_right == type_double) {
7923 } else if (type_left == type_float || type_right == type_float) {
7927 type_left = promote_integer(type_left);
7928 type_right = promote_integer(type_right);
7930 if (type_left == type_right)
7933 bool const signed_left = is_type_signed(type_left);
7934 bool const signed_right = is_type_signed(type_right);
7935 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7936 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7938 if (signed_left == signed_right)
7939 return rank_left >= rank_right ? type_left : type_right;
7943 atomic_type_kind_t s_akind;
7944 atomic_type_kind_t u_akind;
7949 u_type = type_right;
7951 s_type = type_right;
7954 s_akind = get_akind(s_type);
7955 u_akind = get_akind(u_type);
7956 s_rank = get_akind_rank(s_akind);
7957 u_rank = get_akind_rank(u_akind);
7959 if (u_rank >= s_rank)
7962 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7966 case ATOMIC_TYPE_INT: return type_unsigned_int;
7967 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7968 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7970 default: panic("invalid atomic type");
7975 * Check the semantic restrictions for a binary expression.
7977 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7979 expression_t *const left = expression->left;
7980 expression_t *const right = expression->right;
7981 type_t *const orig_type_left = left->base.type;
7982 type_t *const orig_type_right = right->base.type;
7983 type_t *const type_left = skip_typeref(orig_type_left);
7984 type_t *const type_right = skip_typeref(orig_type_right);
7986 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7987 /* TODO: improve error message */
7988 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7989 errorf(&expression->base.source_position,
7990 "operation needs arithmetic types");
7995 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7996 expression->left = create_implicit_cast(left, arithmetic_type);
7997 expression->right = create_implicit_cast(right, arithmetic_type);
7998 expression->base.type = arithmetic_type;
8001 static void semantic_binexpr_integer(binary_expression_t *const expression)
8003 expression_t *const left = expression->left;
8004 expression_t *const right = expression->right;
8005 type_t *const orig_type_left = left->base.type;
8006 type_t *const orig_type_right = right->base.type;
8007 type_t *const type_left = skip_typeref(orig_type_left);
8008 type_t *const type_right = skip_typeref(orig_type_right);
8010 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8011 /* TODO: improve error message */
8012 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8013 errorf(&expression->base.source_position,
8014 "operation needs integer types");
8019 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8020 expression->left = create_implicit_cast(left, result_type);
8021 expression->right = create_implicit_cast(right, result_type);
8022 expression->base.type = result_type;
8025 static void warn_div_by_zero(binary_expression_t const *const expression)
8027 if (!is_type_integer(expression->base.type))
8030 expression_t const *const right = expression->right;
8031 /* The type of the right operand can be different for /= */
8032 if (is_type_integer(right->base.type) &&
8033 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8034 !fold_constant_to_bool(right)) {
8035 source_position_t const *const pos = &expression->base.source_position;
8036 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8041 * Check the semantic restrictions for a div/mod expression.
8043 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8045 semantic_binexpr_arithmetic(expression);
8046 warn_div_by_zero(expression);
8049 static void warn_addsub_in_shift(const expression_t *const expr)
8051 if (expr->base.parenthesized)
8055 switch (expr->kind) {
8056 case EXPR_BINARY_ADD: op = '+'; break;
8057 case EXPR_BINARY_SUB: op = '-'; break;
8061 source_position_t const *const pos = &expr->base.source_position;
8062 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8065 static bool semantic_shift(binary_expression_t *expression)
8067 expression_t *const left = expression->left;
8068 expression_t *const right = expression->right;
8069 type_t *const orig_type_left = left->base.type;
8070 type_t *const orig_type_right = right->base.type;
8071 type_t * type_left = skip_typeref(orig_type_left);
8072 type_t * type_right = skip_typeref(orig_type_right);
8074 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8075 /* TODO: improve error message */
8076 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8077 errorf(&expression->base.source_position,
8078 "operands of shift operation must have integer types");
8083 type_left = promote_integer(type_left);
8085 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8086 source_position_t const *const pos = &right->base.source_position;
8087 long const count = fold_constant_to_int(right);
8089 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8090 } else if ((unsigned long)count >=
8091 get_atomic_type_size(type_left->atomic.akind) * 8) {
8092 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8096 type_right = promote_integer(type_right);
8097 expression->right = create_implicit_cast(right, type_right);
8102 static void semantic_shift_op(binary_expression_t *expression)
8104 expression_t *const left = expression->left;
8105 expression_t *const right = expression->right;
8107 if (!semantic_shift(expression))
8110 warn_addsub_in_shift(left);
8111 warn_addsub_in_shift(right);
8113 type_t *const orig_type_left = left->base.type;
8114 type_t * type_left = skip_typeref(orig_type_left);
8116 type_left = promote_integer(type_left);
8117 expression->left = create_implicit_cast(left, type_left);
8118 expression->base.type = type_left;
8121 static void semantic_add(binary_expression_t *expression)
8123 expression_t *const left = expression->left;
8124 expression_t *const right = expression->right;
8125 type_t *const orig_type_left = left->base.type;
8126 type_t *const orig_type_right = right->base.type;
8127 type_t *const type_left = skip_typeref(orig_type_left);
8128 type_t *const type_right = skip_typeref(orig_type_right);
8131 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8132 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8133 expression->left = create_implicit_cast(left, arithmetic_type);
8134 expression->right = create_implicit_cast(right, arithmetic_type);
8135 expression->base.type = arithmetic_type;
8136 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8137 check_pointer_arithmetic(&expression->base.source_position,
8138 type_left, orig_type_left);
8139 expression->base.type = type_left;
8140 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8141 check_pointer_arithmetic(&expression->base.source_position,
8142 type_right, orig_type_right);
8143 expression->base.type = type_right;
8144 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8145 errorf(&expression->base.source_position,
8146 "invalid operands to binary + ('%T', '%T')",
8147 orig_type_left, orig_type_right);
8151 static void semantic_sub(binary_expression_t *expression)
8153 expression_t *const left = expression->left;
8154 expression_t *const right = expression->right;
8155 type_t *const orig_type_left = left->base.type;
8156 type_t *const orig_type_right = right->base.type;
8157 type_t *const type_left = skip_typeref(orig_type_left);
8158 type_t *const type_right = skip_typeref(orig_type_right);
8159 source_position_t const *const pos = &expression->base.source_position;
8162 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8163 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8164 expression->left = create_implicit_cast(left, arithmetic_type);
8165 expression->right = create_implicit_cast(right, arithmetic_type);
8166 expression->base.type = arithmetic_type;
8167 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8168 check_pointer_arithmetic(&expression->base.source_position,
8169 type_left, orig_type_left);
8170 expression->base.type = type_left;
8171 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8172 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8173 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8174 if (!types_compatible(unqual_left, unqual_right)) {
8176 "subtracting pointers to incompatible types '%T' and '%T'",
8177 orig_type_left, orig_type_right);
8178 } else if (!is_type_object(unqual_left)) {
8179 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8180 errorf(pos, "subtracting pointers to non-object types '%T'",
8183 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8186 expression->base.type = type_ptrdiff_t;
8187 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8188 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8189 orig_type_left, orig_type_right);
8193 static void warn_string_literal_address(expression_t const* expr)
8195 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8196 expr = expr->unary.value;
8197 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8199 expr = expr->unary.value;
8202 if (expr->kind == EXPR_STRING_LITERAL
8203 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8204 source_position_t const *const pos = &expr->base.source_position;
8205 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8209 static bool maybe_negative(expression_t const *const expr)
8211 switch (is_constant_expression(expr)) {
8212 case EXPR_CLASS_ERROR: return false;
8213 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8214 default: return true;
8218 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8220 warn_string_literal_address(expr);
8222 expression_t const* const ref = get_reference_address(expr);
8223 if (ref != NULL && is_null_pointer_constant(other)) {
8224 entity_t const *const ent = ref->reference.entity;
8225 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8228 if (!expr->base.parenthesized) {
8229 switch (expr->base.kind) {
8230 case EXPR_BINARY_LESS:
8231 case EXPR_BINARY_GREATER:
8232 case EXPR_BINARY_LESSEQUAL:
8233 case EXPR_BINARY_GREATEREQUAL:
8234 case EXPR_BINARY_NOTEQUAL:
8235 case EXPR_BINARY_EQUAL:
8236 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8245 * Check the semantics of comparison expressions.
8247 * @param expression The expression to check.
8249 static void semantic_comparison(binary_expression_t *expression)
8251 source_position_t const *const pos = &expression->base.source_position;
8252 expression_t *const left = expression->left;
8253 expression_t *const right = expression->right;
8255 warn_comparison(pos, left, right);
8256 warn_comparison(pos, right, left);
8258 type_t *orig_type_left = left->base.type;
8259 type_t *orig_type_right = right->base.type;
8260 type_t *type_left = skip_typeref(orig_type_left);
8261 type_t *type_right = skip_typeref(orig_type_right);
8263 /* TODO non-arithmetic types */
8264 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8265 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8267 /* test for signed vs unsigned compares */
8268 if (is_type_integer(arithmetic_type)) {
8269 bool const signed_left = is_type_signed(type_left);
8270 bool const signed_right = is_type_signed(type_right);
8271 if (signed_left != signed_right) {
8272 /* FIXME long long needs better const folding magic */
8273 /* TODO check whether constant value can be represented by other type */
8274 if ((signed_left && maybe_negative(left)) ||
8275 (signed_right && maybe_negative(right))) {
8276 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8281 expression->left = create_implicit_cast(left, arithmetic_type);
8282 expression->right = create_implicit_cast(right, arithmetic_type);
8283 expression->base.type = arithmetic_type;
8284 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8285 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8286 is_type_float(arithmetic_type)) {
8287 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8289 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8290 /* TODO check compatibility */
8291 } else if (is_type_pointer(type_left)) {
8292 expression->right = create_implicit_cast(right, type_left);
8293 } else if (is_type_pointer(type_right)) {
8294 expression->left = create_implicit_cast(left, type_right);
8295 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8296 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8298 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8302 * Checks if a compound type has constant fields.
8304 static bool has_const_fields(const compound_type_t *type)
8306 compound_t *compound = type->compound;
8307 entity_t *entry = compound->members.entities;
8309 for (; entry != NULL; entry = entry->base.next) {
8310 if (!is_declaration(entry))
8313 const type_t *decl_type = skip_typeref(entry->declaration.type);
8314 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8321 static bool is_valid_assignment_lhs(expression_t const* const left)
8323 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8324 type_t *const type_left = skip_typeref(orig_type_left);
8326 if (!is_lvalue(left)) {
8327 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8332 if (left->kind == EXPR_REFERENCE
8333 && left->reference.entity->kind == ENTITY_FUNCTION) {
8334 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8338 if (is_type_array(type_left)) {
8339 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8342 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8343 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8347 if (is_type_incomplete(type_left)) {
8348 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8349 left, orig_type_left);
8352 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8353 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8354 left, orig_type_left);
8361 static void semantic_arithmetic_assign(binary_expression_t *expression)
8363 expression_t *left = expression->left;
8364 expression_t *right = expression->right;
8365 type_t *orig_type_left = left->base.type;
8366 type_t *orig_type_right = right->base.type;
8368 if (!is_valid_assignment_lhs(left))
8371 type_t *type_left = skip_typeref(orig_type_left);
8372 type_t *type_right = skip_typeref(orig_type_right);
8374 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8375 /* TODO: improve error message */
8376 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8377 errorf(&expression->base.source_position,
8378 "operation needs arithmetic types");
8383 /* combined instructions are tricky. We can't create an implicit cast on
8384 * the left side, because we need the uncasted form for the store.
8385 * The ast2firm pass has to know that left_type must be right_type
8386 * for the arithmetic operation and create a cast by itself */
8387 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8388 expression->right = create_implicit_cast(right, arithmetic_type);
8389 expression->base.type = type_left;
8392 static void semantic_divmod_assign(binary_expression_t *expression)
8394 semantic_arithmetic_assign(expression);
8395 warn_div_by_zero(expression);
8398 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8400 expression_t *const left = expression->left;
8401 expression_t *const right = expression->right;
8402 type_t *const orig_type_left = left->base.type;
8403 type_t *const orig_type_right = right->base.type;
8404 type_t *const type_left = skip_typeref(orig_type_left);
8405 type_t *const type_right = skip_typeref(orig_type_right);
8407 if (!is_valid_assignment_lhs(left))
8410 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8411 /* combined instructions are tricky. We can't create an implicit cast on
8412 * the left side, because we need the uncasted form for the store.
8413 * The ast2firm pass has to know that left_type must be right_type
8414 * for the arithmetic operation and create a cast by itself */
8415 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8416 expression->right = create_implicit_cast(right, arithmetic_type);
8417 expression->base.type = type_left;
8418 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8419 check_pointer_arithmetic(&expression->base.source_position,
8420 type_left, orig_type_left);
8421 expression->base.type = type_left;
8422 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8423 errorf(&expression->base.source_position,
8424 "incompatible types '%T' and '%T' in assignment",
8425 orig_type_left, orig_type_right);
8429 static void semantic_integer_assign(binary_expression_t *expression)
8431 expression_t *left = expression->left;
8432 expression_t *right = expression->right;
8433 type_t *orig_type_left = left->base.type;
8434 type_t *orig_type_right = right->base.type;
8436 if (!is_valid_assignment_lhs(left))
8439 type_t *type_left = skip_typeref(orig_type_left);
8440 type_t *type_right = skip_typeref(orig_type_right);
8442 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8443 /* TODO: improve error message */
8444 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8445 errorf(&expression->base.source_position,
8446 "operation needs integer types");
8451 /* combined instructions are tricky. We can't create an implicit cast on
8452 * the left side, because we need the uncasted form for the store.
8453 * The ast2firm pass has to know that left_type must be right_type
8454 * for the arithmetic operation and create a cast by itself */
8455 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8456 expression->right = create_implicit_cast(right, arithmetic_type);
8457 expression->base.type = type_left;
8460 static void semantic_shift_assign(binary_expression_t *expression)
8462 expression_t *left = expression->left;
8464 if (!is_valid_assignment_lhs(left))
8467 if (!semantic_shift(expression))
8470 expression->base.type = skip_typeref(left->base.type);
8473 static void warn_logical_and_within_or(const expression_t *const expr)
8475 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8477 if (expr->base.parenthesized)
8479 source_position_t const *const pos = &expr->base.source_position;
8480 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8484 * Check the semantic restrictions of a logical expression.
8486 static void semantic_logical_op(binary_expression_t *expression)
8488 /* §6.5.13:2 Each of the operands shall have scalar type.
8489 * §6.5.14:2 Each of the operands shall have scalar type. */
8490 semantic_condition(expression->left, "left operand of logical operator");
8491 semantic_condition(expression->right, "right operand of logical operator");
8492 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8493 warn_logical_and_within_or(expression->left);
8494 warn_logical_and_within_or(expression->right);
8496 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8500 * Check the semantic restrictions of a binary assign expression.
8502 static void semantic_binexpr_assign(binary_expression_t *expression)
8504 expression_t *left = expression->left;
8505 type_t *orig_type_left = left->base.type;
8507 if (!is_valid_assignment_lhs(left))
8510 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8511 report_assign_error(error, orig_type_left, expression->right,
8512 "assignment", &left->base.source_position);
8513 expression->right = create_implicit_cast(expression->right, orig_type_left);
8514 expression->base.type = orig_type_left;
8518 * Determine if the outermost operation (or parts thereof) of the given
8519 * expression has no effect in order to generate a warning about this fact.
8520 * Therefore in some cases this only examines some of the operands of the
8521 * expression (see comments in the function and examples below).
8523 * f() + 23; // warning, because + has no effect
8524 * x || f(); // no warning, because x controls execution of f()
8525 * x ? y : f(); // warning, because y has no effect
8526 * (void)x; // no warning to be able to suppress the warning
8527 * This function can NOT be used for an "expression has definitely no effect"-
8529 static bool expression_has_effect(const expression_t *const expr)
8531 switch (expr->kind) {
8532 case EXPR_ERROR: return true; /* do NOT warn */
8533 case EXPR_REFERENCE: return false;
8534 case EXPR_REFERENCE_ENUM_VALUE: return false;
8535 case EXPR_LABEL_ADDRESS: return false;
8537 /* suppress the warning for microsoft __noop operations */
8538 case EXPR_LITERAL_MS_NOOP: return true;
8539 case EXPR_LITERAL_BOOLEAN:
8540 case EXPR_LITERAL_CHARACTER:
8541 case EXPR_LITERAL_WIDE_CHARACTER:
8542 case EXPR_LITERAL_INTEGER:
8543 case EXPR_LITERAL_INTEGER_OCTAL:
8544 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8545 case EXPR_LITERAL_FLOATINGPOINT:
8546 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8547 case EXPR_STRING_LITERAL: return false;
8548 case EXPR_WIDE_STRING_LITERAL: return false;
8551 const call_expression_t *const call = &expr->call;
8552 if (call->function->kind != EXPR_REFERENCE)
8555 switch (call->function->reference.entity->function.btk) {
8556 /* FIXME: which builtins have no effect? */
8557 default: return true;
8561 /* Generate the warning if either the left or right hand side of a
8562 * conditional expression has no effect */
8563 case EXPR_CONDITIONAL: {
8564 conditional_expression_t const *const cond = &expr->conditional;
8565 expression_t const *const t = cond->true_expression;
8567 (t == NULL || expression_has_effect(t)) &&
8568 expression_has_effect(cond->false_expression);
8571 case EXPR_SELECT: return false;
8572 case EXPR_ARRAY_ACCESS: return false;
8573 case EXPR_SIZEOF: return false;
8574 case EXPR_CLASSIFY_TYPE: return false;
8575 case EXPR_ALIGNOF: return false;
8577 case EXPR_FUNCNAME: return false;
8578 case EXPR_BUILTIN_CONSTANT_P: return false;
8579 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8580 case EXPR_OFFSETOF: return false;
8581 case EXPR_VA_START: return true;
8582 case EXPR_VA_ARG: return true;
8583 case EXPR_VA_COPY: return true;
8584 case EXPR_STATEMENT: return true; // TODO
8585 case EXPR_COMPOUND_LITERAL: return false;
8587 case EXPR_UNARY_NEGATE: return false;
8588 case EXPR_UNARY_PLUS: return false;
8589 case EXPR_UNARY_BITWISE_NEGATE: return false;
8590 case EXPR_UNARY_NOT: return false;
8591 case EXPR_UNARY_DEREFERENCE: return false;
8592 case EXPR_UNARY_TAKE_ADDRESS: return false;
8593 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8594 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8595 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8596 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8598 /* Treat void casts as if they have an effect in order to being able to
8599 * suppress the warning */
8600 case EXPR_UNARY_CAST: {
8601 type_t *const type = skip_typeref(expr->base.type);
8602 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8605 case EXPR_UNARY_ASSUME: return true;
8606 case EXPR_UNARY_DELETE: return true;
8607 case EXPR_UNARY_DELETE_ARRAY: return true;
8608 case EXPR_UNARY_THROW: return true;
8610 case EXPR_BINARY_ADD: return false;
8611 case EXPR_BINARY_SUB: return false;
8612 case EXPR_BINARY_MUL: return false;
8613 case EXPR_BINARY_DIV: return false;
8614 case EXPR_BINARY_MOD: return false;
8615 case EXPR_BINARY_EQUAL: return false;
8616 case EXPR_BINARY_NOTEQUAL: return false;
8617 case EXPR_BINARY_LESS: return false;
8618 case EXPR_BINARY_LESSEQUAL: return false;
8619 case EXPR_BINARY_GREATER: return false;
8620 case EXPR_BINARY_GREATEREQUAL: return false;
8621 case EXPR_BINARY_BITWISE_AND: return false;
8622 case EXPR_BINARY_BITWISE_OR: return false;
8623 case EXPR_BINARY_BITWISE_XOR: return false;
8624 case EXPR_BINARY_SHIFTLEFT: return false;
8625 case EXPR_BINARY_SHIFTRIGHT: return false;
8626 case EXPR_BINARY_ASSIGN: return true;
8627 case EXPR_BINARY_MUL_ASSIGN: return true;
8628 case EXPR_BINARY_DIV_ASSIGN: return true;
8629 case EXPR_BINARY_MOD_ASSIGN: return true;
8630 case EXPR_BINARY_ADD_ASSIGN: return true;
8631 case EXPR_BINARY_SUB_ASSIGN: return true;
8632 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8633 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8634 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8635 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8636 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8638 /* Only examine the right hand side of && and ||, because the left hand
8639 * side already has the effect of controlling the execution of the right
8641 case EXPR_BINARY_LOGICAL_AND:
8642 case EXPR_BINARY_LOGICAL_OR:
8643 /* Only examine the right hand side of a comma expression, because the left
8644 * hand side has a separate warning */
8645 case EXPR_BINARY_COMMA:
8646 return expression_has_effect(expr->binary.right);
8648 case EXPR_BINARY_ISGREATER: return false;
8649 case EXPR_BINARY_ISGREATEREQUAL: return false;
8650 case EXPR_BINARY_ISLESS: return false;
8651 case EXPR_BINARY_ISLESSEQUAL: return false;
8652 case EXPR_BINARY_ISLESSGREATER: return false;
8653 case EXPR_BINARY_ISUNORDERED: return false;
8656 internal_errorf(HERE, "unexpected expression");
8659 static void semantic_comma(binary_expression_t *expression)
8661 const expression_t *const left = expression->left;
8662 if (!expression_has_effect(left)) {
8663 source_position_t const *const pos = &left->base.source_position;
8664 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8666 expression->base.type = expression->right->base.type;
8670 * @param prec_r precedence of the right operand
8672 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8673 static expression_t *parse_##binexpression_type(expression_t *left) \
8675 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8676 binexpr->binary.left = left; \
8679 expression_t *right = parse_subexpression(prec_r); \
8681 binexpr->binary.right = right; \
8682 sfunc(&binexpr->binary); \
8687 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8688 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8689 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8690 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8691 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8692 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8693 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8694 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8695 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8696 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8697 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8698 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8699 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8700 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8701 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8702 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8703 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8704 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8705 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8706 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8707 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8708 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8709 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8710 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8711 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8712 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8713 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8714 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8715 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8716 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8719 static expression_t *parse_subexpression(precedence_t precedence)
8721 if (token.kind < 0) {
8722 return expected_expression_error();
8725 expression_parser_function_t *parser
8726 = &expression_parsers[token.kind];
8729 if (parser->parser != NULL) {
8730 left = parser->parser();
8732 left = parse_primary_expression();
8734 assert(left != NULL);
8737 if (token.kind < 0) {
8738 return expected_expression_error();
8741 parser = &expression_parsers[token.kind];
8742 if (parser->infix_parser == NULL)
8744 if (parser->infix_precedence < precedence)
8747 left = parser->infix_parser(left);
8749 assert(left != NULL);
8756 * Parse an expression.
8758 static expression_t *parse_expression(void)
8760 return parse_subexpression(PREC_EXPRESSION);
8764 * Register a parser for a prefix-like operator.
8766 * @param parser the parser function
8767 * @param token_kind the token type of the prefix token
8769 static void register_expression_parser(parse_expression_function parser,
8772 expression_parser_function_t *entry = &expression_parsers[token_kind];
8774 if (entry->parser != NULL) {
8775 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8776 panic("trying to register multiple expression parsers for a token");
8778 entry->parser = parser;
8782 * Register a parser for an infix operator with given precedence.
8784 * @param parser the parser function
8785 * @param token_kind the token type of the infix operator
8786 * @param precedence the precedence of the operator
8788 static void register_infix_parser(parse_expression_infix_function parser,
8789 int token_kind, precedence_t precedence)
8791 expression_parser_function_t *entry = &expression_parsers[token_kind];
8793 if (entry->infix_parser != NULL) {
8794 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8795 panic("trying to register multiple infix expression parsers for a "
8798 entry->infix_parser = parser;
8799 entry->infix_precedence = precedence;
8803 * Initialize the expression parsers.
8805 static void init_expression_parsers(void)
8807 memset(&expression_parsers, 0, sizeof(expression_parsers));
8809 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8810 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8811 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8812 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8813 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8814 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8815 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8816 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8817 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8818 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8819 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8820 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8821 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8822 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8823 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8824 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8825 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8826 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8827 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8828 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8829 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8830 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8831 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8832 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8833 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8834 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8835 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8836 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8837 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8838 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8839 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8840 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8841 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8842 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8843 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8844 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8845 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8847 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8848 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8849 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8850 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8851 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8852 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8853 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8854 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8855 register_expression_parser(parse_sizeof, T_sizeof);
8856 register_expression_parser(parse_alignof, T___alignof__);
8857 register_expression_parser(parse_extension, T___extension__);
8858 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8859 register_expression_parser(parse_delete, T_delete);
8860 register_expression_parser(parse_throw, T_throw);
8864 * Parse a asm statement arguments specification.
8866 static asm_argument_t *parse_asm_arguments(bool is_out)
8868 asm_argument_t *result = NULL;
8869 asm_argument_t **anchor = &result;
8871 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8872 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8873 memset(argument, 0, sizeof(argument[0]));
8876 if (token.kind != T_IDENTIFIER) {
8877 parse_error_expected("while parsing asm argument",
8878 T_IDENTIFIER, NULL);
8881 argument->symbol = token.identifier.symbol;
8883 expect(']', end_error);
8886 argument->constraints = parse_string_literals();
8887 expect('(', end_error);
8888 add_anchor_token(')');
8889 expression_t *expression = parse_expression();
8890 rem_anchor_token(')');
8892 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8893 * change size or type representation (e.g. int -> long is ok, but
8894 * int -> float is not) */
8895 if (expression->kind == EXPR_UNARY_CAST) {
8896 type_t *const type = expression->base.type;
8897 type_kind_t const kind = type->kind;
8898 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8901 if (kind == TYPE_ATOMIC) {
8902 atomic_type_kind_t const akind = type->atomic.akind;
8903 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8904 size = get_atomic_type_size(akind);
8906 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8907 size = get_type_size(type_void_ptr);
8911 expression_t *const value = expression->unary.value;
8912 type_t *const value_type = value->base.type;
8913 type_kind_t const value_kind = value_type->kind;
8915 unsigned value_flags;
8916 unsigned value_size;
8917 if (value_kind == TYPE_ATOMIC) {
8918 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8919 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8920 value_size = get_atomic_type_size(value_akind);
8921 } else if (value_kind == TYPE_POINTER) {
8922 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8923 value_size = get_type_size(type_void_ptr);
8928 if (value_flags != flags || value_size != size)
8932 } while (expression->kind == EXPR_UNARY_CAST);
8936 if (!is_lvalue(expression)) {
8937 errorf(&expression->base.source_position,
8938 "asm output argument is not an lvalue");
8941 if (argument->constraints.begin[0] == '=')
8942 determine_lhs_ent(expression, NULL);
8944 mark_vars_read(expression, NULL);
8946 mark_vars_read(expression, NULL);
8948 argument->expression = expression;
8949 expect(')', end_error);
8951 set_address_taken(expression, true);
8954 anchor = &argument->next;
8966 * Parse a asm statement clobber specification.
8968 static asm_clobber_t *parse_asm_clobbers(void)
8970 asm_clobber_t *result = NULL;
8971 asm_clobber_t **anchor = &result;
8973 while (token.kind == T_STRING_LITERAL) {
8974 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8975 clobber->clobber = parse_string_literals();
8978 anchor = &clobber->next;
8988 * Parse an asm statement.
8990 static statement_t *parse_asm_statement(void)
8992 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8993 asm_statement_t *asm_statement = &statement->asms;
8997 if (next_if(T_volatile))
8998 asm_statement->is_volatile = true;
9000 expect('(', end_error);
9001 add_anchor_token(')');
9002 if (token.kind != T_STRING_LITERAL) {
9003 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9006 asm_statement->asm_text = parse_string_literals();
9008 add_anchor_token(':');
9009 if (!next_if(':')) {
9010 rem_anchor_token(':');
9014 asm_statement->outputs = parse_asm_arguments(true);
9015 if (!next_if(':')) {
9016 rem_anchor_token(':');
9020 asm_statement->inputs = parse_asm_arguments(false);
9021 if (!next_if(':')) {
9022 rem_anchor_token(':');
9025 rem_anchor_token(':');
9027 asm_statement->clobbers = parse_asm_clobbers();
9030 rem_anchor_token(')');
9031 expect(')', end_error);
9032 expect(';', end_error);
9034 if (asm_statement->outputs == NULL) {
9035 /* GCC: An 'asm' instruction without any output operands will be treated
9036 * identically to a volatile 'asm' instruction. */
9037 asm_statement->is_volatile = true;
9042 return create_error_statement();
9045 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9047 statement_t *inner_stmt;
9048 switch (token.kind) {
9050 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9051 inner_stmt = create_error_statement();
9055 if (label->kind == STATEMENT_LABEL) {
9056 /* Eat an empty statement here, to avoid the warning about an empty
9057 * statement after a label. label:; is commonly used to have a label
9058 * before a closing brace. */
9059 inner_stmt = create_empty_statement();
9066 inner_stmt = parse_statement();
9067 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9068 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9069 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9070 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9078 * Parse a case statement.
9080 static statement_t *parse_case_statement(void)
9082 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9083 source_position_t *const pos = &statement->base.source_position;
9087 expression_t *const expression = parse_expression();
9088 statement->case_label.expression = expression;
9089 expression_classification_t const expr_class = is_constant_expression(expression);
9090 if (expr_class != EXPR_CLASS_CONSTANT) {
9091 if (expr_class != EXPR_CLASS_ERROR) {
9092 errorf(pos, "case label does not reduce to an integer constant");
9094 statement->case_label.is_bad = true;
9096 long const val = fold_constant_to_int(expression);
9097 statement->case_label.first_case = val;
9098 statement->case_label.last_case = val;
9102 if (next_if(T_DOTDOTDOT)) {
9103 expression_t *const end_range = parse_expression();
9104 statement->case_label.end_range = end_range;
9105 expression_classification_t const end_class = is_constant_expression(end_range);
9106 if (end_class != EXPR_CLASS_CONSTANT) {
9107 if (end_class != EXPR_CLASS_ERROR) {
9108 errorf(pos, "case range does not reduce to an integer constant");
9110 statement->case_label.is_bad = true;
9112 long const val = fold_constant_to_int(end_range);
9113 statement->case_label.last_case = val;
9115 if (val < statement->case_label.first_case) {
9116 statement->case_label.is_empty_range = true;
9117 warningf(WARN_OTHER, pos, "empty range specified");
9123 PUSH_PARENT(statement);
9125 expect(':', end_error);
9128 if (current_switch != NULL) {
9129 if (! statement->case_label.is_bad) {
9130 /* Check for duplicate case values */
9131 case_label_statement_t *c = &statement->case_label;
9132 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9133 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9136 if (c->last_case < l->first_case || c->first_case > l->last_case)
9139 errorf(pos, "duplicate case value (previously used %P)",
9140 &l->base.source_position);
9144 /* link all cases into the switch statement */
9145 if (current_switch->last_case == NULL) {
9146 current_switch->first_case = &statement->case_label;
9148 current_switch->last_case->next = &statement->case_label;
9150 current_switch->last_case = &statement->case_label;
9152 errorf(pos, "case label not within a switch statement");
9155 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9162 * Parse a default statement.
9164 static statement_t *parse_default_statement(void)
9166 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9170 PUSH_PARENT(statement);
9172 expect(':', end_error);
9175 if (current_switch != NULL) {
9176 const case_label_statement_t *def_label = current_switch->default_label;
9177 if (def_label != NULL) {
9178 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9180 current_switch->default_label = &statement->case_label;
9182 /* link all cases into the switch statement */
9183 if (current_switch->last_case == NULL) {
9184 current_switch->first_case = &statement->case_label;
9186 current_switch->last_case->next = &statement->case_label;
9188 current_switch->last_case = &statement->case_label;
9191 errorf(&statement->base.source_position,
9192 "'default' label not within a switch statement");
9195 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9202 * Parse a label statement.
9204 static statement_t *parse_label_statement(void)
9206 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9207 label_t *const label = get_label();
9208 statement->label.label = label;
9210 PUSH_PARENT(statement);
9212 /* if statement is already set then the label is defined twice,
9213 * otherwise it was just mentioned in a goto/local label declaration so far
9215 source_position_t const* const pos = &statement->base.source_position;
9216 if (label->statement != NULL) {
9217 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9219 label->base.source_position = *pos;
9220 label->statement = statement;
9225 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9226 parse_attributes(NULL); // TODO process attributes
9229 statement->label.statement = parse_label_inner_statement(statement, "label");
9231 /* remember the labels in a list for later checking */
9232 *label_anchor = &statement->label;
9233 label_anchor = &statement->label.next;
9239 static statement_t *parse_inner_statement(void)
9241 statement_t *const stmt = parse_statement();
9242 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9243 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9244 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9245 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9251 * Parse an if statement.
9253 static statement_t *parse_if(void)
9255 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9259 PUSH_PARENT(statement);
9261 add_anchor_token('{');
9263 expect('(', end_error);
9264 add_anchor_token(')');
9265 expression_t *const expr = parse_expression();
9266 statement->ifs.condition = expr;
9267 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9269 semantic_condition(expr, "condition of 'if'-statment");
9270 mark_vars_read(expr, NULL);
9271 rem_anchor_token(')');
9272 expect(')', end_error);
9275 rem_anchor_token('{');
9277 add_anchor_token(T_else);
9278 statement_t *const true_stmt = parse_inner_statement();
9279 statement->ifs.true_statement = true_stmt;
9280 rem_anchor_token(T_else);
9282 if (true_stmt->kind == STATEMENT_EMPTY) {
9283 warningf(WARN_EMPTY_BODY, HERE,
9284 "suggest braces around empty body in an ‘if’ statement");
9287 if (next_if(T_else)) {
9288 statement->ifs.false_statement = parse_inner_statement();
9290 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9291 warningf(WARN_EMPTY_BODY, HERE,
9292 "suggest braces around empty body in an ‘if’ statement");
9294 } else if (true_stmt->kind == STATEMENT_IF &&
9295 true_stmt->ifs.false_statement != NULL) {
9296 source_position_t const *const pos = &true_stmt->base.source_position;
9297 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9305 * Check that all enums are handled in a switch.
9307 * @param statement the switch statement to check
9309 static void check_enum_cases(const switch_statement_t *statement)
9311 if (!is_warn_on(WARN_SWITCH_ENUM))
9313 const type_t *type = skip_typeref(statement->expression->base.type);
9314 if (! is_type_enum(type))
9316 const enum_type_t *enumt = &type->enumt;
9318 /* if we have a default, no warnings */
9319 if (statement->default_label != NULL)
9322 /* FIXME: calculation of value should be done while parsing */
9323 /* TODO: quadratic algorithm here. Change to an n log n one */
9324 long last_value = -1;
9325 const entity_t *entry = enumt->enume->base.next;
9326 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9327 entry = entry->base.next) {
9328 const expression_t *expression = entry->enum_value.value;
9329 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9331 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9332 if (l->expression == NULL)
9334 if (l->first_case <= value && value <= l->last_case) {
9340 source_position_t const *const pos = &statement->base.source_position;
9341 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9348 * Parse a switch statement.
9350 static statement_t *parse_switch(void)
9352 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9356 PUSH_PARENT(statement);
9358 expect('(', end_error);
9359 add_anchor_token(')');
9360 expression_t *const expr = parse_expression();
9361 mark_vars_read(expr, NULL);
9362 type_t * type = skip_typeref(expr->base.type);
9363 if (is_type_integer(type)) {
9364 type = promote_integer(type);
9365 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9366 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9368 } else if (is_type_valid(type)) {
9369 errorf(&expr->base.source_position,
9370 "switch quantity is not an integer, but '%T'", type);
9371 type = type_error_type;
9373 statement->switchs.expression = create_implicit_cast(expr, type);
9374 expect(')', end_error);
9375 rem_anchor_token(')');
9377 switch_statement_t *rem = current_switch;
9378 current_switch = &statement->switchs;
9379 statement->switchs.body = parse_inner_statement();
9380 current_switch = rem;
9382 if (statement->switchs.default_label == NULL) {
9383 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9385 check_enum_cases(&statement->switchs);
9391 return create_error_statement();
9394 static statement_t *parse_loop_body(statement_t *const loop)
9396 statement_t *const rem = current_loop;
9397 current_loop = loop;
9399 statement_t *const body = parse_inner_statement();
9406 * Parse a while statement.
9408 static statement_t *parse_while(void)
9410 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9414 PUSH_PARENT(statement);
9416 expect('(', end_error);
9417 add_anchor_token(')');
9418 expression_t *const cond = parse_expression();
9419 statement->whiles.condition = cond;
9420 /* §6.8.5:2 The controlling expression of an iteration statement shall
9421 * have scalar type. */
9422 semantic_condition(cond, "condition of 'while'-statement");
9423 mark_vars_read(cond, NULL);
9424 rem_anchor_token(')');
9425 expect(')', end_error);
9427 statement->whiles.body = parse_loop_body(statement);
9433 return create_error_statement();
9437 * Parse a do statement.
9439 static statement_t *parse_do(void)
9441 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9445 PUSH_PARENT(statement);
9447 add_anchor_token(T_while);
9448 statement->do_while.body = parse_loop_body(statement);
9449 rem_anchor_token(T_while);
9451 expect(T_while, end_error);
9452 expect('(', end_error);
9453 add_anchor_token(')');
9454 expression_t *const cond = parse_expression();
9455 statement->do_while.condition = cond;
9456 /* §6.8.5:2 The controlling expression of an iteration statement shall
9457 * have scalar type. */
9458 semantic_condition(cond, "condition of 'do-while'-statement");
9459 mark_vars_read(cond, NULL);
9460 rem_anchor_token(')');
9461 expect(')', end_error);
9462 expect(';', end_error);
9468 return create_error_statement();
9472 * Parse a for statement.
9474 static statement_t *parse_for(void)
9476 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9480 expect('(', end_error1);
9481 add_anchor_token(')');
9483 PUSH_PARENT(statement);
9484 PUSH_SCOPE(&statement->fors.scope);
9489 } else if (is_declaration_specifier(&token)) {
9490 parse_declaration(record_entity, DECL_FLAGS_NONE);
9492 add_anchor_token(';');
9493 expression_t *const init = parse_expression();
9494 statement->fors.initialisation = init;
9495 mark_vars_read(init, ENT_ANY);
9496 if (!expression_has_effect(init)) {
9497 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9499 rem_anchor_token(';');
9500 expect(';', end_error2);
9505 if (token.kind != ';') {
9506 add_anchor_token(';');
9507 expression_t *const cond = parse_expression();
9508 statement->fors.condition = cond;
9509 /* §6.8.5:2 The controlling expression of an iteration statement
9510 * shall have scalar type. */
9511 semantic_condition(cond, "condition of 'for'-statement");
9512 mark_vars_read(cond, NULL);
9513 rem_anchor_token(';');
9515 expect(';', end_error2);
9516 if (token.kind != ')') {
9517 expression_t *const step = parse_expression();
9518 statement->fors.step = step;
9519 mark_vars_read(step, ENT_ANY);
9520 if (!expression_has_effect(step)) {
9521 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9524 expect(')', end_error2);
9525 rem_anchor_token(')');
9526 statement->fors.body = parse_loop_body(statement);
9534 rem_anchor_token(')');
9539 return create_error_statement();
9543 * Parse a goto statement.
9545 static statement_t *parse_goto(void)
9547 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9550 if (GNU_MODE && next_if('*')) {
9551 expression_t *expression = parse_expression();
9552 mark_vars_read(expression, NULL);
9554 /* Argh: although documentation says the expression must be of type void*,
9555 * gcc accepts anything that can be casted into void* without error */
9556 type_t *type = expression->base.type;
9558 if (type != type_error_type) {
9559 if (!is_type_pointer(type) && !is_type_integer(type)) {
9560 errorf(&expression->base.source_position,
9561 "cannot convert to a pointer type");
9562 } else if (type != type_void_ptr) {
9563 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9565 expression = create_implicit_cast(expression, type_void_ptr);
9568 statement->gotos.expression = expression;
9569 } else if (token.kind == T_IDENTIFIER) {
9570 label_t *const label = get_label();
9572 statement->gotos.label = label;
9575 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9577 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9579 return create_error_statement();
9582 /* remember the goto's in a list for later checking */
9583 *goto_anchor = &statement->gotos;
9584 goto_anchor = &statement->gotos.next;
9586 expect(';', end_error);
9593 * Parse a continue statement.
9595 static statement_t *parse_continue(void)
9597 if (current_loop == NULL) {
9598 errorf(HERE, "continue statement not within loop");
9601 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9604 expect(';', end_error);
9611 * Parse a break statement.
9613 static statement_t *parse_break(void)
9615 if (current_switch == NULL && current_loop == NULL) {
9616 errorf(HERE, "break statement not within loop or switch");
9619 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9622 expect(';', end_error);
9629 * Parse a __leave statement.
9631 static statement_t *parse_leave_statement(void)
9633 if (current_try == NULL) {
9634 errorf(HERE, "__leave statement not within __try");
9637 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9640 expect(';', end_error);
9647 * Check if a given entity represents a local variable.
9649 static bool is_local_variable(const entity_t *entity)
9651 if (entity->kind != ENTITY_VARIABLE)
9654 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9655 case STORAGE_CLASS_AUTO:
9656 case STORAGE_CLASS_REGISTER: {
9657 const type_t *type = skip_typeref(entity->declaration.type);
9658 if (is_type_function(type)) {
9670 * Check if a given expression represents a local variable.
9672 static bool expression_is_local_variable(const expression_t *expression)
9674 if (expression->base.kind != EXPR_REFERENCE) {
9677 const entity_t *entity = expression->reference.entity;
9678 return is_local_variable(entity);
9682 * Check if a given expression represents a local variable and
9683 * return its declaration then, else return NULL.
9685 entity_t *expression_is_variable(const expression_t *expression)
9687 if (expression->base.kind != EXPR_REFERENCE) {
9690 entity_t *entity = expression->reference.entity;
9691 if (entity->kind != ENTITY_VARIABLE)
9698 * Parse a return statement.
9700 static statement_t *parse_return(void)
9702 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9705 expression_t *return_value = NULL;
9706 if (token.kind != ';') {
9707 return_value = parse_expression();
9708 mark_vars_read(return_value, NULL);
9711 const type_t *const func_type = skip_typeref(current_function->base.type);
9712 assert(is_type_function(func_type));
9713 type_t *const return_type = skip_typeref(func_type->function.return_type);
9715 source_position_t const *const pos = &statement->base.source_position;
9716 if (return_value != NULL) {
9717 type_t *return_value_type = skip_typeref(return_value->base.type);
9719 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9720 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9721 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9722 /* Only warn in C mode, because GCC does the same */
9723 if (c_mode & _CXX || strict_mode) {
9725 "'return' with a value, in function returning 'void'");
9727 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9729 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9730 /* Only warn in C mode, because GCC does the same */
9733 "'return' with expression in function returning 'void'");
9735 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9739 assign_error_t error = semantic_assign(return_type, return_value);
9740 report_assign_error(error, return_type, return_value, "'return'",
9743 return_value = create_implicit_cast(return_value, return_type);
9744 /* check for returning address of a local var */
9745 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9746 const expression_t *expression = return_value->unary.value;
9747 if (expression_is_local_variable(expression)) {
9748 warningf(WARN_OTHER, pos, "function returns address of local variable");
9751 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9752 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9753 if (c_mode & _CXX || strict_mode) {
9755 "'return' without value, in function returning non-void");
9757 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9760 statement->returns.value = return_value;
9762 expect(';', end_error);
9769 * Parse a declaration statement.
9771 static statement_t *parse_declaration_statement(void)
9773 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9775 entity_t *before = current_scope->last_entity;
9777 parse_external_declaration();
9779 parse_declaration(record_entity, DECL_FLAGS_NONE);
9782 declaration_statement_t *const decl = &statement->declaration;
9783 entity_t *const begin =
9784 before != NULL ? before->base.next : current_scope->entities;
9785 decl->declarations_begin = begin;
9786 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9792 * Parse an expression statement, ie. expr ';'.
9794 static statement_t *parse_expression_statement(void)
9796 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9798 expression_t *const expr = parse_expression();
9799 statement->expression.expression = expr;
9800 mark_vars_read(expr, ENT_ANY);
9802 expect(';', end_error);
9809 * Parse a microsoft __try { } __finally { } or
9810 * __try{ } __except() { }
9812 static statement_t *parse_ms_try_statment(void)
9814 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9817 PUSH_PARENT(statement);
9819 ms_try_statement_t *rem = current_try;
9820 current_try = &statement->ms_try;
9821 statement->ms_try.try_statement = parse_compound_statement(false);
9826 if (next_if(T___except)) {
9827 expect('(', end_error);
9828 add_anchor_token(')');
9829 expression_t *const expr = parse_expression();
9830 mark_vars_read(expr, NULL);
9831 type_t * type = skip_typeref(expr->base.type);
9832 if (is_type_integer(type)) {
9833 type = promote_integer(type);
9834 } else if (is_type_valid(type)) {
9835 errorf(&expr->base.source_position,
9836 "__expect expression is not an integer, but '%T'", type);
9837 type = type_error_type;
9839 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9840 rem_anchor_token(')');
9841 expect(')', end_error);
9842 statement->ms_try.final_statement = parse_compound_statement(false);
9843 } else if (next_if(T__finally)) {
9844 statement->ms_try.final_statement = parse_compound_statement(false);
9846 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9847 return create_error_statement();
9851 return create_error_statement();
9854 static statement_t *parse_empty_statement(void)
9856 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9857 statement_t *const statement = create_empty_statement();
9862 static statement_t *parse_local_label_declaration(void)
9864 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9868 entity_t *begin = NULL;
9869 entity_t *end = NULL;
9870 entity_t **anchor = &begin;
9872 if (token.kind != T_IDENTIFIER) {
9873 parse_error_expected("while parsing local label declaration",
9874 T_IDENTIFIER, NULL);
9877 symbol_t *symbol = token.identifier.symbol;
9878 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9879 if (entity != NULL && entity->base.parent_scope == current_scope) {
9880 source_position_t const *const ppos = &entity->base.source_position;
9881 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9883 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9884 entity->base.parent_scope = current_scope;
9885 entity->base.source_position = token.base.source_position;
9888 anchor = &entity->base.next;
9891 environment_push(entity);
9894 } while (next_if(','));
9895 expect(';', end_error);
9897 statement->declaration.declarations_begin = begin;
9898 statement->declaration.declarations_end = end;
9902 static void parse_namespace_definition(void)
9906 entity_t *entity = NULL;
9907 symbol_t *symbol = NULL;
9909 if (token.kind == T_IDENTIFIER) {
9910 symbol = token.identifier.symbol;
9913 entity = get_entity(symbol, NAMESPACE_NORMAL);
9915 && entity->kind != ENTITY_NAMESPACE
9916 && entity->base.parent_scope == current_scope) {
9917 if (is_entity_valid(entity)) {
9918 error_redefined_as_different_kind(&token.base.source_position,
9919 entity, ENTITY_NAMESPACE);
9925 if (entity == NULL) {
9926 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9927 entity->base.source_position = token.base.source_position;
9928 entity->base.parent_scope = current_scope;
9931 if (token.kind == '=') {
9932 /* TODO: parse namespace alias */
9933 panic("namespace alias definition not supported yet");
9936 environment_push(entity);
9937 append_entity(current_scope, entity);
9939 PUSH_SCOPE(&entity->namespacee.members);
9941 entity_t *old_current_entity = current_entity;
9942 current_entity = entity;
9944 expect('{', end_error);
9946 expect('}', end_error);
9949 assert(current_entity == entity);
9950 current_entity = old_current_entity;
9955 * Parse a statement.
9956 * There's also parse_statement() which additionally checks for
9957 * "statement has no effect" warnings
9959 static statement_t *intern_parse_statement(void)
9961 statement_t *statement = NULL;
9963 /* declaration or statement */
9964 add_anchor_token(';');
9965 switch (token.kind) {
9966 case T_IDENTIFIER: {
9967 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9968 if (la1_type == ':') {
9969 statement = parse_label_statement();
9970 } else if (is_typedef_symbol(token.identifier.symbol)) {
9971 statement = parse_declaration_statement();
9973 /* it's an identifier, the grammar says this must be an
9974 * expression statement. However it is common that users mistype
9975 * declaration types, so we guess a bit here to improve robustness
9976 * for incorrect programs */
9980 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9982 statement = parse_expression_statement();
9986 statement = parse_declaration_statement();
9994 case T___extension__: {
9995 /* This can be a prefix to a declaration or an expression statement.
9996 * We simply eat it now and parse the rest with tail recursion. */
9998 statement = intern_parse_statement();
10004 statement = parse_declaration_statement();
10008 statement = parse_local_label_declaration();
10011 case ';': statement = parse_empty_statement(); break;
10012 case '{': statement = parse_compound_statement(false); break;
10013 case T___leave: statement = parse_leave_statement(); break;
10014 case T___try: statement = parse_ms_try_statment(); break;
10015 case T_asm: statement = parse_asm_statement(); break;
10016 case T_break: statement = parse_break(); break;
10017 case T_case: statement = parse_case_statement(); break;
10018 case T_continue: statement = parse_continue(); break;
10019 case T_default: statement = parse_default_statement(); break;
10020 case T_do: statement = parse_do(); break;
10021 case T_for: statement = parse_for(); break;
10022 case T_goto: statement = parse_goto(); break;
10023 case T_if: statement = parse_if(); break;
10024 case T_return: statement = parse_return(); break;
10025 case T_switch: statement = parse_switch(); break;
10026 case T_while: statement = parse_while(); break;
10029 statement = parse_expression_statement();
10033 errorf(HERE, "unexpected token %K while parsing statement", &token);
10034 statement = create_error_statement();
10039 rem_anchor_token(';');
10041 assert(statement != NULL
10042 && statement->base.source_position.input_name != NULL);
10048 * parse a statement and emits "statement has no effect" warning if needed
10049 * (This is really a wrapper around intern_parse_statement with check for 1
10050 * single warning. It is needed, because for statement expressions we have
10051 * to avoid the warning on the last statement)
10053 static statement_t *parse_statement(void)
10055 statement_t *statement = intern_parse_statement();
10057 if (statement->kind == STATEMENT_EXPRESSION) {
10058 expression_t *expression = statement->expression.expression;
10059 if (!expression_has_effect(expression)) {
10060 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10068 * Parse a compound statement.
10070 static statement_t *parse_compound_statement(bool inside_expression_statement)
10072 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10074 PUSH_PARENT(statement);
10075 PUSH_SCOPE(&statement->compound.scope);
10078 add_anchor_token('}');
10079 /* tokens, which can start a statement */
10080 /* TODO MS, __builtin_FOO */
10081 add_anchor_token('!');
10082 add_anchor_token('&');
10083 add_anchor_token('(');
10084 add_anchor_token('*');
10085 add_anchor_token('+');
10086 add_anchor_token('-');
10087 add_anchor_token('{');
10088 add_anchor_token('~');
10089 add_anchor_token(T_CHARACTER_CONSTANT);
10090 add_anchor_token(T_COLONCOLON);
10091 add_anchor_token(T_FLOATINGPOINT);
10092 add_anchor_token(T_IDENTIFIER);
10093 add_anchor_token(T_INTEGER);
10094 add_anchor_token(T_MINUSMINUS);
10095 add_anchor_token(T_PLUSPLUS);
10096 add_anchor_token(T_STRING_LITERAL);
10097 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10098 add_anchor_token(T_WIDE_STRING_LITERAL);
10099 add_anchor_token(T__Bool);
10100 add_anchor_token(T__Complex);
10101 add_anchor_token(T__Imaginary);
10102 add_anchor_token(T___FUNCTION__);
10103 add_anchor_token(T___PRETTY_FUNCTION__);
10104 add_anchor_token(T___alignof__);
10105 add_anchor_token(T___attribute__);
10106 add_anchor_token(T___builtin_va_start);
10107 add_anchor_token(T___extension__);
10108 add_anchor_token(T___func__);
10109 add_anchor_token(T___imag__);
10110 add_anchor_token(T___label__);
10111 add_anchor_token(T___real__);
10112 add_anchor_token(T___thread);
10113 add_anchor_token(T_asm);
10114 add_anchor_token(T_auto);
10115 add_anchor_token(T_bool);
10116 add_anchor_token(T_break);
10117 add_anchor_token(T_case);
10118 add_anchor_token(T_char);
10119 add_anchor_token(T_class);
10120 add_anchor_token(T_const);
10121 add_anchor_token(T_const_cast);
10122 add_anchor_token(T_continue);
10123 add_anchor_token(T_default);
10124 add_anchor_token(T_delete);
10125 add_anchor_token(T_double);
10126 add_anchor_token(T_do);
10127 add_anchor_token(T_dynamic_cast);
10128 add_anchor_token(T_enum);
10129 add_anchor_token(T_extern);
10130 add_anchor_token(T_false);
10131 add_anchor_token(T_float);
10132 add_anchor_token(T_for);
10133 add_anchor_token(T_goto);
10134 add_anchor_token(T_if);
10135 add_anchor_token(T_inline);
10136 add_anchor_token(T_int);
10137 add_anchor_token(T_long);
10138 add_anchor_token(T_new);
10139 add_anchor_token(T_operator);
10140 add_anchor_token(T_register);
10141 add_anchor_token(T_reinterpret_cast);
10142 add_anchor_token(T_restrict);
10143 add_anchor_token(T_return);
10144 add_anchor_token(T_short);
10145 add_anchor_token(T_signed);
10146 add_anchor_token(T_sizeof);
10147 add_anchor_token(T_static);
10148 add_anchor_token(T_static_cast);
10149 add_anchor_token(T_struct);
10150 add_anchor_token(T_switch);
10151 add_anchor_token(T_template);
10152 add_anchor_token(T_this);
10153 add_anchor_token(T_throw);
10154 add_anchor_token(T_true);
10155 add_anchor_token(T_try);
10156 add_anchor_token(T_typedef);
10157 add_anchor_token(T_typeid);
10158 add_anchor_token(T_typename);
10159 add_anchor_token(T_typeof);
10160 add_anchor_token(T_union);
10161 add_anchor_token(T_unsigned);
10162 add_anchor_token(T_using);
10163 add_anchor_token(T_void);
10164 add_anchor_token(T_volatile);
10165 add_anchor_token(T_wchar_t);
10166 add_anchor_token(T_while);
10168 statement_t **anchor = &statement->compound.statements;
10169 bool only_decls_so_far = true;
10170 while (token.kind != '}') {
10171 if (token.kind == T_EOF) {
10172 errorf(&statement->base.source_position,
10173 "EOF while parsing compound statement");
10176 statement_t *sub_statement = intern_parse_statement();
10177 if (sub_statement->kind == STATEMENT_ERROR) {
10178 /* an error occurred. if we are at an anchor, return */
10184 if (sub_statement->kind != STATEMENT_DECLARATION) {
10185 only_decls_so_far = false;
10186 } else if (!only_decls_so_far) {
10187 source_position_t const *const pos = &sub_statement->base.source_position;
10188 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10191 *anchor = sub_statement;
10193 while (sub_statement->base.next != NULL)
10194 sub_statement = sub_statement->base.next;
10196 anchor = &sub_statement->base.next;
10200 /* look over all statements again to produce no effect warnings */
10201 if (is_warn_on(WARN_UNUSED_VALUE)) {
10202 statement_t *sub_statement = statement->compound.statements;
10203 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10204 if (sub_statement->kind != STATEMENT_EXPRESSION)
10206 /* don't emit a warning for the last expression in an expression
10207 * statement as it has always an effect */
10208 if (inside_expression_statement && sub_statement->base.next == NULL)
10211 expression_t *expression = sub_statement->expression.expression;
10212 if (!expression_has_effect(expression)) {
10213 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10219 rem_anchor_token(T_while);
10220 rem_anchor_token(T_wchar_t);
10221 rem_anchor_token(T_volatile);
10222 rem_anchor_token(T_void);
10223 rem_anchor_token(T_using);
10224 rem_anchor_token(T_unsigned);
10225 rem_anchor_token(T_union);
10226 rem_anchor_token(T_typeof);
10227 rem_anchor_token(T_typename);
10228 rem_anchor_token(T_typeid);
10229 rem_anchor_token(T_typedef);
10230 rem_anchor_token(T_try);
10231 rem_anchor_token(T_true);
10232 rem_anchor_token(T_throw);
10233 rem_anchor_token(T_this);
10234 rem_anchor_token(T_template);
10235 rem_anchor_token(T_switch);
10236 rem_anchor_token(T_struct);
10237 rem_anchor_token(T_static_cast);
10238 rem_anchor_token(T_static);
10239 rem_anchor_token(T_sizeof);
10240 rem_anchor_token(T_signed);
10241 rem_anchor_token(T_short);
10242 rem_anchor_token(T_return);
10243 rem_anchor_token(T_restrict);
10244 rem_anchor_token(T_reinterpret_cast);
10245 rem_anchor_token(T_register);
10246 rem_anchor_token(T_operator);
10247 rem_anchor_token(T_new);
10248 rem_anchor_token(T_long);
10249 rem_anchor_token(T_int);
10250 rem_anchor_token(T_inline);
10251 rem_anchor_token(T_if);
10252 rem_anchor_token(T_goto);
10253 rem_anchor_token(T_for);
10254 rem_anchor_token(T_float);
10255 rem_anchor_token(T_false);
10256 rem_anchor_token(T_extern);
10257 rem_anchor_token(T_enum);
10258 rem_anchor_token(T_dynamic_cast);
10259 rem_anchor_token(T_do);
10260 rem_anchor_token(T_double);
10261 rem_anchor_token(T_delete);
10262 rem_anchor_token(T_default);
10263 rem_anchor_token(T_continue);
10264 rem_anchor_token(T_const_cast);
10265 rem_anchor_token(T_const);
10266 rem_anchor_token(T_class);
10267 rem_anchor_token(T_char);
10268 rem_anchor_token(T_case);
10269 rem_anchor_token(T_break);
10270 rem_anchor_token(T_bool);
10271 rem_anchor_token(T_auto);
10272 rem_anchor_token(T_asm);
10273 rem_anchor_token(T___thread);
10274 rem_anchor_token(T___real__);
10275 rem_anchor_token(T___label__);
10276 rem_anchor_token(T___imag__);
10277 rem_anchor_token(T___func__);
10278 rem_anchor_token(T___extension__);
10279 rem_anchor_token(T___builtin_va_start);
10280 rem_anchor_token(T___attribute__);
10281 rem_anchor_token(T___alignof__);
10282 rem_anchor_token(T___PRETTY_FUNCTION__);
10283 rem_anchor_token(T___FUNCTION__);
10284 rem_anchor_token(T__Imaginary);
10285 rem_anchor_token(T__Complex);
10286 rem_anchor_token(T__Bool);
10287 rem_anchor_token(T_WIDE_STRING_LITERAL);
10288 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10289 rem_anchor_token(T_STRING_LITERAL);
10290 rem_anchor_token(T_PLUSPLUS);
10291 rem_anchor_token(T_MINUSMINUS);
10292 rem_anchor_token(T_INTEGER);
10293 rem_anchor_token(T_IDENTIFIER);
10294 rem_anchor_token(T_FLOATINGPOINT);
10295 rem_anchor_token(T_COLONCOLON);
10296 rem_anchor_token(T_CHARACTER_CONSTANT);
10297 rem_anchor_token('~');
10298 rem_anchor_token('{');
10299 rem_anchor_token('-');
10300 rem_anchor_token('+');
10301 rem_anchor_token('*');
10302 rem_anchor_token('(');
10303 rem_anchor_token('&');
10304 rem_anchor_token('!');
10305 rem_anchor_token('}');
10313 * Check for unused global static functions and variables
10315 static void check_unused_globals(void)
10317 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10320 for (const entity_t *entity = file_scope->entities; entity != NULL;
10321 entity = entity->base.next) {
10322 if (!is_declaration(entity))
10325 const declaration_t *declaration = &entity->declaration;
10326 if (declaration->used ||
10327 declaration->modifiers & DM_UNUSED ||
10328 declaration->modifiers & DM_USED ||
10329 declaration->storage_class != STORAGE_CLASS_STATIC)
10334 if (entity->kind == ENTITY_FUNCTION) {
10335 /* inhibit warning for static inline functions */
10336 if (entity->function.is_inline)
10339 why = WARN_UNUSED_FUNCTION;
10340 s = entity->function.statement != NULL ? "defined" : "declared";
10342 why = WARN_UNUSED_VARIABLE;
10346 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10350 static void parse_global_asm(void)
10352 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10355 expect('(', end_error);
10357 statement->asms.asm_text = parse_string_literals();
10358 statement->base.next = unit->global_asm;
10359 unit->global_asm = statement;
10361 expect(')', end_error);
10362 expect(';', end_error);
10367 static void parse_linkage_specification(void)
10371 source_position_t const pos = *HERE;
10372 char const *const linkage = parse_string_literals().begin;
10374 linkage_kind_t old_linkage = current_linkage;
10375 linkage_kind_t new_linkage;
10376 if (streq(linkage, "C")) {
10377 new_linkage = LINKAGE_C;
10378 } else if (streq(linkage, "C++")) {
10379 new_linkage = LINKAGE_CXX;
10381 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10382 new_linkage = LINKAGE_C;
10384 current_linkage = new_linkage;
10386 if (next_if('{')) {
10388 expect('}', end_error);
10394 assert(current_linkage == new_linkage);
10395 current_linkage = old_linkage;
10398 static void parse_external(void)
10400 switch (token.kind) {
10402 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10403 parse_linkage_specification();
10405 DECLARATION_START_NO_EXTERN
10407 case T___extension__:
10408 /* tokens below are for implicit int */
10409 case '&': /* & x; -> int& x; (and error later, because C++ has no
10411 case '*': /* * x; -> int* x; */
10412 case '(': /* (x); -> int (x); */
10414 parse_external_declaration();
10420 parse_global_asm();
10424 parse_namespace_definition();
10428 if (!strict_mode) {
10429 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10436 errorf(HERE, "stray %K outside of function", &token);
10437 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10438 eat_until_matching_token(token.kind);
10444 static void parse_externals(void)
10446 add_anchor_token('}');
10447 add_anchor_token(T_EOF);
10450 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10451 unsigned short token_anchor_copy[T_LAST_TOKEN];
10452 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10455 while (token.kind != T_EOF && token.kind != '}') {
10457 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10458 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10460 /* the anchor set and its copy differs */
10461 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10464 if (in_gcc_extension) {
10465 /* an gcc extension scope was not closed */
10466 internal_errorf(HERE, "Leaked __extension__");
10473 rem_anchor_token(T_EOF);
10474 rem_anchor_token('}');
10478 * Parse a translation unit.
10480 static void parse_translation_unit(void)
10482 add_anchor_token(T_EOF);
10487 if (token.kind == T_EOF)
10490 errorf(HERE, "stray %K outside of function", &token);
10491 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10492 eat_until_matching_token(token.kind);
10497 void set_default_visibility(elf_visibility_tag_t visibility)
10499 default_visibility = visibility;
10505 * @return the translation unit or NULL if errors occurred.
10507 void start_parsing(void)
10509 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10510 label_stack = NEW_ARR_F(stack_entry_t, 0);
10511 diagnostic_count = 0;
10515 print_to_file(stderr);
10517 assert(unit == NULL);
10518 unit = allocate_ast_zero(sizeof(unit[0]));
10520 assert(file_scope == NULL);
10521 file_scope = &unit->scope;
10523 assert(current_scope == NULL);
10524 scope_push(&unit->scope);
10526 create_gnu_builtins();
10528 create_microsoft_intrinsics();
10531 translation_unit_t *finish_parsing(void)
10533 assert(current_scope == &unit->scope);
10536 assert(file_scope == &unit->scope);
10537 check_unused_globals();
10540 DEL_ARR_F(environment_stack);
10541 DEL_ARR_F(label_stack);
10543 translation_unit_t *result = unit;
10548 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10549 * are given length one. */
10550 static void complete_incomplete_arrays(void)
10552 size_t n = ARR_LEN(incomplete_arrays);
10553 for (size_t i = 0; i != n; ++i) {
10554 declaration_t *const decl = incomplete_arrays[i];
10555 type_t *const type = skip_typeref(decl->type);
10557 if (!is_type_incomplete(type))
10560 source_position_t const *const pos = &decl->base.source_position;
10561 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10563 type_t *const new_type = duplicate_type(type);
10564 new_type->array.size_constant = true;
10565 new_type->array.has_implicit_size = true;
10566 new_type->array.size = 1;
10568 type_t *const result = identify_new_type(new_type);
10570 decl->type = result;
10574 void prepare_main_collect2(entity_t *entity)
10576 // create call to __main
10577 symbol_t *symbol = symbol_table_insert("__main");
10578 entity_t *subsubmain_ent
10579 = create_implicit_function(symbol, &builtin_source_position);
10581 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10582 type_t *ftype = subsubmain_ent->declaration.type;
10583 ref->base.source_position = builtin_source_position;
10584 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10585 ref->reference.entity = subsubmain_ent;
10587 expression_t *call = allocate_expression_zero(EXPR_CALL);
10588 call->base.source_position = builtin_source_position;
10589 call->base.type = type_void;
10590 call->call.function = ref;
10592 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10593 expr_statement->base.source_position = builtin_source_position;
10594 expr_statement->expression.expression = call;
10596 statement_t *statement = entity->function.statement;
10597 assert(statement->kind == STATEMENT_COMPOUND);
10598 compound_statement_t *compounds = &statement->compound;
10600 expr_statement->base.next = compounds->statements;
10601 compounds->statements = expr_statement;
10606 lookahead_bufpos = 0;
10607 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10610 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10611 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10612 parse_translation_unit();
10613 complete_incomplete_arrays();
10614 DEL_ARR_F(incomplete_arrays);
10615 incomplete_arrays = NULL;
10619 * Initialize the parser.
10621 void init_parser(void)
10623 sym_anonymous = symbol_table_insert("<anonymous>");
10625 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10627 init_expression_parsers();
10628 obstack_init(&temp_obst);
10632 * Terminate the parser.
10634 void exit_parser(void)
10636 obstack_free(&temp_obst, NULL);