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_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
298 [STATEMENT_GOTO] = sizeof(goto_statement_t),
299 [STATEMENT_LABEL] = sizeof(label_statement_t),
300 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
301 [STATEMENT_WHILE] = sizeof(while_statement_t),
302 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
303 [STATEMENT_FOR] = sizeof(for_statement_t),
304 [STATEMENT_ASM] = sizeof(asm_statement_t),
305 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
306 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
308 assert((size_t)kind < lengthof(sizes));
309 assert(sizes[kind] != 0);
314 * Returns the size of an expression node.
316 * @param kind the expression kind
318 static size_t get_expression_struct_size(expression_kind_t kind)
320 static const size_t sizes[] = {
321 [EXPR_ERROR] = sizeof(expression_base_t),
322 [EXPR_REFERENCE] = sizeof(reference_expression_t),
323 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
324 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
328 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
332 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
333 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
334 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
335 [EXPR_CALL] = sizeof(call_expression_t),
336 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
337 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
338 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
339 [EXPR_SELECT] = sizeof(select_expression_t),
340 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
341 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
342 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
343 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
344 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
345 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
346 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
347 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
348 [EXPR_VA_START] = sizeof(va_start_expression_t),
349 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
350 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
351 [EXPR_STATEMENT] = sizeof(statement_expression_t),
352 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
354 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
355 return sizes[EXPR_UNARY_FIRST];
357 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
358 return sizes[EXPR_BINARY_FIRST];
360 assert((size_t)kind < lengthof(sizes));
361 assert(sizes[kind] != 0);
366 * Allocate a statement node of given kind and initialize all
367 * fields with zero. Sets its source position to the position
368 * of the current token.
370 static statement_t *allocate_statement_zero(statement_kind_t kind)
372 size_t size = get_statement_struct_size(kind);
373 statement_t *res = allocate_ast_zero(size);
375 res->base.kind = kind;
376 res->base.parent = current_parent;
377 res->base.source_position = token.base.source_position;
382 * Allocate an expression node of given kind and initialize all
385 * @param kind the kind of the expression to allocate
387 static expression_t *allocate_expression_zero(expression_kind_t kind)
389 size_t size = get_expression_struct_size(kind);
390 expression_t *res = allocate_ast_zero(size);
392 res->base.kind = kind;
393 res->base.type = type_error_type;
394 res->base.source_position = token.base.source_position;
399 * Creates a new invalid expression at the source position
400 * of the current token.
402 static expression_t *create_error_expression(void)
404 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
405 expression->base.type = type_error_type;
410 * Creates a new invalid statement.
412 static statement_t *create_error_statement(void)
414 return allocate_statement_zero(STATEMENT_ERROR);
418 * Allocate a new empty statement.
420 static statement_t *create_empty_statement(void)
422 return allocate_statement_zero(STATEMENT_EMPTY);
426 * Returns the size of an initializer node.
428 * @param kind the initializer kind
430 static size_t get_initializer_size(initializer_kind_t kind)
432 static const size_t sizes[] = {
433 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
434 [INITIALIZER_STRING] = sizeof(initializer_string_t),
435 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
436 [INITIALIZER_LIST] = sizeof(initializer_list_t),
437 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
439 assert((size_t)kind < lengthof(sizes));
440 assert(sizes[kind] != 0);
445 * Allocate an initializer node of given kind and initialize all
448 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
450 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
457 * Returns the index of the top element of the environment stack.
459 static size_t environment_top(void)
461 return ARR_LEN(environment_stack);
465 * Returns the index of the top element of the global label stack.
467 static size_t label_top(void)
469 return ARR_LEN(label_stack);
473 * Return the next token.
475 static inline void next_token(void)
477 token = lookahead_buffer[lookahead_bufpos];
478 lookahead_buffer[lookahead_bufpos] = lexer_token;
481 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
484 print_token(stderr, &token);
485 fprintf(stderr, "\n");
489 static inline bool next_if(int const type)
491 if (token.kind == type) {
500 * Return the next token with a given lookahead.
502 static inline const token_t *look_ahead(size_t num)
504 assert(0 < num && num <= MAX_LOOKAHEAD);
505 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
506 return &lookahead_buffer[pos];
510 * Adds a token type to the token type anchor set (a multi-set).
512 static void add_anchor_token(int token_kind)
514 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
515 ++token_anchor_set[token_kind];
519 * Set the number of tokens types of the given type
520 * to zero and return the old count.
522 static int save_and_reset_anchor_state(int token_kind)
524 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
525 int count = token_anchor_set[token_kind];
526 token_anchor_set[token_kind] = 0;
531 * Restore the number of token types to the given count.
533 static void restore_anchor_state(int token_kind, int count)
535 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
536 token_anchor_set[token_kind] = count;
540 * Remove a token type from the token type anchor set (a multi-set).
542 static void rem_anchor_token(int token_kind)
544 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
545 assert(token_anchor_set[token_kind] != 0);
546 --token_anchor_set[token_kind];
550 * Eat tokens until a matching token type is found.
552 static void eat_until_matching_token(int type)
556 case '(': end_token = ')'; break;
557 case '{': end_token = '}'; break;
558 case '[': end_token = ']'; break;
559 default: end_token = type; break;
562 unsigned parenthesis_count = 0;
563 unsigned brace_count = 0;
564 unsigned bracket_count = 0;
565 while (token.kind != end_token ||
566 parenthesis_count != 0 ||
568 bracket_count != 0) {
569 switch (token.kind) {
571 case '(': ++parenthesis_count; break;
572 case '{': ++brace_count; break;
573 case '[': ++bracket_count; break;
576 if (parenthesis_count > 0)
586 if (bracket_count > 0)
589 if (token.kind == end_token &&
590 parenthesis_count == 0 &&
604 * Eat input tokens until an anchor is found.
606 static void eat_until_anchor(void)
608 while (token_anchor_set[token.kind] == 0) {
609 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
610 eat_until_matching_token(token.kind);
616 * Eat a whole block from input tokens.
618 static void eat_block(void)
620 eat_until_matching_token('{');
624 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
627 * Report a parse error because an expected token was not found.
630 #if defined __GNUC__ && __GNUC__ >= 4
631 __attribute__((sentinel))
633 void parse_error_expected(const char *message, ...)
635 if (message != NULL) {
636 errorf(HERE, "%s", message);
639 va_start(ap, message);
640 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
645 * Report an incompatible type.
647 static void type_error_incompatible(const char *msg,
648 const source_position_t *source_position, type_t *type1, type_t *type2)
650 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
655 * Expect the current token is the expected token.
656 * If not, generate an error, eat the current statement,
657 * and goto the error_label label.
659 #define expect(expected, error_label) \
661 if (UNLIKELY(token.kind != (expected))) { \
662 parse_error_expected(NULL, (expected), NULL); \
663 add_anchor_token(expected); \
664 eat_until_anchor(); \
665 rem_anchor_token(expected); \
666 if (token.kind != (expected)) \
673 * Push a given scope on the scope stack and make it the
676 static scope_t *scope_push(scope_t *new_scope)
678 if (current_scope != NULL) {
679 new_scope->depth = current_scope->depth + 1;
682 scope_t *old_scope = current_scope;
683 current_scope = new_scope;
688 * Pop the current scope from the scope stack.
690 static void scope_pop(scope_t *old_scope)
692 current_scope = old_scope;
696 * Search an entity by its symbol in a given namespace.
698 static entity_t *get_entity(const symbol_t *const symbol,
699 namespace_tag_t namespc)
701 entity_t *entity = symbol->entity;
702 for (; entity != NULL; entity = entity->base.symbol_next) {
703 if ((namespace_tag_t)entity->base.namespc == namespc)
710 /* §6.2.3:1 24) There is only one name space for tags even though three are
712 static entity_t *get_tag(symbol_t const *const symbol,
713 entity_kind_tag_t const kind)
715 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
716 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
718 "'%Y' defined as wrong kind of tag (previous definition %P)",
719 symbol, &entity->base.source_position);
726 * pushs an entity on the environment stack and links the corresponding symbol
729 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
731 symbol_t *symbol = entity->base.symbol;
732 entity_namespace_t namespc = entity->base.namespc;
733 assert(namespc != 0);
735 /* replace/add entity into entity list of the symbol */
738 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
743 /* replace an entry? */
744 if (iter->base.namespc == namespc) {
745 entity->base.symbol_next = iter->base.symbol_next;
751 /* remember old declaration */
753 entry.symbol = symbol;
754 entry.old_entity = iter;
755 entry.namespc = namespc;
756 ARR_APP1(stack_entry_t, *stack_ptr, entry);
760 * Push an entity on the environment stack.
762 static void environment_push(entity_t *entity)
764 assert(entity->base.source_position.input_name != NULL);
765 assert(entity->base.parent_scope != NULL);
766 stack_push(&environment_stack, entity);
770 * Push a declaration on the global label stack.
772 * @param declaration the declaration
774 static void label_push(entity_t *label)
776 /* we abuse the parameters scope as parent for the labels */
777 label->base.parent_scope = ¤t_function->parameters;
778 stack_push(&label_stack, label);
782 * pops symbols from the environment stack until @p new_top is the top element
784 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
786 stack_entry_t *stack = *stack_ptr;
787 size_t top = ARR_LEN(stack);
790 assert(new_top <= top);
794 for (i = top; i > new_top; --i) {
795 stack_entry_t *entry = &stack[i - 1];
797 entity_t *old_entity = entry->old_entity;
798 symbol_t *symbol = entry->symbol;
799 entity_namespace_t namespc = entry->namespc;
801 /* replace with old_entity/remove */
804 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
806 assert(iter != NULL);
807 /* replace an entry? */
808 if (iter->base.namespc == namespc)
812 /* restore definition from outer scopes (if there was one) */
813 if (old_entity != NULL) {
814 old_entity->base.symbol_next = iter->base.symbol_next;
815 *anchor = old_entity;
817 /* remove entry from list */
818 *anchor = iter->base.symbol_next;
822 ARR_SHRINKLEN(*stack_ptr, new_top);
826 * Pop all entries from the environment stack until the new_top
829 * @param new_top the new stack top
831 static void environment_pop_to(size_t new_top)
833 stack_pop_to(&environment_stack, new_top);
837 * Pop all entries from the global label stack until the new_top
840 * @param new_top the new stack top
842 static void label_pop_to(size_t new_top)
844 stack_pop_to(&label_stack, new_top);
847 static atomic_type_kind_t get_akind(const type_t *type)
849 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
850 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
851 return type->atomic.akind;
855 * §6.3.1.1:2 Do integer promotion for a given type.
857 * @param type the type to promote
858 * @return the promoted type
860 static type_t *promote_integer(type_t *type)
862 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
869 * Check if a given expression represents a null pointer constant.
871 * @param expression the expression to check
873 static bool is_null_pointer_constant(const expression_t *expression)
875 /* skip void* cast */
876 if (expression->kind == EXPR_UNARY_CAST) {
877 type_t *const type = skip_typeref(expression->base.type);
878 if (types_compatible(type, type_void_ptr))
879 expression = expression->unary.value;
882 type_t *const type = skip_typeref(expression->base.type);
883 if (!is_type_integer(type))
885 switch (is_constant_expression(expression)) {
886 case EXPR_CLASS_ERROR: return true;
887 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
888 default: return false;
893 * Create an implicit cast expression.
895 * @param expression the expression to cast
896 * @param dest_type the destination type
898 static expression_t *create_implicit_cast(expression_t *expression,
901 type_t *const source_type = expression->base.type;
903 if (source_type == dest_type)
906 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
907 cast->unary.value = expression;
908 cast->base.type = dest_type;
909 cast->base.implicit = true;
914 typedef enum assign_error_t {
916 ASSIGN_ERROR_INCOMPATIBLE,
917 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
918 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
919 ASSIGN_WARNING_POINTER_FROM_INT,
920 ASSIGN_WARNING_INT_FROM_POINTER
923 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)
925 type_t *const orig_type_right = right->base.type;
926 type_t *const type_left = skip_typeref(orig_type_left);
927 type_t *const type_right = skip_typeref(orig_type_right);
932 case ASSIGN_ERROR_INCOMPATIBLE:
933 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
936 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
937 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
938 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
940 /* the left type has all qualifiers from the right type */
941 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
942 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);
946 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
947 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
950 case ASSIGN_WARNING_POINTER_FROM_INT:
951 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
954 case ASSIGN_WARNING_INT_FROM_POINTER:
955 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
959 panic("invalid error value");
963 /** Implements the rules from §6.5.16.1 */
964 static assign_error_t semantic_assign(type_t *orig_type_left,
965 const expression_t *const right)
967 type_t *const orig_type_right = right->base.type;
968 type_t *const type_left = skip_typeref(orig_type_left);
969 type_t *const type_right = skip_typeref(orig_type_right);
971 if (is_type_pointer(type_left)) {
972 if (is_null_pointer_constant(right)) {
973 return ASSIGN_SUCCESS;
974 } else if (is_type_pointer(type_right)) {
975 type_t *points_to_left
976 = skip_typeref(type_left->pointer.points_to);
977 type_t *points_to_right
978 = skip_typeref(type_right->pointer.points_to);
979 assign_error_t res = ASSIGN_SUCCESS;
981 /* the left type has all qualifiers from the right type */
982 unsigned missing_qualifiers
983 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
984 if (missing_qualifiers != 0) {
985 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
988 points_to_left = get_unqualified_type(points_to_left);
989 points_to_right = get_unqualified_type(points_to_right);
991 if (is_type_void(points_to_left))
994 if (is_type_void(points_to_right)) {
995 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
996 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
999 if (!types_compatible(points_to_left, points_to_right)) {
1000 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1004 } else if (is_type_integer(type_right)) {
1005 return ASSIGN_WARNING_POINTER_FROM_INT;
1007 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1008 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1009 && is_type_pointer(type_right))) {
1010 return ASSIGN_SUCCESS;
1011 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1012 type_t *const unqual_type_left = get_unqualified_type(type_left);
1013 type_t *const unqual_type_right = get_unqualified_type(type_right);
1014 if (types_compatible(unqual_type_left, unqual_type_right)) {
1015 return ASSIGN_SUCCESS;
1017 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1018 return ASSIGN_WARNING_INT_FROM_POINTER;
1021 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1022 return ASSIGN_SUCCESS;
1024 return ASSIGN_ERROR_INCOMPATIBLE;
1027 static expression_t *parse_constant_expression(void)
1029 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1031 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1032 errorf(&result->base.source_position,
1033 "expression '%E' is not constant", result);
1039 static expression_t *parse_assignment_expression(void)
1041 return parse_subexpression(PREC_ASSIGNMENT);
1044 static void warn_string_concat(const source_position_t *pos)
1046 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1049 static string_t parse_string_literals(void)
1051 assert(token.kind == T_STRING_LITERAL);
1052 string_t result = token.string.string;
1056 while (token.kind == T_STRING_LITERAL) {
1057 warn_string_concat(&token.base.source_position);
1058 result = concat_strings(&result, &token.string.string);
1065 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1067 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1068 attribute->kind = kind;
1069 attribute->source_position = *HERE;
1074 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1077 * __attribute__ ( ( attribute-list ) )
1081 * attribute_list , attrib
1086 * any-word ( identifier )
1087 * any-word ( identifier , nonempty-expr-list )
1088 * any-word ( expr-list )
1090 * where the "identifier" must not be declared as a type, and
1091 * "any-word" may be any identifier (including one declared as a
1092 * type), a reserved word storage class specifier, type specifier or
1093 * type qualifier. ??? This still leaves out most reserved keywords
1094 * (following the old parser), shouldn't we include them, and why not
1095 * allow identifiers declared as types to start the arguments?
1097 * Matze: this all looks confusing and little systematic, so we're even less
1098 * strict and parse any list of things which are identifiers or
1099 * (assignment-)expressions.
1101 static attribute_argument_t *parse_attribute_arguments(void)
1103 attribute_argument_t *first = NULL;
1104 attribute_argument_t **anchor = &first;
1105 if (token.kind != ')') do {
1106 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1108 /* is it an identifier */
1109 if (token.kind == T_IDENTIFIER
1110 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1111 symbol_t *symbol = token.identifier.symbol;
1112 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1113 argument->v.symbol = symbol;
1116 /* must be an expression */
1117 expression_t *expression = parse_assignment_expression();
1119 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1120 argument->v.expression = expression;
1123 /* append argument */
1125 anchor = &argument->next;
1126 } while (next_if(','));
1127 expect(')', end_error);
1132 static attribute_t *parse_attribute_asm(void)
1134 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1137 expect('(', end_error);
1138 attribute->a.arguments = parse_attribute_arguments();
1145 static symbol_t *get_symbol_from_token(void)
1147 switch(token.kind) {
1149 return token.identifier.symbol;
1178 /* maybe we need more tokens ... add them on demand */
1179 return get_token_kind_symbol(token.kind);
1185 static attribute_t *parse_attribute_gnu_single(void)
1187 /* parse "any-word" */
1188 symbol_t *symbol = get_symbol_from_token();
1189 if (symbol == NULL) {
1190 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1194 attribute_kind_t kind;
1195 char const *const name = symbol->string;
1196 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1197 if (kind > ATTRIBUTE_GNU_LAST) {
1198 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1199 /* TODO: we should still save the attribute in the list... */
1200 kind = ATTRIBUTE_UNKNOWN;
1204 const char *attribute_name = get_attribute_name(kind);
1205 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1209 attribute_t *attribute = allocate_attribute_zero(kind);
1212 /* parse arguments */
1214 attribute->a.arguments = parse_attribute_arguments();
1219 static attribute_t *parse_attribute_gnu(void)
1221 attribute_t *first = NULL;
1222 attribute_t **anchor = &first;
1224 eat(T___attribute__);
1225 expect('(', end_error);
1226 expect('(', end_error);
1228 if (token.kind != ')') do {
1229 attribute_t *attribute = parse_attribute_gnu_single();
1230 if (attribute == NULL)
1233 *anchor = attribute;
1234 anchor = &attribute->next;
1235 } while (next_if(','));
1236 expect(')', end_error);
1237 expect(')', end_error);
1243 /** Parse attributes. */
1244 static attribute_t *parse_attributes(attribute_t *first)
1246 attribute_t **anchor = &first;
1248 while (*anchor != NULL)
1249 anchor = &(*anchor)->next;
1251 attribute_t *attribute;
1252 switch (token.kind) {
1253 case T___attribute__:
1254 attribute = parse_attribute_gnu();
1255 if (attribute == NULL)
1260 attribute = parse_attribute_asm();
1264 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1269 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1273 case T__forceinline:
1274 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1275 eat(T__forceinline);
1279 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1284 /* TODO record modifier */
1285 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1286 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1294 *anchor = attribute;
1295 anchor = &attribute->next;
1299 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1301 static entity_t *determine_lhs_ent(expression_t *const expr,
1304 switch (expr->kind) {
1305 case EXPR_REFERENCE: {
1306 entity_t *const entity = expr->reference.entity;
1307 /* we should only find variables as lvalues... */
1308 if (entity->base.kind != ENTITY_VARIABLE
1309 && entity->base.kind != ENTITY_PARAMETER)
1315 case EXPR_ARRAY_ACCESS: {
1316 expression_t *const ref = expr->array_access.array_ref;
1317 entity_t * ent = NULL;
1318 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1319 ent = determine_lhs_ent(ref, lhs_ent);
1322 mark_vars_read(ref, lhs_ent);
1324 mark_vars_read(expr->array_access.index, lhs_ent);
1329 mark_vars_read(expr->select.compound, lhs_ent);
1330 if (is_type_compound(skip_typeref(expr->base.type)))
1331 return determine_lhs_ent(expr->select.compound, lhs_ent);
1335 case EXPR_UNARY_DEREFERENCE: {
1336 expression_t *const val = expr->unary.value;
1337 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1339 return determine_lhs_ent(val->unary.value, lhs_ent);
1341 mark_vars_read(val, NULL);
1347 mark_vars_read(expr, NULL);
1352 #define ENT_ANY ((entity_t*)-1)
1355 * Mark declarations, which are read. This is used to detect variables, which
1359 * x is not marked as "read", because it is only read to calculate its own new
1363 * x and y are not detected as "not read", because multiple variables are
1366 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1368 switch (expr->kind) {
1369 case EXPR_REFERENCE: {
1370 entity_t *const entity = expr->reference.entity;
1371 if (entity->kind != ENTITY_VARIABLE
1372 && entity->kind != ENTITY_PARAMETER)
1375 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1376 if (entity->kind == ENTITY_VARIABLE) {
1377 entity->variable.read = true;
1379 entity->parameter.read = true;
1386 // TODO respect pure/const
1387 mark_vars_read(expr->call.function, NULL);
1388 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1389 mark_vars_read(arg->expression, NULL);
1393 case EXPR_CONDITIONAL:
1394 // TODO lhs_decl should depend on whether true/false have an effect
1395 mark_vars_read(expr->conditional.condition, NULL);
1396 if (expr->conditional.true_expression != NULL)
1397 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1398 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1402 if (lhs_ent == ENT_ANY
1403 && !is_type_compound(skip_typeref(expr->base.type)))
1405 mark_vars_read(expr->select.compound, lhs_ent);
1408 case EXPR_ARRAY_ACCESS: {
1409 mark_vars_read(expr->array_access.index, lhs_ent);
1410 expression_t *const ref = expr->array_access.array_ref;
1411 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1412 if (lhs_ent == ENT_ANY)
1415 mark_vars_read(ref, lhs_ent);
1420 mark_vars_read(expr->va_arge.ap, lhs_ent);
1424 mark_vars_read(expr->va_copye.src, lhs_ent);
1427 case EXPR_UNARY_CAST:
1428 /* Special case: Use void cast to mark a variable as "read" */
1429 if (is_type_void(skip_typeref(expr->base.type)))
1434 case EXPR_UNARY_THROW:
1435 if (expr->unary.value == NULL)
1438 case EXPR_UNARY_DEREFERENCE:
1439 case EXPR_UNARY_DELETE:
1440 case EXPR_UNARY_DELETE_ARRAY:
1441 if (lhs_ent == ENT_ANY)
1445 case EXPR_UNARY_NEGATE:
1446 case EXPR_UNARY_PLUS:
1447 case EXPR_UNARY_BITWISE_NEGATE:
1448 case EXPR_UNARY_NOT:
1449 case EXPR_UNARY_TAKE_ADDRESS:
1450 case EXPR_UNARY_POSTFIX_INCREMENT:
1451 case EXPR_UNARY_POSTFIX_DECREMENT:
1452 case EXPR_UNARY_PREFIX_INCREMENT:
1453 case EXPR_UNARY_PREFIX_DECREMENT:
1454 case EXPR_UNARY_ASSUME:
1456 mark_vars_read(expr->unary.value, lhs_ent);
1459 case EXPR_BINARY_ADD:
1460 case EXPR_BINARY_SUB:
1461 case EXPR_BINARY_MUL:
1462 case EXPR_BINARY_DIV:
1463 case EXPR_BINARY_MOD:
1464 case EXPR_BINARY_EQUAL:
1465 case EXPR_BINARY_NOTEQUAL:
1466 case EXPR_BINARY_LESS:
1467 case EXPR_BINARY_LESSEQUAL:
1468 case EXPR_BINARY_GREATER:
1469 case EXPR_BINARY_GREATEREQUAL:
1470 case EXPR_BINARY_BITWISE_AND:
1471 case EXPR_BINARY_BITWISE_OR:
1472 case EXPR_BINARY_BITWISE_XOR:
1473 case EXPR_BINARY_LOGICAL_AND:
1474 case EXPR_BINARY_LOGICAL_OR:
1475 case EXPR_BINARY_SHIFTLEFT:
1476 case EXPR_BINARY_SHIFTRIGHT:
1477 case EXPR_BINARY_COMMA:
1478 case EXPR_BINARY_ISGREATER:
1479 case EXPR_BINARY_ISGREATEREQUAL:
1480 case EXPR_BINARY_ISLESS:
1481 case EXPR_BINARY_ISLESSEQUAL:
1482 case EXPR_BINARY_ISLESSGREATER:
1483 case EXPR_BINARY_ISUNORDERED:
1484 mark_vars_read(expr->binary.left, lhs_ent);
1485 mark_vars_read(expr->binary.right, lhs_ent);
1488 case EXPR_BINARY_ASSIGN:
1489 case EXPR_BINARY_MUL_ASSIGN:
1490 case EXPR_BINARY_DIV_ASSIGN:
1491 case EXPR_BINARY_MOD_ASSIGN:
1492 case EXPR_BINARY_ADD_ASSIGN:
1493 case EXPR_BINARY_SUB_ASSIGN:
1494 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1495 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1496 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1497 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1498 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1499 if (lhs_ent == ENT_ANY)
1501 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1502 mark_vars_read(expr->binary.right, lhs_ent);
1507 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1510 case EXPR_LITERAL_CASES:
1512 case EXPR_STRING_LITERAL:
1513 case EXPR_WIDE_STRING_LITERAL:
1514 case EXPR_COMPOUND_LITERAL: // TODO init?
1516 case EXPR_CLASSIFY_TYPE:
1519 case EXPR_BUILTIN_CONSTANT_P:
1520 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1522 case EXPR_STATEMENT: // TODO
1523 case EXPR_LABEL_ADDRESS:
1524 case EXPR_ENUM_CONSTANT:
1528 panic("unhandled expression");
1531 static designator_t *parse_designation(void)
1533 designator_t *result = NULL;
1534 designator_t **anchor = &result;
1537 designator_t *designator;
1538 switch (token.kind) {
1540 designator = allocate_ast_zero(sizeof(designator[0]));
1541 designator->source_position = token.base.source_position;
1543 add_anchor_token(']');
1544 designator->array_index = parse_constant_expression();
1545 rem_anchor_token(']');
1546 expect(']', end_error);
1549 designator = allocate_ast_zero(sizeof(designator[0]));
1550 designator->source_position = token.base.source_position;
1552 if (token.kind != T_IDENTIFIER) {
1553 parse_error_expected("while parsing designator",
1554 T_IDENTIFIER, NULL);
1557 designator->symbol = token.identifier.symbol;
1561 expect('=', end_error);
1565 assert(designator != NULL);
1566 *anchor = designator;
1567 anchor = &designator->next;
1573 static initializer_t *initializer_from_string(array_type_t *const type,
1574 const string_t *const string)
1576 /* TODO: check len vs. size of array type */
1579 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1580 initializer->string.string = *string;
1585 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1586 const string_t *const string)
1588 /* TODO: check len vs. size of array type */
1591 initializer_t *const initializer =
1592 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1593 initializer->wide_string.string = *string;
1599 * Build an initializer from a given expression.
1601 static initializer_t *initializer_from_expression(type_t *orig_type,
1602 expression_t *expression)
1604 /* TODO check that expression is a constant expression */
1606 /* §6.7.8.14/15 char array may be initialized by string literals */
1607 type_t *type = skip_typeref(orig_type);
1608 type_t *expr_type_orig = expression->base.type;
1609 type_t *expr_type = skip_typeref(expr_type_orig);
1611 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1612 array_type_t *const array_type = &type->array;
1613 type_t *const element_type = skip_typeref(array_type->element_type);
1615 if (element_type->kind == TYPE_ATOMIC) {
1616 atomic_type_kind_t akind = element_type->atomic.akind;
1617 switch (expression->kind) {
1618 case EXPR_STRING_LITERAL:
1619 if (akind == ATOMIC_TYPE_CHAR
1620 || akind == ATOMIC_TYPE_SCHAR
1621 || akind == ATOMIC_TYPE_UCHAR) {
1622 return initializer_from_string(array_type,
1623 &expression->string_literal.value);
1627 case EXPR_WIDE_STRING_LITERAL: {
1628 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1629 if (get_unqualified_type(element_type) == bare_wchar_type) {
1630 return initializer_from_wide_string(array_type,
1631 &expression->string_literal.value);
1642 assign_error_t error = semantic_assign(type, expression);
1643 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1645 report_assign_error(error, type, expression, "initializer",
1646 &expression->base.source_position);
1648 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1649 result->value.value = create_implicit_cast(expression, type);
1655 * Parses an scalar initializer.
1657 * §6.7.8.11; eat {} without warning
1659 static initializer_t *parse_scalar_initializer(type_t *type,
1660 bool must_be_constant)
1662 /* there might be extra {} hierarchies */
1664 if (token.kind == '{') {
1665 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1669 } while (token.kind == '{');
1672 expression_t *expression = parse_assignment_expression();
1673 mark_vars_read(expression, NULL);
1674 if (must_be_constant && !is_linker_constant(expression)) {
1675 errorf(&expression->base.source_position,
1676 "initialisation expression '%E' is not constant",
1680 initializer_t *initializer = initializer_from_expression(type, expression);
1682 if (initializer == NULL) {
1683 errorf(&expression->base.source_position,
1684 "expression '%E' (type '%T') doesn't match expected type '%T'",
1685 expression, expression->base.type, type);
1690 bool additional_warning_displayed = false;
1691 while (braces > 0) {
1693 if (token.kind != '}') {
1694 if (!additional_warning_displayed) {
1695 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1696 additional_warning_displayed = true;
1707 * An entry in the type path.
1709 typedef struct type_path_entry_t type_path_entry_t;
1710 struct type_path_entry_t {
1711 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1713 size_t index; /**< For array types: the current index. */
1714 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1719 * A type path expression a position inside compound or array types.
1721 typedef struct type_path_t type_path_t;
1722 struct type_path_t {
1723 type_path_entry_t *path; /**< An flexible array containing the current path. */
1724 type_t *top_type; /**< type of the element the path points */
1725 size_t max_index; /**< largest index in outermost array */
1729 * Prints a type path for debugging.
1731 static __attribute__((unused)) void debug_print_type_path(
1732 const type_path_t *path)
1734 size_t len = ARR_LEN(path->path);
1736 for (size_t i = 0; i < len; ++i) {
1737 const type_path_entry_t *entry = & path->path[i];
1739 type_t *type = skip_typeref(entry->type);
1740 if (is_type_compound(type)) {
1741 /* in gcc mode structs can have no members */
1742 if (entry->v.compound_entry == NULL) {
1746 fprintf(stderr, ".%s",
1747 entry->v.compound_entry->base.symbol->string);
1748 } else if (is_type_array(type)) {
1749 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1751 fprintf(stderr, "-INVALID-");
1754 if (path->top_type != NULL) {
1755 fprintf(stderr, " (");
1756 print_type(path->top_type);
1757 fprintf(stderr, ")");
1762 * Return the top type path entry, ie. in a path
1763 * (type).a.b returns the b.
1765 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1767 size_t len = ARR_LEN(path->path);
1769 return &path->path[len-1];
1773 * Enlarge the type path by an (empty) element.
1775 static type_path_entry_t *append_to_type_path(type_path_t *path)
1777 size_t len = ARR_LEN(path->path);
1778 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1780 type_path_entry_t *result = & path->path[len];
1781 memset(result, 0, sizeof(result[0]));
1786 * Descending into a sub-type. Enter the scope of the current top_type.
1788 static void descend_into_subtype(type_path_t *path)
1790 type_t *orig_top_type = path->top_type;
1791 type_t *top_type = skip_typeref(orig_top_type);
1793 type_path_entry_t *top = append_to_type_path(path);
1794 top->type = top_type;
1796 if (is_type_compound(top_type)) {
1797 compound_t *const compound = top_type->compound.compound;
1798 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1800 if (entry != NULL) {
1801 top->v.compound_entry = &entry->declaration;
1802 path->top_type = entry->declaration.type;
1804 path->top_type = NULL;
1806 } else if (is_type_array(top_type)) {
1808 path->top_type = top_type->array.element_type;
1810 assert(!is_type_valid(top_type));
1815 * Pop an entry from the given type path, ie. returning from
1816 * (type).a.b to (type).a
1818 static void ascend_from_subtype(type_path_t *path)
1820 type_path_entry_t *top = get_type_path_top(path);
1822 path->top_type = top->type;
1824 size_t len = ARR_LEN(path->path);
1825 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1829 * Pop entries from the given type path until the given
1830 * path level is reached.
1832 static void ascend_to(type_path_t *path, size_t top_path_level)
1834 size_t len = ARR_LEN(path->path);
1836 while (len > top_path_level) {
1837 ascend_from_subtype(path);
1838 len = ARR_LEN(path->path);
1842 static bool walk_designator(type_path_t *path, const designator_t *designator,
1843 bool used_in_offsetof)
1845 for (; designator != NULL; designator = designator->next) {
1846 type_path_entry_t *top = get_type_path_top(path);
1847 type_t *orig_type = top->type;
1849 type_t *type = skip_typeref(orig_type);
1851 if (designator->symbol != NULL) {
1852 symbol_t *symbol = designator->symbol;
1853 if (!is_type_compound(type)) {
1854 if (is_type_valid(type)) {
1855 errorf(&designator->source_position,
1856 "'.%Y' designator used for non-compound type '%T'",
1860 top->type = type_error_type;
1861 top->v.compound_entry = NULL;
1862 orig_type = type_error_type;
1864 compound_t *compound = type->compound.compound;
1865 entity_t *iter = compound->members.entities;
1866 for (; iter != NULL; iter = iter->base.next) {
1867 if (iter->base.symbol == symbol) {
1872 errorf(&designator->source_position,
1873 "'%T' has no member named '%Y'", orig_type, symbol);
1876 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1877 if (used_in_offsetof && iter->compound_member.bitfield) {
1878 errorf(&designator->source_position,
1879 "offsetof designator '%Y' must not specify bitfield",
1884 top->type = orig_type;
1885 top->v.compound_entry = &iter->declaration;
1886 orig_type = iter->declaration.type;
1889 expression_t *array_index = designator->array_index;
1890 assert(designator->array_index != NULL);
1892 if (!is_type_array(type)) {
1893 if (is_type_valid(type)) {
1894 errorf(&designator->source_position,
1895 "[%E] designator used for non-array type '%T'",
1896 array_index, orig_type);
1901 long index = fold_constant_to_int(array_index);
1902 if (!used_in_offsetof) {
1904 errorf(&designator->source_position,
1905 "array index [%E] must be positive", array_index);
1906 } else if (type->array.size_constant) {
1907 long array_size = type->array.size;
1908 if (index >= array_size) {
1909 errorf(&designator->source_position,
1910 "designator [%E] (%d) exceeds array size %d",
1911 array_index, index, array_size);
1916 top->type = orig_type;
1917 top->v.index = (size_t) index;
1918 orig_type = type->array.element_type;
1920 path->top_type = orig_type;
1922 if (designator->next != NULL) {
1923 descend_into_subtype(path);
1929 static void advance_current_object(type_path_t *path, size_t top_path_level)
1931 type_path_entry_t *top = get_type_path_top(path);
1933 type_t *type = skip_typeref(top->type);
1934 if (is_type_union(type)) {
1935 /* in unions only the first element is initialized */
1936 top->v.compound_entry = NULL;
1937 } else if (is_type_struct(type)) {
1938 declaration_t *entry = top->v.compound_entry;
1940 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1941 if (next_entity != NULL) {
1942 assert(is_declaration(next_entity));
1943 entry = &next_entity->declaration;
1948 top->v.compound_entry = entry;
1949 if (entry != NULL) {
1950 path->top_type = entry->type;
1953 } else if (is_type_array(type)) {
1954 assert(is_type_array(type));
1958 if (!type->array.size_constant || top->v.index < type->array.size) {
1962 assert(!is_type_valid(type));
1966 /* we're past the last member of the current sub-aggregate, try if we
1967 * can ascend in the type hierarchy and continue with another subobject */
1968 size_t len = ARR_LEN(path->path);
1970 if (len > top_path_level) {
1971 ascend_from_subtype(path);
1972 advance_current_object(path, top_path_level);
1974 path->top_type = NULL;
1979 * skip any {...} blocks until a closing bracket is reached.
1981 static void skip_initializers(void)
1985 while (token.kind != '}') {
1986 if (token.kind == T_EOF)
1988 if (token.kind == '{') {
1996 static initializer_t *create_empty_initializer(void)
1998 static initializer_t empty_initializer
1999 = { .list = { { INITIALIZER_LIST }, 0 } };
2000 return &empty_initializer;
2004 * Parse a part of an initialiser for a struct or union,
2006 static initializer_t *parse_sub_initializer(type_path_t *path,
2007 type_t *outer_type, size_t top_path_level,
2008 parse_initializer_env_t *env)
2010 if (token.kind == '}') {
2011 /* empty initializer */
2012 return create_empty_initializer();
2015 type_t *orig_type = path->top_type;
2016 type_t *type = NULL;
2018 if (orig_type == NULL) {
2019 /* We are initializing an empty compound. */
2021 type = skip_typeref(orig_type);
2024 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2027 designator_t *designator = NULL;
2028 if (token.kind == '.' || token.kind == '[') {
2029 designator = parse_designation();
2030 goto finish_designator;
2031 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2032 /* GNU-style designator ("identifier: value") */
2033 designator = allocate_ast_zero(sizeof(designator[0]));
2034 designator->source_position = token.base.source_position;
2035 designator->symbol = token.identifier.symbol;
2040 /* reset path to toplevel, evaluate designator from there */
2041 ascend_to(path, top_path_level);
2042 if (!walk_designator(path, designator, false)) {
2043 /* can't continue after designation error */
2047 initializer_t *designator_initializer
2048 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2049 designator_initializer->designator.designator = designator;
2050 ARR_APP1(initializer_t*, initializers, designator_initializer);
2052 orig_type = path->top_type;
2053 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2058 if (token.kind == '{') {
2059 if (type != NULL && is_type_scalar(type)) {
2060 sub = parse_scalar_initializer(type, env->must_be_constant);
2063 if (env->entity != NULL) {
2065 "extra brace group at end of initializer for '%Y'",
2066 env->entity->base.symbol);
2068 errorf(HERE, "extra brace group at end of initializer");
2073 descend_into_subtype(path);
2076 add_anchor_token('}');
2077 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2079 rem_anchor_token('}');
2082 ascend_from_subtype(path);
2083 expect('}', end_error);
2085 expect('}', end_error);
2086 goto error_parse_next;
2090 /* must be an expression */
2091 expression_t *expression = parse_assignment_expression();
2092 mark_vars_read(expression, NULL);
2094 if (env->must_be_constant && !is_linker_constant(expression)) {
2095 errorf(&expression->base.source_position,
2096 "Initialisation expression '%E' is not constant",
2101 /* we are already outside, ... */
2102 if (outer_type == NULL)
2103 goto error_parse_next;
2104 type_t *const outer_type_skip = skip_typeref(outer_type);
2105 if (is_type_compound(outer_type_skip) &&
2106 !outer_type_skip->compound.compound->complete) {
2107 goto error_parse_next;
2110 source_position_t const* const pos = &expression->base.source_position;
2111 if (env->entity != NULL) {
2112 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2114 warningf(WARN_OTHER, pos, "excess elements in initializer");
2116 goto error_parse_next;
2119 /* handle { "string" } special case */
2120 if ((expression->kind == EXPR_STRING_LITERAL
2121 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2122 && outer_type != NULL) {
2123 sub = initializer_from_expression(outer_type, expression);
2126 if (token.kind != '}') {
2127 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2129 /* TODO: eat , ... */
2134 /* descend into subtypes until expression matches type */
2136 orig_type = path->top_type;
2137 type = skip_typeref(orig_type);
2139 sub = initializer_from_expression(orig_type, expression);
2143 if (!is_type_valid(type)) {
2146 if (is_type_scalar(type)) {
2147 errorf(&expression->base.source_position,
2148 "expression '%E' doesn't match expected type '%T'",
2149 expression, orig_type);
2153 descend_into_subtype(path);
2157 /* update largest index of top array */
2158 const type_path_entry_t *first = &path->path[0];
2159 type_t *first_type = first->type;
2160 first_type = skip_typeref(first_type);
2161 if (is_type_array(first_type)) {
2162 size_t index = first->v.index;
2163 if (index > path->max_index)
2164 path->max_index = index;
2167 /* append to initializers list */
2168 ARR_APP1(initializer_t*, initializers, sub);
2171 if (token.kind == '}') {
2174 expect(',', end_error);
2175 if (token.kind == '}') {
2180 /* advance to the next declaration if we are not at the end */
2181 advance_current_object(path, top_path_level);
2182 orig_type = path->top_type;
2183 if (orig_type != NULL)
2184 type = skip_typeref(orig_type);
2190 size_t len = ARR_LEN(initializers);
2191 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2192 initializer_t *result = allocate_ast_zero(size);
2193 result->kind = INITIALIZER_LIST;
2194 result->list.len = len;
2195 memcpy(&result->list.initializers, initializers,
2196 len * sizeof(initializers[0]));
2198 DEL_ARR_F(initializers);
2199 ascend_to(path, top_path_level+1);
2204 skip_initializers();
2205 DEL_ARR_F(initializers);
2206 ascend_to(path, top_path_level+1);
2210 static expression_t *make_size_literal(size_t value)
2212 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2213 literal->base.type = type_size_t;
2216 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2217 literal->literal.value = make_string(buf);
2223 * Parses an initializer. Parsers either a compound literal
2224 * (env->declaration == NULL) or an initializer of a declaration.
2226 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2228 type_t *type = skip_typeref(env->type);
2229 size_t max_index = 0;
2230 initializer_t *result;
2232 if (is_type_scalar(type)) {
2233 result = parse_scalar_initializer(type, env->must_be_constant);
2234 } else if (token.kind == '{') {
2238 memset(&path, 0, sizeof(path));
2239 path.top_type = env->type;
2240 path.path = NEW_ARR_F(type_path_entry_t, 0);
2242 descend_into_subtype(&path);
2244 add_anchor_token('}');
2245 result = parse_sub_initializer(&path, env->type, 1, env);
2246 rem_anchor_token('}');
2248 max_index = path.max_index;
2249 DEL_ARR_F(path.path);
2251 expect('}', end_error);
2254 /* parse_scalar_initializer() also works in this case: we simply
2255 * have an expression without {} around it */
2256 result = parse_scalar_initializer(type, env->must_be_constant);
2259 /* §6.7.8:22 array initializers for arrays with unknown size determine
2260 * the array type size */
2261 if (is_type_array(type) && type->array.size_expression == NULL
2262 && result != NULL) {
2264 switch (result->kind) {
2265 case INITIALIZER_LIST:
2266 assert(max_index != 0xdeadbeaf);
2267 size = max_index + 1;
2270 case INITIALIZER_STRING:
2271 size = result->string.string.size;
2274 case INITIALIZER_WIDE_STRING:
2275 size = result->wide_string.string.size;
2278 case INITIALIZER_DESIGNATOR:
2279 case INITIALIZER_VALUE:
2280 /* can happen for parse errors */
2285 internal_errorf(HERE, "invalid initializer type");
2288 type_t *new_type = duplicate_type(type);
2290 new_type->array.size_expression = make_size_literal(size);
2291 new_type->array.size_constant = true;
2292 new_type->array.has_implicit_size = true;
2293 new_type->array.size = size;
2294 env->type = new_type;
2300 static void append_entity(scope_t *scope, entity_t *entity)
2302 if (scope->last_entity != NULL) {
2303 scope->last_entity->base.next = entity;
2305 scope->entities = entity;
2307 entity->base.parent_entity = current_entity;
2308 scope->last_entity = entity;
2312 static compound_t *parse_compound_type_specifier(bool is_struct)
2314 source_position_t const pos = *HERE;
2315 eat(is_struct ? T_struct : T_union);
2317 symbol_t *symbol = NULL;
2318 entity_t *entity = NULL;
2319 attribute_t *attributes = NULL;
2321 if (token.kind == T___attribute__) {
2322 attributes = parse_attributes(NULL);
2325 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2326 if (token.kind == T_IDENTIFIER) {
2327 /* the compound has a name, check if we have seen it already */
2328 symbol = token.identifier.symbol;
2329 entity = get_tag(symbol, kind);
2332 if (entity != NULL) {
2333 if (entity->base.parent_scope != current_scope &&
2334 (token.kind == '{' || token.kind == ';')) {
2335 /* we're in an inner scope and have a definition. Shadow
2336 * existing definition in outer scope */
2338 } else if (entity->compound.complete && token.kind == '{') {
2339 source_position_t const *const ppos = &entity->base.source_position;
2340 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2341 /* clear members in the hope to avoid further errors */
2342 entity->compound.members.entities = NULL;
2345 } else if (token.kind != '{') {
2346 char const *const msg =
2347 is_struct ? "while parsing struct type specifier" :
2348 "while parsing union type specifier";
2349 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2354 if (entity == NULL) {
2355 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2356 entity->compound.alignment = 1;
2357 entity->base.source_position = pos;
2358 entity->base.parent_scope = current_scope;
2359 if (symbol != NULL) {
2360 environment_push(entity);
2362 append_entity(current_scope, entity);
2365 if (token.kind == '{') {
2366 parse_compound_type_entries(&entity->compound);
2368 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2369 if (symbol == NULL) {
2370 assert(anonymous_entity == NULL);
2371 anonymous_entity = entity;
2375 if (attributes != NULL) {
2376 handle_entity_attributes(attributes, entity);
2379 return &entity->compound;
2382 static void parse_enum_entries(type_t *const enum_type)
2386 if (token.kind == '}') {
2387 errorf(HERE, "empty enum not allowed");
2392 add_anchor_token('}');
2394 if (token.kind != T_IDENTIFIER) {
2395 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2397 rem_anchor_token('}');
2401 symbol_t *symbol = token.identifier.symbol;
2402 entity_t *const entity
2403 = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol);
2404 entity->enum_value.enum_type = enum_type;
2405 entity->base.source_position = token.base.source_position;
2409 expression_t *value = parse_constant_expression();
2411 value = create_implicit_cast(value, enum_type);
2412 entity->enum_value.value = value;
2417 record_entity(entity, false);
2418 } while (next_if(',') && token.kind != '}');
2419 rem_anchor_token('}');
2421 expect('}', end_error);
2427 static type_t *parse_enum_specifier(void)
2429 source_position_t const pos = *HERE;
2434 switch (token.kind) {
2436 symbol = token.identifier.symbol;
2437 entity = get_tag(symbol, ENTITY_ENUM);
2440 if (entity != NULL) {
2441 if (entity->base.parent_scope != current_scope &&
2442 (token.kind == '{' || token.kind == ';')) {
2443 /* we're in an inner scope and have a definition. Shadow
2444 * existing definition in outer scope */
2446 } else if (entity->enume.complete && token.kind == '{') {
2447 source_position_t const *const ppos = &entity->base.source_position;
2448 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2459 parse_error_expected("while parsing enum type specifier",
2460 T_IDENTIFIER, '{', NULL);
2464 if (entity == NULL) {
2465 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2466 entity->base.source_position = pos;
2467 entity->base.parent_scope = current_scope;
2470 type_t *const type = allocate_type_zero(TYPE_ENUM);
2471 type->enumt.enume = &entity->enume;
2472 type->enumt.base.akind = ATOMIC_TYPE_INT;
2474 if (token.kind == '{') {
2475 if (symbol != NULL) {
2476 environment_push(entity);
2478 append_entity(current_scope, entity);
2479 entity->enume.complete = true;
2481 parse_enum_entries(type);
2482 parse_attributes(NULL);
2484 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2485 if (symbol == NULL) {
2486 assert(anonymous_entity == NULL);
2487 anonymous_entity = entity;
2489 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2490 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2497 * if a symbol is a typedef to another type, return true
2499 static bool is_typedef_symbol(symbol_t *symbol)
2501 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2502 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2505 static type_t *parse_typeof(void)
2511 expect('(', end_error);
2512 add_anchor_token(')');
2514 expression_t *expression = NULL;
2516 switch (token.kind) {
2518 if (is_typedef_symbol(token.identifier.symbol)) {
2520 type = parse_typename();
2523 expression = parse_expression();
2524 type = revert_automatic_type_conversion(expression);
2529 rem_anchor_token(')');
2530 expect(')', end_error);
2532 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2533 typeof_type->typeoft.expression = expression;
2534 typeof_type->typeoft.typeof_type = type;
2541 typedef enum specifiers_t {
2542 SPECIFIER_SIGNED = 1 << 0,
2543 SPECIFIER_UNSIGNED = 1 << 1,
2544 SPECIFIER_LONG = 1 << 2,
2545 SPECIFIER_INT = 1 << 3,
2546 SPECIFIER_DOUBLE = 1 << 4,
2547 SPECIFIER_CHAR = 1 << 5,
2548 SPECIFIER_WCHAR_T = 1 << 6,
2549 SPECIFIER_SHORT = 1 << 7,
2550 SPECIFIER_LONG_LONG = 1 << 8,
2551 SPECIFIER_FLOAT = 1 << 9,
2552 SPECIFIER_BOOL = 1 << 10,
2553 SPECIFIER_VOID = 1 << 11,
2554 SPECIFIER_INT8 = 1 << 12,
2555 SPECIFIER_INT16 = 1 << 13,
2556 SPECIFIER_INT32 = 1 << 14,
2557 SPECIFIER_INT64 = 1 << 15,
2558 SPECIFIER_INT128 = 1 << 16,
2559 SPECIFIER_COMPLEX = 1 << 17,
2560 SPECIFIER_IMAGINARY = 1 << 18,
2563 static type_t *get_typedef_type(symbol_t *symbol)
2565 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2566 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2569 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2570 type->typedeft.typedefe = &entity->typedefe;
2575 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2577 expect('(', end_error);
2579 attribute_property_argument_t *property
2580 = allocate_ast_zero(sizeof(*property));
2583 if (token.kind != T_IDENTIFIER) {
2584 parse_error_expected("while parsing property declspec",
2585 T_IDENTIFIER, NULL);
2590 symbol_t *symbol = token.identifier.symbol;
2591 if (streq(symbol->string, "put")) {
2592 prop = &property->put_symbol;
2593 } else if (streq(symbol->string, "get")) {
2594 prop = &property->get_symbol;
2596 errorf(HERE, "expected put or get in property declspec");
2600 expect('=', end_error);
2601 if (token.kind != T_IDENTIFIER) {
2602 parse_error_expected("while parsing property declspec",
2603 T_IDENTIFIER, NULL);
2607 *prop = token.identifier.symbol;
2609 } while (next_if(','));
2611 attribute->a.property = property;
2613 expect(')', end_error);
2619 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2621 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2622 if (next_if(T_restrict)) {
2623 kind = ATTRIBUTE_MS_RESTRICT;
2624 } else if (token.kind == T_IDENTIFIER) {
2625 const char *name = token.identifier.symbol->string;
2626 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2628 const char *attribute_name = get_attribute_name(k);
2629 if (attribute_name != NULL && streq(attribute_name, name)) {
2635 if (kind == ATTRIBUTE_UNKNOWN) {
2636 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2639 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2643 attribute_t *attribute = allocate_attribute_zero(kind);
2646 if (kind == ATTRIBUTE_MS_PROPERTY) {
2647 return parse_attribute_ms_property(attribute);
2650 /* parse arguments */
2652 attribute->a.arguments = parse_attribute_arguments();
2657 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2661 expect('(', end_error);
2666 add_anchor_token(')');
2668 attribute_t **anchor = &first;
2670 while (*anchor != NULL)
2671 anchor = &(*anchor)->next;
2673 attribute_t *attribute
2674 = parse_microsoft_extended_decl_modifier_single();
2675 if (attribute == NULL)
2678 *anchor = attribute;
2679 anchor = &attribute->next;
2680 } while (next_if(','));
2682 rem_anchor_token(')');
2683 expect(')', end_error);
2687 rem_anchor_token(')');
2691 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2693 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2694 entity->base.source_position = *HERE;
2695 if (is_declaration(entity)) {
2696 entity->declaration.type = type_error_type;
2697 entity->declaration.implicit = true;
2698 } else if (kind == ENTITY_TYPEDEF) {
2699 entity->typedefe.type = type_error_type;
2700 entity->typedefe.builtin = true;
2702 if (kind != ENTITY_COMPOUND_MEMBER)
2703 record_entity(entity, false);
2707 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2709 type_t *type = NULL;
2710 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2711 unsigned type_specifiers = 0;
2712 bool newtype = false;
2713 bool saw_error = false;
2715 memset(specifiers, 0, sizeof(*specifiers));
2716 specifiers->source_position = token.base.source_position;
2719 specifiers->attributes = parse_attributes(specifiers->attributes);
2721 switch (token.kind) {
2723 #define MATCH_STORAGE_CLASS(token, class) \
2725 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2726 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2728 specifiers->storage_class = class; \
2729 if (specifiers->thread_local) \
2730 goto check_thread_storage_class; \
2734 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2735 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2736 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2737 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2738 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2741 specifiers->attributes
2742 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2746 if (specifiers->thread_local) {
2747 errorf(HERE, "duplicate '__thread'");
2749 specifiers->thread_local = true;
2750 check_thread_storage_class:
2751 switch (specifiers->storage_class) {
2752 case STORAGE_CLASS_EXTERN:
2753 case STORAGE_CLASS_NONE:
2754 case STORAGE_CLASS_STATIC:
2758 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2759 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2760 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2761 wrong_thread_storage_class:
2762 errorf(HERE, "'__thread' used with '%s'", wrong);
2769 /* type qualifiers */
2770 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2772 qualifiers |= qualifier; \
2776 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2777 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2778 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2779 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2780 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2781 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2782 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2783 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2785 /* type specifiers */
2786 #define MATCH_SPECIFIER(token, specifier, name) \
2788 if (type_specifiers & specifier) { \
2789 errorf(HERE, "multiple " name " type specifiers given"); \
2791 type_specifiers |= specifier; \
2796 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2797 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2798 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2799 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2800 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2801 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2802 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2803 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2804 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2805 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2806 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2807 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2808 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2809 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2810 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2811 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2812 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2813 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2817 specifiers->is_inline = true;
2821 case T__forceinline:
2823 specifiers->modifiers |= DM_FORCEINLINE;
2828 if (type_specifiers & SPECIFIER_LONG_LONG) {
2829 errorf(HERE, "too many long type specifiers given");
2830 } else if (type_specifiers & SPECIFIER_LONG) {
2831 type_specifiers |= SPECIFIER_LONG_LONG;
2833 type_specifiers |= SPECIFIER_LONG;
2838 #define CHECK_DOUBLE_TYPE() \
2839 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2842 CHECK_DOUBLE_TYPE();
2843 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2845 type->compound.compound = parse_compound_type_specifier(true);
2848 CHECK_DOUBLE_TYPE();
2849 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2850 type->compound.compound = parse_compound_type_specifier(false);
2853 CHECK_DOUBLE_TYPE();
2854 type = parse_enum_specifier();
2857 CHECK_DOUBLE_TYPE();
2858 type = parse_typeof();
2860 case T___builtin_va_list:
2861 CHECK_DOUBLE_TYPE();
2862 type = duplicate_type(type_valist);
2866 case T_IDENTIFIER: {
2867 /* only parse identifier if we haven't found a type yet */
2868 if (type != NULL || type_specifiers != 0) {
2869 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2870 * declaration, so it doesn't generate errors about expecting '(' or
2872 switch (look_ahead(1)->kind) {
2879 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2883 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2888 goto finish_specifiers;
2892 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2893 if (typedef_type == NULL) {
2894 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2895 * declaration, so it doesn't generate 'implicit int' followed by more
2896 * errors later on. */
2897 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2903 errorf(HERE, "%K does not name a type", &token);
2905 symbol_t *symbol = token.identifier.symbol;
2907 = create_error_entity(symbol, ENTITY_TYPEDEF);
2909 type = allocate_type_zero(TYPE_TYPEDEF);
2910 type->typedeft.typedefe = &entity->typedefe;
2918 goto finish_specifiers;
2923 type = typedef_type;
2927 /* function specifier */
2929 goto finish_specifiers;
2934 specifiers->attributes = parse_attributes(specifiers->attributes);
2936 if (type == NULL || (saw_error && type_specifiers != 0)) {
2937 atomic_type_kind_t atomic_type;
2939 /* match valid basic types */
2940 switch (type_specifiers) {
2941 case SPECIFIER_VOID:
2942 atomic_type = ATOMIC_TYPE_VOID;
2944 case SPECIFIER_WCHAR_T:
2945 atomic_type = ATOMIC_TYPE_WCHAR_T;
2947 case SPECIFIER_CHAR:
2948 atomic_type = ATOMIC_TYPE_CHAR;
2950 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2951 atomic_type = ATOMIC_TYPE_SCHAR;
2953 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2954 atomic_type = ATOMIC_TYPE_UCHAR;
2956 case SPECIFIER_SHORT:
2957 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2958 case SPECIFIER_SHORT | SPECIFIER_INT:
2959 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2960 atomic_type = ATOMIC_TYPE_SHORT;
2962 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2963 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2964 atomic_type = ATOMIC_TYPE_USHORT;
2967 case SPECIFIER_SIGNED:
2968 case SPECIFIER_SIGNED | SPECIFIER_INT:
2969 atomic_type = ATOMIC_TYPE_INT;
2971 case SPECIFIER_UNSIGNED:
2972 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2973 atomic_type = ATOMIC_TYPE_UINT;
2975 case SPECIFIER_LONG:
2976 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2977 case SPECIFIER_LONG | SPECIFIER_INT:
2978 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2979 atomic_type = ATOMIC_TYPE_LONG;
2981 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2982 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2983 atomic_type = ATOMIC_TYPE_ULONG;
2986 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2987 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2988 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2989 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2991 atomic_type = ATOMIC_TYPE_LONGLONG;
2992 goto warn_about_long_long;
2994 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2995 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2997 atomic_type = ATOMIC_TYPE_ULONGLONG;
2998 warn_about_long_long:
2999 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3002 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3003 atomic_type = unsigned_int8_type_kind;
3006 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3007 atomic_type = unsigned_int16_type_kind;
3010 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3011 atomic_type = unsigned_int32_type_kind;
3014 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3015 atomic_type = unsigned_int64_type_kind;
3018 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3019 atomic_type = unsigned_int128_type_kind;
3022 case SPECIFIER_INT8:
3023 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3024 atomic_type = int8_type_kind;
3027 case SPECIFIER_INT16:
3028 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3029 atomic_type = int16_type_kind;
3032 case SPECIFIER_INT32:
3033 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3034 atomic_type = int32_type_kind;
3037 case SPECIFIER_INT64:
3038 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3039 atomic_type = int64_type_kind;
3042 case SPECIFIER_INT128:
3043 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3044 atomic_type = int128_type_kind;
3047 case SPECIFIER_FLOAT:
3048 atomic_type = ATOMIC_TYPE_FLOAT;
3050 case SPECIFIER_DOUBLE:
3051 atomic_type = ATOMIC_TYPE_DOUBLE;
3053 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3054 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3056 case SPECIFIER_BOOL:
3057 atomic_type = ATOMIC_TYPE_BOOL;
3059 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3060 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3061 atomic_type = ATOMIC_TYPE_FLOAT;
3063 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3064 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3065 atomic_type = ATOMIC_TYPE_DOUBLE;
3067 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3068 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3069 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3072 /* invalid specifier combination, give an error message */
3073 source_position_t const* const pos = &specifiers->source_position;
3074 if (type_specifiers == 0) {
3076 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3077 if (!(c_mode & _CXX) && !strict_mode) {
3078 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3079 atomic_type = ATOMIC_TYPE_INT;
3082 errorf(pos, "no type specifiers given in declaration");
3085 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3086 (type_specifiers & SPECIFIER_UNSIGNED)) {
3087 errorf(pos, "signed and unsigned specifiers given");
3088 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3089 errorf(pos, "only integer types can be signed or unsigned");
3091 errorf(pos, "multiple datatypes in declaration");
3097 if (type_specifiers & SPECIFIER_COMPLEX) {
3098 type = allocate_type_zero(TYPE_COMPLEX);
3099 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3100 type = allocate_type_zero(TYPE_IMAGINARY);
3102 type = allocate_type_zero(TYPE_ATOMIC);
3104 type->atomic.akind = atomic_type;
3106 } else if (type_specifiers != 0) {
3107 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3110 /* FIXME: check type qualifiers here */
3111 type->base.qualifiers = qualifiers;
3114 type = identify_new_type(type);
3116 type = typehash_insert(type);
3119 if (specifiers->attributes != NULL)
3120 type = handle_type_attributes(specifiers->attributes, type);
3121 specifiers->type = type;
3125 specifiers->type = type_error_type;
3128 static type_qualifiers_t parse_type_qualifiers(void)
3130 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3133 switch (token.kind) {
3134 /* type qualifiers */
3135 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3136 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3137 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3138 /* microsoft extended type modifiers */
3139 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3140 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3141 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3142 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3143 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3152 * Parses an K&R identifier list
3154 static void parse_identifier_list(scope_t *scope)
3156 assert(token.kind == T_IDENTIFIER);
3158 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol);
3159 entity->base.source_position = token.base.source_position;
3160 /* a K&R parameter has no type, yet */
3164 append_entity(scope, entity);
3165 } while (next_if(',') && token.kind == T_IDENTIFIER);
3168 static entity_t *parse_parameter(void)
3170 declaration_specifiers_t specifiers;
3171 parse_declaration_specifiers(&specifiers);
3173 entity_t *entity = parse_declarator(&specifiers,
3174 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3175 anonymous_entity = NULL;
3179 static void semantic_parameter_incomplete(const entity_t *entity)
3181 assert(entity->kind == ENTITY_PARAMETER);
3183 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3184 * list in a function declarator that is part of a
3185 * definition of that function shall not have
3186 * incomplete type. */
3187 type_t *type = skip_typeref(entity->declaration.type);
3188 if (is_type_incomplete(type)) {
3189 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3193 static bool has_parameters(void)
3195 /* func(void) is not a parameter */
3196 if (look_ahead(1)->kind != ')')
3198 if (token.kind == T_IDENTIFIER) {
3199 entity_t const *const entity
3200 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3203 if (entity->kind != ENTITY_TYPEDEF)
3205 type_t const *const type = skip_typeref(entity->typedefe.type);
3206 if (!is_type_void(type))
3208 if (c_mode & _CXX) {
3209 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3210 * is not allowed. */
3211 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3212 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3213 /* §6.7.5.3:10 Qualification is not allowed here. */
3214 errorf(HERE, "'void' as parameter must not have type qualifiers");
3216 } else if (token.kind != T_void) {
3224 * Parses function type parameters (and optionally creates variable_t entities
3225 * for them in a scope)
3227 static void parse_parameters(function_type_t *type, scope_t *scope)
3230 add_anchor_token(')');
3231 int saved_comma_state = save_and_reset_anchor_state(',');
3233 if (token.kind == T_IDENTIFIER
3234 && !is_typedef_symbol(token.identifier.symbol)) {
3235 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3236 if (la1_type == ',' || la1_type == ')') {
3237 type->kr_style_parameters = true;
3238 parse_identifier_list(scope);
3239 goto parameters_finished;
3243 if (token.kind == ')') {
3244 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3245 if (!(c_mode & _CXX))
3246 type->unspecified_parameters = true;
3247 } else if (has_parameters()) {
3248 function_parameter_t **anchor = &type->parameters;
3250 switch (token.kind) {
3253 type->variadic = true;
3254 goto parameters_finished;
3259 entity_t *entity = parse_parameter();
3260 if (entity->kind == ENTITY_TYPEDEF) {
3261 errorf(&entity->base.source_position,
3262 "typedef not allowed as function parameter");
3265 assert(is_declaration(entity));
3267 semantic_parameter_incomplete(entity);
3269 function_parameter_t *const parameter =
3270 allocate_parameter(entity->declaration.type);
3272 if (scope != NULL) {
3273 append_entity(scope, entity);
3276 *anchor = parameter;
3277 anchor = ¶meter->next;
3282 goto parameters_finished;
3284 } while (next_if(','));
3287 parameters_finished:
3288 rem_anchor_token(')');
3289 expect(')', end_error);
3292 restore_anchor_state(',', saved_comma_state);
3295 typedef enum construct_type_kind_t {
3296 CONSTRUCT_POINTER = 1,
3297 CONSTRUCT_REFERENCE,
3300 } construct_type_kind_t;
3302 typedef union construct_type_t construct_type_t;
3304 typedef struct construct_type_base_t {
3305 construct_type_kind_t kind;
3306 source_position_t pos;
3307 construct_type_t *next;
3308 } construct_type_base_t;
3310 typedef struct parsed_pointer_t {
3311 construct_type_base_t base;
3312 type_qualifiers_t type_qualifiers;
3313 variable_t *base_variable; /**< MS __based extension. */
3316 typedef struct parsed_reference_t {
3317 construct_type_base_t base;
3318 } parsed_reference_t;
3320 typedef struct construct_function_type_t {
3321 construct_type_base_t base;
3322 type_t *function_type;
3323 } construct_function_type_t;
3325 typedef struct parsed_array_t {
3326 construct_type_base_t base;
3327 type_qualifiers_t type_qualifiers;
3333 union construct_type_t {
3334 construct_type_kind_t kind;
3335 construct_type_base_t base;
3336 parsed_pointer_t pointer;
3337 parsed_reference_t reference;
3338 construct_function_type_t function;
3339 parsed_array_t array;
3342 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3344 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3345 memset(cons, 0, size);
3347 cons->base.pos = *HERE;
3352 static construct_type_t *parse_pointer_declarator(void)
3354 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3356 cons->pointer.type_qualifiers = parse_type_qualifiers();
3357 //cons->pointer.base_variable = base_variable;
3362 /* ISO/IEC 14882:1998(E) §8.3.2 */
3363 static construct_type_t *parse_reference_declarator(void)
3365 if (!(c_mode & _CXX))
3366 errorf(HERE, "references are only available for C++");
3368 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3375 static construct_type_t *parse_array_declarator(void)
3377 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3378 parsed_array_t *const array = &cons->array;
3381 add_anchor_token(']');
3383 bool is_static = next_if(T_static);
3385 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3388 is_static = next_if(T_static);
3390 array->type_qualifiers = type_qualifiers;
3391 array->is_static = is_static;
3393 expression_t *size = NULL;
3394 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3395 array->is_variable = true;
3397 } else if (token.kind != ']') {
3398 size = parse_assignment_expression();
3400 /* §6.7.5.2:1 Array size must have integer type */
3401 type_t *const orig_type = size->base.type;
3402 type_t *const type = skip_typeref(orig_type);
3403 if (!is_type_integer(type) && is_type_valid(type)) {
3404 errorf(&size->base.source_position,
3405 "array size '%E' must have integer type but has type '%T'",
3410 mark_vars_read(size, NULL);
3413 if (is_static && size == NULL)
3414 errorf(&array->base.pos, "static array parameters require a size");
3416 rem_anchor_token(']');
3417 expect(']', end_error);
3424 static construct_type_t *parse_function_declarator(scope_t *scope)
3426 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3428 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3429 function_type_t *ftype = &type->function;
3431 ftype->linkage = current_linkage;
3432 ftype->calling_convention = CC_DEFAULT;
3434 parse_parameters(ftype, scope);
3436 cons->function.function_type = type;
3441 typedef struct parse_declarator_env_t {
3442 bool may_be_abstract : 1;
3443 bool must_be_abstract : 1;
3444 decl_modifiers_t modifiers;
3446 source_position_t source_position;
3448 attribute_t *attributes;
3449 } parse_declarator_env_t;
3452 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3454 /* construct a single linked list of construct_type_t's which describe
3455 * how to construct the final declarator type */
3456 construct_type_t *first = NULL;
3457 construct_type_t **anchor = &first;
3459 env->attributes = parse_attributes(env->attributes);
3462 construct_type_t *type;
3463 //variable_t *based = NULL; /* MS __based extension */
3464 switch (token.kind) {
3466 type = parse_reference_declarator();
3470 panic("based not supported anymore");
3475 type = parse_pointer_declarator();
3479 goto ptr_operator_end;
3483 anchor = &type->base.next;
3485 /* TODO: find out if this is correct */
3486 env->attributes = parse_attributes(env->attributes);
3490 construct_type_t *inner_types = NULL;
3492 switch (token.kind) {
3494 if (env->must_be_abstract) {
3495 errorf(HERE, "no identifier expected in typename");
3497 env->symbol = token.identifier.symbol;
3498 env->source_position = token.base.source_position;
3504 /* Parenthesized declarator or function declarator? */
3505 token_t const *const la1 = look_ahead(1);
3506 switch (la1->kind) {
3508 if (is_typedef_symbol(la1->identifier.symbol)) {
3510 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3511 * interpreted as ``function with no parameter specification'', rather
3512 * than redundant parentheses around the omitted identifier. */
3514 /* Function declarator. */
3515 if (!env->may_be_abstract) {
3516 errorf(HERE, "function declarator must have a name");
3523 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3524 /* Paranthesized declarator. */
3526 add_anchor_token(')');
3527 inner_types = parse_inner_declarator(env);
3528 if (inner_types != NULL) {
3529 /* All later declarators only modify the return type */
3530 env->must_be_abstract = true;
3532 rem_anchor_token(')');
3533 expect(')', end_error);
3541 if (env->may_be_abstract)
3543 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3548 construct_type_t **const p = anchor;
3551 construct_type_t *type;
3552 switch (token.kind) {
3554 scope_t *scope = NULL;
3555 if (!env->must_be_abstract) {
3556 scope = &env->parameters;
3559 type = parse_function_declarator(scope);
3563 type = parse_array_declarator();
3566 goto declarator_finished;
3569 /* insert in the middle of the list (at p) */
3570 type->base.next = *p;
3573 anchor = &type->base.next;
3576 declarator_finished:
3577 /* append inner_types at the end of the list, we don't to set anchor anymore
3578 * as it's not needed anymore */
3579 *anchor = inner_types;
3586 static type_t *construct_declarator_type(construct_type_t *construct_list,
3589 construct_type_t *iter = construct_list;
3590 for (; iter != NULL; iter = iter->base.next) {
3591 source_position_t const* const pos = &iter->base.pos;
3592 switch (iter->kind) {
3593 case CONSTRUCT_FUNCTION: {
3594 construct_function_type_t *function = &iter->function;
3595 type_t *function_type = function->function_type;
3597 function_type->function.return_type = type;
3599 type_t *skipped_return_type = skip_typeref(type);
3601 if (is_type_function(skipped_return_type)) {
3602 errorf(pos, "function returning function is not allowed");
3603 } else if (is_type_array(skipped_return_type)) {
3604 errorf(pos, "function returning array is not allowed");
3606 if (skipped_return_type->base.qualifiers != 0) {
3607 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3611 /* The function type was constructed earlier. Freeing it here will
3612 * destroy other types. */
3613 type = typehash_insert(function_type);
3617 case CONSTRUCT_POINTER: {
3618 if (is_type_reference(skip_typeref(type)))
3619 errorf(pos, "cannot declare a pointer to reference");
3621 parsed_pointer_t *pointer = &iter->pointer;
3622 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3626 case CONSTRUCT_REFERENCE:
3627 if (is_type_reference(skip_typeref(type)))
3628 errorf(pos, "cannot declare a reference to reference");
3630 type = make_reference_type(type);
3633 case CONSTRUCT_ARRAY: {
3634 if (is_type_reference(skip_typeref(type)))
3635 errorf(pos, "cannot declare an array of references");
3637 parsed_array_t *array = &iter->array;
3638 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3640 expression_t *size_expression = array->size;
3641 if (size_expression != NULL) {
3643 = create_implicit_cast(size_expression, type_size_t);
3646 array_type->base.qualifiers = array->type_qualifiers;
3647 array_type->array.element_type = type;
3648 array_type->array.is_static = array->is_static;
3649 array_type->array.is_variable = array->is_variable;
3650 array_type->array.size_expression = size_expression;
3652 if (size_expression != NULL) {
3653 switch (is_constant_expression(size_expression)) {
3654 case EXPR_CLASS_CONSTANT: {
3655 long const size = fold_constant_to_int(size_expression);
3656 array_type->array.size = size;
3657 array_type->array.size_constant = true;
3658 /* §6.7.5.2:1 If the expression is a constant expression,
3659 * it shall have a value greater than zero. */
3661 errorf(&size_expression->base.source_position,
3662 "size of array must be greater than zero");
3663 } else if (size == 0 && !GNU_MODE) {
3664 errorf(&size_expression->base.source_position,
3665 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3670 case EXPR_CLASS_VARIABLE:
3671 array_type->array.is_vla = true;
3674 case EXPR_CLASS_ERROR:
3679 type_t *skipped_type = skip_typeref(type);
3681 if (is_type_incomplete(skipped_type)) {
3682 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3683 } else if (is_type_function(skipped_type)) {
3684 errorf(pos, "array of functions is not allowed");
3686 type = identify_new_type(array_type);
3690 internal_errorf(pos, "invalid type construction found");
3696 static type_t *automatic_type_conversion(type_t *orig_type);
3698 static type_t *semantic_parameter(const source_position_t *pos,
3700 const declaration_specifiers_t *specifiers,
3701 entity_t const *const param)
3703 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3704 * shall be adjusted to ``qualified pointer to type'',
3706 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3707 * type'' shall be adjusted to ``pointer to function
3708 * returning type'', as in 6.3.2.1. */
3709 type = automatic_type_conversion(type);
3711 if (specifiers->is_inline && is_type_valid(type)) {
3712 errorf(pos, "'%N' declared 'inline'", param);
3715 /* §6.9.1:6 The declarations in the declaration list shall contain
3716 * no storage-class specifier other than register and no
3717 * initializations. */
3718 if (specifiers->thread_local || (
3719 specifiers->storage_class != STORAGE_CLASS_NONE &&
3720 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3722 errorf(pos, "invalid storage class for '%N'", param);
3725 /* delay test for incomplete type, because we might have (void)
3726 * which is legal but incomplete... */
3731 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3732 declarator_flags_t flags)
3734 parse_declarator_env_t env;
3735 memset(&env, 0, sizeof(env));
3736 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3738 construct_type_t *construct_type = parse_inner_declarator(&env);
3740 construct_declarator_type(construct_type, specifiers->type);
3741 type_t *type = skip_typeref(orig_type);
3743 if (construct_type != NULL) {
3744 obstack_free(&temp_obst, construct_type);
3747 attribute_t *attributes = parse_attributes(env.attributes);
3748 /* append (shared) specifier attribute behind attributes of this
3750 attribute_t **anchor = &attributes;
3751 while (*anchor != NULL)
3752 anchor = &(*anchor)->next;
3753 *anchor = specifiers->attributes;
3756 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3757 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3758 entity->base.source_position = env.source_position;
3759 entity->typedefe.type = orig_type;
3761 if (anonymous_entity != NULL) {
3762 if (is_type_compound(type)) {
3763 assert(anonymous_entity->compound.alias == NULL);
3764 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3765 anonymous_entity->kind == ENTITY_UNION);
3766 anonymous_entity->compound.alias = entity;
3767 anonymous_entity = NULL;
3768 } else if (is_type_enum(type)) {
3769 assert(anonymous_entity->enume.alias == NULL);
3770 assert(anonymous_entity->kind == ENTITY_ENUM);
3771 anonymous_entity->enume.alias = entity;
3772 anonymous_entity = NULL;
3776 /* create a declaration type entity */
3777 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3778 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3780 if (env.symbol != NULL) {
3781 if (specifiers->is_inline && is_type_valid(type)) {
3782 errorf(&env.source_position,
3783 "compound member '%Y' declared 'inline'", env.symbol);
3786 if (specifiers->thread_local ||
3787 specifiers->storage_class != STORAGE_CLASS_NONE) {
3788 errorf(&env.source_position,
3789 "compound member '%Y' must have no storage class",
3793 } else if (flags & DECL_IS_PARAMETER) {
3794 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3795 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3796 } else if (is_type_function(type)) {
3797 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3798 entity->function.is_inline = specifiers->is_inline;
3799 entity->function.elf_visibility = default_visibility;
3800 entity->function.parameters = env.parameters;
3802 if (env.symbol != NULL) {
3803 /* this needs fixes for C++ */
3804 bool in_function_scope = current_function != NULL;
3806 if (specifiers->thread_local || (
3807 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3808 specifiers->storage_class != STORAGE_CLASS_NONE &&
3809 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3811 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3815 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3816 entity->variable.elf_visibility = default_visibility;
3817 entity->variable.thread_local = specifiers->thread_local;
3819 if (env.symbol != NULL) {
3820 if (specifiers->is_inline && is_type_valid(type)) {
3821 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3824 bool invalid_storage_class = false;
3825 if (current_scope == file_scope) {
3826 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3827 specifiers->storage_class != STORAGE_CLASS_NONE &&
3828 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3829 invalid_storage_class = true;
3832 if (specifiers->thread_local &&
3833 specifiers->storage_class == STORAGE_CLASS_NONE) {
3834 invalid_storage_class = true;
3837 if (invalid_storage_class) {
3838 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3843 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3844 entity->declaration.type = orig_type;
3845 entity->declaration.alignment = get_type_alignment(orig_type);
3846 entity->declaration.modifiers = env.modifiers;
3847 entity->declaration.attributes = attributes;
3849 storage_class_t storage_class = specifiers->storage_class;
3850 entity->declaration.declared_storage_class = storage_class;
3852 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3853 storage_class = STORAGE_CLASS_AUTO;
3854 entity->declaration.storage_class = storage_class;
3857 if (attributes != NULL) {
3858 handle_entity_attributes(attributes, entity);
3861 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3862 adapt_special_functions(&entity->function);
3868 static type_t *parse_abstract_declarator(type_t *base_type)
3870 parse_declarator_env_t env;
3871 memset(&env, 0, sizeof(env));
3872 env.may_be_abstract = true;
3873 env.must_be_abstract = true;
3875 construct_type_t *construct_type = parse_inner_declarator(&env);
3877 type_t *result = construct_declarator_type(construct_type, base_type);
3878 if (construct_type != NULL) {
3879 obstack_free(&temp_obst, construct_type);
3881 result = handle_type_attributes(env.attributes, result);
3887 * Check if the declaration of main is suspicious. main should be a
3888 * function with external linkage, returning int, taking either zero
3889 * arguments, two, or three arguments of appropriate types, ie.
3891 * int main([ int argc, char **argv [, char **env ] ]).
3893 * @param decl the declaration to check
3894 * @param type the function type of the declaration
3896 static void check_main(const entity_t *entity)
3898 const source_position_t *pos = &entity->base.source_position;
3899 if (entity->kind != ENTITY_FUNCTION) {
3900 warningf(WARN_MAIN, pos, "'main' is not a function");
3904 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3905 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3908 type_t *type = skip_typeref(entity->declaration.type);
3909 assert(is_type_function(type));
3911 function_type_t const *const func_type = &type->function;
3912 type_t *const ret_type = func_type->return_type;
3913 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3914 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3916 const function_parameter_t *parm = func_type->parameters;
3918 type_t *const first_type = skip_typeref(parm->type);
3919 type_t *const first_type_unqual = get_unqualified_type(first_type);
3920 if (!types_compatible(first_type_unqual, type_int)) {
3921 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3925 type_t *const second_type = skip_typeref(parm->type);
3926 type_t *const second_type_unqual
3927 = get_unqualified_type(second_type);
3928 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3929 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3933 type_t *const third_type = skip_typeref(parm->type);
3934 type_t *const third_type_unqual
3935 = get_unqualified_type(third_type);
3936 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3937 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3941 goto warn_arg_count;
3945 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3951 * Check if a symbol is the equal to "main".
3953 static bool is_sym_main(const symbol_t *const sym)
3955 return streq(sym->string, "main");
3958 static void error_redefined_as_different_kind(const source_position_t *pos,
3959 const entity_t *old, entity_kind_t new_kind)
3961 char const *const what = get_entity_kind_name(new_kind);
3962 source_position_t const *const ppos = &old->base.source_position;
3963 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3966 static bool is_entity_valid(entity_t *const ent)
3968 if (is_declaration(ent)) {
3969 return is_type_valid(skip_typeref(ent->declaration.type));
3970 } else if (ent->kind == ENTITY_TYPEDEF) {
3971 return is_type_valid(skip_typeref(ent->typedefe.type));
3976 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3978 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3979 if (attributes_equal(tattr, attr))
3986 * test wether new_list contains any attributes not included in old_list
3988 static bool has_new_attributes(const attribute_t *old_list,
3989 const attribute_t *new_list)
3991 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3992 if (!contains_attribute(old_list, attr))
3999 * Merge in attributes from an attribute list (probably from a previous
4000 * declaration with the same name). Warning: destroys the old structure
4001 * of the attribute list - don't reuse attributes after this call.
4003 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4006 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4008 if (contains_attribute(decl->attributes, attr))
4011 /* move attribute to new declarations attributes list */
4012 attr->next = decl->attributes;
4013 decl->attributes = attr;
4018 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4019 * for various problems that occur for multiple definitions
4021 entity_t *record_entity(entity_t *entity, const bool is_definition)
4023 const symbol_t *const symbol = entity->base.symbol;
4024 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4025 const source_position_t *pos = &entity->base.source_position;
4027 /* can happen in error cases */
4031 entity_t *const previous_entity = get_entity(symbol, namespc);
4032 /* pushing the same entity twice will break the stack structure */
4033 assert(previous_entity != entity);
4035 if (entity->kind == ENTITY_FUNCTION) {
4036 type_t *const orig_type = entity->declaration.type;
4037 type_t *const type = skip_typeref(orig_type);
4039 assert(is_type_function(type));
4040 if (type->function.unspecified_parameters &&
4041 previous_entity == NULL &&
4042 !entity->declaration.implicit) {
4043 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4046 if (current_scope == file_scope && is_sym_main(symbol)) {
4051 if (is_declaration(entity) &&
4052 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4053 current_scope != file_scope &&
4054 !entity->declaration.implicit) {
4055 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4058 if (previous_entity != NULL) {
4059 source_position_t const *const ppos = &previous_entity->base.source_position;
4061 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4062 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4063 assert(previous_entity->kind == ENTITY_PARAMETER);
4064 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4068 if (previous_entity->base.parent_scope == current_scope) {
4069 if (previous_entity->kind != entity->kind) {
4070 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4071 error_redefined_as_different_kind(pos, previous_entity,
4076 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4077 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4080 if (previous_entity->kind == ENTITY_TYPEDEF) {
4081 type_t *const type = skip_typeref(entity->typedefe.type);
4082 type_t *const prev_type
4083 = skip_typeref(previous_entity->typedefe.type);
4084 if (c_mode & _CXX) {
4085 /* C++ allows double typedef if they are identical
4086 * (after skipping typedefs) */
4087 if (type == prev_type)
4090 /* GCC extension: redef in system headers is allowed */
4091 if ((pos->is_system_header || ppos->is_system_header) &&
4092 types_compatible(type, prev_type))
4095 errorf(pos, "redefinition of '%N' (declared %P)",
4100 /* at this point we should have only VARIABLES or FUNCTIONS */
4101 assert(is_declaration(previous_entity) && is_declaration(entity));
4103 declaration_t *const prev_decl = &previous_entity->declaration;
4104 declaration_t *const decl = &entity->declaration;
4106 /* can happen for K&R style declarations */
4107 if (prev_decl->type == NULL &&
4108 previous_entity->kind == ENTITY_PARAMETER &&
4109 entity->kind == ENTITY_PARAMETER) {
4110 prev_decl->type = decl->type;
4111 prev_decl->storage_class = decl->storage_class;
4112 prev_decl->declared_storage_class = decl->declared_storage_class;
4113 prev_decl->modifiers = decl->modifiers;
4114 return previous_entity;
4117 type_t *const type = skip_typeref(decl->type);
4118 type_t *const prev_type = skip_typeref(prev_decl->type);
4120 if (!types_compatible(type, prev_type)) {
4121 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4123 unsigned old_storage_class = prev_decl->storage_class;
4125 if (is_definition &&
4127 !(prev_decl->modifiers & DM_USED) &&
4128 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4129 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4132 storage_class_t new_storage_class = decl->storage_class;
4134 /* pretend no storage class means extern for function
4135 * declarations (except if the previous declaration is neither
4136 * none nor extern) */
4137 if (entity->kind == ENTITY_FUNCTION) {
4138 /* the previous declaration could have unspecified parameters or
4139 * be a typedef, so use the new type */
4140 if (prev_type->function.unspecified_parameters || is_definition)
4141 prev_decl->type = type;
4143 switch (old_storage_class) {
4144 case STORAGE_CLASS_NONE:
4145 old_storage_class = STORAGE_CLASS_EXTERN;
4148 case STORAGE_CLASS_EXTERN:
4149 if (is_definition) {
4150 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4151 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4153 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4154 new_storage_class = STORAGE_CLASS_EXTERN;
4161 } else if (is_type_incomplete(prev_type)) {
4162 prev_decl->type = type;
4165 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4166 new_storage_class == STORAGE_CLASS_EXTERN) {
4168 warn_redundant_declaration: ;
4170 = has_new_attributes(prev_decl->attributes,
4172 if (has_new_attrs) {
4173 merge_in_attributes(decl, prev_decl->attributes);
4174 } else if (!is_definition &&
4175 is_type_valid(prev_type) &&
4176 !pos->is_system_header) {
4177 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4179 } else if (current_function == NULL) {
4180 if (old_storage_class != STORAGE_CLASS_STATIC &&
4181 new_storage_class == STORAGE_CLASS_STATIC) {
4182 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4183 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4184 prev_decl->storage_class = STORAGE_CLASS_NONE;
4185 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4187 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4189 goto error_redeclaration;
4190 goto warn_redundant_declaration;
4192 } else if (is_type_valid(prev_type)) {
4193 if (old_storage_class == new_storage_class) {
4194 error_redeclaration:
4195 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4197 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4202 prev_decl->modifiers |= decl->modifiers;
4203 if (entity->kind == ENTITY_FUNCTION) {
4204 previous_entity->function.is_inline |= entity->function.is_inline;
4206 return previous_entity;
4210 if (is_warn_on(why = WARN_SHADOW) ||
4211 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4212 char const *const what = get_entity_kind_name(previous_entity->kind);
4213 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4217 if (entity->kind == ENTITY_FUNCTION) {
4218 if (is_definition &&
4219 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4220 !is_sym_main(symbol)) {
4221 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4222 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4224 goto warn_missing_declaration;
4227 } else if (entity->kind == ENTITY_VARIABLE) {
4228 if (current_scope == file_scope &&
4229 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4230 !entity->declaration.implicit) {
4231 warn_missing_declaration:
4232 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4237 assert(entity->base.parent_scope == NULL);
4238 assert(current_scope != NULL);
4240 entity->base.parent_scope = current_scope;
4241 environment_push(entity);
4242 append_entity(current_scope, entity);
4247 static void parser_error_multiple_definition(entity_t *entity,
4248 const source_position_t *source_position)
4250 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4251 entity->base.symbol, &entity->base.source_position);
4254 static bool is_declaration_specifier(const token_t *token)
4256 switch (token->kind) {
4260 return is_typedef_symbol(token->identifier.symbol);
4267 static void parse_init_declarator_rest(entity_t *entity)
4269 type_t *orig_type = type_error_type;
4271 if (entity->base.kind == ENTITY_TYPEDEF) {
4272 source_position_t const *const pos = &entity->base.source_position;
4273 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4275 assert(is_declaration(entity));
4276 orig_type = entity->declaration.type;
4279 type_t *type = skip_typeref(orig_type);
4281 if (entity->kind == ENTITY_VARIABLE
4282 && entity->variable.initializer != NULL) {
4283 parser_error_multiple_definition(entity, HERE);
4287 declaration_t *const declaration = &entity->declaration;
4288 bool must_be_constant = false;
4289 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4290 entity->base.parent_scope == file_scope) {
4291 must_be_constant = true;
4294 if (is_type_function(type)) {
4295 source_position_t const *const pos = &entity->base.source_position;
4296 errorf(pos, "'%N' is initialized like a variable", entity);
4297 orig_type = type_error_type;
4300 parse_initializer_env_t env;
4301 env.type = orig_type;
4302 env.must_be_constant = must_be_constant;
4303 env.entity = entity;
4305 initializer_t *initializer = parse_initializer(&env);
4307 if (entity->kind == ENTITY_VARIABLE) {
4308 /* §6.7.5:22 array initializers for arrays with unknown size
4309 * determine the array type size */
4310 declaration->type = env.type;
4311 entity->variable.initializer = initializer;
4315 /* parse rest of a declaration without any declarator */
4316 static void parse_anonymous_declaration_rest(
4317 const declaration_specifiers_t *specifiers)
4320 anonymous_entity = NULL;
4322 source_position_t const *const pos = &specifiers->source_position;
4323 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4324 specifiers->thread_local) {
4325 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4328 type_t *type = specifiers->type;
4329 switch (type->kind) {
4330 case TYPE_COMPOUND_STRUCT:
4331 case TYPE_COMPOUND_UNION: {
4332 if (type->compound.compound->base.symbol == NULL) {
4333 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4342 warningf(WARN_OTHER, pos, "empty declaration");
4347 static void check_variable_type_complete(entity_t *ent)
4349 if (ent->kind != ENTITY_VARIABLE)
4352 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4353 * type for the object shall be complete [...] */
4354 declaration_t *decl = &ent->declaration;
4355 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4356 decl->storage_class == STORAGE_CLASS_STATIC)
4359 type_t *const type = skip_typeref(decl->type);
4360 if (!is_type_incomplete(type))
4363 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4364 * are given length one. */
4365 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4366 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4370 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4374 static void parse_declaration_rest(entity_t *ndeclaration,
4375 const declaration_specifiers_t *specifiers,
4376 parsed_declaration_func finished_declaration,
4377 declarator_flags_t flags)
4379 add_anchor_token(';');
4380 add_anchor_token(',');
4382 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4384 if (token.kind == '=') {
4385 parse_init_declarator_rest(entity);
4386 } else if (entity->kind == ENTITY_VARIABLE) {
4387 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4388 * [...] where the extern specifier is explicitly used. */
4389 declaration_t *decl = &entity->declaration;
4390 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4391 type_t *type = decl->type;
4392 if (is_type_reference(skip_typeref(type))) {
4393 source_position_t const *const pos = &entity->base.source_position;
4394 errorf(pos, "reference '%#N' must be initialized", entity);
4399 check_variable_type_complete(entity);
4404 add_anchor_token('=');
4405 ndeclaration = parse_declarator(specifiers, flags);
4406 rem_anchor_token('=');
4408 expect(';', end_error);
4411 anonymous_entity = NULL;
4412 rem_anchor_token(';');
4413 rem_anchor_token(',');
4416 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4418 symbol_t *symbol = entity->base.symbol;
4422 assert(entity->base.namespc == NAMESPACE_NORMAL);
4423 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4424 if (previous_entity == NULL
4425 || previous_entity->base.parent_scope != current_scope) {
4426 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4431 if (is_definition) {
4432 errorf(HERE, "'%N' is initialised", entity);
4435 return record_entity(entity, false);
4438 static void parse_declaration(parsed_declaration_func finished_declaration,
4439 declarator_flags_t flags)
4441 add_anchor_token(';');
4442 declaration_specifiers_t specifiers;
4443 parse_declaration_specifiers(&specifiers);
4444 rem_anchor_token(';');
4446 if (token.kind == ';') {
4447 parse_anonymous_declaration_rest(&specifiers);
4449 entity_t *entity = parse_declarator(&specifiers, flags);
4450 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4455 static type_t *get_default_promoted_type(type_t *orig_type)
4457 type_t *result = orig_type;
4459 type_t *type = skip_typeref(orig_type);
4460 if (is_type_integer(type)) {
4461 result = promote_integer(type);
4462 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4463 result = type_double;
4469 static void parse_kr_declaration_list(entity_t *entity)
4471 if (entity->kind != ENTITY_FUNCTION)
4474 type_t *type = skip_typeref(entity->declaration.type);
4475 assert(is_type_function(type));
4476 if (!type->function.kr_style_parameters)
4479 add_anchor_token('{');
4481 PUSH_SCOPE(&entity->function.parameters);
4483 entity_t *parameter = entity->function.parameters.entities;
4484 for ( ; parameter != NULL; parameter = parameter->base.next) {
4485 assert(parameter->base.parent_scope == NULL);
4486 parameter->base.parent_scope = current_scope;
4487 environment_push(parameter);
4490 /* parse declaration list */
4492 switch (token.kind) {
4494 /* This covers symbols, which are no type, too, and results in
4495 * better error messages. The typical cases are misspelled type
4496 * names and missing includes. */
4498 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4508 /* update function type */
4509 type_t *new_type = duplicate_type(type);
4511 function_parameter_t *parameters = NULL;
4512 function_parameter_t **anchor = ¶meters;
4514 /* did we have an earlier prototype? */
4515 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4516 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4519 function_parameter_t *proto_parameter = NULL;
4520 if (proto_type != NULL) {
4521 type_t *proto_type_type = proto_type->declaration.type;
4522 proto_parameter = proto_type_type->function.parameters;
4523 /* If a K&R function definition has a variadic prototype earlier, then
4524 * make the function definition variadic, too. This should conform to
4525 * §6.7.5.3:15 and §6.9.1:8. */
4526 new_type->function.variadic = proto_type_type->function.variadic;
4528 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4530 new_type->function.unspecified_parameters = true;
4533 bool need_incompatible_warning = false;
4534 parameter = entity->function.parameters.entities;
4535 for (; parameter != NULL; parameter = parameter->base.next,
4537 proto_parameter == NULL ? NULL : proto_parameter->next) {
4538 if (parameter->kind != ENTITY_PARAMETER)
4541 type_t *parameter_type = parameter->declaration.type;
4542 if (parameter_type == NULL) {
4543 source_position_t const* const pos = ¶meter->base.source_position;
4545 errorf(pos, "no type specified for function '%N'", parameter);
4546 parameter_type = type_error_type;
4548 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4549 parameter_type = type_int;
4551 parameter->declaration.type = parameter_type;
4554 semantic_parameter_incomplete(parameter);
4556 /* we need the default promoted types for the function type */
4557 type_t *not_promoted = parameter_type;
4558 parameter_type = get_default_promoted_type(parameter_type);
4560 /* gcc special: if the type of the prototype matches the unpromoted
4561 * type don't promote */
4562 if (!strict_mode && proto_parameter != NULL) {
4563 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4564 type_t *promo_skip = skip_typeref(parameter_type);
4565 type_t *param_skip = skip_typeref(not_promoted);
4566 if (!types_compatible(proto_p_type, promo_skip)
4567 && types_compatible(proto_p_type, param_skip)) {
4569 need_incompatible_warning = true;
4570 parameter_type = not_promoted;
4573 function_parameter_t *const function_parameter
4574 = allocate_parameter(parameter_type);
4576 *anchor = function_parameter;
4577 anchor = &function_parameter->next;
4580 new_type->function.parameters = parameters;
4581 new_type = identify_new_type(new_type);
4583 if (need_incompatible_warning) {
4584 symbol_t const *const sym = entity->base.symbol;
4585 source_position_t const *const pos = &entity->base.source_position;
4586 source_position_t const *const ppos = &proto_type->base.source_position;
4587 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4589 entity->declaration.type = new_type;
4591 rem_anchor_token('{');
4594 static bool first_err = true;
4597 * When called with first_err set, prints the name of the current function,
4600 static void print_in_function(void)
4604 char const *const file = current_function->base.base.source_position.input_name;
4605 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4610 * Check if all labels are defined in the current function.
4611 * Check if all labels are used in the current function.
4613 static void check_labels(void)
4615 for (const goto_statement_t *goto_statement = goto_first;
4616 goto_statement != NULL;
4617 goto_statement = goto_statement->next) {
4618 label_t *label = goto_statement->label;
4619 if (label->base.source_position.input_name == NULL) {
4620 print_in_function();
4621 source_position_t const *const pos = &goto_statement->base.source_position;
4622 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4626 if (is_warn_on(WARN_UNUSED_LABEL)) {
4627 for (const label_statement_t *label_statement = label_first;
4628 label_statement != NULL;
4629 label_statement = label_statement->next) {
4630 label_t *label = label_statement->label;
4632 if (! label->used) {
4633 print_in_function();
4634 source_position_t const *const pos = &label_statement->base.source_position;
4635 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4641 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4643 entity_t const *const end = last != NULL ? last->base.next : NULL;
4644 for (; entity != end; entity = entity->base.next) {
4645 if (!is_declaration(entity))
4648 declaration_t *declaration = &entity->declaration;
4649 if (declaration->implicit)
4652 if (!declaration->used) {
4653 print_in_function();
4654 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4655 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4656 print_in_function();
4657 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4662 static void check_unused_variables(statement_t *const stmt, void *const env)
4666 switch (stmt->kind) {
4667 case STATEMENT_DECLARATION: {
4668 declaration_statement_t const *const decls = &stmt->declaration;
4669 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4674 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4683 * Check declarations of current_function for unused entities.
4685 static void check_declarations(void)
4687 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4688 const scope_t *scope = ¤t_function->parameters;
4690 /* do not issue unused warnings for main */
4691 if (!is_sym_main(current_function->base.base.symbol)) {
4692 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4695 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4696 walk_statements(current_function->statement, check_unused_variables,
4701 static int determine_truth(expression_t const* const cond)
4704 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4705 fold_constant_to_bool(cond) ? 1 :
4709 static void check_reachable(statement_t *);
4710 static bool reaches_end;
4712 static bool expression_returns(expression_t const *const expr)
4714 switch (expr->kind) {
4716 expression_t const *const func = expr->call.function;
4717 type_t const *const type = skip_typeref(func->base.type);
4718 if (type->kind == TYPE_POINTER) {
4719 type_t const *const points_to
4720 = skip_typeref(type->pointer.points_to);
4721 if (points_to->kind == TYPE_FUNCTION
4722 && points_to->function.modifiers & DM_NORETURN)
4726 if (!expression_returns(func))
4729 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4730 if (!expression_returns(arg->expression))
4737 case EXPR_REFERENCE:
4738 case EXPR_ENUM_CONSTANT:
4739 case EXPR_LITERAL_CASES:
4740 case EXPR_STRING_LITERAL:
4741 case EXPR_WIDE_STRING_LITERAL:
4742 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4743 case EXPR_LABEL_ADDRESS:
4744 case EXPR_CLASSIFY_TYPE:
4745 case EXPR_SIZEOF: // TODO handle obscure VLA case
4748 case EXPR_BUILTIN_CONSTANT_P:
4749 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4754 case EXPR_STATEMENT: {
4755 bool old_reaches_end = reaches_end;
4756 reaches_end = false;
4757 check_reachable(expr->statement.statement);
4758 bool returns = reaches_end;
4759 reaches_end = old_reaches_end;
4763 case EXPR_CONDITIONAL:
4764 // TODO handle constant expression
4766 if (!expression_returns(expr->conditional.condition))
4769 if (expr->conditional.true_expression != NULL
4770 && expression_returns(expr->conditional.true_expression))
4773 return expression_returns(expr->conditional.false_expression);
4776 return expression_returns(expr->select.compound);
4778 case EXPR_ARRAY_ACCESS:
4780 expression_returns(expr->array_access.array_ref) &&
4781 expression_returns(expr->array_access.index);
4784 return expression_returns(expr->va_starte.ap);
4787 return expression_returns(expr->va_arge.ap);
4790 return expression_returns(expr->va_copye.src);
4792 case EXPR_UNARY_CASES_MANDATORY:
4793 return expression_returns(expr->unary.value);
4795 case EXPR_UNARY_THROW:
4798 case EXPR_BINARY_CASES:
4799 // TODO handle constant lhs of && and ||
4801 expression_returns(expr->binary.left) &&
4802 expression_returns(expr->binary.right);
4805 panic("unhandled expression");
4808 static bool initializer_returns(initializer_t const *const init)
4810 switch (init->kind) {
4811 case INITIALIZER_VALUE:
4812 return expression_returns(init->value.value);
4814 case INITIALIZER_LIST: {
4815 initializer_t * const* i = init->list.initializers;
4816 initializer_t * const* const end = i + init->list.len;
4817 bool returns = true;
4818 for (; i != end; ++i) {
4819 if (!initializer_returns(*i))
4825 case INITIALIZER_STRING:
4826 case INITIALIZER_WIDE_STRING:
4827 case INITIALIZER_DESIGNATOR: // designators have no payload
4830 panic("unhandled initializer");
4833 static bool noreturn_candidate;
4835 static void check_reachable(statement_t *const stmt)
4837 if (stmt->base.reachable)
4839 if (stmt->kind != STATEMENT_DO_WHILE)
4840 stmt->base.reachable = true;
4842 statement_t *last = stmt;
4844 switch (stmt->kind) {
4845 case STATEMENT_ERROR:
4846 case STATEMENT_EMPTY:
4848 next = stmt->base.next;
4851 case STATEMENT_DECLARATION: {
4852 declaration_statement_t const *const decl = &stmt->declaration;
4853 entity_t const * ent = decl->declarations_begin;
4854 entity_t const *const last_decl = decl->declarations_end;
4856 for (;; ent = ent->base.next) {
4857 if (ent->kind == ENTITY_VARIABLE &&
4858 ent->variable.initializer != NULL &&
4859 !initializer_returns(ent->variable.initializer)) {
4862 if (ent == last_decl)
4866 next = stmt->base.next;
4870 case STATEMENT_COMPOUND:
4871 next = stmt->compound.statements;
4873 next = stmt->base.next;
4876 case STATEMENT_RETURN: {
4877 expression_t const *const val = stmt->returns.value;
4878 if (val == NULL || expression_returns(val))
4879 noreturn_candidate = false;
4883 case STATEMENT_IF: {
4884 if_statement_t const *const ifs = &stmt->ifs;
4885 expression_t const *const cond = ifs->condition;
4887 if (!expression_returns(cond))
4890 int const val = determine_truth(cond);
4893 check_reachable(ifs->true_statement);
4898 if (ifs->false_statement != NULL) {
4899 check_reachable(ifs->false_statement);
4903 next = stmt->base.next;
4907 case STATEMENT_SWITCH: {
4908 switch_statement_t const *const switchs = &stmt->switchs;
4909 expression_t const *const expr = switchs->expression;
4911 if (!expression_returns(expr))
4914 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4915 long const val = fold_constant_to_int(expr);
4916 case_label_statement_t * defaults = NULL;
4917 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4918 if (i->expression == NULL) {
4923 if (i->first_case <= val && val <= i->last_case) {
4924 check_reachable((statement_t*)i);
4929 if (defaults != NULL) {
4930 check_reachable((statement_t*)defaults);
4934 bool has_default = false;
4935 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4936 if (i->expression == NULL)
4939 check_reachable((statement_t*)i);
4946 next = stmt->base.next;
4950 case STATEMENT_EXPRESSION: {
4951 /* Check for noreturn function call */
4952 expression_t const *const expr = stmt->expression.expression;
4953 if (!expression_returns(expr))
4956 next = stmt->base.next;
4960 case STATEMENT_CONTINUE:
4961 for (statement_t *parent = stmt;;) {
4962 parent = parent->base.parent;
4963 if (parent == NULL) /* continue not within loop */
4967 switch (parent->kind) {
4968 case STATEMENT_WHILE: goto continue_while;
4969 case STATEMENT_DO_WHILE: goto continue_do_while;
4970 case STATEMENT_FOR: goto continue_for;
4976 case STATEMENT_BREAK:
4977 for (statement_t *parent = stmt;;) {
4978 parent = parent->base.parent;
4979 if (parent == NULL) /* break not within loop/switch */
4982 switch (parent->kind) {
4983 case STATEMENT_SWITCH:
4984 case STATEMENT_WHILE:
4985 case STATEMENT_DO_WHILE:
4988 next = parent->base.next;
4989 goto found_break_parent;
4997 case STATEMENT_COMPUTED_GOTO: {
4998 if (!expression_returns(stmt->computed_goto.expression))
5001 statement_t *parent = stmt->base.parent;
5002 if (parent == NULL) /* top level goto */
5008 case STATEMENT_GOTO:
5009 next = stmt->gotos.label->statement;
5010 if (next == NULL) /* missing label */
5014 case STATEMENT_LABEL:
5015 next = stmt->label.statement;
5018 case STATEMENT_CASE_LABEL:
5019 next = stmt->case_label.statement;
5022 case STATEMENT_WHILE: {
5023 while_statement_t const *const whiles = &stmt->whiles;
5024 expression_t const *const cond = whiles->condition;
5026 if (!expression_returns(cond))
5029 int const val = determine_truth(cond);
5032 check_reachable(whiles->body);
5037 next = stmt->base.next;
5041 case STATEMENT_DO_WHILE:
5042 next = stmt->do_while.body;
5045 case STATEMENT_FOR: {
5046 for_statement_t *const fors = &stmt->fors;
5048 if (fors->condition_reachable)
5050 fors->condition_reachable = true;
5052 expression_t const *const cond = fors->condition;
5057 } else if (expression_returns(cond)) {
5058 val = determine_truth(cond);
5064 check_reachable(fors->body);
5069 next = stmt->base.next;
5073 case STATEMENT_MS_TRY: {
5074 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5075 check_reachable(ms_try->try_statement);
5076 next = ms_try->final_statement;
5080 case STATEMENT_LEAVE: {
5081 statement_t *parent = stmt;
5083 parent = parent->base.parent;
5084 if (parent == NULL) /* __leave not within __try */
5087 if (parent->kind == STATEMENT_MS_TRY) {
5089 next = parent->ms_try.final_statement;
5097 panic("invalid statement kind");
5100 while (next == NULL) {
5101 next = last->base.parent;
5103 noreturn_candidate = false;
5105 type_t *const type = skip_typeref(current_function->base.type);
5106 assert(is_type_function(type));
5107 type_t *const ret = skip_typeref(type->function.return_type);
5108 if (!is_type_void(ret) &&
5109 is_type_valid(ret) &&
5110 !is_sym_main(current_function->base.base.symbol)) {
5111 source_position_t const *const pos = &stmt->base.source_position;
5112 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5117 switch (next->kind) {
5118 case STATEMENT_ERROR:
5119 case STATEMENT_EMPTY:
5120 case STATEMENT_DECLARATION:
5121 case STATEMENT_EXPRESSION:
5123 case STATEMENT_RETURN:
5124 case STATEMENT_CONTINUE:
5125 case STATEMENT_BREAK:
5126 case STATEMENT_COMPUTED_GOTO:
5127 case STATEMENT_GOTO:
5128 case STATEMENT_LEAVE:
5129 panic("invalid control flow in function");
5131 case STATEMENT_COMPOUND:
5132 if (next->compound.stmt_expr) {
5138 case STATEMENT_SWITCH:
5139 case STATEMENT_LABEL:
5140 case STATEMENT_CASE_LABEL:
5142 next = next->base.next;
5145 case STATEMENT_WHILE: {
5147 if (next->base.reachable)
5149 next->base.reachable = true;
5151 while_statement_t const *const whiles = &next->whiles;
5152 expression_t const *const cond = whiles->condition;
5154 if (!expression_returns(cond))
5157 int const val = determine_truth(cond);
5160 check_reachable(whiles->body);
5166 next = next->base.next;
5170 case STATEMENT_DO_WHILE: {
5172 if (next->base.reachable)
5174 next->base.reachable = true;
5176 do_while_statement_t const *const dw = &next->do_while;
5177 expression_t const *const cond = dw->condition;
5179 if (!expression_returns(cond))
5182 int const val = determine_truth(cond);
5185 check_reachable(dw->body);
5191 next = next->base.next;
5195 case STATEMENT_FOR: {
5197 for_statement_t *const fors = &next->fors;
5199 fors->step_reachable = true;
5201 if (fors->condition_reachable)
5203 fors->condition_reachable = true;
5205 expression_t const *const cond = fors->condition;
5210 } else if (expression_returns(cond)) {
5211 val = determine_truth(cond);
5217 check_reachable(fors->body);
5223 next = next->base.next;
5227 case STATEMENT_MS_TRY:
5229 next = next->ms_try.final_statement;
5234 check_reachable(next);
5237 static void check_unreachable(statement_t* const stmt, void *const env)
5241 switch (stmt->kind) {
5242 case STATEMENT_DO_WHILE:
5243 if (!stmt->base.reachable) {
5244 expression_t const *const cond = stmt->do_while.condition;
5245 if (determine_truth(cond) >= 0) {
5246 source_position_t const *const pos = &cond->base.source_position;
5247 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5252 case STATEMENT_FOR: {
5253 for_statement_t const* const fors = &stmt->fors;
5255 // if init and step are unreachable, cond is unreachable, too
5256 if (!stmt->base.reachable && !fors->step_reachable) {
5257 goto warn_unreachable;
5259 if (!stmt->base.reachable && fors->initialisation != NULL) {
5260 source_position_t const *const pos = &fors->initialisation->base.source_position;
5261 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5264 if (!fors->condition_reachable && fors->condition != NULL) {
5265 source_position_t const *const pos = &fors->condition->base.source_position;
5266 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5269 if (!fors->step_reachable && fors->step != NULL) {
5270 source_position_t const *const pos = &fors->step->base.source_position;
5271 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5277 case STATEMENT_COMPOUND:
5278 if (stmt->compound.statements != NULL)
5280 goto warn_unreachable;
5282 case STATEMENT_DECLARATION: {
5283 /* Only warn if there is at least one declarator with an initializer.
5284 * This typically occurs in switch statements. */
5285 declaration_statement_t const *const decl = &stmt->declaration;
5286 entity_t const * ent = decl->declarations_begin;
5287 entity_t const *const last = decl->declarations_end;
5289 for (;; ent = ent->base.next) {
5290 if (ent->kind == ENTITY_VARIABLE &&
5291 ent->variable.initializer != NULL) {
5292 goto warn_unreachable;
5302 if (!stmt->base.reachable) {
5303 source_position_t const *const pos = &stmt->base.source_position;
5304 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5310 static bool is_main(entity_t *entity)
5312 static symbol_t *sym_main = NULL;
5313 if (sym_main == NULL) {
5314 sym_main = symbol_table_insert("main");
5317 if (entity->base.symbol != sym_main)
5319 /* must be in outermost scope */
5320 if (entity->base.parent_scope != file_scope)
5326 static void parse_external_declaration(void)
5328 /* function-definitions and declarations both start with declaration
5330 add_anchor_token(';');
5331 declaration_specifiers_t specifiers;
5332 parse_declaration_specifiers(&specifiers);
5333 rem_anchor_token(';');
5335 /* must be a declaration */
5336 if (token.kind == ';') {
5337 parse_anonymous_declaration_rest(&specifiers);
5341 add_anchor_token(',');
5342 add_anchor_token('=');
5343 add_anchor_token(';');
5344 add_anchor_token('{');
5346 /* declarator is common to both function-definitions and declarations */
5347 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5349 rem_anchor_token('{');
5350 rem_anchor_token(';');
5351 rem_anchor_token('=');
5352 rem_anchor_token(',');
5354 /* must be a declaration */
5355 switch (token.kind) {
5359 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5364 /* must be a function definition */
5365 parse_kr_declaration_list(ndeclaration);
5367 if (token.kind != '{') {
5368 parse_error_expected("while parsing function definition", '{', NULL);
5369 eat_until_matching_token(';');
5373 assert(is_declaration(ndeclaration));
5374 type_t *const orig_type = ndeclaration->declaration.type;
5375 type_t * type = skip_typeref(orig_type);
5377 if (!is_type_function(type)) {
5378 if (is_type_valid(type)) {
5379 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5385 source_position_t const *const pos = &ndeclaration->base.source_position;
5386 if (is_typeref(orig_type)) {
5388 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5391 if (is_type_compound(skip_typeref(type->function.return_type))) {
5392 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5394 if (type->function.unspecified_parameters) {
5395 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5397 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5400 /* §6.7.5.3:14 a function definition with () means no
5401 * parameters (and not unspecified parameters) */
5402 if (type->function.unspecified_parameters &&
5403 type->function.parameters == NULL) {
5404 type_t *copy = duplicate_type(type);
5405 copy->function.unspecified_parameters = false;
5406 type = identify_new_type(copy);
5408 ndeclaration->declaration.type = type;
5411 entity_t *const entity = record_entity(ndeclaration, true);
5412 assert(entity->kind == ENTITY_FUNCTION);
5413 assert(ndeclaration->kind == ENTITY_FUNCTION);
5415 function_t *const function = &entity->function;
5416 if (ndeclaration != entity) {
5417 function->parameters = ndeclaration->function.parameters;
5419 assert(is_declaration(entity));
5420 type = skip_typeref(entity->declaration.type);
5422 PUSH_SCOPE(&function->parameters);
5424 entity_t *parameter = function->parameters.entities;
5425 for (; parameter != NULL; parameter = parameter->base.next) {
5426 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5427 parameter->base.parent_scope = current_scope;
5429 assert(parameter->base.parent_scope == NULL
5430 || parameter->base.parent_scope == current_scope);
5431 parameter->base.parent_scope = current_scope;
5432 if (parameter->base.symbol == NULL) {
5433 errorf(¶meter->base.source_position, "parameter name omitted");
5436 environment_push(parameter);
5439 if (function->statement != NULL) {
5440 parser_error_multiple_definition(entity, HERE);
5443 /* parse function body */
5444 int label_stack_top = label_top();
5445 function_t *old_current_function = current_function;
5446 entity_t *old_current_entity = current_entity;
5447 current_function = function;
5448 current_entity = entity;
5452 goto_anchor = &goto_first;
5454 label_anchor = &label_first;
5456 statement_t *const body = parse_compound_statement(false);
5457 function->statement = body;
5460 check_declarations();
5461 if (is_warn_on(WARN_RETURN_TYPE) ||
5462 is_warn_on(WARN_UNREACHABLE_CODE) ||
5463 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5464 noreturn_candidate = true;
5465 check_reachable(body);
5466 if (is_warn_on(WARN_UNREACHABLE_CODE))
5467 walk_statements(body, check_unreachable, NULL);
5468 if (noreturn_candidate &&
5469 !(function->base.modifiers & DM_NORETURN)) {
5470 source_position_t const *const pos = &body->base.source_position;
5471 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5475 if (is_main(entity) && enable_main_collect2_hack)
5476 prepare_main_collect2(entity);
5479 assert(current_function == function);
5480 assert(current_entity == entity);
5481 current_entity = old_current_entity;
5482 current_function = old_current_function;
5483 label_pop_to(label_stack_top);
5489 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5491 entity_t *iter = compound->members.entities;
5492 for (; iter != NULL; iter = iter->base.next) {
5493 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5496 if (iter->base.symbol == symbol) {
5498 } else if (iter->base.symbol == NULL) {
5499 /* search in anonymous structs and unions */
5500 type_t *type = skip_typeref(iter->declaration.type);
5501 if (is_type_compound(type)) {
5502 if (find_compound_entry(type->compound.compound, symbol)
5513 static void check_deprecated(const source_position_t *source_position,
5514 const entity_t *entity)
5516 if (!is_declaration(entity))
5518 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5521 source_position_t const *const epos = &entity->base.source_position;
5522 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5524 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5526 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5531 static expression_t *create_select(const source_position_t *pos,
5533 type_qualifiers_t qualifiers,
5536 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5538 check_deprecated(pos, entry);
5540 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5541 select->select.compound = addr;
5542 select->select.compound_entry = entry;
5544 type_t *entry_type = entry->declaration.type;
5545 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5547 /* bitfields need special treatment */
5548 if (entry->compound_member.bitfield) {
5549 unsigned bit_size = entry->compound_member.bit_size;
5550 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5551 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5552 res_type = type_int;
5556 /* we always do the auto-type conversions; the & and sizeof parser contains
5557 * code to revert this! */
5558 select->base.type = automatic_type_conversion(res_type);
5565 * Find entry with symbol in compound. Search anonymous structs and unions and
5566 * creates implicit select expressions for them.
5567 * Returns the adress for the innermost compound.
5569 static expression_t *find_create_select(const source_position_t *pos,
5571 type_qualifiers_t qualifiers,
5572 compound_t *compound, symbol_t *symbol)
5574 entity_t *iter = compound->members.entities;
5575 for (; iter != NULL; iter = iter->base.next) {
5576 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5579 symbol_t *iter_symbol = iter->base.symbol;
5580 if (iter_symbol == NULL) {
5581 type_t *type = iter->declaration.type;
5582 if (type->kind != TYPE_COMPOUND_STRUCT
5583 && type->kind != TYPE_COMPOUND_UNION)
5586 compound_t *sub_compound = type->compound.compound;
5588 if (find_compound_entry(sub_compound, symbol) == NULL)
5591 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5592 sub_addr->base.source_position = *pos;
5593 sub_addr->base.implicit = true;
5594 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5598 if (iter_symbol == symbol) {
5599 return create_select(pos, addr, qualifiers, iter);
5606 static void parse_bitfield_member(entity_t *entity)
5610 expression_t *size = parse_constant_expression();
5613 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5614 type_t *type = entity->declaration.type;
5615 if (!is_type_integer(skip_typeref(type))) {
5616 errorf(HERE, "bitfield base type '%T' is not an integer type",
5620 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5621 /* error already reported by parse_constant_expression */
5622 size_long = get_type_size(type) * 8;
5624 size_long = fold_constant_to_int(size);
5626 const symbol_t *symbol = entity->base.symbol;
5627 const symbol_t *user_symbol
5628 = symbol == NULL ? sym_anonymous : symbol;
5629 unsigned bit_size = get_type_size(type) * 8;
5630 if (size_long < 0) {
5631 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5632 } else if (size_long == 0 && symbol != NULL) {
5633 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5634 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5635 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5638 /* hope that people don't invent crazy types with more bits
5639 * than our struct can hold */
5641 (1 << sizeof(entity->compound_member.bit_size)*8));
5645 entity->compound_member.bitfield = true;
5646 entity->compound_member.bit_size = (unsigned char)size_long;
5649 static void parse_compound_declarators(compound_t *compound,
5650 const declaration_specifiers_t *specifiers)
5655 if (token.kind == ':') {
5656 /* anonymous bitfield */
5657 type_t *type = specifiers->type;
5658 entity_t *entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER,
5659 NAMESPACE_NORMAL, NULL);
5660 entity->base.source_position = *HERE;
5661 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5662 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5663 entity->declaration.type = type;
5665 parse_bitfield_member(entity);
5667 attribute_t *attributes = parse_attributes(NULL);
5668 attribute_t **anchor = &attributes;
5669 while (*anchor != NULL)
5670 anchor = &(*anchor)->next;
5671 *anchor = specifiers->attributes;
5672 if (attributes != NULL) {
5673 handle_entity_attributes(attributes, entity);
5675 entity->declaration.attributes = attributes;
5677 append_entity(&compound->members, entity);
5679 entity = parse_declarator(specifiers,
5680 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5681 source_position_t const *const pos = &entity->base.source_position;
5682 if (entity->kind == ENTITY_TYPEDEF) {
5683 errorf(pos, "typedef not allowed as compound member");
5685 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5687 /* make sure we don't define a symbol multiple times */
5688 symbol_t *symbol = entity->base.symbol;
5689 if (symbol != NULL) {
5690 entity_t *prev = find_compound_entry(compound, symbol);
5692 source_position_t const *const ppos = &prev->base.source_position;
5693 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5697 if (token.kind == ':') {
5698 parse_bitfield_member(entity);
5700 attribute_t *attributes = parse_attributes(NULL);
5701 handle_entity_attributes(attributes, entity);
5703 type_t *orig_type = entity->declaration.type;
5704 type_t *type = skip_typeref(orig_type);
5705 if (is_type_function(type)) {
5706 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5707 } else if (is_type_incomplete(type)) {
5708 /* §6.7.2.1:16 flexible array member */
5709 if (!is_type_array(type) ||
5710 token.kind != ';' ||
5711 look_ahead(1)->kind != '}') {
5712 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5713 } else if (compound->members.entities == NULL) {
5714 errorf(pos, "flexible array member in otherwise empty struct");
5719 append_entity(&compound->members, entity);
5722 } while (next_if(','));
5723 expect(';', end_error);
5726 anonymous_entity = NULL;
5729 static void parse_compound_type_entries(compound_t *compound)
5732 add_anchor_token('}');
5735 switch (token.kind) {
5737 case T___extension__:
5738 case T_IDENTIFIER: {
5740 declaration_specifiers_t specifiers;
5741 parse_declaration_specifiers(&specifiers);
5742 parse_compound_declarators(compound, &specifiers);
5748 rem_anchor_token('}');
5749 expect('}', end_error);
5752 compound->complete = true;
5758 static type_t *parse_typename(void)
5760 declaration_specifiers_t specifiers;
5761 parse_declaration_specifiers(&specifiers);
5762 if (specifiers.storage_class != STORAGE_CLASS_NONE
5763 || specifiers.thread_local) {
5764 /* TODO: improve error message, user does probably not know what a
5765 * storage class is...
5767 errorf(&specifiers.source_position, "typename must not have a storage class");
5770 type_t *result = parse_abstract_declarator(specifiers.type);
5778 typedef expression_t* (*parse_expression_function)(void);
5779 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5781 typedef struct expression_parser_function_t expression_parser_function_t;
5782 struct expression_parser_function_t {
5783 parse_expression_function parser;
5784 precedence_t infix_precedence;
5785 parse_expression_infix_function infix_parser;
5788 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5791 * Prints an error message if an expression was expected but not read
5793 static expression_t *expected_expression_error(void)
5795 /* skip the error message if the error token was read */
5796 if (token.kind != T_ERROR) {
5797 errorf(HERE, "expected expression, got token %K", &token);
5801 return create_error_expression();
5804 static type_t *get_string_type(void)
5806 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5809 static type_t *get_wide_string_type(void)
5811 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5815 * Parse a string constant.
5817 static expression_t *parse_string_literal(void)
5819 source_position_t begin = token.base.source_position;
5820 string_t res = token.string.string;
5821 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5824 while (token.kind == T_STRING_LITERAL
5825 || token.kind == T_WIDE_STRING_LITERAL) {
5826 warn_string_concat(&token.base.source_position);
5827 res = concat_strings(&res, &token.string.string);
5829 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5832 expression_t *literal;
5834 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5835 literal->base.type = get_wide_string_type();
5837 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5838 literal->base.type = get_string_type();
5840 literal->base.source_position = begin;
5841 literal->literal.value = res;
5847 * Parse a boolean constant.
5849 static expression_t *parse_boolean_literal(bool value)
5851 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5852 literal->base.type = type_bool;
5853 literal->literal.value.begin = value ? "true" : "false";
5854 literal->literal.value.size = value ? 4 : 5;
5860 static void warn_traditional_suffix(void)
5862 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5863 &token.number.suffix);
5866 static void check_integer_suffix(void)
5868 const string_t *suffix = &token.number.suffix;
5869 if (suffix->size == 0)
5872 bool not_traditional = false;
5873 const char *c = suffix->begin;
5874 if (*c == 'l' || *c == 'L') {
5877 not_traditional = true;
5879 if (*c == 'u' || *c == 'U') {
5882 } else if (*c == 'u' || *c == 'U') {
5883 not_traditional = true;
5886 } else if (*c == 'u' || *c == 'U') {
5887 not_traditional = true;
5889 if (*c == 'l' || *c == 'L') {
5897 errorf(&token.base.source_position,
5898 "invalid suffix '%S' on integer constant", suffix);
5899 } else if (not_traditional) {
5900 warn_traditional_suffix();
5904 static type_t *check_floatingpoint_suffix(void)
5906 const string_t *suffix = &token.number.suffix;
5907 type_t *type = type_double;
5908 if (suffix->size == 0)
5911 bool not_traditional = false;
5912 const char *c = suffix->begin;
5913 if (*c == 'f' || *c == 'F') {
5916 } else if (*c == 'l' || *c == 'L') {
5918 type = type_long_double;
5921 errorf(&token.base.source_position,
5922 "invalid suffix '%S' on floatingpoint constant", suffix);
5923 } else if (not_traditional) {
5924 warn_traditional_suffix();
5931 * Parse an integer constant.
5933 static expression_t *parse_number_literal(void)
5935 expression_kind_t kind;
5938 switch (token.kind) {
5940 kind = EXPR_LITERAL_INTEGER;
5941 check_integer_suffix();
5944 case T_INTEGER_OCTAL:
5945 kind = EXPR_LITERAL_INTEGER_OCTAL;
5946 check_integer_suffix();
5949 case T_INTEGER_HEXADECIMAL:
5950 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5951 check_integer_suffix();
5954 case T_FLOATINGPOINT:
5955 kind = EXPR_LITERAL_FLOATINGPOINT;
5956 type = check_floatingpoint_suffix();
5958 case T_FLOATINGPOINT_HEXADECIMAL:
5959 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5960 type = check_floatingpoint_suffix();
5963 panic("unexpected token type in parse_number_literal");
5966 expression_t *literal = allocate_expression_zero(kind);
5967 literal->base.type = type;
5968 literal->literal.value = token.number.number;
5969 literal->literal.suffix = token.number.suffix;
5972 /* integer type depends on the size of the number and the size
5973 * representable by the types. The backend/codegeneration has to determine
5976 determine_literal_type(&literal->literal);
5981 * Parse a character constant.
5983 static expression_t *parse_character_constant(void)
5985 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5986 literal->base.type = c_mode & _CXX ? type_char : type_int;
5987 literal->literal.value = token.string.string;
5989 size_t len = literal->literal.value.size;
5991 if (!GNU_MODE && !(c_mode & _C99)) {
5992 errorf(HERE, "more than 1 character in character constant");
5994 literal->base.type = type_int;
5995 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6004 * Parse a wide character constant.
6006 static expression_t *parse_wide_character_constant(void)
6008 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6009 literal->base.type = type_int;
6010 literal->literal.value = token.string.string;
6012 size_t len = wstrlen(&literal->literal.value);
6014 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6021 static entity_t *create_implicit_function(symbol_t *symbol,
6022 const source_position_t *source_position)
6024 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6025 ntype->function.return_type = type_int;
6026 ntype->function.unspecified_parameters = true;
6027 ntype->function.linkage = LINKAGE_C;
6028 type_t *type = identify_new_type(ntype);
6030 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6031 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6032 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6033 entity->declaration.type = type;
6034 entity->declaration.implicit = true;
6035 entity->base.source_position = *source_position;
6037 if (current_scope != NULL)
6038 record_entity(entity, false);
6044 * Performs automatic type cast as described in §6.3.2.1.
6046 * @param orig_type the original type
6048 static type_t *automatic_type_conversion(type_t *orig_type)
6050 type_t *type = skip_typeref(orig_type);
6051 if (is_type_array(type)) {
6052 array_type_t *array_type = &type->array;
6053 type_t *element_type = array_type->element_type;
6054 unsigned qualifiers = array_type->base.qualifiers;
6056 return make_pointer_type(element_type, qualifiers);
6059 if (is_type_function(type)) {
6060 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6067 * reverts the automatic casts of array to pointer types and function
6068 * to function-pointer types as defined §6.3.2.1
6070 type_t *revert_automatic_type_conversion(const expression_t *expression)
6072 switch (expression->kind) {
6073 case EXPR_REFERENCE: {
6074 entity_t *entity = expression->reference.entity;
6075 if (is_declaration(entity)) {
6076 return entity->declaration.type;
6077 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6078 return entity->enum_value.enum_type;
6080 panic("no declaration or enum in reference");
6085 entity_t *entity = expression->select.compound_entry;
6086 assert(is_declaration(entity));
6087 type_t *type = entity->declaration.type;
6088 return get_qualified_type(type, expression->base.type->base.qualifiers);
6091 case EXPR_UNARY_DEREFERENCE: {
6092 const expression_t *const value = expression->unary.value;
6093 type_t *const type = skip_typeref(value->base.type);
6094 if (!is_type_pointer(type))
6095 return type_error_type;
6096 return type->pointer.points_to;
6099 case EXPR_ARRAY_ACCESS: {
6100 const expression_t *array_ref = expression->array_access.array_ref;
6101 type_t *type_left = skip_typeref(array_ref->base.type);
6102 if (!is_type_pointer(type_left))
6103 return type_error_type;
6104 return type_left->pointer.points_to;
6107 case EXPR_STRING_LITERAL: {
6108 size_t size = expression->string_literal.value.size;
6109 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6112 case EXPR_WIDE_STRING_LITERAL: {
6113 size_t size = wstrlen(&expression->string_literal.value);
6114 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6117 case EXPR_COMPOUND_LITERAL:
6118 return expression->compound_literal.type;
6123 return expression->base.type;
6127 * Find an entity matching a symbol in a scope.
6128 * Uses current scope if scope is NULL
6130 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6131 namespace_tag_t namespc)
6133 if (scope == NULL) {
6134 return get_entity(symbol, namespc);
6137 /* we should optimize here, if scope grows above a certain size we should
6138 construct a hashmap here... */
6139 entity_t *entity = scope->entities;
6140 for ( ; entity != NULL; entity = entity->base.next) {
6141 if (entity->base.symbol == symbol
6142 && (namespace_tag_t)entity->base.namespc == namespc)
6149 static entity_t *parse_qualified_identifier(void)
6151 /* namespace containing the symbol */
6153 source_position_t pos;
6154 const scope_t *lookup_scope = NULL;
6156 if (next_if(T_COLONCOLON))
6157 lookup_scope = &unit->scope;
6161 if (token.kind != T_IDENTIFIER) {
6162 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6163 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6165 symbol = token.identifier.symbol;
6170 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6172 if (!next_if(T_COLONCOLON))
6175 switch (entity->kind) {
6176 case ENTITY_NAMESPACE:
6177 lookup_scope = &entity->namespacee.members;
6182 lookup_scope = &entity->compound.members;
6185 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6186 symbol, get_entity_kind_name(entity->kind));
6188 /* skip further qualifications */
6189 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6191 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6195 if (entity == NULL) {
6196 if (!strict_mode && token.kind == '(') {
6197 /* an implicitly declared function */
6198 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6199 "implicit declaration of function '%Y'", symbol);
6200 entity = create_implicit_function(symbol, &pos);
6202 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6203 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6210 static expression_t *parse_reference(void)
6212 source_position_t const pos = token.base.source_position;
6213 entity_t *const entity = parse_qualified_identifier();
6216 if (is_declaration(entity)) {
6217 orig_type = entity->declaration.type;
6218 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6219 orig_type = entity->enum_value.enum_type;
6221 panic("expected declaration or enum value in reference");
6224 /* we always do the auto-type conversions; the & and sizeof parser contains
6225 * code to revert this! */
6226 type_t *type = automatic_type_conversion(orig_type);
6228 expression_kind_t kind = EXPR_REFERENCE;
6229 if (entity->kind == ENTITY_ENUM_VALUE)
6230 kind = EXPR_ENUM_CONSTANT;
6232 expression_t *expression = allocate_expression_zero(kind);
6233 expression->base.source_position = pos;
6234 expression->base.type = type;
6235 expression->reference.entity = entity;
6237 /* this declaration is used */
6238 if (is_declaration(entity)) {
6239 entity->declaration.used = true;
6242 if (entity->base.parent_scope != file_scope
6243 && (current_function != NULL
6244 && entity->base.parent_scope->depth < current_function->parameters.depth)
6245 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6246 if (entity->kind == ENTITY_VARIABLE) {
6247 /* access of a variable from an outer function */
6248 entity->variable.address_taken = true;
6249 } else if (entity->kind == ENTITY_PARAMETER) {
6250 entity->parameter.address_taken = true;
6252 current_function->need_closure = true;
6255 check_deprecated(&pos, entity);
6260 static bool semantic_cast(expression_t *cast)
6262 expression_t *expression = cast->unary.value;
6263 type_t *orig_dest_type = cast->base.type;
6264 type_t *orig_type_right = expression->base.type;
6265 type_t const *dst_type = skip_typeref(orig_dest_type);
6266 type_t const *src_type = skip_typeref(orig_type_right);
6267 source_position_t const *pos = &cast->base.source_position;
6269 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6270 if (is_type_void(dst_type))
6273 /* only integer and pointer can be casted to pointer */
6274 if (is_type_pointer(dst_type) &&
6275 !is_type_pointer(src_type) &&
6276 !is_type_integer(src_type) &&
6277 is_type_valid(src_type)) {
6278 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6282 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6283 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6287 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6288 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6292 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6293 type_t *src = skip_typeref(src_type->pointer.points_to);
6294 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6295 unsigned missing_qualifiers =
6296 src->base.qualifiers & ~dst->base.qualifiers;
6297 if (missing_qualifiers != 0) {
6298 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6304 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6306 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6307 expression->base.source_position = *pos;
6309 parse_initializer_env_t env;
6312 env.must_be_constant = false;
6313 initializer_t *initializer = parse_initializer(&env);
6316 expression->compound_literal.initializer = initializer;
6317 expression->compound_literal.type = type;
6318 expression->base.type = automatic_type_conversion(type);
6324 * Parse a cast expression.
6326 static expression_t *parse_cast(void)
6328 source_position_t const pos = *HERE;
6331 add_anchor_token(')');
6333 type_t *type = parse_typename();
6335 rem_anchor_token(')');
6336 expect(')', end_error);
6338 if (token.kind == '{') {
6339 return parse_compound_literal(&pos, type);
6342 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6343 cast->base.source_position = pos;
6345 expression_t *value = parse_subexpression(PREC_CAST);
6346 cast->base.type = type;
6347 cast->unary.value = value;
6349 if (! semantic_cast(cast)) {
6350 /* TODO: record the error in the AST. else it is impossible to detect it */
6355 return create_error_expression();
6359 * Parse a statement expression.
6361 static expression_t *parse_statement_expression(void)
6363 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6366 add_anchor_token(')');
6368 statement_t *statement = parse_compound_statement(true);
6369 statement->compound.stmt_expr = true;
6370 expression->statement.statement = statement;
6372 /* find last statement and use its type */
6373 type_t *type = type_void;
6374 const statement_t *stmt = statement->compound.statements;
6376 while (stmt->base.next != NULL)
6377 stmt = stmt->base.next;
6379 if (stmt->kind == STATEMENT_EXPRESSION) {
6380 type = stmt->expression.expression->base.type;
6383 source_position_t const *const pos = &expression->base.source_position;
6384 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6386 expression->base.type = type;
6388 rem_anchor_token(')');
6389 expect(')', end_error);
6396 * Parse a parenthesized expression.
6398 static expression_t *parse_parenthesized_expression(void)
6400 token_t const* const la1 = look_ahead(1);
6401 switch (la1->kind) {
6403 /* gcc extension: a statement expression */
6404 return parse_statement_expression();
6407 if (is_typedef_symbol(la1->identifier.symbol)) {
6409 return parse_cast();
6414 add_anchor_token(')');
6415 expression_t *result = parse_expression();
6416 result->base.parenthesized = true;
6417 rem_anchor_token(')');
6418 expect(')', end_error);
6424 static expression_t *parse_function_keyword(void)
6428 if (current_function == NULL) {
6429 errorf(HERE, "'__func__' used outside of a function");
6432 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6433 expression->base.type = type_char_ptr;
6434 expression->funcname.kind = FUNCNAME_FUNCTION;
6441 static expression_t *parse_pretty_function_keyword(void)
6443 if (current_function == NULL) {
6444 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6447 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6448 expression->base.type = type_char_ptr;
6449 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6451 eat(T___PRETTY_FUNCTION__);
6456 static expression_t *parse_funcsig_keyword(void)
6458 if (current_function == NULL) {
6459 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6462 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6463 expression->base.type = type_char_ptr;
6464 expression->funcname.kind = FUNCNAME_FUNCSIG;
6471 static expression_t *parse_funcdname_keyword(void)
6473 if (current_function == NULL) {
6474 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6477 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6478 expression->base.type = type_char_ptr;
6479 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6481 eat(T___FUNCDNAME__);
6486 static designator_t *parse_designator(void)
6488 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6489 result->source_position = *HERE;
6491 if (token.kind != T_IDENTIFIER) {
6492 parse_error_expected("while parsing member designator",
6493 T_IDENTIFIER, NULL);
6496 result->symbol = token.identifier.symbol;
6499 designator_t *last_designator = result;
6502 if (token.kind != T_IDENTIFIER) {
6503 parse_error_expected("while parsing member designator",
6504 T_IDENTIFIER, NULL);
6507 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6508 designator->source_position = *HERE;
6509 designator->symbol = token.identifier.symbol;
6512 last_designator->next = designator;
6513 last_designator = designator;
6517 add_anchor_token(']');
6518 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6519 designator->source_position = *HERE;
6520 designator->array_index = parse_expression();
6521 rem_anchor_token(']');
6522 expect(']', end_error);
6523 if (designator->array_index == NULL) {
6527 last_designator->next = designator;
6528 last_designator = designator;
6540 * Parse the __builtin_offsetof() expression.
6542 static expression_t *parse_offsetof(void)
6544 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6545 expression->base.type = type_size_t;
6547 eat(T___builtin_offsetof);
6549 expect('(', end_error);
6550 add_anchor_token(',');
6551 type_t *type = parse_typename();
6552 rem_anchor_token(',');
6553 expect(',', end_error);
6554 add_anchor_token(')');
6555 designator_t *designator = parse_designator();
6556 rem_anchor_token(')');
6557 expect(')', end_error);
6559 expression->offsetofe.type = type;
6560 expression->offsetofe.designator = designator;
6563 memset(&path, 0, sizeof(path));
6564 path.top_type = type;
6565 path.path = NEW_ARR_F(type_path_entry_t, 0);
6567 descend_into_subtype(&path);
6569 if (!walk_designator(&path, designator, true)) {
6570 return create_error_expression();
6573 DEL_ARR_F(path.path);
6577 return create_error_expression();
6581 * Parses a _builtin_va_start() expression.
6583 static expression_t *parse_va_start(void)
6585 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6587 eat(T___builtin_va_start);
6589 expect('(', end_error);
6590 add_anchor_token(',');
6591 expression->va_starte.ap = parse_assignment_expression();
6592 rem_anchor_token(',');
6593 expect(',', end_error);
6594 expression_t *const expr = parse_assignment_expression();
6595 if (expr->kind == EXPR_REFERENCE) {
6596 entity_t *const entity = expr->reference.entity;
6597 if (!current_function->base.type->function.variadic) {
6598 errorf(&expr->base.source_position,
6599 "'va_start' used in non-variadic function");
6600 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6601 entity->base.next != NULL ||
6602 entity->kind != ENTITY_PARAMETER) {
6603 errorf(&expr->base.source_position,
6604 "second argument of 'va_start' must be last parameter of the current function");
6606 expression->va_starte.parameter = &entity->variable;
6608 expect(')', end_error);
6611 expect(')', end_error);
6613 return create_error_expression();
6617 * Parses a __builtin_va_arg() expression.
6619 static expression_t *parse_va_arg(void)
6621 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6623 eat(T___builtin_va_arg);
6625 expect('(', end_error);
6627 ap.expression = parse_assignment_expression();
6628 expression->va_arge.ap = ap.expression;
6629 check_call_argument(type_valist, &ap, 1);
6631 expect(',', end_error);
6632 expression->base.type = parse_typename();
6633 expect(')', end_error);
6637 return create_error_expression();
6641 * Parses a __builtin_va_copy() expression.
6643 static expression_t *parse_va_copy(void)
6645 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6647 eat(T___builtin_va_copy);
6649 expect('(', end_error);
6650 expression_t *dst = parse_assignment_expression();
6651 assign_error_t error = semantic_assign(type_valist, dst);
6652 report_assign_error(error, type_valist, dst, "call argument 1",
6653 &dst->base.source_position);
6654 expression->va_copye.dst = dst;
6656 expect(',', end_error);
6658 call_argument_t src;
6659 src.expression = parse_assignment_expression();
6660 check_call_argument(type_valist, &src, 2);
6661 expression->va_copye.src = src.expression;
6662 expect(')', end_error);
6666 return create_error_expression();
6670 * Parses a __builtin_constant_p() expression.
6672 static expression_t *parse_builtin_constant(void)
6674 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6676 eat(T___builtin_constant_p);
6678 expect('(', end_error);
6679 add_anchor_token(')');
6680 expression->builtin_constant.value = parse_assignment_expression();
6681 rem_anchor_token(')');
6682 expect(')', end_error);
6683 expression->base.type = type_int;
6687 return create_error_expression();
6691 * Parses a __builtin_types_compatible_p() expression.
6693 static expression_t *parse_builtin_types_compatible(void)
6695 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6697 eat(T___builtin_types_compatible_p);
6699 expect('(', end_error);
6700 add_anchor_token(')');
6701 add_anchor_token(',');
6702 expression->builtin_types_compatible.left = parse_typename();
6703 rem_anchor_token(',');
6704 expect(',', end_error);
6705 expression->builtin_types_compatible.right = parse_typename();
6706 rem_anchor_token(')');
6707 expect(')', end_error);
6708 expression->base.type = type_int;
6712 return create_error_expression();
6716 * Parses a __builtin_is_*() compare expression.
6718 static expression_t *parse_compare_builtin(void)
6720 expression_t *expression;
6722 switch (token.kind) {
6723 case T___builtin_isgreater:
6724 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6726 case T___builtin_isgreaterequal:
6727 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6729 case T___builtin_isless:
6730 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6732 case T___builtin_islessequal:
6733 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6735 case T___builtin_islessgreater:
6736 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6738 case T___builtin_isunordered:
6739 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6742 internal_errorf(HERE, "invalid compare builtin found");
6744 expression->base.source_position = *HERE;
6747 expect('(', end_error);
6748 expression->binary.left = parse_assignment_expression();
6749 expect(',', end_error);
6750 expression->binary.right = parse_assignment_expression();
6751 expect(')', end_error);
6753 type_t *const orig_type_left = expression->binary.left->base.type;
6754 type_t *const orig_type_right = expression->binary.right->base.type;
6756 type_t *const type_left = skip_typeref(orig_type_left);
6757 type_t *const type_right = skip_typeref(orig_type_right);
6758 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6759 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6760 type_error_incompatible("invalid operands in comparison",
6761 &expression->base.source_position, orig_type_left, orig_type_right);
6764 semantic_comparison(&expression->binary);
6769 return create_error_expression();
6773 * Parses a MS assume() expression.
6775 static expression_t *parse_assume(void)
6777 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6781 expect('(', end_error);
6782 add_anchor_token(')');
6783 expression->unary.value = parse_assignment_expression();
6784 rem_anchor_token(')');
6785 expect(')', end_error);
6787 expression->base.type = type_void;
6790 return create_error_expression();
6794 * Return the label for the current symbol or create a new one.
6796 static label_t *get_label(void)
6798 assert(token.kind == T_IDENTIFIER);
6799 assert(current_function != NULL);
6801 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6802 /* If we find a local label, we already created the declaration. */
6803 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6804 if (label->base.parent_scope != current_scope) {
6805 assert(label->base.parent_scope->depth < current_scope->depth);
6806 current_function->goto_to_outer = true;
6808 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6809 /* There is no matching label in the same function, so create a new one. */
6810 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol);
6815 return &label->label;
6819 * Parses a GNU && label address expression.
6821 static expression_t *parse_label_address(void)
6823 source_position_t source_position = token.base.source_position;
6825 if (token.kind != T_IDENTIFIER) {
6826 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6827 return create_error_expression();
6830 label_t *const label = get_label();
6832 label->address_taken = true;
6834 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6835 expression->base.source_position = source_position;
6837 /* label address is treated as a void pointer */
6838 expression->base.type = type_void_ptr;
6839 expression->label_address.label = label;
6844 * Parse a microsoft __noop expression.
6846 static expression_t *parse_noop_expression(void)
6848 /* the result is a (int)0 */
6849 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6850 literal->base.type = type_int;
6851 literal->literal.value.begin = "__noop";
6852 literal->literal.value.size = 6;
6856 if (token.kind == '(') {
6857 /* parse arguments */
6859 add_anchor_token(')');
6860 add_anchor_token(',');
6862 if (token.kind != ')') do {
6863 (void)parse_assignment_expression();
6864 } while (next_if(','));
6866 rem_anchor_token(',');
6867 rem_anchor_token(')');
6869 expect(')', end_error);
6876 * Parses a primary expression.
6878 static expression_t *parse_primary_expression(void)
6880 switch (token.kind) {
6881 case T_false: return parse_boolean_literal(false);
6882 case T_true: return parse_boolean_literal(true);
6884 case T_INTEGER_OCTAL:
6885 case T_INTEGER_HEXADECIMAL:
6886 case T_FLOATINGPOINT:
6887 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6888 case T_CHARACTER_CONSTANT: return parse_character_constant();
6889 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6890 case T_STRING_LITERAL:
6891 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6892 case T___FUNCTION__:
6893 case T___func__: return parse_function_keyword();
6894 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6895 case T___FUNCSIG__: return parse_funcsig_keyword();
6896 case T___FUNCDNAME__: return parse_funcdname_keyword();
6897 case T___builtin_offsetof: return parse_offsetof();
6898 case T___builtin_va_start: return parse_va_start();
6899 case T___builtin_va_arg: return parse_va_arg();
6900 case T___builtin_va_copy: return parse_va_copy();
6901 case T___builtin_isgreater:
6902 case T___builtin_isgreaterequal:
6903 case T___builtin_isless:
6904 case T___builtin_islessequal:
6905 case T___builtin_islessgreater:
6906 case T___builtin_isunordered: return parse_compare_builtin();
6907 case T___builtin_constant_p: return parse_builtin_constant();
6908 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6909 case T__assume: return parse_assume();
6912 return parse_label_address();
6915 case '(': return parse_parenthesized_expression();
6916 case T___noop: return parse_noop_expression();
6918 /* Gracefully handle type names while parsing expressions. */
6920 return parse_reference();
6922 if (!is_typedef_symbol(token.identifier.symbol)) {
6923 return parse_reference();
6927 source_position_t const pos = *HERE;
6928 declaration_specifiers_t specifiers;
6929 parse_declaration_specifiers(&specifiers);
6930 type_t const *const type = parse_abstract_declarator(specifiers.type);
6931 errorf(&pos, "encountered type '%T' while parsing expression", type);
6932 return create_error_expression();
6936 errorf(HERE, "unexpected token %K, expected an expression", &token);
6938 return create_error_expression();
6941 static expression_t *parse_array_expression(expression_t *left)
6943 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6944 array_access_expression_t *const arr = &expr->array_access;
6947 add_anchor_token(']');
6949 expression_t *const inside = parse_expression();
6951 type_t *const orig_type_left = left->base.type;
6952 type_t *const orig_type_inside = inside->base.type;
6954 type_t *const type_left = skip_typeref(orig_type_left);
6955 type_t *const type_inside = skip_typeref(orig_type_inside);
6961 if (is_type_pointer(type_left)) {
6964 idx_type = type_inside;
6965 res_type = type_left->pointer.points_to;
6967 } else if (is_type_pointer(type_inside)) {
6968 arr->flipped = true;
6971 idx_type = type_left;
6972 res_type = type_inside->pointer.points_to;
6974 res_type = automatic_type_conversion(res_type);
6975 if (!is_type_integer(idx_type)) {
6976 errorf(&idx->base.source_position, "array subscript must have integer type");
6977 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6978 source_position_t const *const pos = &idx->base.source_position;
6979 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6982 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6983 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6985 res_type = type_error_type;
6990 arr->array_ref = ref;
6992 arr->base.type = res_type;
6994 rem_anchor_token(']');
6995 expect(']', end_error);
7000 static bool is_bitfield(const expression_t *expression)
7002 return expression->kind == EXPR_SELECT
7003 && expression->select.compound_entry->compound_member.bitfield;
7006 static expression_t *parse_typeprop(expression_kind_t const kind)
7008 expression_t *tp_expression = allocate_expression_zero(kind);
7009 tp_expression->base.type = type_size_t;
7011 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7014 expression_t *expression;
7015 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
7016 source_position_t const pos = *HERE;
7018 add_anchor_token(')');
7019 orig_type = parse_typename();
7020 rem_anchor_token(')');
7021 expect(')', end_error);
7023 if (token.kind == '{') {
7024 /* It was not sizeof(type) after all. It is sizeof of an expression
7025 * starting with a compound literal */
7026 expression = parse_compound_literal(&pos, orig_type);
7027 goto typeprop_expression;
7030 expression = parse_subexpression(PREC_UNARY);
7032 typeprop_expression:
7033 if (is_bitfield(expression)) {
7034 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7035 errorf(&tp_expression->base.source_position,
7036 "operand of %s expression must not be a bitfield", what);
7039 tp_expression->typeprop.tp_expression = expression;
7041 orig_type = revert_automatic_type_conversion(expression);
7042 expression->base.type = orig_type;
7045 tp_expression->typeprop.type = orig_type;
7046 type_t const* const type = skip_typeref(orig_type);
7047 char const* wrong_type = NULL;
7048 if (is_type_incomplete(type)) {
7049 if (!is_type_void(type) || !GNU_MODE)
7050 wrong_type = "incomplete";
7051 } else if (type->kind == TYPE_FUNCTION) {
7053 /* function types are allowed (and return 1) */
7054 source_position_t const *const pos = &tp_expression->base.source_position;
7055 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7056 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7058 wrong_type = "function";
7062 if (wrong_type != NULL) {
7063 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7064 errorf(&tp_expression->base.source_position,
7065 "operand of %s expression must not be of %s type '%T'",
7066 what, wrong_type, orig_type);
7070 return tp_expression;
7073 static expression_t *parse_sizeof(void)
7075 return parse_typeprop(EXPR_SIZEOF);
7078 static expression_t *parse_alignof(void)
7080 return parse_typeprop(EXPR_ALIGNOF);
7083 static expression_t *parse_select_expression(expression_t *addr)
7085 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7086 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7087 source_position_t const pos = *HERE;
7090 if (token.kind != T_IDENTIFIER) {
7091 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7092 return create_error_expression();
7094 symbol_t *symbol = token.identifier.symbol;
7097 type_t *const orig_type = addr->base.type;
7098 type_t *const type = skip_typeref(orig_type);
7101 bool saw_error = false;
7102 if (is_type_pointer(type)) {
7103 if (!select_left_arrow) {
7105 "request for member '%Y' in something not a struct or union, but '%T'",
7109 type_left = skip_typeref(type->pointer.points_to);
7111 if (select_left_arrow && is_type_valid(type)) {
7112 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7118 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7119 type_left->kind != TYPE_COMPOUND_UNION) {
7121 if (is_type_valid(type_left) && !saw_error) {
7123 "request for member '%Y' in something not a struct or union, but '%T'",
7126 return create_error_expression();
7129 compound_t *compound = type_left->compound.compound;
7130 if (!compound->complete) {
7131 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7133 return create_error_expression();
7136 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7137 expression_t *result =
7138 find_create_select(&pos, addr, qualifiers, compound, symbol);
7140 if (result == NULL) {
7141 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7142 return create_error_expression();
7148 static void check_call_argument(type_t *expected_type,
7149 call_argument_t *argument, unsigned pos)
7151 type_t *expected_type_skip = skip_typeref(expected_type);
7152 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7153 expression_t *arg_expr = argument->expression;
7154 type_t *arg_type = skip_typeref(arg_expr->base.type);
7156 /* handle transparent union gnu extension */
7157 if (is_type_union(expected_type_skip)
7158 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7159 compound_t *union_decl = expected_type_skip->compound.compound;
7160 type_t *best_type = NULL;
7161 entity_t *entry = union_decl->members.entities;
7162 for ( ; entry != NULL; entry = entry->base.next) {
7163 assert(is_declaration(entry));
7164 type_t *decl_type = entry->declaration.type;
7165 error = semantic_assign(decl_type, arg_expr);
7166 if (error == ASSIGN_ERROR_INCOMPATIBLE
7167 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7170 if (error == ASSIGN_SUCCESS) {
7171 best_type = decl_type;
7172 } else if (best_type == NULL) {
7173 best_type = decl_type;
7177 if (best_type != NULL) {
7178 expected_type = best_type;
7182 error = semantic_assign(expected_type, arg_expr);
7183 argument->expression = create_implicit_cast(arg_expr, expected_type);
7185 if (error != ASSIGN_SUCCESS) {
7186 /* report exact scope in error messages (like "in argument 3") */
7188 snprintf(buf, sizeof(buf), "call argument %u", pos);
7189 report_assign_error(error, expected_type, arg_expr, buf,
7190 &arg_expr->base.source_position);
7192 type_t *const promoted_type = get_default_promoted_type(arg_type);
7193 if (!types_compatible(expected_type_skip, promoted_type) &&
7194 !types_compatible(expected_type_skip, type_void_ptr) &&
7195 !types_compatible(type_void_ptr, promoted_type)) {
7196 /* Deliberately show the skipped types in this warning */
7197 source_position_t const *const apos = &arg_expr->base.source_position;
7198 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7204 * Handle the semantic restrictions of builtin calls
7206 static void handle_builtin_argument_restrictions(call_expression_t *call)
7208 entity_t *entity = call->function->reference.entity;
7209 switch (entity->function.btk) {
7211 switch (entity->function.b.firm_builtin_kind) {
7212 case ir_bk_return_address:
7213 case ir_bk_frame_address: {
7214 /* argument must be constant */
7215 call_argument_t *argument = call->arguments;
7217 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7218 errorf(&call->base.source_position,
7219 "argument of '%Y' must be a constant expression",
7220 call->function->reference.entity->base.symbol);
7224 case ir_bk_prefetch:
7225 /* second and third argument must be constant if existent */
7226 if (call->arguments == NULL)
7228 call_argument_t *rw = call->arguments->next;
7229 call_argument_t *locality = NULL;
7232 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7233 errorf(&call->base.source_position,
7234 "second argument of '%Y' must be a constant expression",
7235 call->function->reference.entity->base.symbol);
7237 locality = rw->next;
7239 if (locality != NULL) {
7240 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7241 errorf(&call->base.source_position,
7242 "third argument of '%Y' must be a constant expression",
7243 call->function->reference.entity->base.symbol);
7245 locality = rw->next;
7252 case BUILTIN_OBJECT_SIZE:
7253 if (call->arguments == NULL)
7256 call_argument_t *arg = call->arguments->next;
7257 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7258 errorf(&call->base.source_position,
7259 "second argument of '%Y' must be a constant expression",
7260 call->function->reference.entity->base.symbol);
7269 * Parse a call expression, ie. expression '( ... )'.
7271 * @param expression the function address
7273 static expression_t *parse_call_expression(expression_t *expression)
7275 expression_t *result = allocate_expression_zero(EXPR_CALL);
7276 call_expression_t *call = &result->call;
7277 call->function = expression;
7279 type_t *const orig_type = expression->base.type;
7280 type_t *const type = skip_typeref(orig_type);
7282 function_type_t *function_type = NULL;
7283 if (is_type_pointer(type)) {
7284 type_t *const to_type = skip_typeref(type->pointer.points_to);
7286 if (is_type_function(to_type)) {
7287 function_type = &to_type->function;
7288 call->base.type = function_type->return_type;
7292 if (function_type == NULL && is_type_valid(type)) {
7294 "called object '%E' (type '%T') is not a pointer to a function",
7295 expression, orig_type);
7298 /* parse arguments */
7300 add_anchor_token(')');
7301 add_anchor_token(',');
7303 if (token.kind != ')') {
7304 call_argument_t **anchor = &call->arguments;
7306 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7307 argument->expression = parse_assignment_expression();
7310 anchor = &argument->next;
7311 } while (next_if(','));
7313 rem_anchor_token(',');
7314 rem_anchor_token(')');
7315 expect(')', end_error);
7317 if (function_type == NULL)
7320 /* check type and count of call arguments */
7321 function_parameter_t *parameter = function_type->parameters;
7322 call_argument_t *argument = call->arguments;
7323 if (!function_type->unspecified_parameters) {
7324 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7325 parameter = parameter->next, argument = argument->next) {
7326 check_call_argument(parameter->type, argument, ++pos);
7329 if (parameter != NULL) {
7330 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7331 } else if (argument != NULL && !function_type->variadic) {
7332 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7336 /* do default promotion for other arguments */
7337 for (; argument != NULL; argument = argument->next) {
7338 type_t *argument_type = argument->expression->base.type;
7339 if (!is_type_object(skip_typeref(argument_type))) {
7340 errorf(&argument->expression->base.source_position,
7341 "call argument '%E' must not be void", argument->expression);
7344 argument_type = get_default_promoted_type(argument_type);
7346 argument->expression
7347 = create_implicit_cast(argument->expression, argument_type);
7352 if (is_type_compound(skip_typeref(function_type->return_type))) {
7353 source_position_t const *const pos = &expression->base.source_position;
7354 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7357 if (expression->kind == EXPR_REFERENCE) {
7358 reference_expression_t *reference = &expression->reference;
7359 if (reference->entity->kind == ENTITY_FUNCTION &&
7360 reference->entity->function.btk != BUILTIN_NONE)
7361 handle_builtin_argument_restrictions(call);
7368 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7370 static bool same_compound_type(const type_t *type1, const type_t *type2)
7373 is_type_compound(type1) &&
7374 type1->kind == type2->kind &&
7375 type1->compound.compound == type2->compound.compound;
7378 static expression_t const *get_reference_address(expression_t const *expr)
7380 bool regular_take_address = true;
7382 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7383 expr = expr->unary.value;
7385 regular_take_address = false;
7388 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7391 expr = expr->unary.value;
7394 if (expr->kind != EXPR_REFERENCE)
7397 /* special case for functions which are automatically converted to a
7398 * pointer to function without an extra TAKE_ADDRESS operation */
7399 if (!regular_take_address &&
7400 expr->reference.entity->kind != ENTITY_FUNCTION) {
7407 static void warn_reference_address_as_bool(expression_t const* expr)
7409 expr = get_reference_address(expr);
7411 source_position_t const *const pos = &expr->base.source_position;
7412 entity_t const *const ent = expr->reference.entity;
7413 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7417 static void warn_assignment_in_condition(const expression_t *const expr)
7419 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7421 if (expr->base.parenthesized)
7423 source_position_t const *const pos = &expr->base.source_position;
7424 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7427 static void semantic_condition(expression_t const *const expr,
7428 char const *const context)
7430 type_t *const type = skip_typeref(expr->base.type);
7431 if (is_type_scalar(type)) {
7432 warn_reference_address_as_bool(expr);
7433 warn_assignment_in_condition(expr);
7434 } else if (is_type_valid(type)) {
7435 errorf(&expr->base.source_position,
7436 "%s must have scalar type", context);
7441 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7443 * @param expression the conditional expression
7445 static expression_t *parse_conditional_expression(expression_t *expression)
7447 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7449 conditional_expression_t *conditional = &result->conditional;
7450 conditional->condition = expression;
7453 add_anchor_token(':');
7455 /* §6.5.15:2 The first operand shall have scalar type. */
7456 semantic_condition(expression, "condition of conditional operator");
7458 expression_t *true_expression = expression;
7459 bool gnu_cond = false;
7460 if (GNU_MODE && token.kind == ':') {
7463 true_expression = parse_expression();
7465 rem_anchor_token(':');
7466 expect(':', end_error);
7468 expression_t *false_expression =
7469 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7471 type_t *const orig_true_type = true_expression->base.type;
7472 type_t *const orig_false_type = false_expression->base.type;
7473 type_t *const true_type = skip_typeref(orig_true_type);
7474 type_t *const false_type = skip_typeref(orig_false_type);
7477 source_position_t const *const pos = &conditional->base.source_position;
7478 type_t *result_type;
7479 if (is_type_void(true_type) || is_type_void(false_type)) {
7480 /* ISO/IEC 14882:1998(E) §5.16:2 */
7481 if (true_expression->kind == EXPR_UNARY_THROW) {
7482 result_type = false_type;
7483 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7484 result_type = true_type;
7486 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7487 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7489 result_type = type_void;
7491 } else if (is_type_arithmetic(true_type)
7492 && is_type_arithmetic(false_type)) {
7493 result_type = semantic_arithmetic(true_type, false_type);
7494 } else if (same_compound_type(true_type, false_type)) {
7495 /* just take 1 of the 2 types */
7496 result_type = true_type;
7497 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7498 type_t *pointer_type;
7500 expression_t *other_expression;
7501 if (is_type_pointer(true_type) &&
7502 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7503 pointer_type = true_type;
7504 other_type = false_type;
7505 other_expression = false_expression;
7507 pointer_type = false_type;
7508 other_type = true_type;
7509 other_expression = true_expression;
7512 if (is_null_pointer_constant(other_expression)) {
7513 result_type = pointer_type;
7514 } else if (is_type_pointer(other_type)) {
7515 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7516 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7519 if (is_type_void(to1) || is_type_void(to2)) {
7521 } else if (types_compatible(get_unqualified_type(to1),
7522 get_unqualified_type(to2))) {
7525 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7529 type_t *const type =
7530 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7531 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7532 } else if (is_type_integer(other_type)) {
7533 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7534 result_type = pointer_type;
7536 goto types_incompatible;
7540 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7541 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7543 result_type = type_error_type;
7546 conditional->true_expression
7547 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7548 conditional->false_expression
7549 = create_implicit_cast(false_expression, result_type);
7550 conditional->base.type = result_type;
7555 * Parse an extension expression.
7557 static expression_t *parse_extension(void)
7560 expression_t *expression = parse_subexpression(PREC_UNARY);
7566 * Parse a __builtin_classify_type() expression.
7568 static expression_t *parse_builtin_classify_type(void)
7570 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7571 result->base.type = type_int;
7573 eat(T___builtin_classify_type);
7575 expect('(', end_error);
7576 add_anchor_token(')');
7577 expression_t *expression = parse_expression();
7578 rem_anchor_token(')');
7579 expect(')', end_error);
7580 result->classify_type.type_expression = expression;
7584 return create_error_expression();
7588 * Parse a delete expression
7589 * ISO/IEC 14882:1998(E) §5.3.5
7591 static expression_t *parse_delete(void)
7593 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7594 result->base.type = type_void;
7599 result->kind = EXPR_UNARY_DELETE_ARRAY;
7600 expect(']', end_error);
7604 expression_t *const value = parse_subexpression(PREC_CAST);
7605 result->unary.value = value;
7607 type_t *const type = skip_typeref(value->base.type);
7608 if (!is_type_pointer(type)) {
7609 if (is_type_valid(type)) {
7610 errorf(&value->base.source_position,
7611 "operand of delete must have pointer type");
7613 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7614 source_position_t const *const pos = &value->base.source_position;
7615 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7622 * Parse a throw expression
7623 * ISO/IEC 14882:1998(E) §15:1
7625 static expression_t *parse_throw(void)
7627 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7628 result->base.type = type_void;
7632 expression_t *value = NULL;
7633 switch (token.kind) {
7635 value = parse_assignment_expression();
7636 /* ISO/IEC 14882:1998(E) §15.1:3 */
7637 type_t *const orig_type = value->base.type;
7638 type_t *const type = skip_typeref(orig_type);
7639 if (is_type_incomplete(type)) {
7640 errorf(&value->base.source_position,
7641 "cannot throw object of incomplete type '%T'", orig_type);
7642 } else if (is_type_pointer(type)) {
7643 type_t *const points_to = skip_typeref(type->pointer.points_to);
7644 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7645 errorf(&value->base.source_position,
7646 "cannot throw pointer to incomplete type '%T'", orig_type);
7654 result->unary.value = value;
7659 static bool check_pointer_arithmetic(const source_position_t *source_position,
7660 type_t *pointer_type,
7661 type_t *orig_pointer_type)
7663 type_t *points_to = pointer_type->pointer.points_to;
7664 points_to = skip_typeref(points_to);
7666 if (is_type_incomplete(points_to)) {
7667 if (!GNU_MODE || !is_type_void(points_to)) {
7668 errorf(source_position,
7669 "arithmetic with pointer to incomplete type '%T' not allowed",
7673 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7675 } else if (is_type_function(points_to)) {
7677 errorf(source_position,
7678 "arithmetic with pointer to function type '%T' not allowed",
7682 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7688 static bool is_lvalue(const expression_t *expression)
7690 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7691 switch (expression->kind) {
7692 case EXPR_ARRAY_ACCESS:
7693 case EXPR_COMPOUND_LITERAL:
7694 case EXPR_REFERENCE:
7696 case EXPR_UNARY_DEREFERENCE:
7700 type_t *type = skip_typeref(expression->base.type);
7702 /* ISO/IEC 14882:1998(E) §3.10:3 */
7703 is_type_reference(type) ||
7704 /* Claim it is an lvalue, if the type is invalid. There was a parse
7705 * error before, which maybe prevented properly recognizing it as
7707 !is_type_valid(type);
7712 static void semantic_incdec(unary_expression_t *expression)
7714 type_t *const orig_type = expression->value->base.type;
7715 type_t *const type = skip_typeref(orig_type);
7716 if (is_type_pointer(type)) {
7717 if (!check_pointer_arithmetic(&expression->base.source_position,
7721 } else if (!is_type_real(type) && is_type_valid(type)) {
7722 /* TODO: improve error message */
7723 errorf(&expression->base.source_position,
7724 "operation needs an arithmetic or pointer type");
7727 if (!is_lvalue(expression->value)) {
7728 /* TODO: improve error message */
7729 errorf(&expression->base.source_position, "lvalue required as operand");
7731 expression->base.type = orig_type;
7734 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7736 type_t *const res_type = promote_integer(type);
7737 expr->base.type = res_type;
7738 expr->value = create_implicit_cast(expr->value, res_type);
7741 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7743 type_t *const orig_type = expression->value->base.type;
7744 type_t *const type = skip_typeref(orig_type);
7745 if (!is_type_arithmetic(type)) {
7746 if (is_type_valid(type)) {
7747 /* TODO: improve error message */
7748 errorf(&expression->base.source_position,
7749 "operation needs an arithmetic type");
7752 } else if (is_type_integer(type)) {
7753 promote_unary_int_expr(expression, type);
7755 expression->base.type = orig_type;
7759 static void semantic_unexpr_plus(unary_expression_t *expression)
7761 semantic_unexpr_arithmetic(expression);
7762 source_position_t const *const pos = &expression->base.source_position;
7763 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7766 static void semantic_not(unary_expression_t *expression)
7768 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7769 semantic_condition(expression->value, "operand of !");
7770 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7773 static void semantic_unexpr_integer(unary_expression_t *expression)
7775 type_t *const orig_type = expression->value->base.type;
7776 type_t *const type = skip_typeref(orig_type);
7777 if (!is_type_integer(type)) {
7778 if (is_type_valid(type)) {
7779 errorf(&expression->base.source_position,
7780 "operand of ~ must be of integer type");
7785 promote_unary_int_expr(expression, type);
7788 static void semantic_dereference(unary_expression_t *expression)
7790 type_t *const orig_type = expression->value->base.type;
7791 type_t *const type = skip_typeref(orig_type);
7792 if (!is_type_pointer(type)) {
7793 if (is_type_valid(type)) {
7794 errorf(&expression->base.source_position,
7795 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7800 type_t *result_type = type->pointer.points_to;
7801 result_type = automatic_type_conversion(result_type);
7802 expression->base.type = result_type;
7806 * Record that an address is taken (expression represents an lvalue).
7808 * @param expression the expression
7809 * @param may_be_register if true, the expression might be an register
7811 static void set_address_taken(expression_t *expression, bool may_be_register)
7813 if (expression->kind != EXPR_REFERENCE)
7816 entity_t *const entity = expression->reference.entity;
7818 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7821 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7822 && !may_be_register) {
7823 source_position_t const *const pos = &expression->base.source_position;
7824 errorf(pos, "address of register '%N' requested", entity);
7827 if (entity->kind == ENTITY_VARIABLE) {
7828 entity->variable.address_taken = true;
7830 assert(entity->kind == ENTITY_PARAMETER);
7831 entity->parameter.address_taken = true;
7836 * Check the semantic of the address taken expression.
7838 static void semantic_take_addr(unary_expression_t *expression)
7840 expression_t *value = expression->value;
7841 value->base.type = revert_automatic_type_conversion(value);
7843 type_t *orig_type = value->base.type;
7844 type_t *type = skip_typeref(orig_type);
7845 if (!is_type_valid(type))
7849 if (!is_lvalue(value)) {
7850 errorf(&expression->base.source_position, "'&' requires an lvalue");
7852 if (is_bitfield(value)) {
7853 errorf(&expression->base.source_position,
7854 "'&' not allowed on bitfield");
7857 set_address_taken(value, false);
7859 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7862 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7863 static expression_t *parse_##unexpression_type(void) \
7865 expression_t *unary_expression \
7866 = allocate_expression_zero(unexpression_type); \
7868 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7870 sfunc(&unary_expression->unary); \
7872 return unary_expression; \
7875 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7876 semantic_unexpr_arithmetic)
7877 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7878 semantic_unexpr_plus)
7879 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7881 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7882 semantic_dereference)
7883 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7885 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7886 semantic_unexpr_integer)
7887 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7889 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7892 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7894 static expression_t *parse_##unexpression_type(expression_t *left) \
7896 expression_t *unary_expression \
7897 = allocate_expression_zero(unexpression_type); \
7899 unary_expression->unary.value = left; \
7901 sfunc(&unary_expression->unary); \
7903 return unary_expression; \
7906 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7907 EXPR_UNARY_POSTFIX_INCREMENT,
7909 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7910 EXPR_UNARY_POSTFIX_DECREMENT,
7913 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7915 /* TODO: handle complex + imaginary types */
7917 type_left = get_unqualified_type(type_left);
7918 type_right = get_unqualified_type(type_right);
7920 /* §6.3.1.8 Usual arithmetic conversions */
7921 if (type_left == type_long_double || type_right == type_long_double) {
7922 return type_long_double;
7923 } else if (type_left == type_double || type_right == type_double) {
7925 } else if (type_left == type_float || type_right == type_float) {
7929 type_left = promote_integer(type_left);
7930 type_right = promote_integer(type_right);
7932 if (type_left == type_right)
7935 bool const signed_left = is_type_signed(type_left);
7936 bool const signed_right = is_type_signed(type_right);
7937 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7938 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7940 if (signed_left == signed_right)
7941 return rank_left >= rank_right ? type_left : type_right;
7945 atomic_type_kind_t s_akind;
7946 atomic_type_kind_t u_akind;
7951 u_type = type_right;
7953 s_type = type_right;
7956 s_akind = get_akind(s_type);
7957 u_akind = get_akind(u_type);
7958 s_rank = get_akind_rank(s_akind);
7959 u_rank = get_akind_rank(u_akind);
7961 if (u_rank >= s_rank)
7964 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7968 case ATOMIC_TYPE_INT: return type_unsigned_int;
7969 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7970 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7972 default: panic("invalid atomic type");
7977 * Check the semantic restrictions for a binary expression.
7979 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7981 expression_t *const left = expression->left;
7982 expression_t *const right = expression->right;
7983 type_t *const orig_type_left = left->base.type;
7984 type_t *const orig_type_right = right->base.type;
7985 type_t *const type_left = skip_typeref(orig_type_left);
7986 type_t *const type_right = skip_typeref(orig_type_right);
7988 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7989 /* TODO: improve error message */
7990 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7991 errorf(&expression->base.source_position,
7992 "operation needs arithmetic types");
7997 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7998 expression->left = create_implicit_cast(left, arithmetic_type);
7999 expression->right = create_implicit_cast(right, arithmetic_type);
8000 expression->base.type = arithmetic_type;
8003 static void semantic_binexpr_integer(binary_expression_t *const expression)
8005 expression_t *const left = expression->left;
8006 expression_t *const right = expression->right;
8007 type_t *const orig_type_left = left->base.type;
8008 type_t *const orig_type_right = right->base.type;
8009 type_t *const type_left = skip_typeref(orig_type_left);
8010 type_t *const type_right = skip_typeref(orig_type_right);
8012 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8013 /* TODO: improve error message */
8014 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8015 errorf(&expression->base.source_position,
8016 "operation needs integer types");
8021 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8022 expression->left = create_implicit_cast(left, result_type);
8023 expression->right = create_implicit_cast(right, result_type);
8024 expression->base.type = result_type;
8027 static void warn_div_by_zero(binary_expression_t const *const expression)
8029 if (!is_type_integer(expression->base.type))
8032 expression_t const *const right = expression->right;
8033 /* The type of the right operand can be different for /= */
8034 if (is_type_integer(right->base.type) &&
8035 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8036 !fold_constant_to_bool(right)) {
8037 source_position_t const *const pos = &expression->base.source_position;
8038 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8043 * Check the semantic restrictions for a div/mod expression.
8045 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8047 semantic_binexpr_arithmetic(expression);
8048 warn_div_by_zero(expression);
8051 static void warn_addsub_in_shift(const expression_t *const expr)
8053 if (expr->base.parenthesized)
8057 switch (expr->kind) {
8058 case EXPR_BINARY_ADD: op = '+'; break;
8059 case EXPR_BINARY_SUB: op = '-'; break;
8063 source_position_t const *const pos = &expr->base.source_position;
8064 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8067 static bool semantic_shift(binary_expression_t *expression)
8069 expression_t *const left = expression->left;
8070 expression_t *const right = expression->right;
8071 type_t *const orig_type_left = left->base.type;
8072 type_t *const orig_type_right = right->base.type;
8073 type_t * type_left = skip_typeref(orig_type_left);
8074 type_t * type_right = skip_typeref(orig_type_right);
8076 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8077 /* TODO: improve error message */
8078 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8079 errorf(&expression->base.source_position,
8080 "operands of shift operation must have integer types");
8085 type_left = promote_integer(type_left);
8087 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8088 source_position_t const *const pos = &right->base.source_position;
8089 long const count = fold_constant_to_int(right);
8091 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8092 } else if ((unsigned long)count >=
8093 get_atomic_type_size(type_left->atomic.akind) * 8) {
8094 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8098 type_right = promote_integer(type_right);
8099 expression->right = create_implicit_cast(right, type_right);
8104 static void semantic_shift_op(binary_expression_t *expression)
8106 expression_t *const left = expression->left;
8107 expression_t *const right = expression->right;
8109 if (!semantic_shift(expression))
8112 warn_addsub_in_shift(left);
8113 warn_addsub_in_shift(right);
8115 type_t *const orig_type_left = left->base.type;
8116 type_t * type_left = skip_typeref(orig_type_left);
8118 type_left = promote_integer(type_left);
8119 expression->left = create_implicit_cast(left, type_left);
8120 expression->base.type = type_left;
8123 static void semantic_add(binary_expression_t *expression)
8125 expression_t *const left = expression->left;
8126 expression_t *const right = expression->right;
8127 type_t *const orig_type_left = left->base.type;
8128 type_t *const orig_type_right = right->base.type;
8129 type_t *const type_left = skip_typeref(orig_type_left);
8130 type_t *const type_right = skip_typeref(orig_type_right);
8133 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8134 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8135 expression->left = create_implicit_cast(left, arithmetic_type);
8136 expression->right = create_implicit_cast(right, arithmetic_type);
8137 expression->base.type = arithmetic_type;
8138 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8139 check_pointer_arithmetic(&expression->base.source_position,
8140 type_left, orig_type_left);
8141 expression->base.type = type_left;
8142 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8143 check_pointer_arithmetic(&expression->base.source_position,
8144 type_right, orig_type_right);
8145 expression->base.type = type_right;
8146 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8147 errorf(&expression->base.source_position,
8148 "invalid operands to binary + ('%T', '%T')",
8149 orig_type_left, orig_type_right);
8153 static void semantic_sub(binary_expression_t *expression)
8155 expression_t *const left = expression->left;
8156 expression_t *const right = expression->right;
8157 type_t *const orig_type_left = left->base.type;
8158 type_t *const orig_type_right = right->base.type;
8159 type_t *const type_left = skip_typeref(orig_type_left);
8160 type_t *const type_right = skip_typeref(orig_type_right);
8161 source_position_t const *const pos = &expression->base.source_position;
8164 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8165 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8166 expression->left = create_implicit_cast(left, arithmetic_type);
8167 expression->right = create_implicit_cast(right, arithmetic_type);
8168 expression->base.type = arithmetic_type;
8169 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8170 check_pointer_arithmetic(&expression->base.source_position,
8171 type_left, orig_type_left);
8172 expression->base.type = type_left;
8173 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8174 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8175 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8176 if (!types_compatible(unqual_left, unqual_right)) {
8178 "subtracting pointers to incompatible types '%T' and '%T'",
8179 orig_type_left, orig_type_right);
8180 } else if (!is_type_object(unqual_left)) {
8181 if (!is_type_void(unqual_left)) {
8182 errorf(pos, "subtracting pointers to non-object types '%T'",
8185 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8188 expression->base.type = type_ptrdiff_t;
8189 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8190 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8191 orig_type_left, orig_type_right);
8195 static void warn_string_literal_address(expression_t const* expr)
8197 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8198 expr = expr->unary.value;
8199 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8201 expr = expr->unary.value;
8204 if (expr->kind == EXPR_STRING_LITERAL
8205 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8206 source_position_t const *const pos = &expr->base.source_position;
8207 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8211 static bool maybe_negative(expression_t const *const expr)
8213 switch (is_constant_expression(expr)) {
8214 case EXPR_CLASS_ERROR: return false;
8215 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8216 default: return true;
8220 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8222 warn_string_literal_address(expr);
8224 expression_t const* const ref = get_reference_address(expr);
8225 if (ref != NULL && is_null_pointer_constant(other)) {
8226 entity_t const *const ent = ref->reference.entity;
8227 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8230 if (!expr->base.parenthesized) {
8231 switch (expr->base.kind) {
8232 case EXPR_BINARY_LESS:
8233 case EXPR_BINARY_GREATER:
8234 case EXPR_BINARY_LESSEQUAL:
8235 case EXPR_BINARY_GREATEREQUAL:
8236 case EXPR_BINARY_NOTEQUAL:
8237 case EXPR_BINARY_EQUAL:
8238 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8247 * Check the semantics of comparison expressions.
8249 * @param expression The expression to check.
8251 static void semantic_comparison(binary_expression_t *expression)
8253 source_position_t const *const pos = &expression->base.source_position;
8254 expression_t *const left = expression->left;
8255 expression_t *const right = expression->right;
8257 warn_comparison(pos, left, right);
8258 warn_comparison(pos, right, left);
8260 type_t *orig_type_left = left->base.type;
8261 type_t *orig_type_right = right->base.type;
8262 type_t *type_left = skip_typeref(orig_type_left);
8263 type_t *type_right = skip_typeref(orig_type_right);
8265 /* TODO non-arithmetic types */
8266 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8267 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8269 /* test for signed vs unsigned compares */
8270 if (is_type_integer(arithmetic_type)) {
8271 bool const signed_left = is_type_signed(type_left);
8272 bool const signed_right = is_type_signed(type_right);
8273 if (signed_left != signed_right) {
8274 /* FIXME long long needs better const folding magic */
8275 /* TODO check whether constant value can be represented by other type */
8276 if ((signed_left && maybe_negative(left)) ||
8277 (signed_right && maybe_negative(right))) {
8278 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8283 expression->left = create_implicit_cast(left, arithmetic_type);
8284 expression->right = create_implicit_cast(right, arithmetic_type);
8285 expression->base.type = arithmetic_type;
8286 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8287 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8288 is_type_float(arithmetic_type)) {
8289 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8291 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8292 /* TODO check compatibility */
8293 } else if (is_type_pointer(type_left)) {
8294 expression->right = create_implicit_cast(right, type_left);
8295 } else if (is_type_pointer(type_right)) {
8296 expression->left = create_implicit_cast(left, type_right);
8297 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8298 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8300 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8304 * Checks if a compound type has constant fields.
8306 static bool has_const_fields(const compound_type_t *type)
8308 compound_t *compound = type->compound;
8309 entity_t *entry = compound->members.entities;
8311 for (; entry != NULL; entry = entry->base.next) {
8312 if (!is_declaration(entry))
8315 const type_t *decl_type = skip_typeref(entry->declaration.type);
8316 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8323 static bool is_valid_assignment_lhs(expression_t const* const left)
8325 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8326 type_t *const type_left = skip_typeref(orig_type_left);
8328 if (!is_lvalue(left)) {
8329 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8334 if (left->kind == EXPR_REFERENCE
8335 && left->reference.entity->kind == ENTITY_FUNCTION) {
8336 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8340 if (is_type_array(type_left)) {
8341 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8344 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8345 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8349 if (is_type_incomplete(type_left)) {
8350 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8351 left, orig_type_left);
8354 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8355 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8356 left, orig_type_left);
8363 static void semantic_arithmetic_assign(binary_expression_t *expression)
8365 expression_t *left = expression->left;
8366 expression_t *right = expression->right;
8367 type_t *orig_type_left = left->base.type;
8368 type_t *orig_type_right = right->base.type;
8370 if (!is_valid_assignment_lhs(left))
8373 type_t *type_left = skip_typeref(orig_type_left);
8374 type_t *type_right = skip_typeref(orig_type_right);
8376 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8377 /* TODO: improve error message */
8378 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8379 errorf(&expression->base.source_position,
8380 "operation needs arithmetic types");
8385 /* combined instructions are tricky. We can't create an implicit cast on
8386 * the left side, because we need the uncasted form for the store.
8387 * The ast2firm pass has to know that left_type must be right_type
8388 * for the arithmetic operation and create a cast by itself */
8389 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8390 expression->right = create_implicit_cast(right, arithmetic_type);
8391 expression->base.type = type_left;
8394 static void semantic_divmod_assign(binary_expression_t *expression)
8396 semantic_arithmetic_assign(expression);
8397 warn_div_by_zero(expression);
8400 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8402 expression_t *const left = expression->left;
8403 expression_t *const right = expression->right;
8404 type_t *const orig_type_left = left->base.type;
8405 type_t *const orig_type_right = right->base.type;
8406 type_t *const type_left = skip_typeref(orig_type_left);
8407 type_t *const type_right = skip_typeref(orig_type_right);
8409 if (!is_valid_assignment_lhs(left))
8412 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8413 /* combined instructions are tricky. We can't create an implicit cast on
8414 * the left side, because we need the uncasted form for the store.
8415 * The ast2firm pass has to know that left_type must be right_type
8416 * for the arithmetic operation and create a cast by itself */
8417 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8418 expression->right = create_implicit_cast(right, arithmetic_type);
8419 expression->base.type = type_left;
8420 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8421 check_pointer_arithmetic(&expression->base.source_position,
8422 type_left, orig_type_left);
8423 expression->base.type = type_left;
8424 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8425 errorf(&expression->base.source_position,
8426 "incompatible types '%T' and '%T' in assignment",
8427 orig_type_left, orig_type_right);
8431 static void semantic_integer_assign(binary_expression_t *expression)
8433 expression_t *left = expression->left;
8434 expression_t *right = expression->right;
8435 type_t *orig_type_left = left->base.type;
8436 type_t *orig_type_right = right->base.type;
8438 if (!is_valid_assignment_lhs(left))
8441 type_t *type_left = skip_typeref(orig_type_left);
8442 type_t *type_right = skip_typeref(orig_type_right);
8444 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8445 /* TODO: improve error message */
8446 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8447 errorf(&expression->base.source_position,
8448 "operation needs integer types");
8453 /* combined instructions are tricky. We can't create an implicit cast on
8454 * the left side, because we need the uncasted form for the store.
8455 * The ast2firm pass has to know that left_type must be right_type
8456 * for the arithmetic operation and create a cast by itself */
8457 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8458 expression->right = create_implicit_cast(right, arithmetic_type);
8459 expression->base.type = type_left;
8462 static void semantic_shift_assign(binary_expression_t *expression)
8464 expression_t *left = expression->left;
8466 if (!is_valid_assignment_lhs(left))
8469 if (!semantic_shift(expression))
8472 expression->base.type = skip_typeref(left->base.type);
8475 static void warn_logical_and_within_or(const expression_t *const expr)
8477 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8479 if (expr->base.parenthesized)
8481 source_position_t const *const pos = &expr->base.source_position;
8482 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8486 * Check the semantic restrictions of a logical expression.
8488 static void semantic_logical_op(binary_expression_t *expression)
8490 /* §6.5.13:2 Each of the operands shall have scalar type.
8491 * §6.5.14:2 Each of the operands shall have scalar type. */
8492 semantic_condition(expression->left, "left operand of logical operator");
8493 semantic_condition(expression->right, "right operand of logical operator");
8494 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8495 warn_logical_and_within_or(expression->left);
8496 warn_logical_and_within_or(expression->right);
8498 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8502 * Check the semantic restrictions of a binary assign expression.
8504 static void semantic_binexpr_assign(binary_expression_t *expression)
8506 expression_t *left = expression->left;
8507 type_t *orig_type_left = left->base.type;
8509 if (!is_valid_assignment_lhs(left))
8512 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8513 report_assign_error(error, orig_type_left, expression->right,
8514 "assignment", &left->base.source_position);
8515 expression->right = create_implicit_cast(expression->right, orig_type_left);
8516 expression->base.type = orig_type_left;
8520 * Determine if the outermost operation (or parts thereof) of the given
8521 * expression has no effect in order to generate a warning about this fact.
8522 * Therefore in some cases this only examines some of the operands of the
8523 * expression (see comments in the function and examples below).
8525 * f() + 23; // warning, because + has no effect
8526 * x || f(); // no warning, because x controls execution of f()
8527 * x ? y : f(); // warning, because y has no effect
8528 * (void)x; // no warning to be able to suppress the warning
8529 * This function can NOT be used for an "expression has definitely no effect"-
8531 static bool expression_has_effect(const expression_t *const expr)
8533 switch (expr->kind) {
8534 case EXPR_ERROR: return true; /* do NOT warn */
8535 case EXPR_REFERENCE: return false;
8536 case EXPR_ENUM_CONSTANT: return false;
8537 case EXPR_LABEL_ADDRESS: return false;
8539 /* suppress the warning for microsoft __noop operations */
8540 case EXPR_LITERAL_MS_NOOP: return true;
8541 case EXPR_LITERAL_BOOLEAN:
8542 case EXPR_LITERAL_CHARACTER:
8543 case EXPR_LITERAL_WIDE_CHARACTER:
8544 case EXPR_LITERAL_INTEGER:
8545 case EXPR_LITERAL_INTEGER_OCTAL:
8546 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8547 case EXPR_LITERAL_FLOATINGPOINT:
8548 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8549 case EXPR_STRING_LITERAL: return false;
8550 case EXPR_WIDE_STRING_LITERAL: return false;
8553 const call_expression_t *const call = &expr->call;
8554 if (call->function->kind != EXPR_REFERENCE)
8557 switch (call->function->reference.entity->function.btk) {
8558 /* FIXME: which builtins have no effect? */
8559 default: return true;
8563 /* Generate the warning if either the left or right hand side of a
8564 * conditional expression has no effect */
8565 case EXPR_CONDITIONAL: {
8566 conditional_expression_t const *const cond = &expr->conditional;
8567 expression_t const *const t = cond->true_expression;
8569 (t == NULL || expression_has_effect(t)) &&
8570 expression_has_effect(cond->false_expression);
8573 case EXPR_SELECT: return false;
8574 case EXPR_ARRAY_ACCESS: return false;
8575 case EXPR_SIZEOF: return false;
8576 case EXPR_CLASSIFY_TYPE: return false;
8577 case EXPR_ALIGNOF: return false;
8579 case EXPR_FUNCNAME: return false;
8580 case EXPR_BUILTIN_CONSTANT_P: return false;
8581 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8582 case EXPR_OFFSETOF: return false;
8583 case EXPR_VA_START: return true;
8584 case EXPR_VA_ARG: return true;
8585 case EXPR_VA_COPY: return true;
8586 case EXPR_STATEMENT: return true; // TODO
8587 case EXPR_COMPOUND_LITERAL: return false;
8589 case EXPR_UNARY_NEGATE: return false;
8590 case EXPR_UNARY_PLUS: return false;
8591 case EXPR_UNARY_BITWISE_NEGATE: return false;
8592 case EXPR_UNARY_NOT: return false;
8593 case EXPR_UNARY_DEREFERENCE: return false;
8594 case EXPR_UNARY_TAKE_ADDRESS: return false;
8595 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8596 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8597 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8598 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8600 /* Treat void casts as if they have an effect in order to being able to
8601 * suppress the warning */
8602 case EXPR_UNARY_CAST: {
8603 type_t *const type = skip_typeref(expr->base.type);
8604 return is_type_void(type);
8607 case EXPR_UNARY_ASSUME: return true;
8608 case EXPR_UNARY_DELETE: return true;
8609 case EXPR_UNARY_DELETE_ARRAY: return true;
8610 case EXPR_UNARY_THROW: return true;
8612 case EXPR_BINARY_ADD: return false;
8613 case EXPR_BINARY_SUB: return false;
8614 case EXPR_BINARY_MUL: return false;
8615 case EXPR_BINARY_DIV: return false;
8616 case EXPR_BINARY_MOD: return false;
8617 case EXPR_BINARY_EQUAL: return false;
8618 case EXPR_BINARY_NOTEQUAL: return false;
8619 case EXPR_BINARY_LESS: return false;
8620 case EXPR_BINARY_LESSEQUAL: return false;
8621 case EXPR_BINARY_GREATER: return false;
8622 case EXPR_BINARY_GREATEREQUAL: return false;
8623 case EXPR_BINARY_BITWISE_AND: return false;
8624 case EXPR_BINARY_BITWISE_OR: return false;
8625 case EXPR_BINARY_BITWISE_XOR: return false;
8626 case EXPR_BINARY_SHIFTLEFT: return false;
8627 case EXPR_BINARY_SHIFTRIGHT: return false;
8628 case EXPR_BINARY_ASSIGN: return true;
8629 case EXPR_BINARY_MUL_ASSIGN: return true;
8630 case EXPR_BINARY_DIV_ASSIGN: return true;
8631 case EXPR_BINARY_MOD_ASSIGN: return true;
8632 case EXPR_BINARY_ADD_ASSIGN: return true;
8633 case EXPR_BINARY_SUB_ASSIGN: return true;
8634 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8635 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8636 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8637 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8638 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8640 /* Only examine the right hand side of && and ||, because the left hand
8641 * side already has the effect of controlling the execution of the right
8643 case EXPR_BINARY_LOGICAL_AND:
8644 case EXPR_BINARY_LOGICAL_OR:
8645 /* Only examine the right hand side of a comma expression, because the left
8646 * hand side has a separate warning */
8647 case EXPR_BINARY_COMMA:
8648 return expression_has_effect(expr->binary.right);
8650 case EXPR_BINARY_ISGREATER: return false;
8651 case EXPR_BINARY_ISGREATEREQUAL: return false;
8652 case EXPR_BINARY_ISLESS: return false;
8653 case EXPR_BINARY_ISLESSEQUAL: return false;
8654 case EXPR_BINARY_ISLESSGREATER: return false;
8655 case EXPR_BINARY_ISUNORDERED: return false;
8658 internal_errorf(HERE, "unexpected expression");
8661 static void semantic_comma(binary_expression_t *expression)
8663 const expression_t *const left = expression->left;
8664 if (!expression_has_effect(left)) {
8665 source_position_t const *const pos = &left->base.source_position;
8666 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8668 expression->base.type = expression->right->base.type;
8672 * @param prec_r precedence of the right operand
8674 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8675 static expression_t *parse_##binexpression_type(expression_t *left) \
8677 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8678 binexpr->binary.left = left; \
8681 expression_t *right = parse_subexpression(prec_r); \
8683 binexpr->binary.right = right; \
8684 sfunc(&binexpr->binary); \
8689 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8690 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8691 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8692 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8693 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8694 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8695 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8696 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8697 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8698 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8699 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8700 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8701 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8702 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8703 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8704 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8705 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8706 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8707 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8708 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8709 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8710 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8711 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8712 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8713 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8714 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8715 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8716 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8717 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8718 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8721 static expression_t *parse_subexpression(precedence_t precedence)
8723 if (token.kind < 0) {
8724 return expected_expression_error();
8727 expression_parser_function_t *parser
8728 = &expression_parsers[token.kind];
8731 if (parser->parser != NULL) {
8732 left = parser->parser();
8734 left = parse_primary_expression();
8736 assert(left != NULL);
8739 if (token.kind < 0) {
8740 return expected_expression_error();
8743 parser = &expression_parsers[token.kind];
8744 if (parser->infix_parser == NULL)
8746 if (parser->infix_precedence < precedence)
8749 left = parser->infix_parser(left);
8751 assert(left != NULL);
8758 * Parse an expression.
8760 static expression_t *parse_expression(void)
8762 return parse_subexpression(PREC_EXPRESSION);
8766 * Register a parser for a prefix-like operator.
8768 * @param parser the parser function
8769 * @param token_kind the token type of the prefix token
8771 static void register_expression_parser(parse_expression_function parser,
8774 expression_parser_function_t *entry = &expression_parsers[token_kind];
8776 if (entry->parser != NULL) {
8777 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8778 panic("trying to register multiple expression parsers for a token");
8780 entry->parser = parser;
8784 * Register a parser for an infix operator with given precedence.
8786 * @param parser the parser function
8787 * @param token_kind the token type of the infix operator
8788 * @param precedence the precedence of the operator
8790 static void register_infix_parser(parse_expression_infix_function parser,
8791 int token_kind, precedence_t precedence)
8793 expression_parser_function_t *entry = &expression_parsers[token_kind];
8795 if (entry->infix_parser != NULL) {
8796 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8797 panic("trying to register multiple infix expression parsers for a "
8800 entry->infix_parser = parser;
8801 entry->infix_precedence = precedence;
8805 * Initialize the expression parsers.
8807 static void init_expression_parsers(void)
8809 memset(&expression_parsers, 0, sizeof(expression_parsers));
8811 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8812 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8813 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8814 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8815 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8816 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8817 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8818 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8819 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8820 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8821 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8822 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8823 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8824 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8825 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8826 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8827 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8828 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8829 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8830 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8831 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8832 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8833 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8834 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8835 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8836 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8837 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8838 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8839 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8840 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8841 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8842 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8843 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8844 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8845 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8846 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8847 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8849 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8850 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8851 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8852 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8853 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8854 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8855 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8856 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8857 register_expression_parser(parse_sizeof, T_sizeof);
8858 register_expression_parser(parse_alignof, T___alignof__);
8859 register_expression_parser(parse_extension, T___extension__);
8860 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8861 register_expression_parser(parse_delete, T_delete);
8862 register_expression_parser(parse_throw, T_throw);
8866 * Parse a asm statement arguments specification.
8868 static asm_argument_t *parse_asm_arguments(bool is_out)
8870 asm_argument_t *result = NULL;
8871 asm_argument_t **anchor = &result;
8873 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8874 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8875 memset(argument, 0, sizeof(argument[0]));
8878 if (token.kind != T_IDENTIFIER) {
8879 parse_error_expected("while parsing asm argument",
8880 T_IDENTIFIER, NULL);
8883 argument->symbol = token.identifier.symbol;
8885 expect(']', end_error);
8888 argument->constraints = parse_string_literals();
8889 expect('(', end_error);
8890 add_anchor_token(')');
8891 expression_t *expression = parse_expression();
8892 rem_anchor_token(')');
8894 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8895 * change size or type representation (e.g. int -> long is ok, but
8896 * int -> float is not) */
8897 if (expression->kind == EXPR_UNARY_CAST) {
8898 type_t *const type = expression->base.type;
8899 type_kind_t const kind = type->kind;
8900 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8903 if (kind == TYPE_ATOMIC) {
8904 atomic_type_kind_t const akind = type->atomic.akind;
8905 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8906 size = get_atomic_type_size(akind);
8908 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8909 size = get_type_size(type_void_ptr);
8913 expression_t *const value = expression->unary.value;
8914 type_t *const value_type = value->base.type;
8915 type_kind_t const value_kind = value_type->kind;
8917 unsigned value_flags;
8918 unsigned value_size;
8919 if (value_kind == TYPE_ATOMIC) {
8920 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8921 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8922 value_size = get_atomic_type_size(value_akind);
8923 } else if (value_kind == TYPE_POINTER) {
8924 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8925 value_size = get_type_size(type_void_ptr);
8930 if (value_flags != flags || value_size != size)
8934 } while (expression->kind == EXPR_UNARY_CAST);
8938 if (!is_lvalue(expression)) {
8939 errorf(&expression->base.source_position,
8940 "asm output argument is not an lvalue");
8943 if (argument->constraints.begin[0] == '=')
8944 determine_lhs_ent(expression, NULL);
8946 mark_vars_read(expression, NULL);
8948 mark_vars_read(expression, NULL);
8950 argument->expression = expression;
8951 expect(')', end_error);
8953 set_address_taken(expression, true);
8956 anchor = &argument->next;
8968 * Parse a asm statement clobber specification.
8970 static asm_clobber_t *parse_asm_clobbers(void)
8972 asm_clobber_t *result = NULL;
8973 asm_clobber_t **anchor = &result;
8975 while (token.kind == T_STRING_LITERAL) {
8976 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8977 clobber->clobber = parse_string_literals();
8980 anchor = &clobber->next;
8990 * Parse an asm statement.
8992 static statement_t *parse_asm_statement(void)
8994 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8995 asm_statement_t *asm_statement = &statement->asms;
8999 if (next_if(T_volatile))
9000 asm_statement->is_volatile = true;
9002 expect('(', end_error);
9003 add_anchor_token(')');
9004 if (token.kind != T_STRING_LITERAL) {
9005 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9008 asm_statement->asm_text = parse_string_literals();
9010 add_anchor_token(':');
9011 if (!next_if(':')) {
9012 rem_anchor_token(':');
9016 asm_statement->outputs = parse_asm_arguments(true);
9017 if (!next_if(':')) {
9018 rem_anchor_token(':');
9022 asm_statement->inputs = parse_asm_arguments(false);
9023 if (!next_if(':')) {
9024 rem_anchor_token(':');
9027 rem_anchor_token(':');
9029 asm_statement->clobbers = parse_asm_clobbers();
9032 rem_anchor_token(')');
9033 expect(')', end_error);
9034 expect(';', end_error);
9037 if (asm_statement->outputs == NULL) {
9038 /* GCC: An 'asm' instruction without any output operands will be treated
9039 * identically to a volatile 'asm' instruction. */
9040 asm_statement->is_volatile = true;
9046 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9048 statement_t *inner_stmt;
9049 switch (token.kind) {
9051 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9052 inner_stmt = create_error_statement();
9056 if (label->kind == STATEMENT_LABEL) {
9057 /* Eat an empty statement here, to avoid the warning about an empty
9058 * statement after a label. label:; is commonly used to have a label
9059 * before a closing brace. */
9060 inner_stmt = create_empty_statement();
9067 inner_stmt = parse_statement();
9068 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9069 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9070 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9071 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9079 * Parse a case statement.
9081 static statement_t *parse_case_statement(void)
9083 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9084 source_position_t *const pos = &statement->base.source_position;
9088 expression_t *expression = parse_expression();
9089 type_t *expression_type = expression->base.type;
9090 type_t *skipped = skip_typeref(expression_type);
9091 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9092 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9093 expression, expression_type);
9096 type_t *type = expression_type;
9097 if (current_switch != NULL) {
9098 type_t *switch_type = current_switch->expression->base.type;
9099 if (is_type_valid(switch_type)) {
9100 expression = create_implicit_cast(expression, switch_type);
9104 statement->case_label.expression = expression;
9105 expression_classification_t const expr_class = is_constant_expression(expression);
9106 if (expr_class != EXPR_CLASS_CONSTANT) {
9107 if (expr_class != EXPR_CLASS_ERROR) {
9108 errorf(pos, "case label does not reduce to an integer constant");
9110 statement->case_label.is_bad = true;
9112 long const val = fold_constant_to_int(expression);
9113 statement->case_label.first_case = val;
9114 statement->case_label.last_case = val;
9118 if (next_if(T_DOTDOTDOT)) {
9119 expression_t *end_range = parse_expression();
9120 expression_type = expression->base.type;
9121 skipped = skip_typeref(expression_type);
9122 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9123 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9124 expression, expression_type);
9127 end_range = create_implicit_cast(end_range, type);
9128 statement->case_label.end_range = end_range;
9129 expression_classification_t const end_class = is_constant_expression(end_range);
9130 if (end_class != EXPR_CLASS_CONSTANT) {
9131 if (end_class != EXPR_CLASS_ERROR) {
9132 errorf(pos, "case range does not reduce to an integer constant");
9134 statement->case_label.is_bad = true;
9136 long const val = fold_constant_to_int(end_range);
9137 statement->case_label.last_case = val;
9139 if (val < statement->case_label.first_case) {
9140 statement->case_label.is_empty_range = true;
9141 warningf(WARN_OTHER, pos, "empty range specified");
9147 PUSH_PARENT(statement);
9149 expect(':', end_error);
9152 if (current_switch != NULL) {
9153 if (! statement->case_label.is_bad) {
9154 /* Check for duplicate case values */
9155 case_label_statement_t *c = &statement->case_label;
9156 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9157 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9160 if (c->last_case < l->first_case || c->first_case > l->last_case)
9163 errorf(pos, "duplicate case value (previously used %P)",
9164 &l->base.source_position);
9168 /* link all cases into the switch statement */
9169 if (current_switch->last_case == NULL) {
9170 current_switch->first_case = &statement->case_label;
9172 current_switch->last_case->next = &statement->case_label;
9174 current_switch->last_case = &statement->case_label;
9176 errorf(pos, "case label not within a switch statement");
9179 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9186 * Parse a default statement.
9188 static statement_t *parse_default_statement(void)
9190 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9194 PUSH_PARENT(statement);
9196 expect(':', end_error);
9199 if (current_switch != NULL) {
9200 const case_label_statement_t *def_label = current_switch->default_label;
9201 if (def_label != NULL) {
9202 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9204 current_switch->default_label = &statement->case_label;
9206 /* link all cases into the switch statement */
9207 if (current_switch->last_case == NULL) {
9208 current_switch->first_case = &statement->case_label;
9210 current_switch->last_case->next = &statement->case_label;
9212 current_switch->last_case = &statement->case_label;
9215 errorf(&statement->base.source_position,
9216 "'default' label not within a switch statement");
9219 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9226 * Parse a label statement.
9228 static statement_t *parse_label_statement(void)
9230 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9231 label_t *const label = get_label();
9232 statement->label.label = label;
9234 PUSH_PARENT(statement);
9236 /* if statement is already set then the label is defined twice,
9237 * otherwise it was just mentioned in a goto/local label declaration so far
9239 source_position_t const* const pos = &statement->base.source_position;
9240 if (label->statement != NULL) {
9241 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9243 label->base.source_position = *pos;
9244 label->statement = statement;
9249 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9250 parse_attributes(NULL); // TODO process attributes
9253 statement->label.statement = parse_label_inner_statement(statement, "label");
9255 /* remember the labels in a list for later checking */
9256 *label_anchor = &statement->label;
9257 label_anchor = &statement->label.next;
9263 static statement_t *parse_inner_statement(void)
9265 statement_t *const stmt = parse_statement();
9266 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9267 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9268 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9269 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9275 * Parse an expression in parentheses and mark its variables as read.
9277 static expression_t *parse_condition(void)
9279 expect('(', end_error0);
9280 add_anchor_token(')');
9281 expression_t *const expr = parse_expression();
9282 mark_vars_read(expr, NULL);
9283 rem_anchor_token(')');
9284 expect(')', end_error1);
9288 return create_error_expression();
9292 * Parse an if statement.
9294 static statement_t *parse_if(void)
9296 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9300 PUSH_PARENT(statement);
9302 add_anchor_token('{');
9304 expression_t *const expr = parse_condition();
9305 statement->ifs.condition = expr;
9306 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9308 semantic_condition(expr, "condition of 'if'-statment");
9310 rem_anchor_token('{');
9312 add_anchor_token(T_else);
9313 statement_t *const true_stmt = parse_inner_statement();
9314 statement->ifs.true_statement = true_stmt;
9315 rem_anchor_token(T_else);
9317 if (true_stmt->kind == STATEMENT_EMPTY) {
9318 warningf(WARN_EMPTY_BODY, HERE,
9319 "suggest braces around empty body in an ‘if’ statement");
9322 if (next_if(T_else)) {
9323 statement->ifs.false_statement = parse_inner_statement();
9325 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9326 warningf(WARN_EMPTY_BODY, HERE,
9327 "suggest braces around empty body in an ‘if’ statement");
9329 } else if (true_stmt->kind == STATEMENT_IF &&
9330 true_stmt->ifs.false_statement != NULL) {
9331 source_position_t const *const pos = &true_stmt->base.source_position;
9332 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9340 * Check that all enums are handled in a switch.
9342 * @param statement the switch statement to check
9344 static void check_enum_cases(const switch_statement_t *statement)
9346 if (!is_warn_on(WARN_SWITCH_ENUM))
9348 const type_t *type = skip_typeref(statement->expression->base.type);
9349 if (! is_type_enum(type))
9351 const enum_type_t *enumt = &type->enumt;
9353 /* if we have a default, no warnings */
9354 if (statement->default_label != NULL)
9357 /* FIXME: calculation of value should be done while parsing */
9358 /* TODO: quadratic algorithm here. Change to an n log n one */
9359 long last_value = -1;
9360 const entity_t *entry = enumt->enume->base.next;
9361 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9362 entry = entry->base.next) {
9363 const expression_t *expression = entry->enum_value.value;
9364 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9366 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9367 if (l->expression == NULL)
9369 if (l->first_case <= value && value <= l->last_case) {
9375 source_position_t const *const pos = &statement->base.source_position;
9376 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9383 * Parse a switch statement.
9385 static statement_t *parse_switch(void)
9387 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9391 PUSH_PARENT(statement);
9393 expression_t *const expr = parse_condition();
9394 type_t * type = skip_typeref(expr->base.type);
9395 if (is_type_integer(type)) {
9396 type = promote_integer(type);
9397 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9398 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9400 } else if (is_type_valid(type)) {
9401 errorf(&expr->base.source_position,
9402 "switch quantity is not an integer, but '%T'", type);
9403 type = type_error_type;
9405 statement->switchs.expression = create_implicit_cast(expr, type);
9407 switch_statement_t *rem = current_switch;
9408 current_switch = &statement->switchs;
9409 statement->switchs.body = parse_inner_statement();
9410 current_switch = rem;
9412 if (statement->switchs.default_label == NULL) {
9413 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9415 check_enum_cases(&statement->switchs);
9421 static statement_t *parse_loop_body(statement_t *const loop)
9423 statement_t *const rem = current_loop;
9424 current_loop = loop;
9426 statement_t *const body = parse_inner_statement();
9433 * Parse a while statement.
9435 static statement_t *parse_while(void)
9437 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9441 PUSH_PARENT(statement);
9443 expression_t *const cond = parse_condition();
9444 statement->whiles.condition = cond;
9445 /* §6.8.5:2 The controlling expression of an iteration statement shall
9446 * have scalar type. */
9447 semantic_condition(cond, "condition of 'while'-statement");
9449 statement->whiles.body = parse_loop_body(statement);
9456 * Parse a do statement.
9458 static statement_t *parse_do(void)
9460 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9464 PUSH_PARENT(statement);
9466 add_anchor_token(T_while);
9467 statement->do_while.body = parse_loop_body(statement);
9468 rem_anchor_token(T_while);
9470 expect(T_while, end_error0);
9472 expression_t *const cond = parse_condition();
9473 statement->do_while.condition = cond;
9474 /* §6.8.5:2 The controlling expression of an iteration statement shall
9475 * have scalar type. */
9476 semantic_condition(cond, "condition of 'do-while'-statement");
9477 expect(';', end_error1);
9485 * Parse a for statement.
9487 static statement_t *parse_for(void)
9489 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9493 PUSH_PARENT(statement);
9494 PUSH_SCOPE(&statement->fors.scope);
9496 expect('(', end_error1);
9497 add_anchor_token(')');
9502 } else if (is_declaration_specifier(&token)) {
9503 parse_declaration(record_entity, DECL_FLAGS_NONE);
9505 add_anchor_token(';');
9506 expression_t *const init = parse_expression();
9507 statement->fors.initialisation = init;
9508 mark_vars_read(init, ENT_ANY);
9509 if (!expression_has_effect(init)) {
9510 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9512 rem_anchor_token(';');
9513 expect(';', end_error3);
9519 if (token.kind != ';') {
9520 add_anchor_token(';');
9521 expression_t *const cond = parse_expression();
9522 statement->fors.condition = cond;
9523 /* §6.8.5:2 The controlling expression of an iteration statement
9524 * shall have scalar type. */
9525 semantic_condition(cond, "condition of 'for'-statement");
9526 mark_vars_read(cond, NULL);
9527 rem_anchor_token(';');
9529 expect(';', end_error2);
9531 if (token.kind != ')') {
9532 expression_t *const step = parse_expression();
9533 statement->fors.step = step;
9534 mark_vars_read(step, ENT_ANY);
9535 if (!expression_has_effect(step)) {
9536 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9539 rem_anchor_token(')');
9540 expect(')', end_error1);
9542 statement->fors.body = parse_loop_body(statement);
9550 * Parse a goto statement.
9552 static statement_t *parse_goto(void)
9554 statement_t *statement;
9555 if (GNU_MODE && look_ahead(1)->kind == '*') {
9556 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9560 expression_t *expression = parse_expression();
9561 mark_vars_read(expression, NULL);
9563 /* Argh: although documentation says the expression must be of type void*,
9564 * gcc accepts anything that can be casted into void* without error */
9565 type_t *type = expression->base.type;
9567 if (type != type_error_type) {
9568 if (!is_type_pointer(type) && !is_type_integer(type)) {
9569 errorf(&expression->base.source_position,
9570 "cannot convert to a pointer type");
9571 } else if (type != type_void_ptr) {
9572 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9574 expression = create_implicit_cast(expression, type_void_ptr);
9577 statement->computed_goto.expression = expression;
9579 statement = allocate_statement_zero(STATEMENT_GOTO);
9581 if (token.kind == T_IDENTIFIER) {
9582 label_t *const label = get_label();
9584 statement->gotos.label = label;
9586 /* remember the goto's in a list for later checking */
9587 *goto_anchor = &statement->gotos;
9588 goto_anchor = &statement->gotos.next;
9591 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9593 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9595 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous)->label;
9599 expect(';', end_error);
9606 * Parse a continue statement.
9608 static statement_t *parse_continue(void)
9610 if (current_loop == NULL) {
9611 errorf(HERE, "continue statement not within loop");
9614 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9617 expect(';', end_error);
9624 * Parse a break statement.
9626 static statement_t *parse_break(void)
9628 if (current_switch == NULL && current_loop == NULL) {
9629 errorf(HERE, "break statement not within loop or switch");
9632 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9635 expect(';', end_error);
9642 * Parse a __leave statement.
9644 static statement_t *parse_leave_statement(void)
9646 if (current_try == NULL) {
9647 errorf(HERE, "__leave statement not within __try");
9650 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9653 expect(';', end_error);
9660 * Check if a given entity represents a local variable.
9662 static bool is_local_variable(const entity_t *entity)
9664 if (entity->kind != ENTITY_VARIABLE)
9667 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9668 case STORAGE_CLASS_AUTO:
9669 case STORAGE_CLASS_REGISTER: {
9670 const type_t *type = skip_typeref(entity->declaration.type);
9671 if (is_type_function(type)) {
9683 * Check if a given expression represents a local variable.
9685 static bool expression_is_local_variable(const expression_t *expression)
9687 if (expression->base.kind != EXPR_REFERENCE) {
9690 const entity_t *entity = expression->reference.entity;
9691 return is_local_variable(entity);
9695 * Check if a given expression represents a local variable and
9696 * return its declaration then, else return NULL.
9698 entity_t *expression_is_variable(const expression_t *expression)
9700 if (expression->base.kind != EXPR_REFERENCE) {
9703 entity_t *entity = expression->reference.entity;
9704 if (entity->kind != ENTITY_VARIABLE)
9710 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9712 if (c_mode & _CXX || strict_mode) {
9715 warningf(WARN_OTHER, pos, msg);
9720 * Parse a return statement.
9722 static statement_t *parse_return(void)
9724 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9727 expression_t *return_value = NULL;
9728 if (token.kind != ';') {
9729 return_value = parse_expression();
9730 mark_vars_read(return_value, NULL);
9733 const type_t *const func_type = skip_typeref(current_function->base.type);
9734 assert(is_type_function(func_type));
9735 type_t *const return_type = skip_typeref(func_type->function.return_type);
9737 source_position_t const *const pos = &statement->base.source_position;
9738 if (return_value != NULL) {
9739 type_t *return_value_type = skip_typeref(return_value->base.type);
9741 if (is_type_void(return_type)) {
9742 if (!is_type_void(return_value_type)) {
9743 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9744 /* Only warn in C mode, because GCC does the same */
9745 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9746 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9747 /* Only warn in C mode, because GCC does the same */
9748 err_or_warn(pos, "'return' with expression in function returning 'void'");
9751 assign_error_t error = semantic_assign(return_type, return_value);
9752 report_assign_error(error, return_type, return_value, "'return'",
9755 return_value = create_implicit_cast(return_value, return_type);
9756 /* check for returning address of a local var */
9757 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9758 const expression_t *expression = return_value->unary.value;
9759 if (expression_is_local_variable(expression)) {
9760 warningf(WARN_OTHER, pos, "function returns address of local variable");
9763 } else if (!is_type_void(return_type)) {
9764 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9765 err_or_warn(pos, "'return' without value, in function returning non-void");
9767 statement->returns.value = return_value;
9769 expect(';', end_error);
9776 * Parse a declaration statement.
9778 static statement_t *parse_declaration_statement(void)
9780 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9782 entity_t *before = current_scope->last_entity;
9784 parse_external_declaration();
9786 parse_declaration(record_entity, DECL_FLAGS_NONE);
9789 declaration_statement_t *const decl = &statement->declaration;
9790 entity_t *const begin =
9791 before != NULL ? before->base.next : current_scope->entities;
9792 decl->declarations_begin = begin;
9793 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9799 * Parse an expression statement, ie. expr ';'.
9801 static statement_t *parse_expression_statement(void)
9803 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9805 expression_t *const expr = parse_expression();
9806 statement->expression.expression = expr;
9807 mark_vars_read(expr, ENT_ANY);
9809 expect(';', end_error);
9816 * Parse a microsoft __try { } __finally { } or
9817 * __try{ } __except() { }
9819 static statement_t *parse_ms_try_statment(void)
9821 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9824 PUSH_PARENT(statement);
9826 ms_try_statement_t *rem = current_try;
9827 current_try = &statement->ms_try;
9828 statement->ms_try.try_statement = parse_compound_statement(false);
9833 if (next_if(T___except)) {
9834 expression_t *const expr = parse_condition();
9835 type_t * type = skip_typeref(expr->base.type);
9836 if (is_type_integer(type)) {
9837 type = promote_integer(type);
9838 } else if (is_type_valid(type)) {
9839 errorf(&expr->base.source_position,
9840 "__expect expression is not an integer, but '%T'", type);
9841 type = type_error_type;
9843 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9844 } else if (!next_if(T__finally)) {
9845 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9847 statement->ms_try.final_statement = parse_compound_statement(false);
9851 static statement_t *parse_empty_statement(void)
9853 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9854 statement_t *const statement = create_empty_statement();
9859 static statement_t *parse_local_label_declaration(void)
9861 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9865 entity_t *begin = NULL;
9866 entity_t *end = NULL;
9867 entity_t **anchor = &begin;
9869 if (token.kind != T_IDENTIFIER) {
9870 parse_error_expected("while parsing local label declaration",
9871 T_IDENTIFIER, NULL);
9874 symbol_t *symbol = token.identifier.symbol;
9875 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9876 if (entity != NULL && entity->base.parent_scope == current_scope) {
9877 source_position_t const *const ppos = &entity->base.source_position;
9878 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9880 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9881 entity->base.parent_scope = current_scope;
9882 entity->base.source_position = token.base.source_position;
9885 anchor = &entity->base.next;
9888 environment_push(entity);
9891 } while (next_if(','));
9892 expect(';', end_error);
9894 statement->declaration.declarations_begin = begin;
9895 statement->declaration.declarations_end = end;
9899 static void parse_namespace_definition(void)
9903 entity_t *entity = NULL;
9904 symbol_t *symbol = NULL;
9906 if (token.kind == T_IDENTIFIER) {
9907 symbol = token.identifier.symbol;
9910 entity = get_entity(symbol, NAMESPACE_NORMAL);
9912 && entity->kind != ENTITY_NAMESPACE
9913 && entity->base.parent_scope == current_scope) {
9914 if (is_entity_valid(entity)) {
9915 error_redefined_as_different_kind(&token.base.source_position,
9916 entity, ENTITY_NAMESPACE);
9922 if (entity == NULL) {
9923 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9924 entity->base.source_position = token.base.source_position;
9925 entity->base.parent_scope = current_scope;
9928 if (token.kind == '=') {
9929 /* TODO: parse namespace alias */
9930 panic("namespace alias definition not supported yet");
9933 environment_push(entity);
9934 append_entity(current_scope, entity);
9936 PUSH_SCOPE(&entity->namespacee.members);
9938 entity_t *old_current_entity = current_entity;
9939 current_entity = entity;
9941 expect('{', end_error);
9943 expect('}', end_error);
9946 assert(current_entity == entity);
9947 current_entity = old_current_entity;
9952 * Parse a statement.
9953 * There's also parse_statement() which additionally checks for
9954 * "statement has no effect" warnings
9956 static statement_t *intern_parse_statement(void)
9958 /* declaration or statement */
9959 statement_t *statement;
9960 switch (token.kind) {
9961 case T_IDENTIFIER: {
9962 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9963 if (la1_type == ':') {
9964 statement = parse_label_statement();
9965 } else if (is_typedef_symbol(token.identifier.symbol)) {
9966 statement = parse_declaration_statement();
9968 /* it's an identifier, the grammar says this must be an
9969 * expression statement. However it is common that users mistype
9970 * declaration types, so we guess a bit here to improve robustness
9971 * for incorrect programs */
9975 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9977 statement = parse_expression_statement();
9981 statement = parse_declaration_statement();
9989 case T___extension__: {
9990 /* This can be a prefix to a declaration or an expression statement.
9991 * We simply eat it now and parse the rest with tail recursion. */
9993 statement = intern_parse_statement();
9999 statement = parse_declaration_statement();
10003 statement = parse_local_label_declaration();
10006 case ';': statement = parse_empty_statement(); break;
10007 case '{': statement = parse_compound_statement(false); break;
10008 case T___leave: statement = parse_leave_statement(); break;
10009 case T___try: statement = parse_ms_try_statment(); break;
10010 case T_asm: statement = parse_asm_statement(); break;
10011 case T_break: statement = parse_break(); break;
10012 case T_case: statement = parse_case_statement(); break;
10013 case T_continue: statement = parse_continue(); break;
10014 case T_default: statement = parse_default_statement(); break;
10015 case T_do: statement = parse_do(); break;
10016 case T_for: statement = parse_for(); break;
10017 case T_goto: statement = parse_goto(); break;
10018 case T_if: statement = parse_if(); break;
10019 case T_return: statement = parse_return(); break;
10020 case T_switch: statement = parse_switch(); break;
10021 case T_while: statement = parse_while(); break;
10024 statement = parse_expression_statement();
10028 errorf(HERE, "unexpected token %K while parsing statement", &token);
10029 statement = create_error_statement();
10030 eat_until_anchor();
10038 * parse a statement and emits "statement has no effect" warning if needed
10039 * (This is really a wrapper around intern_parse_statement with check for 1
10040 * single warning. It is needed, because for statement expressions we have
10041 * to avoid the warning on the last statement)
10043 static statement_t *parse_statement(void)
10045 statement_t *statement = intern_parse_statement();
10047 if (statement->kind == STATEMENT_EXPRESSION) {
10048 expression_t *expression = statement->expression.expression;
10049 if (!expression_has_effect(expression)) {
10050 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10058 * Parse a compound statement.
10060 static statement_t *parse_compound_statement(bool inside_expression_statement)
10062 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10064 PUSH_PARENT(statement);
10065 PUSH_SCOPE(&statement->compound.scope);
10068 add_anchor_token('}');
10069 /* tokens, which can start a statement */
10070 /* TODO MS, __builtin_FOO */
10071 add_anchor_token('!');
10072 add_anchor_token('&');
10073 add_anchor_token('(');
10074 add_anchor_token('*');
10075 add_anchor_token('+');
10076 add_anchor_token('-');
10077 add_anchor_token(';');
10078 add_anchor_token('{');
10079 add_anchor_token('~');
10080 add_anchor_token(T_CHARACTER_CONSTANT);
10081 add_anchor_token(T_COLONCOLON);
10082 add_anchor_token(T_FLOATINGPOINT);
10083 add_anchor_token(T_IDENTIFIER);
10084 add_anchor_token(T_INTEGER);
10085 add_anchor_token(T_MINUSMINUS);
10086 add_anchor_token(T_PLUSPLUS);
10087 add_anchor_token(T_STRING_LITERAL);
10088 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10089 add_anchor_token(T_WIDE_STRING_LITERAL);
10090 add_anchor_token(T__Bool);
10091 add_anchor_token(T__Complex);
10092 add_anchor_token(T__Imaginary);
10093 add_anchor_token(T___FUNCTION__);
10094 add_anchor_token(T___PRETTY_FUNCTION__);
10095 add_anchor_token(T___alignof__);
10096 add_anchor_token(T___attribute__);
10097 add_anchor_token(T___builtin_va_start);
10098 add_anchor_token(T___extension__);
10099 add_anchor_token(T___func__);
10100 add_anchor_token(T___imag__);
10101 add_anchor_token(T___label__);
10102 add_anchor_token(T___real__);
10103 add_anchor_token(T___thread);
10104 add_anchor_token(T_asm);
10105 add_anchor_token(T_auto);
10106 add_anchor_token(T_bool);
10107 add_anchor_token(T_break);
10108 add_anchor_token(T_case);
10109 add_anchor_token(T_char);
10110 add_anchor_token(T_class);
10111 add_anchor_token(T_const);
10112 add_anchor_token(T_const_cast);
10113 add_anchor_token(T_continue);
10114 add_anchor_token(T_default);
10115 add_anchor_token(T_delete);
10116 add_anchor_token(T_double);
10117 add_anchor_token(T_do);
10118 add_anchor_token(T_dynamic_cast);
10119 add_anchor_token(T_enum);
10120 add_anchor_token(T_extern);
10121 add_anchor_token(T_false);
10122 add_anchor_token(T_float);
10123 add_anchor_token(T_for);
10124 add_anchor_token(T_goto);
10125 add_anchor_token(T_if);
10126 add_anchor_token(T_inline);
10127 add_anchor_token(T_int);
10128 add_anchor_token(T_long);
10129 add_anchor_token(T_new);
10130 add_anchor_token(T_operator);
10131 add_anchor_token(T_register);
10132 add_anchor_token(T_reinterpret_cast);
10133 add_anchor_token(T_restrict);
10134 add_anchor_token(T_return);
10135 add_anchor_token(T_short);
10136 add_anchor_token(T_signed);
10137 add_anchor_token(T_sizeof);
10138 add_anchor_token(T_static);
10139 add_anchor_token(T_static_cast);
10140 add_anchor_token(T_struct);
10141 add_anchor_token(T_switch);
10142 add_anchor_token(T_template);
10143 add_anchor_token(T_this);
10144 add_anchor_token(T_throw);
10145 add_anchor_token(T_true);
10146 add_anchor_token(T_try);
10147 add_anchor_token(T_typedef);
10148 add_anchor_token(T_typeid);
10149 add_anchor_token(T_typename);
10150 add_anchor_token(T_typeof);
10151 add_anchor_token(T_union);
10152 add_anchor_token(T_unsigned);
10153 add_anchor_token(T_using);
10154 add_anchor_token(T_void);
10155 add_anchor_token(T_volatile);
10156 add_anchor_token(T_wchar_t);
10157 add_anchor_token(T_while);
10159 statement_t **anchor = &statement->compound.statements;
10160 bool only_decls_so_far = true;
10161 while (token.kind != '}') {
10162 if (token.kind == T_EOF) {
10163 errorf(&statement->base.source_position,
10164 "EOF while parsing compound statement");
10167 statement_t *sub_statement = intern_parse_statement();
10168 if (sub_statement->kind == STATEMENT_ERROR) {
10172 if (sub_statement->kind != STATEMENT_DECLARATION) {
10173 only_decls_so_far = false;
10174 } else if (!only_decls_so_far) {
10175 source_position_t const *const pos = &sub_statement->base.source_position;
10176 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10179 *anchor = sub_statement;
10180 anchor = &sub_statement->base.next;
10184 /* look over all statements again to produce no effect warnings */
10185 if (is_warn_on(WARN_UNUSED_VALUE)) {
10186 statement_t *sub_statement = statement->compound.statements;
10187 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10188 if (sub_statement->kind != STATEMENT_EXPRESSION)
10190 /* don't emit a warning for the last expression in an expression
10191 * statement as it has always an effect */
10192 if (inside_expression_statement && sub_statement->base.next == NULL)
10195 expression_t *expression = sub_statement->expression.expression;
10196 if (!expression_has_effect(expression)) {
10197 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10203 rem_anchor_token(T_while);
10204 rem_anchor_token(T_wchar_t);
10205 rem_anchor_token(T_volatile);
10206 rem_anchor_token(T_void);
10207 rem_anchor_token(T_using);
10208 rem_anchor_token(T_unsigned);
10209 rem_anchor_token(T_union);
10210 rem_anchor_token(T_typeof);
10211 rem_anchor_token(T_typename);
10212 rem_anchor_token(T_typeid);
10213 rem_anchor_token(T_typedef);
10214 rem_anchor_token(T_try);
10215 rem_anchor_token(T_true);
10216 rem_anchor_token(T_throw);
10217 rem_anchor_token(T_this);
10218 rem_anchor_token(T_template);
10219 rem_anchor_token(T_switch);
10220 rem_anchor_token(T_struct);
10221 rem_anchor_token(T_static_cast);
10222 rem_anchor_token(T_static);
10223 rem_anchor_token(T_sizeof);
10224 rem_anchor_token(T_signed);
10225 rem_anchor_token(T_short);
10226 rem_anchor_token(T_return);
10227 rem_anchor_token(T_restrict);
10228 rem_anchor_token(T_reinterpret_cast);
10229 rem_anchor_token(T_register);
10230 rem_anchor_token(T_operator);
10231 rem_anchor_token(T_new);
10232 rem_anchor_token(T_long);
10233 rem_anchor_token(T_int);
10234 rem_anchor_token(T_inline);
10235 rem_anchor_token(T_if);
10236 rem_anchor_token(T_goto);
10237 rem_anchor_token(T_for);
10238 rem_anchor_token(T_float);
10239 rem_anchor_token(T_false);
10240 rem_anchor_token(T_extern);
10241 rem_anchor_token(T_enum);
10242 rem_anchor_token(T_dynamic_cast);
10243 rem_anchor_token(T_do);
10244 rem_anchor_token(T_double);
10245 rem_anchor_token(T_delete);
10246 rem_anchor_token(T_default);
10247 rem_anchor_token(T_continue);
10248 rem_anchor_token(T_const_cast);
10249 rem_anchor_token(T_const);
10250 rem_anchor_token(T_class);
10251 rem_anchor_token(T_char);
10252 rem_anchor_token(T_case);
10253 rem_anchor_token(T_break);
10254 rem_anchor_token(T_bool);
10255 rem_anchor_token(T_auto);
10256 rem_anchor_token(T_asm);
10257 rem_anchor_token(T___thread);
10258 rem_anchor_token(T___real__);
10259 rem_anchor_token(T___label__);
10260 rem_anchor_token(T___imag__);
10261 rem_anchor_token(T___func__);
10262 rem_anchor_token(T___extension__);
10263 rem_anchor_token(T___builtin_va_start);
10264 rem_anchor_token(T___attribute__);
10265 rem_anchor_token(T___alignof__);
10266 rem_anchor_token(T___PRETTY_FUNCTION__);
10267 rem_anchor_token(T___FUNCTION__);
10268 rem_anchor_token(T__Imaginary);
10269 rem_anchor_token(T__Complex);
10270 rem_anchor_token(T__Bool);
10271 rem_anchor_token(T_WIDE_STRING_LITERAL);
10272 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10273 rem_anchor_token(T_STRING_LITERAL);
10274 rem_anchor_token(T_PLUSPLUS);
10275 rem_anchor_token(T_MINUSMINUS);
10276 rem_anchor_token(T_INTEGER);
10277 rem_anchor_token(T_IDENTIFIER);
10278 rem_anchor_token(T_FLOATINGPOINT);
10279 rem_anchor_token(T_COLONCOLON);
10280 rem_anchor_token(T_CHARACTER_CONSTANT);
10281 rem_anchor_token('~');
10282 rem_anchor_token('{');
10283 rem_anchor_token(';');
10284 rem_anchor_token('-');
10285 rem_anchor_token('+');
10286 rem_anchor_token('*');
10287 rem_anchor_token('(');
10288 rem_anchor_token('&');
10289 rem_anchor_token('!');
10290 rem_anchor_token('}');
10298 * Check for unused global static functions and variables
10300 static void check_unused_globals(void)
10302 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10305 for (const entity_t *entity = file_scope->entities; entity != NULL;
10306 entity = entity->base.next) {
10307 if (!is_declaration(entity))
10310 const declaration_t *declaration = &entity->declaration;
10311 if (declaration->used ||
10312 declaration->modifiers & DM_UNUSED ||
10313 declaration->modifiers & DM_USED ||
10314 declaration->storage_class != STORAGE_CLASS_STATIC)
10319 if (entity->kind == ENTITY_FUNCTION) {
10320 /* inhibit warning for static inline functions */
10321 if (entity->function.is_inline)
10324 why = WARN_UNUSED_FUNCTION;
10325 s = entity->function.statement != NULL ? "defined" : "declared";
10327 why = WARN_UNUSED_VARIABLE;
10331 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10335 static void parse_global_asm(void)
10337 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10340 expect('(', end_error);
10342 statement->asms.asm_text = parse_string_literals();
10343 statement->base.next = unit->global_asm;
10344 unit->global_asm = statement;
10346 expect(')', end_error);
10347 expect(';', end_error);
10352 static void parse_linkage_specification(void)
10356 source_position_t const pos = *HERE;
10357 char const *const linkage = parse_string_literals().begin;
10359 linkage_kind_t old_linkage = current_linkage;
10360 linkage_kind_t new_linkage;
10361 if (streq(linkage, "C")) {
10362 new_linkage = LINKAGE_C;
10363 } else if (streq(linkage, "C++")) {
10364 new_linkage = LINKAGE_CXX;
10366 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10367 new_linkage = LINKAGE_C;
10369 current_linkage = new_linkage;
10371 if (next_if('{')) {
10373 expect('}', end_error);
10379 assert(current_linkage == new_linkage);
10380 current_linkage = old_linkage;
10383 static void parse_external(void)
10385 switch (token.kind) {
10387 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10388 parse_linkage_specification();
10390 DECLARATION_START_NO_EXTERN
10392 case T___extension__:
10393 /* tokens below are for implicit int */
10394 case '&': /* & x; -> int& x; (and error later, because C++ has no
10396 case '*': /* * x; -> int* x; */
10397 case '(': /* (x); -> int (x); */
10399 parse_external_declaration();
10405 parse_global_asm();
10409 parse_namespace_definition();
10413 if (!strict_mode) {
10414 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10421 errorf(HERE, "stray %K outside of function", &token);
10422 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10423 eat_until_matching_token(token.kind);
10429 static void parse_externals(void)
10431 add_anchor_token('}');
10432 add_anchor_token(T_EOF);
10435 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10436 unsigned short token_anchor_copy[T_LAST_TOKEN];
10437 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10440 while (token.kind != T_EOF && token.kind != '}') {
10442 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10443 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10445 /* the anchor set and its copy differs */
10446 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10449 if (in_gcc_extension) {
10450 /* an gcc extension scope was not closed */
10451 internal_errorf(HERE, "Leaked __extension__");
10458 rem_anchor_token(T_EOF);
10459 rem_anchor_token('}');
10463 * Parse a translation unit.
10465 static void parse_translation_unit(void)
10467 add_anchor_token(T_EOF);
10472 if (token.kind == T_EOF)
10475 errorf(HERE, "stray %K outside of function", &token);
10476 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10477 eat_until_matching_token(token.kind);
10482 void set_default_visibility(elf_visibility_tag_t visibility)
10484 default_visibility = visibility;
10490 * @return the translation unit or NULL if errors occurred.
10492 void start_parsing(void)
10494 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10495 label_stack = NEW_ARR_F(stack_entry_t, 0);
10496 diagnostic_count = 0;
10500 print_to_file(stderr);
10502 assert(unit == NULL);
10503 unit = allocate_ast_zero(sizeof(unit[0]));
10505 assert(file_scope == NULL);
10506 file_scope = &unit->scope;
10508 assert(current_scope == NULL);
10509 scope_push(&unit->scope);
10511 create_gnu_builtins();
10513 create_microsoft_intrinsics();
10516 translation_unit_t *finish_parsing(void)
10518 assert(current_scope == &unit->scope);
10521 assert(file_scope == &unit->scope);
10522 check_unused_globals();
10525 DEL_ARR_F(environment_stack);
10526 DEL_ARR_F(label_stack);
10528 translation_unit_t *result = unit;
10533 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10534 * are given length one. */
10535 static void complete_incomplete_arrays(void)
10537 size_t n = ARR_LEN(incomplete_arrays);
10538 for (size_t i = 0; i != n; ++i) {
10539 declaration_t *const decl = incomplete_arrays[i];
10540 type_t *const type = skip_typeref(decl->type);
10542 if (!is_type_incomplete(type))
10545 source_position_t const *const pos = &decl->base.source_position;
10546 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10548 type_t *const new_type = duplicate_type(type);
10549 new_type->array.size_constant = true;
10550 new_type->array.has_implicit_size = true;
10551 new_type->array.size = 1;
10553 type_t *const result = identify_new_type(new_type);
10555 decl->type = result;
10559 void prepare_main_collect2(entity_t *entity)
10561 PUSH_SCOPE(&entity->function.statement->compound.scope);
10563 // create call to __main
10564 symbol_t *symbol = symbol_table_insert("__main");
10565 entity_t *subsubmain_ent
10566 = create_implicit_function(symbol, &builtin_source_position);
10568 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10569 type_t *ftype = subsubmain_ent->declaration.type;
10570 ref->base.source_position = builtin_source_position;
10571 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10572 ref->reference.entity = subsubmain_ent;
10574 expression_t *call = allocate_expression_zero(EXPR_CALL);
10575 call->base.source_position = builtin_source_position;
10576 call->base.type = type_void;
10577 call->call.function = ref;
10579 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10580 expr_statement->base.source_position = builtin_source_position;
10581 expr_statement->expression.expression = call;
10583 statement_t *statement = entity->function.statement;
10584 assert(statement->kind == STATEMENT_COMPOUND);
10585 compound_statement_t *compounds = &statement->compound;
10587 expr_statement->base.next = compounds->statements;
10588 compounds->statements = expr_statement;
10595 lookahead_bufpos = 0;
10596 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10599 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10600 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10601 parse_translation_unit();
10602 complete_incomplete_arrays();
10603 DEL_ARR_F(incomplete_arrays);
10604 incomplete_arrays = NULL;
10608 * Initialize the parser.
10610 void init_parser(void)
10612 sym_anonymous = symbol_table_insert("<anonymous>");
10614 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10616 init_expression_parsers();
10617 obstack_init(&temp_obst);
10621 * Terminate the parser.
10623 void exit_parser(void)
10625 obstack_free(&temp_obst, NULL);