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_CURRENT_ENTITY(entity) \
113 entity_t *const new_current_entity = (entity); \
114 entity_t *const old_current_entity = current_entity; \
115 ((void)(current_entity = new_current_entity))
116 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
118 #define PUSH_PARENT(stmt) \
119 statement_t *const new_parent = (stmt); \
120 statement_t *const old_parent = current_parent; \
121 ((void)(current_parent = new_parent))
122 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
124 #define PUSH_SCOPE(scope) \
125 size_t const top = environment_top(); \
126 scope_t *const new_scope = (scope); \
127 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
128 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
129 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
131 #define PUSH_EXTENSION() \
133 bool const old_gcc_extension = in_gcc_extension; \
134 while (next_if(T___extension__)) { \
135 in_gcc_extension = true; \
138 #define POP_EXTENSION() \
139 ((void)(in_gcc_extension = old_gcc_extension))
141 /** special symbol used for anonymous entities. */
142 static symbol_t *sym_anonymous = NULL;
144 /** The token anchor set */
145 static unsigned short token_anchor_set[T_LAST_TOKEN];
147 /** The current source position. */
148 #define HERE (&token.base.source_position)
150 /** true if we are in GCC mode. */
151 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
153 static statement_t *parse_compound_statement(bool inside_expression_statement);
154 static statement_t *parse_statement(void);
156 static expression_t *parse_subexpression(precedence_t);
157 static expression_t *parse_expression(void);
158 static type_t *parse_typename(void);
159 static void parse_externals(void);
160 static void parse_external(void);
162 static void parse_compound_type_entries(compound_t *compound_declaration);
164 static void check_call_argument(type_t *expected_type,
165 call_argument_t *argument, unsigned pos);
167 typedef enum declarator_flags_t {
169 DECL_MAY_BE_ABSTRACT = 1U << 0,
170 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
171 DECL_IS_PARAMETER = 1U << 2
172 } declarator_flags_t;
174 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
175 declarator_flags_t flags);
177 static void semantic_comparison(binary_expression_t *expression);
179 #define STORAGE_CLASSES \
180 STORAGE_CLASSES_NO_EXTERN \
183 #define STORAGE_CLASSES_NO_EXTERN \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #define COMPLEX_SPECIFIERS \
200 #define IMAGINARY_SPECIFIERS \
203 #define TYPE_SPECIFIERS \
205 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define DECLARATION_START_NO_EXTERN \
236 STORAGE_CLASSES_NO_EXTERN \
240 #define EXPRESSION_START \
249 case T_CHARACTER_CONSTANT: \
250 case T_FLOATINGPOINT: \
251 case T_FLOATINGPOINT_HEXADECIMAL: \
253 case T_INTEGER_HEXADECIMAL: \
254 case T_INTEGER_OCTAL: \
257 case T_STRING_LITERAL: \
258 case T_WIDE_CHARACTER_CONSTANT: \
259 case T_WIDE_STRING_LITERAL: \
260 case T___FUNCDNAME__: \
261 case T___FUNCSIG__: \
262 case T___FUNCTION__: \
263 case T___PRETTY_FUNCTION__: \
264 case T___alignof__: \
265 case T___builtin_classify_type: \
266 case T___builtin_constant_p: \
267 case T___builtin_isgreater: \
268 case T___builtin_isgreaterequal: \
269 case T___builtin_isless: \
270 case T___builtin_islessequal: \
271 case T___builtin_islessgreater: \
272 case T___builtin_isunordered: \
273 case T___builtin_offsetof: \
274 case T___builtin_va_arg: \
275 case T___builtin_va_copy: \
276 case T___builtin_va_start: \
287 * Returns the size of a statement node.
289 * @param kind the statement kind
291 static size_t get_statement_struct_size(statement_kind_t kind)
293 static const size_t sizes[] = {
294 [STATEMENT_ERROR] = sizeof(statement_base_t),
295 [STATEMENT_EMPTY] = sizeof(statement_base_t),
296 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
297 [STATEMENT_RETURN] = sizeof(return_statement_t),
298 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
299 [STATEMENT_IF] = sizeof(if_statement_t),
300 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
301 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
302 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
303 [STATEMENT_BREAK] = sizeof(statement_base_t),
304 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
305 [STATEMENT_GOTO] = sizeof(goto_statement_t),
306 [STATEMENT_LABEL] = sizeof(label_statement_t),
307 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
308 [STATEMENT_WHILE] = sizeof(while_statement_t),
309 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
310 [STATEMENT_FOR] = sizeof(for_statement_t),
311 [STATEMENT_ASM] = sizeof(asm_statement_t),
312 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
313 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
315 assert((size_t)kind < lengthof(sizes));
316 assert(sizes[kind] != 0);
321 * Returns the size of an expression node.
323 * @param kind the expression kind
325 static size_t get_expression_struct_size(expression_kind_t kind)
327 static const size_t sizes[] = {
328 [EXPR_ERROR] = sizeof(expression_base_t),
329 [EXPR_REFERENCE] = sizeof(reference_expression_t),
330 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
331 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
332 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
333 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
334 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
335 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
336 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
337 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
338 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
339 [EXPR_CALL] = sizeof(call_expression_t),
340 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
341 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
342 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
343 [EXPR_SELECT] = sizeof(select_expression_t),
344 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
345 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
346 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
347 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
348 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
349 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
350 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
351 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
352 [EXPR_VA_START] = sizeof(va_start_expression_t),
353 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
354 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
355 [EXPR_STATEMENT] = sizeof(statement_expression_t),
356 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
358 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
359 return sizes[EXPR_UNARY_FIRST];
361 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
362 return sizes[EXPR_BINARY_FIRST];
364 assert((size_t)kind < lengthof(sizes));
365 assert(sizes[kind] != 0);
370 * Allocate a statement node of given kind and initialize all
371 * fields with zero. Sets its source position to the position
372 * of the current token.
374 static statement_t *allocate_statement_zero(statement_kind_t kind)
376 size_t size = get_statement_struct_size(kind);
377 statement_t *res = allocate_ast_zero(size);
379 res->base.kind = kind;
380 res->base.parent = current_parent;
381 res->base.source_position = token.base.source_position;
386 * Allocate an expression node of given kind and initialize all
389 * @param kind the kind of the expression to allocate
391 static expression_t *allocate_expression_zero(expression_kind_t kind)
393 size_t size = get_expression_struct_size(kind);
394 expression_t *res = allocate_ast_zero(size);
396 res->base.kind = kind;
397 res->base.type = type_error_type;
398 res->base.source_position = token.base.source_position;
403 * Creates a new invalid expression at the source position
404 * of the current token.
406 static expression_t *create_error_expression(void)
408 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
409 expression->base.type = type_error_type;
414 * Creates a new invalid statement.
416 static statement_t *create_error_statement(void)
418 return allocate_statement_zero(STATEMENT_ERROR);
422 * Allocate a new empty statement.
424 static statement_t *create_empty_statement(void)
426 return allocate_statement_zero(STATEMENT_EMPTY);
430 * Returns the size of an initializer node.
432 * @param kind the initializer kind
434 static size_t get_initializer_size(initializer_kind_t kind)
436 static const size_t sizes[] = {
437 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
438 [INITIALIZER_STRING] = sizeof(initializer_string_t),
439 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
440 [INITIALIZER_LIST] = sizeof(initializer_list_t),
441 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
443 assert((size_t)kind < lengthof(sizes));
444 assert(sizes[kind] != 0);
449 * Allocate an initializer node of given kind and initialize all
452 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
454 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
461 * Returns the index of the top element of the environment stack.
463 static size_t environment_top(void)
465 return ARR_LEN(environment_stack);
469 * Returns the index of the top element of the global label stack.
471 static size_t label_top(void)
473 return ARR_LEN(label_stack);
477 * Return the next token.
479 static inline void next_token(void)
481 token = lookahead_buffer[lookahead_bufpos];
482 lookahead_buffer[lookahead_bufpos] = lexer_token;
485 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
488 print_token(stderr, &token);
489 fprintf(stderr, "\n");
493 static inline bool next_if(token_kind_t const type)
495 if (token.kind == type) {
504 * Return the next token with a given lookahead.
506 static inline const token_t *look_ahead(size_t num)
508 assert(0 < num && num <= MAX_LOOKAHEAD);
509 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
510 return &lookahead_buffer[pos];
514 * Adds a token type to the token type anchor set (a multi-set).
516 static void add_anchor_token(token_kind_t const token_kind)
518 assert(token_kind < T_LAST_TOKEN);
519 ++token_anchor_set[token_kind];
523 * Remove a token type from the token type anchor set (a multi-set).
525 static void rem_anchor_token(token_kind_t const token_kind)
527 assert(token_kind < T_LAST_TOKEN);
528 assert(token_anchor_set[token_kind] != 0);
529 --token_anchor_set[token_kind];
533 * Eat tokens until a matching token type is found.
535 static void eat_until_matching_token(token_kind_t const type)
537 token_kind_t end_token;
539 case '(': end_token = ')'; break;
540 case '{': end_token = '}'; break;
541 case '[': end_token = ']'; break;
542 default: end_token = type; break;
545 unsigned parenthesis_count = 0;
546 unsigned brace_count = 0;
547 unsigned bracket_count = 0;
548 while (token.kind != end_token ||
549 parenthesis_count != 0 ||
551 bracket_count != 0) {
552 switch (token.kind) {
554 case '(': ++parenthesis_count; break;
555 case '{': ++brace_count; break;
556 case '[': ++bracket_count; break;
559 if (parenthesis_count > 0)
569 if (bracket_count > 0)
572 if (token.kind == end_token &&
573 parenthesis_count == 0 &&
587 * Eat input tokens until an anchor is found.
589 static void eat_until_anchor(void)
591 while (token_anchor_set[token.kind] == 0) {
592 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
593 eat_until_matching_token(token.kind);
599 * Eat a whole block from input tokens.
601 static void eat_block(void)
603 eat_until_matching_token('{');
607 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
610 * Report a parse error because an expected token was not found.
613 #if defined __GNUC__ && __GNUC__ >= 4
614 __attribute__((sentinel))
616 void parse_error_expected(const char *message, ...)
618 if (message != NULL) {
619 errorf(HERE, "%s", message);
622 va_start(ap, message);
623 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
628 * Report an incompatible type.
630 static void type_error_incompatible(const char *msg,
631 const source_position_t *source_position, type_t *type1, type_t *type2)
633 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
638 * Expect the current token is the expected token.
639 * If not, generate an error and skip until the next anchor.
641 static void expect(token_kind_t const expected)
643 if (UNLIKELY(token.kind != expected)) {
644 parse_error_expected(NULL, expected, NULL);
645 add_anchor_token(expected);
647 rem_anchor_token(expected);
648 if (token.kind != expected)
654 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
656 if (token.kind != T_IDENTIFIER) {
657 parse_error_expected(context, T_IDENTIFIER, NULL);
658 add_anchor_token(T_IDENTIFIER);
660 rem_anchor_token(T_IDENTIFIER);
661 if (token.kind != T_IDENTIFIER)
664 symbol_t *const sym = token.identifier.symbol;
672 * Push a given scope on the scope stack and make it the
675 static scope_t *scope_push(scope_t *new_scope)
677 if (current_scope != NULL) {
678 new_scope->depth = current_scope->depth + 1;
681 scope_t *old_scope = current_scope;
682 current_scope = new_scope;
687 * Pop the current scope from the scope stack.
689 static void scope_pop(scope_t *old_scope)
691 current_scope = old_scope;
695 * Search an entity by its symbol in a given namespace.
697 static entity_t *get_entity(const symbol_t *const symbol,
698 namespace_tag_t namespc)
700 entity_t *entity = symbol->entity;
701 for (; entity != NULL; entity = entity->base.symbol_next) {
702 if ((namespace_tag_t)entity->base.namespc == namespc)
709 /* §6.2.3:1 24) There is only one name space for tags even though three are
711 static entity_t *get_tag(symbol_t const *const symbol,
712 entity_kind_tag_t const kind)
714 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
715 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
717 "'%Y' defined as wrong kind of tag (previous definition %P)",
718 symbol, &entity->base.source_position);
725 * pushs an entity on the environment stack and links the corresponding symbol
728 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
730 symbol_t *symbol = entity->base.symbol;
731 entity_namespace_t namespc = entity->base.namespc;
732 assert(namespc != 0);
734 /* replace/add entity into entity list of the symbol */
737 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
742 /* replace an entry? */
743 if (iter->base.namespc == namespc) {
744 entity->base.symbol_next = iter->base.symbol_next;
750 /* remember old declaration */
752 entry.symbol = symbol;
753 entry.old_entity = iter;
754 entry.namespc = namespc;
755 ARR_APP1(stack_entry_t, *stack_ptr, entry);
759 * Push an entity on the environment stack.
761 static void environment_push(entity_t *entity)
763 assert(entity->base.source_position.input_name != NULL);
764 assert(entity->base.parent_scope != NULL);
765 stack_push(&environment_stack, entity);
769 * Push a declaration on the global label stack.
771 * @param declaration the declaration
773 static void label_push(entity_t *label)
775 /* we abuse the parameters scope as parent for the labels */
776 label->base.parent_scope = ¤t_function->parameters;
777 stack_push(&label_stack, label);
781 * pops symbols from the environment stack until @p new_top is the top element
783 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
785 stack_entry_t *stack = *stack_ptr;
786 size_t top = ARR_LEN(stack);
789 assert(new_top <= top);
793 for (i = top; i > new_top; --i) {
794 stack_entry_t *entry = &stack[i - 1];
796 entity_t *old_entity = entry->old_entity;
797 symbol_t *symbol = entry->symbol;
798 entity_namespace_t namespc = entry->namespc;
800 /* replace with old_entity/remove */
803 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
805 assert(iter != NULL);
806 /* replace an entry? */
807 if (iter->base.namespc == namespc)
811 /* restore definition from outer scopes (if there was one) */
812 if (old_entity != NULL) {
813 old_entity->base.symbol_next = iter->base.symbol_next;
814 *anchor = old_entity;
816 /* remove entry from list */
817 *anchor = iter->base.symbol_next;
821 ARR_SHRINKLEN(*stack_ptr, new_top);
825 * Pop all entries from the environment stack until the new_top
828 * @param new_top the new stack top
830 static void environment_pop_to(size_t new_top)
832 stack_pop_to(&environment_stack, new_top);
836 * Pop all entries from the global label stack until the new_top
839 * @param new_top the new stack top
841 static void label_pop_to(size_t new_top)
843 stack_pop_to(&label_stack, new_top);
846 static atomic_type_kind_t get_akind(const type_t *type)
848 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
849 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
850 return type->atomic.akind;
854 * §6.3.1.1:2 Do integer promotion for a given type.
856 * @param type the type to promote
857 * @return the promoted type
859 static type_t *promote_integer(type_t *type)
861 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
868 * Check if a given expression represents a null pointer constant.
870 * @param expression the expression to check
872 static bool is_null_pointer_constant(const expression_t *expression)
874 /* skip void* cast */
875 if (expression->kind == EXPR_UNARY_CAST) {
876 type_t *const type = skip_typeref(expression->base.type);
877 if (types_compatible(type, type_void_ptr))
878 expression = expression->unary.value;
881 type_t *const type = skip_typeref(expression->base.type);
882 if (!is_type_integer(type))
884 switch (is_constant_expression(expression)) {
885 case EXPR_CLASS_ERROR: return true;
886 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
887 default: return false;
892 * Create an implicit cast expression.
894 * @param expression the expression to cast
895 * @param dest_type the destination type
897 static expression_t *create_implicit_cast(expression_t *expression,
900 type_t *const source_type = expression->base.type;
902 if (source_type == dest_type)
905 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
906 cast->unary.value = expression;
907 cast->base.type = dest_type;
908 cast->base.implicit = true;
913 typedef enum assign_error_t {
915 ASSIGN_ERROR_INCOMPATIBLE,
916 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
917 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
918 ASSIGN_WARNING_POINTER_FROM_INT,
919 ASSIGN_WARNING_INT_FROM_POINTER
922 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)
924 type_t *const orig_type_right = right->base.type;
925 type_t *const type_left = skip_typeref(orig_type_left);
926 type_t *const type_right = skip_typeref(orig_type_right);
931 case ASSIGN_ERROR_INCOMPATIBLE:
932 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
935 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
936 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
937 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
939 /* the left type has all qualifiers from the right type */
940 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
941 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);
945 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
946 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
949 case ASSIGN_WARNING_POINTER_FROM_INT:
950 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
953 case ASSIGN_WARNING_INT_FROM_POINTER:
954 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
958 panic("invalid error value");
962 /** Implements the rules from §6.5.16.1 */
963 static assign_error_t semantic_assign(type_t *orig_type_left,
964 const expression_t *const right)
966 type_t *const orig_type_right = right->base.type;
967 type_t *const type_left = skip_typeref(orig_type_left);
968 type_t *const type_right = skip_typeref(orig_type_right);
970 if (is_type_pointer(type_left)) {
971 if (is_null_pointer_constant(right)) {
972 return ASSIGN_SUCCESS;
973 } else if (is_type_pointer(type_right)) {
974 type_t *points_to_left
975 = skip_typeref(type_left->pointer.points_to);
976 type_t *points_to_right
977 = skip_typeref(type_right->pointer.points_to);
978 assign_error_t res = ASSIGN_SUCCESS;
980 /* the left type has all qualifiers from the right type */
981 unsigned missing_qualifiers
982 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
983 if (missing_qualifiers != 0) {
984 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
987 points_to_left = get_unqualified_type(points_to_left);
988 points_to_right = get_unqualified_type(points_to_right);
990 if (is_type_void(points_to_left))
993 if (is_type_void(points_to_right)) {
994 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
995 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
998 if (!types_compatible(points_to_left, points_to_right)) {
999 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1003 } else if (is_type_integer(type_right)) {
1004 return ASSIGN_WARNING_POINTER_FROM_INT;
1006 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1007 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1008 && is_type_pointer(type_right))) {
1009 return ASSIGN_SUCCESS;
1010 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1011 type_t *const unqual_type_left = get_unqualified_type(type_left);
1012 type_t *const unqual_type_right = get_unqualified_type(type_right);
1013 if (types_compatible(unqual_type_left, unqual_type_right)) {
1014 return ASSIGN_SUCCESS;
1016 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1017 return ASSIGN_WARNING_INT_FROM_POINTER;
1020 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1021 return ASSIGN_SUCCESS;
1023 return ASSIGN_ERROR_INCOMPATIBLE;
1026 static expression_t *parse_constant_expression(void)
1028 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1030 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1031 errorf(&result->base.source_position,
1032 "expression '%E' is not constant", result);
1038 static expression_t *parse_assignment_expression(void)
1040 return parse_subexpression(PREC_ASSIGNMENT);
1043 static void warn_string_concat(const source_position_t *pos)
1045 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1048 static string_t parse_string_literals(void)
1050 assert(token.kind == T_STRING_LITERAL);
1051 string_t result = token.string.string;
1055 while (token.kind == T_STRING_LITERAL) {
1056 warn_string_concat(&token.base.source_position);
1057 result = concat_strings(&result, &token.string.string);
1064 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1066 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1067 attribute->kind = kind;
1068 attribute->source_position = *HERE;
1073 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1076 * __attribute__ ( ( attribute-list ) )
1080 * attribute_list , attrib
1085 * any-word ( identifier )
1086 * any-word ( identifier , nonempty-expr-list )
1087 * any-word ( expr-list )
1089 * where the "identifier" must not be declared as a type, and
1090 * "any-word" may be any identifier (including one declared as a
1091 * type), a reserved word storage class specifier, type specifier or
1092 * type qualifier. ??? This still leaves out most reserved keywords
1093 * (following the old parser), shouldn't we include them, and why not
1094 * allow identifiers declared as types to start the arguments?
1096 * Matze: this all looks confusing and little systematic, so we're even less
1097 * strict and parse any list of things which are identifiers or
1098 * (assignment-)expressions.
1100 static attribute_argument_t *parse_attribute_arguments(void)
1102 attribute_argument_t *first = NULL;
1103 attribute_argument_t **anchor = &first;
1104 if (token.kind != ')') do {
1105 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1107 /* is it an identifier */
1108 if (token.kind == T_IDENTIFIER
1109 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1110 symbol_t *symbol = token.identifier.symbol;
1111 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1112 argument->v.symbol = symbol;
1115 /* must be an expression */
1116 expression_t *expression = parse_assignment_expression();
1118 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1119 argument->v.expression = expression;
1122 /* append argument */
1124 anchor = &argument->next;
1125 } while (next_if(','));
1130 static attribute_t *parse_attribute_asm(void)
1132 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1135 attribute->a.arguments = parse_attribute_arguments();
1139 static symbol_t *get_symbol_from_token(void)
1141 switch(token.kind) {
1142 case T_CHARACTER_CONSTANT:
1144 case T_FLOATINGPOINT:
1145 case T_FLOATINGPOINT_HEXADECIMAL:
1147 case T_INTEGER_HEXADECIMAL:
1148 case T_INTEGER_OCTAL:
1149 case T_STRING_LITERAL:
1150 case T_WIDE_CHARACTER_CONSTANT:
1151 case T_WIDE_STRING_LITERAL:
1155 return token.identifier.symbol;
1159 static attribute_t *parse_attribute_gnu_single(void)
1161 /* parse "any-word" */
1162 symbol_t *symbol = get_symbol_from_token();
1163 if (symbol == NULL) {
1164 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1168 attribute_kind_t kind;
1169 char const *const name = symbol->string;
1170 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1171 if (kind > ATTRIBUTE_GNU_LAST) {
1172 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1173 /* TODO: we should still save the attribute in the list... */
1174 kind = ATTRIBUTE_UNKNOWN;
1178 const char *attribute_name = get_attribute_name(kind);
1179 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1183 attribute_t *attribute = allocate_attribute_zero(kind);
1186 /* parse arguments */
1188 attribute->a.arguments = parse_attribute_arguments();
1193 static attribute_t *parse_attribute_gnu(void)
1195 attribute_t *first = NULL;
1196 attribute_t **anchor = &first;
1198 eat(T___attribute__);
1202 add_anchor_token(')');
1203 add_anchor_token(',');
1204 if (token.kind != ')') do {
1205 attribute_t *attribute = parse_attribute_gnu_single();
1207 *anchor = attribute;
1208 anchor = &attribute->next;
1210 } while (next_if(','));
1211 rem_anchor_token(',');
1212 rem_anchor_token(')');
1219 /** Parse attributes. */
1220 static attribute_t *parse_attributes(attribute_t *first)
1222 attribute_t **anchor = &first;
1224 while (*anchor != NULL)
1225 anchor = &(*anchor)->next;
1227 attribute_t *attribute;
1228 switch (token.kind) {
1229 case T___attribute__:
1230 attribute = parse_attribute_gnu();
1231 if (attribute == NULL)
1236 attribute = parse_attribute_asm();
1240 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1245 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1249 case T__forceinline:
1250 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1251 eat(T__forceinline);
1255 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1260 /* TODO record modifier */
1261 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1262 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1270 *anchor = attribute;
1271 anchor = &attribute->next;
1275 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1277 static entity_t *determine_lhs_ent(expression_t *const expr,
1280 switch (expr->kind) {
1281 case EXPR_REFERENCE: {
1282 entity_t *const entity = expr->reference.entity;
1283 /* we should only find variables as lvalues... */
1284 if (entity->base.kind != ENTITY_VARIABLE
1285 && entity->base.kind != ENTITY_PARAMETER)
1291 case EXPR_ARRAY_ACCESS: {
1292 expression_t *const ref = expr->array_access.array_ref;
1293 entity_t * ent = NULL;
1294 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1295 ent = determine_lhs_ent(ref, lhs_ent);
1298 mark_vars_read(ref, lhs_ent);
1300 mark_vars_read(expr->array_access.index, lhs_ent);
1305 mark_vars_read(expr->select.compound, lhs_ent);
1306 if (is_type_compound(skip_typeref(expr->base.type)))
1307 return determine_lhs_ent(expr->select.compound, lhs_ent);
1311 case EXPR_UNARY_DEREFERENCE: {
1312 expression_t *const val = expr->unary.value;
1313 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1315 return determine_lhs_ent(val->unary.value, lhs_ent);
1317 mark_vars_read(val, NULL);
1323 mark_vars_read(expr, NULL);
1328 #define ENT_ANY ((entity_t*)-1)
1331 * Mark declarations, which are read. This is used to detect variables, which
1335 * x is not marked as "read", because it is only read to calculate its own new
1339 * x and y are not detected as "not read", because multiple variables are
1342 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1344 switch (expr->kind) {
1345 case EXPR_REFERENCE: {
1346 entity_t *const entity = expr->reference.entity;
1347 if (entity->kind != ENTITY_VARIABLE
1348 && entity->kind != ENTITY_PARAMETER)
1351 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1352 if (entity->kind == ENTITY_VARIABLE) {
1353 entity->variable.read = true;
1355 entity->parameter.read = true;
1362 // TODO respect pure/const
1363 mark_vars_read(expr->call.function, NULL);
1364 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1365 mark_vars_read(arg->expression, NULL);
1369 case EXPR_CONDITIONAL:
1370 // TODO lhs_decl should depend on whether true/false have an effect
1371 mark_vars_read(expr->conditional.condition, NULL);
1372 if (expr->conditional.true_expression != NULL)
1373 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1374 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1378 if (lhs_ent == ENT_ANY
1379 && !is_type_compound(skip_typeref(expr->base.type)))
1381 mark_vars_read(expr->select.compound, lhs_ent);
1384 case EXPR_ARRAY_ACCESS: {
1385 mark_vars_read(expr->array_access.index, lhs_ent);
1386 expression_t *const ref = expr->array_access.array_ref;
1387 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1388 if (lhs_ent == ENT_ANY)
1391 mark_vars_read(ref, lhs_ent);
1396 mark_vars_read(expr->va_arge.ap, lhs_ent);
1400 mark_vars_read(expr->va_copye.src, lhs_ent);
1403 case EXPR_UNARY_CAST:
1404 /* Special case: Use void cast to mark a variable as "read" */
1405 if (is_type_void(skip_typeref(expr->base.type)))
1410 case EXPR_UNARY_THROW:
1411 if (expr->unary.value == NULL)
1414 case EXPR_UNARY_DEREFERENCE:
1415 case EXPR_UNARY_DELETE:
1416 case EXPR_UNARY_DELETE_ARRAY:
1417 if (lhs_ent == ENT_ANY)
1421 case EXPR_UNARY_NEGATE:
1422 case EXPR_UNARY_PLUS:
1423 case EXPR_UNARY_BITWISE_NEGATE:
1424 case EXPR_UNARY_NOT:
1425 case EXPR_UNARY_TAKE_ADDRESS:
1426 case EXPR_UNARY_POSTFIX_INCREMENT:
1427 case EXPR_UNARY_POSTFIX_DECREMENT:
1428 case EXPR_UNARY_PREFIX_INCREMENT:
1429 case EXPR_UNARY_PREFIX_DECREMENT:
1430 case EXPR_UNARY_ASSUME:
1432 mark_vars_read(expr->unary.value, lhs_ent);
1435 case EXPR_BINARY_ADD:
1436 case EXPR_BINARY_SUB:
1437 case EXPR_BINARY_MUL:
1438 case EXPR_BINARY_DIV:
1439 case EXPR_BINARY_MOD:
1440 case EXPR_BINARY_EQUAL:
1441 case EXPR_BINARY_NOTEQUAL:
1442 case EXPR_BINARY_LESS:
1443 case EXPR_BINARY_LESSEQUAL:
1444 case EXPR_BINARY_GREATER:
1445 case EXPR_BINARY_GREATEREQUAL:
1446 case EXPR_BINARY_BITWISE_AND:
1447 case EXPR_BINARY_BITWISE_OR:
1448 case EXPR_BINARY_BITWISE_XOR:
1449 case EXPR_BINARY_LOGICAL_AND:
1450 case EXPR_BINARY_LOGICAL_OR:
1451 case EXPR_BINARY_SHIFTLEFT:
1452 case EXPR_BINARY_SHIFTRIGHT:
1453 case EXPR_BINARY_COMMA:
1454 case EXPR_BINARY_ISGREATER:
1455 case EXPR_BINARY_ISGREATEREQUAL:
1456 case EXPR_BINARY_ISLESS:
1457 case EXPR_BINARY_ISLESSEQUAL:
1458 case EXPR_BINARY_ISLESSGREATER:
1459 case EXPR_BINARY_ISUNORDERED:
1460 mark_vars_read(expr->binary.left, lhs_ent);
1461 mark_vars_read(expr->binary.right, lhs_ent);
1464 case EXPR_BINARY_ASSIGN:
1465 case EXPR_BINARY_MUL_ASSIGN:
1466 case EXPR_BINARY_DIV_ASSIGN:
1467 case EXPR_BINARY_MOD_ASSIGN:
1468 case EXPR_BINARY_ADD_ASSIGN:
1469 case EXPR_BINARY_SUB_ASSIGN:
1470 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1471 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1472 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1473 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1474 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1475 if (lhs_ent == ENT_ANY)
1477 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1478 mark_vars_read(expr->binary.right, lhs_ent);
1483 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1486 case EXPR_LITERAL_CASES:
1488 case EXPR_STRING_LITERAL:
1489 case EXPR_WIDE_STRING_LITERAL:
1490 case EXPR_COMPOUND_LITERAL: // TODO init?
1492 case EXPR_CLASSIFY_TYPE:
1495 case EXPR_BUILTIN_CONSTANT_P:
1496 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1498 case EXPR_STATEMENT: // TODO
1499 case EXPR_LABEL_ADDRESS:
1500 case EXPR_ENUM_CONSTANT:
1504 panic("unhandled expression");
1507 static designator_t *parse_designation(void)
1509 designator_t *result = NULL;
1510 designator_t **anchor = &result;
1513 designator_t *designator;
1514 switch (token.kind) {
1516 designator = allocate_ast_zero(sizeof(designator[0]));
1517 designator->source_position = token.base.source_position;
1519 add_anchor_token(']');
1520 designator->array_index = parse_constant_expression();
1521 rem_anchor_token(']');
1525 designator = allocate_ast_zero(sizeof(designator[0]));
1526 designator->source_position = token.base.source_position;
1528 designator->symbol = expect_identifier("while parsing designator", NULL);
1529 if (!designator->symbol)
1537 assert(designator != NULL);
1538 *anchor = designator;
1539 anchor = &designator->next;
1543 static initializer_t *initializer_from_string(array_type_t *const type,
1544 const string_t *const string)
1546 /* TODO: check len vs. size of array type */
1549 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1550 initializer->string.string = *string;
1555 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1556 const string_t *const string)
1558 /* TODO: check len vs. size of array type */
1561 initializer_t *const initializer =
1562 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1563 initializer->wide_string.string = *string;
1569 * Build an initializer from a given expression.
1571 static initializer_t *initializer_from_expression(type_t *orig_type,
1572 expression_t *expression)
1574 /* TODO check that expression is a constant expression */
1576 /* §6.7.8.14/15 char array may be initialized by string literals */
1577 type_t *type = skip_typeref(orig_type);
1578 type_t *expr_type_orig = expression->base.type;
1579 type_t *expr_type = skip_typeref(expr_type_orig);
1581 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1582 array_type_t *const array_type = &type->array;
1583 type_t *const element_type = skip_typeref(array_type->element_type);
1585 if (element_type->kind == TYPE_ATOMIC) {
1586 atomic_type_kind_t akind = element_type->atomic.akind;
1587 switch (expression->kind) {
1588 case EXPR_STRING_LITERAL:
1589 if (akind == ATOMIC_TYPE_CHAR
1590 || akind == ATOMIC_TYPE_SCHAR
1591 || akind == ATOMIC_TYPE_UCHAR) {
1592 return initializer_from_string(array_type,
1593 &expression->string_literal.value);
1597 case EXPR_WIDE_STRING_LITERAL: {
1598 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1599 if (get_unqualified_type(element_type) == bare_wchar_type) {
1600 return initializer_from_wide_string(array_type,
1601 &expression->string_literal.value);
1612 assign_error_t error = semantic_assign(type, expression);
1613 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1615 report_assign_error(error, type, expression, "initializer",
1616 &expression->base.source_position);
1618 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1619 result->value.value = create_implicit_cast(expression, type);
1625 * Parses an scalar initializer.
1627 * §6.7.8.11; eat {} without warning
1629 static initializer_t *parse_scalar_initializer(type_t *type,
1630 bool must_be_constant)
1632 /* there might be extra {} hierarchies */
1634 if (token.kind == '{') {
1635 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1639 } while (token.kind == '{');
1642 expression_t *expression = parse_assignment_expression();
1643 mark_vars_read(expression, NULL);
1644 if (must_be_constant && !is_linker_constant(expression)) {
1645 errorf(&expression->base.source_position,
1646 "initialisation expression '%E' is not constant",
1650 initializer_t *initializer = initializer_from_expression(type, expression);
1652 if (initializer == NULL) {
1653 errorf(&expression->base.source_position,
1654 "expression '%E' (type '%T') doesn't match expected type '%T'",
1655 expression, expression->base.type, type);
1660 bool additional_warning_displayed = false;
1661 while (braces > 0) {
1663 if (token.kind != '}') {
1664 if (!additional_warning_displayed) {
1665 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1666 additional_warning_displayed = true;
1677 * An entry in the type path.
1679 typedef struct type_path_entry_t type_path_entry_t;
1680 struct type_path_entry_t {
1681 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1683 size_t index; /**< For array types: the current index. */
1684 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1689 * A type path expression a position inside compound or array types.
1691 typedef struct type_path_t type_path_t;
1692 struct type_path_t {
1693 type_path_entry_t *path; /**< An flexible array containing the current path. */
1694 type_t *top_type; /**< type of the element the path points */
1695 size_t max_index; /**< largest index in outermost array */
1699 * Prints a type path for debugging.
1701 static __attribute__((unused)) void debug_print_type_path(
1702 const type_path_t *path)
1704 size_t len = ARR_LEN(path->path);
1706 for (size_t i = 0; i < len; ++i) {
1707 const type_path_entry_t *entry = & path->path[i];
1709 type_t *type = skip_typeref(entry->type);
1710 if (is_type_compound(type)) {
1711 /* in gcc mode structs can have no members */
1712 if (entry->v.compound_entry == NULL) {
1716 fprintf(stderr, ".%s",
1717 entry->v.compound_entry->base.symbol->string);
1718 } else if (is_type_array(type)) {
1719 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1721 fprintf(stderr, "-INVALID-");
1724 if (path->top_type != NULL) {
1725 fprintf(stderr, " (");
1726 print_type(path->top_type);
1727 fprintf(stderr, ")");
1732 * Return the top type path entry, ie. in a path
1733 * (type).a.b returns the b.
1735 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1737 size_t len = ARR_LEN(path->path);
1739 return &path->path[len-1];
1743 * Enlarge the type path by an (empty) element.
1745 static type_path_entry_t *append_to_type_path(type_path_t *path)
1747 size_t len = ARR_LEN(path->path);
1748 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1750 type_path_entry_t *result = & path->path[len];
1751 memset(result, 0, sizeof(result[0]));
1756 * Descending into a sub-type. Enter the scope of the current top_type.
1758 static void descend_into_subtype(type_path_t *path)
1760 type_t *orig_top_type = path->top_type;
1761 type_t *top_type = skip_typeref(orig_top_type);
1763 type_path_entry_t *top = append_to_type_path(path);
1764 top->type = top_type;
1766 if (is_type_compound(top_type)) {
1767 compound_t *const compound = top_type->compound.compound;
1768 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1770 if (entry != NULL) {
1771 top->v.compound_entry = &entry->declaration;
1772 path->top_type = entry->declaration.type;
1774 path->top_type = NULL;
1776 } else if (is_type_array(top_type)) {
1778 path->top_type = top_type->array.element_type;
1780 assert(!is_type_valid(top_type));
1785 * Pop an entry from the given type path, ie. returning from
1786 * (type).a.b to (type).a
1788 static void ascend_from_subtype(type_path_t *path)
1790 type_path_entry_t *top = get_type_path_top(path);
1792 path->top_type = top->type;
1794 size_t len = ARR_LEN(path->path);
1795 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1799 * Pop entries from the given type path until the given
1800 * path level is reached.
1802 static void ascend_to(type_path_t *path, size_t top_path_level)
1804 size_t len = ARR_LEN(path->path);
1806 while (len > top_path_level) {
1807 ascend_from_subtype(path);
1808 len = ARR_LEN(path->path);
1812 static bool walk_designator(type_path_t *path, const designator_t *designator,
1813 bool used_in_offsetof)
1815 for (; designator != NULL; designator = designator->next) {
1816 type_path_entry_t *top = get_type_path_top(path);
1817 type_t *orig_type = top->type;
1819 type_t *type = skip_typeref(orig_type);
1821 if (designator->symbol != NULL) {
1822 symbol_t *symbol = designator->symbol;
1823 if (!is_type_compound(type)) {
1824 if (is_type_valid(type)) {
1825 errorf(&designator->source_position,
1826 "'.%Y' designator used for non-compound type '%T'",
1830 top->type = type_error_type;
1831 top->v.compound_entry = NULL;
1832 orig_type = type_error_type;
1834 compound_t *compound = type->compound.compound;
1835 entity_t *iter = compound->members.entities;
1836 for (; iter != NULL; iter = iter->base.next) {
1837 if (iter->base.symbol == symbol) {
1842 errorf(&designator->source_position,
1843 "'%T' has no member named '%Y'", orig_type, symbol);
1846 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1847 if (used_in_offsetof && iter->compound_member.bitfield) {
1848 errorf(&designator->source_position,
1849 "offsetof designator '%Y' must not specify bitfield",
1854 top->type = orig_type;
1855 top->v.compound_entry = &iter->declaration;
1856 orig_type = iter->declaration.type;
1859 expression_t *array_index = designator->array_index;
1860 assert(designator->array_index != NULL);
1862 if (!is_type_array(type)) {
1863 if (is_type_valid(type)) {
1864 errorf(&designator->source_position,
1865 "[%E] designator used for non-array type '%T'",
1866 array_index, orig_type);
1871 long index = fold_constant_to_int(array_index);
1872 if (!used_in_offsetof) {
1874 errorf(&designator->source_position,
1875 "array index [%E] must be positive", array_index);
1876 } else if (type->array.size_constant) {
1877 long array_size = type->array.size;
1878 if (index >= array_size) {
1879 errorf(&designator->source_position,
1880 "designator [%E] (%d) exceeds array size %d",
1881 array_index, index, array_size);
1886 top->type = orig_type;
1887 top->v.index = (size_t) index;
1888 orig_type = type->array.element_type;
1890 path->top_type = orig_type;
1892 if (designator->next != NULL) {
1893 descend_into_subtype(path);
1899 static void advance_current_object(type_path_t *path, size_t top_path_level)
1901 type_path_entry_t *top = get_type_path_top(path);
1903 type_t *type = skip_typeref(top->type);
1904 if (is_type_union(type)) {
1905 /* in unions only the first element is initialized */
1906 top->v.compound_entry = NULL;
1907 } else if (is_type_struct(type)) {
1908 declaration_t *entry = top->v.compound_entry;
1910 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1911 if (next_entity != NULL) {
1912 assert(is_declaration(next_entity));
1913 entry = &next_entity->declaration;
1918 top->v.compound_entry = entry;
1919 if (entry != NULL) {
1920 path->top_type = entry->type;
1923 } else if (is_type_array(type)) {
1924 assert(is_type_array(type));
1928 if (!type->array.size_constant || top->v.index < type->array.size) {
1932 assert(!is_type_valid(type));
1936 /* we're past the last member of the current sub-aggregate, try if we
1937 * can ascend in the type hierarchy and continue with another subobject */
1938 size_t len = ARR_LEN(path->path);
1940 if (len > top_path_level) {
1941 ascend_from_subtype(path);
1942 advance_current_object(path, top_path_level);
1944 path->top_type = NULL;
1949 * skip any {...} blocks until a closing bracket is reached.
1951 static void skip_initializers(void)
1955 while (token.kind != '}') {
1956 if (token.kind == T_EOF)
1958 if (token.kind == '{') {
1966 static initializer_t *create_empty_initializer(void)
1968 static initializer_t empty_initializer
1969 = { .list = { { INITIALIZER_LIST }, 0 } };
1970 return &empty_initializer;
1974 * Parse a part of an initialiser for a struct or union,
1976 static initializer_t *parse_sub_initializer(type_path_t *path,
1977 type_t *outer_type, size_t top_path_level,
1978 parse_initializer_env_t *env)
1980 if (token.kind == '}') {
1981 /* empty initializer */
1982 return create_empty_initializer();
1985 type_t *orig_type = path->top_type;
1986 type_t *type = NULL;
1988 if (orig_type == NULL) {
1989 /* We are initializing an empty compound. */
1991 type = skip_typeref(orig_type);
1994 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1997 designator_t *designator = NULL;
1998 if (token.kind == '.' || token.kind == '[') {
1999 designator = parse_designation();
2000 goto finish_designator;
2001 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2002 /* GNU-style designator ("identifier: value") */
2003 designator = allocate_ast_zero(sizeof(designator[0]));
2004 designator->source_position = token.base.source_position;
2005 designator->symbol = token.identifier.symbol;
2010 /* reset path to toplevel, evaluate designator from there */
2011 ascend_to(path, top_path_level);
2012 if (!walk_designator(path, designator, false)) {
2013 /* can't continue after designation error */
2017 initializer_t *designator_initializer
2018 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2019 designator_initializer->designator.designator = designator;
2020 ARR_APP1(initializer_t*, initializers, designator_initializer);
2022 orig_type = path->top_type;
2023 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2028 if (token.kind == '{') {
2029 if (type != NULL && is_type_scalar(type)) {
2030 sub = parse_scalar_initializer(type, env->must_be_constant);
2033 if (env->entity != NULL) {
2035 "extra brace group at end of initializer for '%Y'",
2036 env->entity->base.symbol);
2038 errorf(HERE, "extra brace group at end of initializer");
2043 descend_into_subtype(path);
2046 add_anchor_token('}');
2047 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2049 rem_anchor_token('}');
2054 goto error_parse_next;
2056 ascend_from_subtype(path);
2059 /* must be an expression */
2060 expression_t *expression = parse_assignment_expression();
2061 mark_vars_read(expression, NULL);
2063 if (env->must_be_constant && !is_linker_constant(expression)) {
2064 errorf(&expression->base.source_position,
2065 "Initialisation expression '%E' is not constant",
2070 /* we are already outside, ... */
2071 if (outer_type == NULL)
2072 goto error_parse_next;
2073 type_t *const outer_type_skip = skip_typeref(outer_type);
2074 if (is_type_compound(outer_type_skip) &&
2075 !outer_type_skip->compound.compound->complete) {
2076 goto error_parse_next;
2079 source_position_t const* const pos = &expression->base.source_position;
2080 if (env->entity != NULL) {
2081 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2083 warningf(WARN_OTHER, pos, "excess elements in initializer");
2085 goto error_parse_next;
2088 /* handle { "string" } special case */
2089 if ((expression->kind == EXPR_STRING_LITERAL
2090 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2091 && outer_type != NULL) {
2092 sub = initializer_from_expression(outer_type, expression);
2095 if (token.kind != '}') {
2096 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2098 /* TODO: eat , ... */
2103 /* descend into subtypes until expression matches type */
2105 orig_type = path->top_type;
2106 type = skip_typeref(orig_type);
2108 sub = initializer_from_expression(orig_type, expression);
2112 if (!is_type_valid(type)) {
2115 if (is_type_scalar(type)) {
2116 errorf(&expression->base.source_position,
2117 "expression '%E' doesn't match expected type '%T'",
2118 expression, orig_type);
2122 descend_into_subtype(path);
2126 /* update largest index of top array */
2127 const type_path_entry_t *first = &path->path[0];
2128 type_t *first_type = first->type;
2129 first_type = skip_typeref(first_type);
2130 if (is_type_array(first_type)) {
2131 size_t index = first->v.index;
2132 if (index > path->max_index)
2133 path->max_index = index;
2136 /* append to initializers list */
2137 ARR_APP1(initializer_t*, initializers, sub);
2140 if (token.kind == '}') {
2143 add_anchor_token('}');
2145 rem_anchor_token('}');
2146 if (token.kind == '}') {
2151 /* advance to the next declaration if we are not at the end */
2152 advance_current_object(path, top_path_level);
2153 orig_type = path->top_type;
2154 if (orig_type != NULL)
2155 type = skip_typeref(orig_type);
2161 size_t len = ARR_LEN(initializers);
2162 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2163 initializer_t *result = allocate_ast_zero(size);
2164 result->kind = INITIALIZER_LIST;
2165 result->list.len = len;
2166 memcpy(&result->list.initializers, initializers,
2167 len * sizeof(initializers[0]));
2169 DEL_ARR_F(initializers);
2170 ascend_to(path, top_path_level+1);
2175 skip_initializers();
2176 DEL_ARR_F(initializers);
2177 ascend_to(path, top_path_level+1);
2181 static expression_t *make_size_literal(size_t value)
2183 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2184 literal->base.type = type_size_t;
2187 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2188 literal->literal.value = make_string(buf);
2194 * Parses an initializer. Parsers either a compound literal
2195 * (env->declaration == NULL) or an initializer of a declaration.
2197 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2199 type_t *type = skip_typeref(env->type);
2200 size_t max_index = 0;
2201 initializer_t *result;
2203 if (is_type_scalar(type)) {
2204 result = parse_scalar_initializer(type, env->must_be_constant);
2205 } else if (token.kind == '{') {
2209 memset(&path, 0, sizeof(path));
2210 path.top_type = env->type;
2211 path.path = NEW_ARR_F(type_path_entry_t, 0);
2213 descend_into_subtype(&path);
2215 add_anchor_token('}');
2216 result = parse_sub_initializer(&path, env->type, 1, env);
2217 rem_anchor_token('}');
2219 max_index = path.max_index;
2220 DEL_ARR_F(path.path);
2224 /* parse_scalar_initializer() also works in this case: we simply
2225 * have an expression without {} around it */
2226 result = parse_scalar_initializer(type, env->must_be_constant);
2229 /* §6.7.8:22 array initializers for arrays with unknown size determine
2230 * the array type size */
2231 if (is_type_array(type) && type->array.size_expression == NULL
2232 && result != NULL) {
2234 switch (result->kind) {
2235 case INITIALIZER_LIST:
2236 assert(max_index != 0xdeadbeaf);
2237 size = max_index + 1;
2240 case INITIALIZER_STRING:
2241 size = result->string.string.size;
2244 case INITIALIZER_WIDE_STRING:
2245 size = result->wide_string.string.size;
2248 case INITIALIZER_DESIGNATOR:
2249 case INITIALIZER_VALUE:
2250 /* can happen for parse errors */
2255 internal_errorf(HERE, "invalid initializer type");
2258 type_t *new_type = duplicate_type(type);
2260 new_type->array.size_expression = make_size_literal(size);
2261 new_type->array.size_constant = true;
2262 new_type->array.has_implicit_size = true;
2263 new_type->array.size = size;
2264 env->type = new_type;
2270 static void append_entity(scope_t *scope, entity_t *entity)
2272 if (scope->last_entity != NULL) {
2273 scope->last_entity->base.next = entity;
2275 scope->entities = entity;
2277 entity->base.parent_entity = current_entity;
2278 scope->last_entity = entity;
2282 static compound_t *parse_compound_type_specifier(bool is_struct)
2284 source_position_t const pos = *HERE;
2285 eat(is_struct ? T_struct : T_union);
2287 symbol_t *symbol = NULL;
2288 entity_t *entity = NULL;
2289 attribute_t *attributes = NULL;
2291 if (token.kind == T___attribute__) {
2292 attributes = parse_attributes(NULL);
2295 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2296 if (token.kind == T_IDENTIFIER) {
2297 /* the compound has a name, check if we have seen it already */
2298 symbol = token.identifier.symbol;
2299 entity = get_tag(symbol, kind);
2302 if (entity != NULL) {
2303 if (entity->base.parent_scope != current_scope &&
2304 (token.kind == '{' || token.kind == ';')) {
2305 /* we're in an inner scope and have a definition. Shadow
2306 * existing definition in outer scope */
2308 } else if (entity->compound.complete && token.kind == '{') {
2309 source_position_t const *const ppos = &entity->base.source_position;
2310 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2311 /* clear members in the hope to avoid further errors */
2312 entity->compound.members.entities = NULL;
2315 } else if (token.kind != '{') {
2316 char const *const msg =
2317 is_struct ? "while parsing struct type specifier" :
2318 "while parsing union type specifier";
2319 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2324 if (entity == NULL) {
2325 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2326 entity->compound.alignment = 1;
2327 entity->base.parent_scope = current_scope;
2328 if (symbol != NULL) {
2329 environment_push(entity);
2331 append_entity(current_scope, entity);
2334 if (token.kind == '{') {
2335 parse_compound_type_entries(&entity->compound);
2337 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2338 if (symbol == NULL) {
2339 assert(anonymous_entity == NULL);
2340 anonymous_entity = entity;
2344 if (attributes != NULL) {
2345 handle_entity_attributes(attributes, entity);
2348 return &entity->compound;
2351 static void parse_enum_entries(type_t *const enum_type)
2355 if (token.kind == '}') {
2356 errorf(HERE, "empty enum not allowed");
2361 add_anchor_token('}');
2362 add_anchor_token(',');
2364 add_anchor_token('=');
2365 source_position_t pos;
2366 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2367 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2368 entity->enum_value.enum_type = enum_type;
2369 rem_anchor_token('=');
2372 expression_t *value = parse_constant_expression();
2374 value = create_implicit_cast(value, enum_type);
2375 entity->enum_value.value = value;
2380 record_entity(entity, false);
2381 } while (next_if(',') && token.kind != '}');
2382 rem_anchor_token(',');
2383 rem_anchor_token('}');
2388 static type_t *parse_enum_specifier(void)
2390 source_position_t const pos = *HERE;
2395 switch (token.kind) {
2397 symbol = token.identifier.symbol;
2398 entity = get_tag(symbol, ENTITY_ENUM);
2401 if (entity != NULL) {
2402 if (entity->base.parent_scope != current_scope &&
2403 (token.kind == '{' || token.kind == ';')) {
2404 /* we're in an inner scope and have a definition. Shadow
2405 * existing definition in outer scope */
2407 } else if (entity->enume.complete && token.kind == '{') {
2408 source_position_t const *const ppos = &entity->base.source_position;
2409 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2420 parse_error_expected("while parsing enum type specifier",
2421 T_IDENTIFIER, '{', NULL);
2425 if (entity == NULL) {
2426 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2427 entity->base.parent_scope = current_scope;
2430 type_t *const type = allocate_type_zero(TYPE_ENUM);
2431 type->enumt.enume = &entity->enume;
2432 type->enumt.base.akind = ATOMIC_TYPE_INT;
2434 if (token.kind == '{') {
2435 if (symbol != NULL) {
2436 environment_push(entity);
2438 append_entity(current_scope, entity);
2439 entity->enume.complete = true;
2441 parse_enum_entries(type);
2442 parse_attributes(NULL);
2444 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2445 if (symbol == NULL) {
2446 assert(anonymous_entity == NULL);
2447 anonymous_entity = entity;
2449 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2450 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2457 * if a symbol is a typedef to another type, return true
2459 static bool is_typedef_symbol(symbol_t *symbol)
2461 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2462 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2465 static type_t *parse_typeof(void)
2472 add_anchor_token(')');
2474 expression_t *expression = NULL;
2476 switch (token.kind) {
2478 if (is_typedef_symbol(token.identifier.symbol)) {
2480 type = parse_typename();
2483 expression = parse_expression();
2484 type = revert_automatic_type_conversion(expression);
2489 rem_anchor_token(')');
2492 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2493 typeof_type->typeoft.expression = expression;
2494 typeof_type->typeoft.typeof_type = type;
2499 typedef enum specifiers_t {
2500 SPECIFIER_SIGNED = 1 << 0,
2501 SPECIFIER_UNSIGNED = 1 << 1,
2502 SPECIFIER_LONG = 1 << 2,
2503 SPECIFIER_INT = 1 << 3,
2504 SPECIFIER_DOUBLE = 1 << 4,
2505 SPECIFIER_CHAR = 1 << 5,
2506 SPECIFIER_WCHAR_T = 1 << 6,
2507 SPECIFIER_SHORT = 1 << 7,
2508 SPECIFIER_LONG_LONG = 1 << 8,
2509 SPECIFIER_FLOAT = 1 << 9,
2510 SPECIFIER_BOOL = 1 << 10,
2511 SPECIFIER_VOID = 1 << 11,
2512 SPECIFIER_INT8 = 1 << 12,
2513 SPECIFIER_INT16 = 1 << 13,
2514 SPECIFIER_INT32 = 1 << 14,
2515 SPECIFIER_INT64 = 1 << 15,
2516 SPECIFIER_INT128 = 1 << 16,
2517 SPECIFIER_COMPLEX = 1 << 17,
2518 SPECIFIER_IMAGINARY = 1 << 18,
2521 static type_t *get_typedef_type(symbol_t *symbol)
2523 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2524 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2527 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2528 type->typedeft.typedefe = &entity->typedefe;
2533 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2535 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2539 add_anchor_token(')');
2540 add_anchor_token(',');
2542 add_anchor_token('=');
2543 source_position_t pos;
2544 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2545 rem_anchor_token('=');
2547 symbol_t **prop = NULL;
2549 if (streq(prop_sym->string, "put")) {
2550 prop = &property->put_symbol;
2551 } else if (streq(prop_sym->string, "get")) {
2552 prop = &property->get_symbol;
2554 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2558 add_anchor_token(T_IDENTIFIER);
2560 rem_anchor_token(T_IDENTIFIER);
2562 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2564 *prop = sym ? sym : sym_anonymous;
2565 } while (next_if(','));
2566 rem_anchor_token(',');
2567 rem_anchor_token(')');
2569 attribute->a.property = property;
2575 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2577 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2578 if (next_if(T_restrict)) {
2579 kind = ATTRIBUTE_MS_RESTRICT;
2580 } else if (token.kind == T_IDENTIFIER) {
2581 const char *name = token.identifier.symbol->string;
2582 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2584 const char *attribute_name = get_attribute_name(k);
2585 if (attribute_name != NULL && streq(attribute_name, name)) {
2591 if (kind == ATTRIBUTE_UNKNOWN) {
2592 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2595 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2599 attribute_t *attribute = allocate_attribute_zero(kind);
2602 if (kind == ATTRIBUTE_MS_PROPERTY) {
2603 return parse_attribute_ms_property(attribute);
2606 /* parse arguments */
2608 attribute->a.arguments = parse_attribute_arguments();
2613 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2618 if (token.kind != ')') {
2619 add_anchor_token(')');
2621 attribute_t **anchor = &first;
2623 while (*anchor != NULL)
2624 anchor = &(*anchor)->next;
2626 attribute_t *attribute
2627 = parse_microsoft_extended_decl_modifier_single();
2628 if (attribute == NULL)
2631 *anchor = attribute;
2632 anchor = &attribute->next;
2633 } while (next_if(','));
2635 rem_anchor_token(')');
2641 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2643 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2644 if (is_declaration(entity)) {
2645 entity->declaration.type = type_error_type;
2646 entity->declaration.implicit = true;
2647 } else if (kind == ENTITY_TYPEDEF) {
2648 entity->typedefe.type = type_error_type;
2649 entity->typedefe.builtin = true;
2651 if (kind != ENTITY_COMPOUND_MEMBER)
2652 record_entity(entity, false);
2656 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2658 type_t *type = NULL;
2659 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2660 unsigned type_specifiers = 0;
2661 bool newtype = false;
2662 bool saw_error = false;
2664 memset(specifiers, 0, sizeof(*specifiers));
2665 specifiers->source_position = token.base.source_position;
2668 specifiers->attributes = parse_attributes(specifiers->attributes);
2670 switch (token.kind) {
2672 #define MATCH_STORAGE_CLASS(token, class) \
2674 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2675 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2677 specifiers->storage_class = class; \
2678 if (specifiers->thread_local) \
2679 goto check_thread_storage_class; \
2683 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2684 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2685 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2686 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2687 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2690 specifiers->attributes
2691 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2695 if (specifiers->thread_local) {
2696 errorf(HERE, "duplicate '__thread'");
2698 specifiers->thread_local = true;
2699 check_thread_storage_class:
2700 switch (specifiers->storage_class) {
2701 case STORAGE_CLASS_EXTERN:
2702 case STORAGE_CLASS_NONE:
2703 case STORAGE_CLASS_STATIC:
2707 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2708 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2709 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2710 wrong_thread_storage_class:
2711 errorf(HERE, "'__thread' used with '%s'", wrong);
2718 /* type qualifiers */
2719 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2721 qualifiers |= qualifier; \
2725 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2726 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2727 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2728 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2729 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2730 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2731 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2732 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2734 /* type specifiers */
2735 #define MATCH_SPECIFIER(token, specifier, name) \
2737 if (type_specifiers & specifier) { \
2738 errorf(HERE, "multiple " name " type specifiers given"); \
2740 type_specifiers |= specifier; \
2745 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2746 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2747 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2748 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2749 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2750 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2751 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2752 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2753 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2754 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2755 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2756 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2757 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2758 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2759 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2760 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2761 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2762 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2766 specifiers->is_inline = true;
2770 case T__forceinline:
2772 specifiers->modifiers |= DM_FORCEINLINE;
2777 if (type_specifiers & SPECIFIER_LONG_LONG) {
2778 errorf(HERE, "too many long type specifiers given");
2779 } else if (type_specifiers & SPECIFIER_LONG) {
2780 type_specifiers |= SPECIFIER_LONG_LONG;
2782 type_specifiers |= SPECIFIER_LONG;
2787 #define CHECK_DOUBLE_TYPE() \
2788 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2791 CHECK_DOUBLE_TYPE();
2792 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2794 type->compound.compound = parse_compound_type_specifier(true);
2797 CHECK_DOUBLE_TYPE();
2798 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2799 type->compound.compound = parse_compound_type_specifier(false);
2802 CHECK_DOUBLE_TYPE();
2803 type = parse_enum_specifier();
2806 CHECK_DOUBLE_TYPE();
2807 type = parse_typeof();
2809 case T___builtin_va_list:
2810 CHECK_DOUBLE_TYPE();
2811 type = duplicate_type(type_valist);
2815 case T_IDENTIFIER: {
2816 /* only parse identifier if we haven't found a type yet */
2817 if (type != NULL || type_specifiers != 0) {
2818 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2819 * declaration, so it doesn't generate errors about expecting '(' or
2821 switch (look_ahead(1)->kind) {
2828 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2832 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2837 goto finish_specifiers;
2841 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2842 if (typedef_type == NULL) {
2843 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2844 * declaration, so it doesn't generate 'implicit int' followed by more
2845 * errors later on. */
2846 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2852 errorf(HERE, "%K does not name a type", &token);
2854 symbol_t *symbol = token.identifier.symbol;
2856 = create_error_entity(symbol, ENTITY_TYPEDEF);
2858 type = allocate_type_zero(TYPE_TYPEDEF);
2859 type->typedeft.typedefe = &entity->typedefe;
2867 goto finish_specifiers;
2872 type = typedef_type;
2876 /* function specifier */
2878 goto finish_specifiers;
2883 specifiers->attributes = parse_attributes(specifiers->attributes);
2885 if (type == NULL || (saw_error && type_specifiers != 0)) {
2886 atomic_type_kind_t atomic_type;
2888 /* match valid basic types */
2889 switch (type_specifiers) {
2890 case SPECIFIER_VOID:
2891 atomic_type = ATOMIC_TYPE_VOID;
2893 case SPECIFIER_WCHAR_T:
2894 atomic_type = ATOMIC_TYPE_WCHAR_T;
2896 case SPECIFIER_CHAR:
2897 atomic_type = ATOMIC_TYPE_CHAR;
2899 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2900 atomic_type = ATOMIC_TYPE_SCHAR;
2902 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2903 atomic_type = ATOMIC_TYPE_UCHAR;
2905 case SPECIFIER_SHORT:
2906 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2907 case SPECIFIER_SHORT | SPECIFIER_INT:
2908 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2909 atomic_type = ATOMIC_TYPE_SHORT;
2911 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2912 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2913 atomic_type = ATOMIC_TYPE_USHORT;
2916 case SPECIFIER_SIGNED:
2917 case SPECIFIER_SIGNED | SPECIFIER_INT:
2918 atomic_type = ATOMIC_TYPE_INT;
2920 case SPECIFIER_UNSIGNED:
2921 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2922 atomic_type = ATOMIC_TYPE_UINT;
2924 case SPECIFIER_LONG:
2925 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2926 case SPECIFIER_LONG | SPECIFIER_INT:
2927 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2928 atomic_type = ATOMIC_TYPE_LONG;
2930 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2931 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2932 atomic_type = ATOMIC_TYPE_ULONG;
2935 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2936 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2937 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2938 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2940 atomic_type = ATOMIC_TYPE_LONGLONG;
2941 goto warn_about_long_long;
2943 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2944 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2946 atomic_type = ATOMIC_TYPE_ULONGLONG;
2947 warn_about_long_long:
2948 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2951 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2952 atomic_type = unsigned_int8_type_kind;
2955 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2956 atomic_type = unsigned_int16_type_kind;
2959 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2960 atomic_type = unsigned_int32_type_kind;
2963 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2964 atomic_type = unsigned_int64_type_kind;
2967 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2968 atomic_type = unsigned_int128_type_kind;
2971 case SPECIFIER_INT8:
2972 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2973 atomic_type = int8_type_kind;
2976 case SPECIFIER_INT16:
2977 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2978 atomic_type = int16_type_kind;
2981 case SPECIFIER_INT32:
2982 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2983 atomic_type = int32_type_kind;
2986 case SPECIFIER_INT64:
2987 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2988 atomic_type = int64_type_kind;
2991 case SPECIFIER_INT128:
2992 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2993 atomic_type = int128_type_kind;
2996 case SPECIFIER_FLOAT:
2997 atomic_type = ATOMIC_TYPE_FLOAT;
2999 case SPECIFIER_DOUBLE:
3000 atomic_type = ATOMIC_TYPE_DOUBLE;
3002 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3003 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3005 case SPECIFIER_BOOL:
3006 atomic_type = ATOMIC_TYPE_BOOL;
3008 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3009 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3010 atomic_type = ATOMIC_TYPE_FLOAT;
3012 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3013 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3014 atomic_type = ATOMIC_TYPE_DOUBLE;
3016 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3017 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3018 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3021 /* invalid specifier combination, give an error message */
3022 source_position_t const* const pos = &specifiers->source_position;
3023 if (type_specifiers == 0) {
3025 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3026 if (!(c_mode & _CXX) && !strict_mode) {
3027 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3028 atomic_type = ATOMIC_TYPE_INT;
3031 errorf(pos, "no type specifiers given in declaration");
3034 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3035 (type_specifiers & SPECIFIER_UNSIGNED)) {
3036 errorf(pos, "signed and unsigned specifiers given");
3037 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3038 errorf(pos, "only integer types can be signed or unsigned");
3040 errorf(pos, "multiple datatypes in declaration");
3046 if (type_specifiers & SPECIFIER_COMPLEX) {
3047 type = allocate_type_zero(TYPE_COMPLEX);
3048 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3049 type = allocate_type_zero(TYPE_IMAGINARY);
3051 type = allocate_type_zero(TYPE_ATOMIC);
3053 type->atomic.akind = atomic_type;
3055 } else if (type_specifiers != 0) {
3056 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3059 /* FIXME: check type qualifiers here */
3060 type->base.qualifiers = qualifiers;
3063 type = identify_new_type(type);
3065 type = typehash_insert(type);
3068 if (specifiers->attributes != NULL)
3069 type = handle_type_attributes(specifiers->attributes, type);
3070 specifiers->type = type;
3074 specifiers->type = type_error_type;
3077 static type_qualifiers_t parse_type_qualifiers(void)
3079 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3082 switch (token.kind) {
3083 /* type qualifiers */
3084 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3085 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3086 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3087 /* microsoft extended type modifiers */
3088 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3089 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3090 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3091 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3092 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3101 * Parses an K&R identifier list
3103 static void parse_identifier_list(scope_t *scope)
3105 assert(token.kind == T_IDENTIFIER);
3107 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3108 /* a K&R parameter has no type, yet */
3112 append_entity(scope, entity);
3113 } while (next_if(',') && token.kind == T_IDENTIFIER);
3116 static entity_t *parse_parameter(void)
3118 declaration_specifiers_t specifiers;
3119 parse_declaration_specifiers(&specifiers);
3121 entity_t *entity = parse_declarator(&specifiers,
3122 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3123 anonymous_entity = NULL;
3127 static void semantic_parameter_incomplete(const entity_t *entity)
3129 assert(entity->kind == ENTITY_PARAMETER);
3131 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3132 * list in a function declarator that is part of a
3133 * definition of that function shall not have
3134 * incomplete type. */
3135 type_t *type = skip_typeref(entity->declaration.type);
3136 if (is_type_incomplete(type)) {
3137 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3141 static bool has_parameters(void)
3143 /* func(void) is not a parameter */
3144 if (look_ahead(1)->kind != ')')
3146 if (token.kind == T_IDENTIFIER) {
3147 entity_t const *const entity
3148 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3151 if (entity->kind != ENTITY_TYPEDEF)
3153 type_t const *const type = skip_typeref(entity->typedefe.type);
3154 if (!is_type_void(type))
3156 if (c_mode & _CXX) {
3157 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3158 * is not allowed. */
3159 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3160 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3161 /* §6.7.5.3:10 Qualification is not allowed here. */
3162 errorf(HERE, "'void' as parameter must not have type qualifiers");
3164 } else if (token.kind != T_void) {
3172 * Parses function type parameters (and optionally creates variable_t entities
3173 * for them in a scope)
3175 static void parse_parameters(function_type_t *type, scope_t *scope)
3178 add_anchor_token(')');
3180 if (token.kind == T_IDENTIFIER &&
3181 !is_typedef_symbol(token.identifier.symbol) &&
3182 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3183 type->kr_style_parameters = true;
3184 parse_identifier_list(scope);
3185 } else if (token.kind == ')') {
3186 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3187 if (!(c_mode & _CXX))
3188 type->unspecified_parameters = true;
3189 } else if (has_parameters()) {
3190 function_parameter_t **anchor = &type->parameters;
3191 add_anchor_token(',');
3193 switch (token.kind) {
3196 type->variadic = true;
3197 goto parameters_finished;
3202 entity_t *entity = parse_parameter();
3203 if (entity->kind == ENTITY_TYPEDEF) {
3204 errorf(&entity->base.source_position,
3205 "typedef not allowed as function parameter");
3208 assert(is_declaration(entity));
3210 semantic_parameter_incomplete(entity);
3212 function_parameter_t *const parameter =
3213 allocate_parameter(entity->declaration.type);
3215 if (scope != NULL) {
3216 append_entity(scope, entity);
3219 *anchor = parameter;
3220 anchor = ¶meter->next;
3225 goto parameters_finished;
3227 } while (next_if(','));
3228 parameters_finished:
3229 rem_anchor_token(',');
3232 rem_anchor_token(')');
3236 typedef enum construct_type_kind_t {
3237 CONSTRUCT_POINTER = 1,
3238 CONSTRUCT_REFERENCE,
3241 } construct_type_kind_t;
3243 typedef union construct_type_t construct_type_t;
3245 typedef struct construct_type_base_t {
3246 construct_type_kind_t kind;
3247 source_position_t pos;
3248 construct_type_t *next;
3249 } construct_type_base_t;
3251 typedef struct parsed_pointer_t {
3252 construct_type_base_t base;
3253 type_qualifiers_t type_qualifiers;
3254 variable_t *base_variable; /**< MS __based extension. */
3257 typedef struct parsed_reference_t {
3258 construct_type_base_t base;
3259 } parsed_reference_t;
3261 typedef struct construct_function_type_t {
3262 construct_type_base_t base;
3263 type_t *function_type;
3264 } construct_function_type_t;
3266 typedef struct parsed_array_t {
3267 construct_type_base_t base;
3268 type_qualifiers_t type_qualifiers;
3274 union construct_type_t {
3275 construct_type_kind_t kind;
3276 construct_type_base_t base;
3277 parsed_pointer_t pointer;
3278 parsed_reference_t reference;
3279 construct_function_type_t function;
3280 parsed_array_t array;
3283 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3285 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3286 memset(cons, 0, size);
3288 cons->base.pos = *HERE;
3293 static construct_type_t *parse_pointer_declarator(void)
3295 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3297 cons->pointer.type_qualifiers = parse_type_qualifiers();
3298 //cons->pointer.base_variable = base_variable;
3303 /* ISO/IEC 14882:1998(E) §8.3.2 */
3304 static construct_type_t *parse_reference_declarator(void)
3306 if (!(c_mode & _CXX))
3307 errorf(HERE, "references are only available for C++");
3309 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3316 static construct_type_t *parse_array_declarator(void)
3318 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3319 parsed_array_t *const array = &cons->array;
3322 add_anchor_token(']');
3324 bool is_static = next_if(T_static);
3326 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3329 is_static = next_if(T_static);
3331 array->type_qualifiers = type_qualifiers;
3332 array->is_static = is_static;
3334 expression_t *size = NULL;
3335 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3336 array->is_variable = true;
3338 } else if (token.kind != ']') {
3339 size = parse_assignment_expression();
3341 /* §6.7.5.2:1 Array size must have integer type */
3342 type_t *const orig_type = size->base.type;
3343 type_t *const type = skip_typeref(orig_type);
3344 if (!is_type_integer(type) && is_type_valid(type)) {
3345 errorf(&size->base.source_position,
3346 "array size '%E' must have integer type but has type '%T'",
3351 mark_vars_read(size, NULL);
3354 if (is_static && size == NULL)
3355 errorf(&array->base.pos, "static array parameters require a size");
3357 rem_anchor_token(']');
3363 static construct_type_t *parse_function_declarator(scope_t *scope)
3365 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3367 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3368 function_type_t *ftype = &type->function;
3370 ftype->linkage = current_linkage;
3371 ftype->calling_convention = CC_DEFAULT;
3373 parse_parameters(ftype, scope);
3375 cons->function.function_type = type;
3380 typedef struct parse_declarator_env_t {
3381 bool may_be_abstract : 1;
3382 bool must_be_abstract : 1;
3383 decl_modifiers_t modifiers;
3385 source_position_t source_position;
3387 attribute_t *attributes;
3388 } parse_declarator_env_t;
3391 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3393 /* construct a single linked list of construct_type_t's which describe
3394 * how to construct the final declarator type */
3395 construct_type_t *first = NULL;
3396 construct_type_t **anchor = &first;
3398 env->attributes = parse_attributes(env->attributes);
3401 construct_type_t *type;
3402 //variable_t *based = NULL; /* MS __based extension */
3403 switch (token.kind) {
3405 type = parse_reference_declarator();
3409 panic("based not supported anymore");
3414 type = parse_pointer_declarator();
3418 goto ptr_operator_end;
3422 anchor = &type->base.next;
3424 /* TODO: find out if this is correct */
3425 env->attributes = parse_attributes(env->attributes);
3429 construct_type_t *inner_types = NULL;
3431 switch (token.kind) {
3433 if (env->must_be_abstract) {
3434 errorf(HERE, "no identifier expected in typename");
3436 env->symbol = token.identifier.symbol;
3437 env->source_position = token.base.source_position;
3443 /* Parenthesized declarator or function declarator? */
3444 token_t const *const la1 = look_ahead(1);
3445 switch (la1->kind) {
3447 if (is_typedef_symbol(la1->identifier.symbol)) {
3449 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3450 * interpreted as ``function with no parameter specification'', rather
3451 * than redundant parentheses around the omitted identifier. */
3453 /* Function declarator. */
3454 if (!env->may_be_abstract) {
3455 errorf(HERE, "function declarator must have a name");
3462 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3463 /* Paranthesized declarator. */
3465 add_anchor_token(')');
3466 inner_types = parse_inner_declarator(env);
3467 if (inner_types != NULL) {
3468 /* All later declarators only modify the return type */
3469 env->must_be_abstract = true;
3471 rem_anchor_token(')');
3480 if (env->may_be_abstract)
3482 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3487 construct_type_t **const p = anchor;
3490 construct_type_t *type;
3491 switch (token.kind) {
3493 scope_t *scope = NULL;
3494 if (!env->must_be_abstract) {
3495 scope = &env->parameters;
3498 type = parse_function_declarator(scope);
3502 type = parse_array_declarator();
3505 goto declarator_finished;
3508 /* insert in the middle of the list (at p) */
3509 type->base.next = *p;
3512 anchor = &type->base.next;
3515 declarator_finished:
3516 /* append inner_types at the end of the list, we don't to set anchor anymore
3517 * as it's not needed anymore */
3518 *anchor = inner_types;
3523 static type_t *construct_declarator_type(construct_type_t *construct_list,
3526 construct_type_t *iter = construct_list;
3527 for (; iter != NULL; iter = iter->base.next) {
3528 source_position_t const* const pos = &iter->base.pos;
3529 switch (iter->kind) {
3530 case CONSTRUCT_FUNCTION: {
3531 construct_function_type_t *function = &iter->function;
3532 type_t *function_type = function->function_type;
3534 function_type->function.return_type = type;
3536 type_t *skipped_return_type = skip_typeref(type);
3538 if (is_type_function(skipped_return_type)) {
3539 errorf(pos, "function returning function is not allowed");
3540 } else if (is_type_array(skipped_return_type)) {
3541 errorf(pos, "function returning array is not allowed");
3543 if (skipped_return_type->base.qualifiers != 0) {
3544 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3548 /* The function type was constructed earlier. Freeing it here will
3549 * destroy other types. */
3550 type = typehash_insert(function_type);
3554 case CONSTRUCT_POINTER: {
3555 if (is_type_reference(skip_typeref(type)))
3556 errorf(pos, "cannot declare a pointer to reference");
3558 parsed_pointer_t *pointer = &iter->pointer;
3559 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3563 case CONSTRUCT_REFERENCE:
3564 if (is_type_reference(skip_typeref(type)))
3565 errorf(pos, "cannot declare a reference to reference");
3567 type = make_reference_type(type);
3570 case CONSTRUCT_ARRAY: {
3571 if (is_type_reference(skip_typeref(type)))
3572 errorf(pos, "cannot declare an array of references");
3574 parsed_array_t *array = &iter->array;
3575 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3577 expression_t *size_expression = array->size;
3578 if (size_expression != NULL) {
3580 = create_implicit_cast(size_expression, type_size_t);
3583 array_type->base.qualifiers = array->type_qualifiers;
3584 array_type->array.element_type = type;
3585 array_type->array.is_static = array->is_static;
3586 array_type->array.is_variable = array->is_variable;
3587 array_type->array.size_expression = size_expression;
3589 if (size_expression != NULL) {
3590 switch (is_constant_expression(size_expression)) {
3591 case EXPR_CLASS_CONSTANT: {
3592 long const size = fold_constant_to_int(size_expression);
3593 array_type->array.size = size;
3594 array_type->array.size_constant = true;
3595 /* §6.7.5.2:1 If the expression is a constant expression,
3596 * it shall have a value greater than zero. */
3598 errorf(&size_expression->base.source_position,
3599 "size of array must be greater than zero");
3600 } else if (size == 0 && !GNU_MODE) {
3601 errorf(&size_expression->base.source_position,
3602 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3607 case EXPR_CLASS_VARIABLE:
3608 array_type->array.is_vla = true;
3611 case EXPR_CLASS_ERROR:
3616 type_t *skipped_type = skip_typeref(type);
3618 if (is_type_incomplete(skipped_type)) {
3619 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3620 } else if (is_type_function(skipped_type)) {
3621 errorf(pos, "array of functions is not allowed");
3623 type = identify_new_type(array_type);
3627 internal_errorf(pos, "invalid type construction found");
3633 static type_t *automatic_type_conversion(type_t *orig_type);
3635 static type_t *semantic_parameter(const source_position_t *pos,
3637 const declaration_specifiers_t *specifiers,
3638 entity_t const *const param)
3640 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3641 * shall be adjusted to ``qualified pointer to type'',
3643 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3644 * type'' shall be adjusted to ``pointer to function
3645 * returning type'', as in 6.3.2.1. */
3646 type = automatic_type_conversion(type);
3648 if (specifiers->is_inline && is_type_valid(type)) {
3649 errorf(pos, "'%N' declared 'inline'", param);
3652 /* §6.9.1:6 The declarations in the declaration list shall contain
3653 * no storage-class specifier other than register and no
3654 * initializations. */
3655 if (specifiers->thread_local || (
3656 specifiers->storage_class != STORAGE_CLASS_NONE &&
3657 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3659 errorf(pos, "invalid storage class for '%N'", param);
3662 /* delay test for incomplete type, because we might have (void)
3663 * which is legal but incomplete... */
3668 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3669 declarator_flags_t flags)
3671 parse_declarator_env_t env;
3672 memset(&env, 0, sizeof(env));
3673 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3675 construct_type_t *construct_type = parse_inner_declarator(&env);
3677 construct_declarator_type(construct_type, specifiers->type);
3678 type_t *type = skip_typeref(orig_type);
3680 if (construct_type != NULL) {
3681 obstack_free(&temp_obst, construct_type);
3684 attribute_t *attributes = parse_attributes(env.attributes);
3685 /* append (shared) specifier attribute behind attributes of this
3687 attribute_t **anchor = &attributes;
3688 while (*anchor != NULL)
3689 anchor = &(*anchor)->next;
3690 *anchor = specifiers->attributes;
3693 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3694 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3695 entity->typedefe.type = orig_type;
3697 if (anonymous_entity != NULL) {
3698 if (is_type_compound(type)) {
3699 assert(anonymous_entity->compound.alias == NULL);
3700 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3701 anonymous_entity->kind == ENTITY_UNION);
3702 anonymous_entity->compound.alias = entity;
3703 anonymous_entity = NULL;
3704 } else if (is_type_enum(type)) {
3705 assert(anonymous_entity->enume.alias == NULL);
3706 assert(anonymous_entity->kind == ENTITY_ENUM);
3707 anonymous_entity->enume.alias = entity;
3708 anonymous_entity = NULL;
3712 /* create a declaration type entity */
3713 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3714 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3715 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3717 if (env.symbol != NULL) {
3718 if (specifiers->is_inline && is_type_valid(type)) {
3719 errorf(&env.source_position,
3720 "compound member '%Y' declared 'inline'", env.symbol);
3723 if (specifiers->thread_local ||
3724 specifiers->storage_class != STORAGE_CLASS_NONE) {
3725 errorf(&env.source_position,
3726 "compound member '%Y' must have no storage class",
3730 } else if (flags & DECL_IS_PARAMETER) {
3731 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3732 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3733 } else if (is_type_function(type)) {
3734 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3735 entity->function.is_inline = specifiers->is_inline;
3736 entity->function.elf_visibility = default_visibility;
3737 entity->function.parameters = env.parameters;
3739 if (env.symbol != NULL) {
3740 /* this needs fixes for C++ */
3741 bool in_function_scope = current_function != NULL;
3743 if (specifiers->thread_local || (
3744 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3745 specifiers->storage_class != STORAGE_CLASS_NONE &&
3746 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3748 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3752 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3753 entity->variable.elf_visibility = default_visibility;
3754 entity->variable.thread_local = specifiers->thread_local;
3756 if (env.symbol != NULL) {
3757 if (specifiers->is_inline && is_type_valid(type)) {
3758 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3761 bool invalid_storage_class = false;
3762 if (current_scope == file_scope) {
3763 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3764 specifiers->storage_class != STORAGE_CLASS_NONE &&
3765 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3766 invalid_storage_class = true;
3769 if (specifiers->thread_local &&
3770 specifiers->storage_class == STORAGE_CLASS_NONE) {
3771 invalid_storage_class = true;
3774 if (invalid_storage_class) {
3775 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3780 entity->declaration.type = orig_type;
3781 entity->declaration.alignment = get_type_alignment(orig_type);
3782 entity->declaration.modifiers = env.modifiers;
3783 entity->declaration.attributes = attributes;
3785 storage_class_t storage_class = specifiers->storage_class;
3786 entity->declaration.declared_storage_class = storage_class;
3788 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3789 storage_class = STORAGE_CLASS_AUTO;
3790 entity->declaration.storage_class = storage_class;
3793 if (attributes != NULL) {
3794 handle_entity_attributes(attributes, entity);
3797 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3798 adapt_special_functions(&entity->function);
3804 static type_t *parse_abstract_declarator(type_t *base_type)
3806 parse_declarator_env_t env;
3807 memset(&env, 0, sizeof(env));
3808 env.may_be_abstract = true;
3809 env.must_be_abstract = true;
3811 construct_type_t *construct_type = parse_inner_declarator(&env);
3813 type_t *result = construct_declarator_type(construct_type, base_type);
3814 if (construct_type != NULL) {
3815 obstack_free(&temp_obst, construct_type);
3817 result = handle_type_attributes(env.attributes, result);
3823 * Check if the declaration of main is suspicious. main should be a
3824 * function with external linkage, returning int, taking either zero
3825 * arguments, two, or three arguments of appropriate types, ie.
3827 * int main([ int argc, char **argv [, char **env ] ]).
3829 * @param decl the declaration to check
3830 * @param type the function type of the declaration
3832 static void check_main(const entity_t *entity)
3834 const source_position_t *pos = &entity->base.source_position;
3835 if (entity->kind != ENTITY_FUNCTION) {
3836 warningf(WARN_MAIN, pos, "'main' is not a function");
3840 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3841 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3844 type_t *type = skip_typeref(entity->declaration.type);
3845 assert(is_type_function(type));
3847 function_type_t const *const func_type = &type->function;
3848 type_t *const ret_type = func_type->return_type;
3849 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3850 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3852 const function_parameter_t *parm = func_type->parameters;
3854 type_t *const first_type = skip_typeref(parm->type);
3855 type_t *const first_type_unqual = get_unqualified_type(first_type);
3856 if (!types_compatible(first_type_unqual, type_int)) {
3857 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3861 type_t *const second_type = skip_typeref(parm->type);
3862 type_t *const second_type_unqual
3863 = get_unqualified_type(second_type);
3864 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3865 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3869 type_t *const third_type = skip_typeref(parm->type);
3870 type_t *const third_type_unqual
3871 = get_unqualified_type(third_type);
3872 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3873 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3877 goto warn_arg_count;
3881 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3886 static void error_redefined_as_different_kind(const source_position_t *pos,
3887 const entity_t *old, entity_kind_t new_kind)
3889 char const *const what = get_entity_kind_name(new_kind);
3890 source_position_t const *const ppos = &old->base.source_position;
3891 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3894 static bool is_entity_valid(entity_t *const ent)
3896 if (is_declaration(ent)) {
3897 return is_type_valid(skip_typeref(ent->declaration.type));
3898 } else if (ent->kind == ENTITY_TYPEDEF) {
3899 return is_type_valid(skip_typeref(ent->typedefe.type));
3904 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3906 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3907 if (attributes_equal(tattr, attr))
3914 * test wether new_list contains any attributes not included in old_list
3916 static bool has_new_attributes(const attribute_t *old_list,
3917 const attribute_t *new_list)
3919 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3920 if (!contains_attribute(old_list, attr))
3927 * Merge in attributes from an attribute list (probably from a previous
3928 * declaration with the same name). Warning: destroys the old structure
3929 * of the attribute list - don't reuse attributes after this call.
3931 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3934 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3936 if (contains_attribute(decl->attributes, attr))
3939 /* move attribute to new declarations attributes list */
3940 attr->next = decl->attributes;
3941 decl->attributes = attr;
3945 static bool is_main(entity_t*);
3948 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3949 * for various problems that occur for multiple definitions
3951 entity_t *record_entity(entity_t *entity, const bool is_definition)
3953 const symbol_t *const symbol = entity->base.symbol;
3954 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3955 const source_position_t *pos = &entity->base.source_position;
3957 /* can happen in error cases */
3961 assert(!entity->base.parent_scope);
3962 assert(current_scope);
3963 entity->base.parent_scope = current_scope;
3965 entity_t *const previous_entity = get_entity(symbol, namespc);
3966 /* pushing the same entity twice will break the stack structure */
3967 assert(previous_entity != entity);
3969 if (entity->kind == ENTITY_FUNCTION) {
3970 type_t *const orig_type = entity->declaration.type;
3971 type_t *const type = skip_typeref(orig_type);
3973 assert(is_type_function(type));
3974 if (type->function.unspecified_parameters &&
3975 previous_entity == NULL &&
3976 !entity->declaration.implicit) {
3977 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3980 if (is_main(entity)) {
3985 if (is_declaration(entity) &&
3986 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3987 current_scope != file_scope &&
3988 !entity->declaration.implicit) {
3989 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3992 if (previous_entity != NULL) {
3993 source_position_t const *const ppos = &previous_entity->base.source_position;
3995 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3996 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3997 assert(previous_entity->kind == ENTITY_PARAMETER);
3998 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4002 if (previous_entity->base.parent_scope == current_scope) {
4003 if (previous_entity->kind != entity->kind) {
4004 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4005 error_redefined_as_different_kind(pos, previous_entity,
4010 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4011 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4014 if (previous_entity->kind == ENTITY_TYPEDEF) {
4015 type_t *const type = skip_typeref(entity->typedefe.type);
4016 type_t *const prev_type
4017 = skip_typeref(previous_entity->typedefe.type);
4018 if (c_mode & _CXX) {
4019 /* C++ allows double typedef if they are identical
4020 * (after skipping typedefs) */
4021 if (type == prev_type)
4024 /* GCC extension: redef in system headers is allowed */
4025 if ((pos->is_system_header || ppos->is_system_header) &&
4026 types_compatible(type, prev_type))
4029 errorf(pos, "redefinition of '%N' (declared %P)",
4034 /* at this point we should have only VARIABLES or FUNCTIONS */
4035 assert(is_declaration(previous_entity) && is_declaration(entity));
4037 declaration_t *const prev_decl = &previous_entity->declaration;
4038 declaration_t *const decl = &entity->declaration;
4040 /* can happen for K&R style declarations */
4041 if (prev_decl->type == NULL &&
4042 previous_entity->kind == ENTITY_PARAMETER &&
4043 entity->kind == ENTITY_PARAMETER) {
4044 prev_decl->type = decl->type;
4045 prev_decl->storage_class = decl->storage_class;
4046 prev_decl->declared_storage_class = decl->declared_storage_class;
4047 prev_decl->modifiers = decl->modifiers;
4048 return previous_entity;
4051 type_t *const type = skip_typeref(decl->type);
4052 type_t *const prev_type = skip_typeref(prev_decl->type);
4054 if (!types_compatible(type, prev_type)) {
4055 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4057 unsigned old_storage_class = prev_decl->storage_class;
4059 if (is_definition &&
4061 !(prev_decl->modifiers & DM_USED) &&
4062 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4063 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4066 storage_class_t new_storage_class = decl->storage_class;
4068 /* pretend no storage class means extern for function
4069 * declarations (except if the previous declaration is neither
4070 * none nor extern) */
4071 if (entity->kind == ENTITY_FUNCTION) {
4072 /* the previous declaration could have unspecified parameters or
4073 * be a typedef, so use the new type */
4074 if (prev_type->function.unspecified_parameters || is_definition)
4075 prev_decl->type = type;
4077 switch (old_storage_class) {
4078 case STORAGE_CLASS_NONE:
4079 old_storage_class = STORAGE_CLASS_EXTERN;
4082 case STORAGE_CLASS_EXTERN:
4083 if (is_definition) {
4084 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4085 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4087 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4088 new_storage_class = STORAGE_CLASS_EXTERN;
4095 } else if (is_type_incomplete(prev_type)) {
4096 prev_decl->type = type;
4099 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4100 new_storage_class == STORAGE_CLASS_EXTERN) {
4102 warn_redundant_declaration: ;
4104 = has_new_attributes(prev_decl->attributes,
4106 if (has_new_attrs) {
4107 merge_in_attributes(decl, prev_decl->attributes);
4108 } else if (!is_definition &&
4109 is_type_valid(prev_type) &&
4110 !pos->is_system_header) {
4111 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4113 } else if (current_function == NULL) {
4114 if (old_storage_class != STORAGE_CLASS_STATIC &&
4115 new_storage_class == STORAGE_CLASS_STATIC) {
4116 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4117 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4118 prev_decl->storage_class = STORAGE_CLASS_NONE;
4119 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4121 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4123 goto error_redeclaration;
4124 goto warn_redundant_declaration;
4126 } else if (is_type_valid(prev_type)) {
4127 if (old_storage_class == new_storage_class) {
4128 error_redeclaration:
4129 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4131 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4136 prev_decl->modifiers |= decl->modifiers;
4137 if (entity->kind == ENTITY_FUNCTION) {
4138 previous_entity->function.is_inline |= entity->function.is_inline;
4140 return previous_entity;
4144 if (is_warn_on(why = WARN_SHADOW) ||
4145 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4146 char const *const what = get_entity_kind_name(previous_entity->kind);
4147 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4151 if (entity->kind == ENTITY_FUNCTION) {
4152 if (is_definition &&
4153 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4155 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4156 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4158 goto warn_missing_declaration;
4161 } else if (entity->kind == ENTITY_VARIABLE) {
4162 if (current_scope == file_scope &&
4163 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4164 !entity->declaration.implicit) {
4165 warn_missing_declaration:
4166 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4171 environment_push(entity);
4172 append_entity(current_scope, entity);
4177 static void parser_error_multiple_definition(entity_t *entity,
4178 const source_position_t *source_position)
4180 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4181 entity->base.symbol, &entity->base.source_position);
4184 static bool is_declaration_specifier(const token_t *token)
4186 switch (token->kind) {
4190 return is_typedef_symbol(token->identifier.symbol);
4197 static void parse_init_declarator_rest(entity_t *entity)
4199 type_t *orig_type = type_error_type;
4201 if (entity->base.kind == ENTITY_TYPEDEF) {
4202 source_position_t const *const pos = &entity->base.source_position;
4203 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4205 assert(is_declaration(entity));
4206 orig_type = entity->declaration.type;
4209 type_t *type = skip_typeref(orig_type);
4211 if (entity->kind == ENTITY_VARIABLE
4212 && entity->variable.initializer != NULL) {
4213 parser_error_multiple_definition(entity, HERE);
4217 declaration_t *const declaration = &entity->declaration;
4218 bool must_be_constant = false;
4219 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4220 entity->base.parent_scope == file_scope) {
4221 must_be_constant = true;
4224 if (is_type_function(type)) {
4225 source_position_t const *const pos = &entity->base.source_position;
4226 errorf(pos, "'%N' is initialized like a variable", entity);
4227 orig_type = type_error_type;
4230 parse_initializer_env_t env;
4231 env.type = orig_type;
4232 env.must_be_constant = must_be_constant;
4233 env.entity = entity;
4235 initializer_t *initializer = parse_initializer(&env);
4237 if (entity->kind == ENTITY_VARIABLE) {
4238 /* §6.7.5:22 array initializers for arrays with unknown size
4239 * determine the array type size */
4240 declaration->type = env.type;
4241 entity->variable.initializer = initializer;
4245 /* parse rest of a declaration without any declarator */
4246 static void parse_anonymous_declaration_rest(
4247 const declaration_specifiers_t *specifiers)
4250 anonymous_entity = NULL;
4252 source_position_t const *const pos = &specifiers->source_position;
4253 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4254 specifiers->thread_local) {
4255 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4258 type_t *type = specifiers->type;
4259 switch (type->kind) {
4260 case TYPE_COMPOUND_STRUCT:
4261 case TYPE_COMPOUND_UNION: {
4262 if (type->compound.compound->base.symbol == NULL) {
4263 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4272 warningf(WARN_OTHER, pos, "empty declaration");
4277 static void check_variable_type_complete(entity_t *ent)
4279 if (ent->kind != ENTITY_VARIABLE)
4282 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4283 * type for the object shall be complete [...] */
4284 declaration_t *decl = &ent->declaration;
4285 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4286 decl->storage_class == STORAGE_CLASS_STATIC)
4289 type_t *const type = skip_typeref(decl->type);
4290 if (!is_type_incomplete(type))
4293 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4294 * are given length one. */
4295 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4296 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4300 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4304 static void parse_declaration_rest(entity_t *ndeclaration,
4305 const declaration_specifiers_t *specifiers,
4306 parsed_declaration_func finished_declaration,
4307 declarator_flags_t flags)
4309 add_anchor_token(';');
4310 add_anchor_token(',');
4312 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4314 if (token.kind == '=') {
4315 parse_init_declarator_rest(entity);
4316 } else if (entity->kind == ENTITY_VARIABLE) {
4317 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4318 * [...] where the extern specifier is explicitly used. */
4319 declaration_t *decl = &entity->declaration;
4320 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4321 is_type_reference(skip_typeref(decl->type))) {
4322 source_position_t const *const pos = &entity->base.source_position;
4323 errorf(pos, "reference '%#N' must be initialized", entity);
4327 check_variable_type_complete(entity);
4332 add_anchor_token('=');
4333 ndeclaration = parse_declarator(specifiers, flags);
4334 rem_anchor_token('=');
4336 rem_anchor_token(',');
4337 rem_anchor_token(';');
4340 anonymous_entity = NULL;
4343 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4345 symbol_t *symbol = entity->base.symbol;
4349 assert(entity->base.namespc == NAMESPACE_NORMAL);
4350 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4351 if (previous_entity == NULL
4352 || previous_entity->base.parent_scope != current_scope) {
4353 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4358 if (is_definition) {
4359 errorf(HERE, "'%N' is initialised", entity);
4362 return record_entity(entity, false);
4365 static void parse_declaration(parsed_declaration_func finished_declaration,
4366 declarator_flags_t flags)
4368 add_anchor_token(';');
4369 declaration_specifiers_t specifiers;
4370 parse_declaration_specifiers(&specifiers);
4371 rem_anchor_token(';');
4373 if (token.kind == ';') {
4374 parse_anonymous_declaration_rest(&specifiers);
4376 entity_t *entity = parse_declarator(&specifiers, flags);
4377 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4382 static type_t *get_default_promoted_type(type_t *orig_type)
4384 type_t *result = orig_type;
4386 type_t *type = skip_typeref(orig_type);
4387 if (is_type_integer(type)) {
4388 result = promote_integer(type);
4389 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4390 result = type_double;
4396 static void parse_kr_declaration_list(entity_t *entity)
4398 if (entity->kind != ENTITY_FUNCTION)
4401 type_t *type = skip_typeref(entity->declaration.type);
4402 assert(is_type_function(type));
4403 if (!type->function.kr_style_parameters)
4406 add_anchor_token('{');
4408 PUSH_SCOPE(&entity->function.parameters);
4410 entity_t *parameter = entity->function.parameters.entities;
4411 for ( ; parameter != NULL; parameter = parameter->base.next) {
4412 assert(parameter->base.parent_scope == NULL);
4413 parameter->base.parent_scope = current_scope;
4414 environment_push(parameter);
4417 /* parse declaration list */
4419 switch (token.kind) {
4421 /* This covers symbols, which are no type, too, and results in
4422 * better error messages. The typical cases are misspelled type
4423 * names and missing includes. */
4425 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4435 /* update function type */
4436 type_t *new_type = duplicate_type(type);
4438 function_parameter_t *parameters = NULL;
4439 function_parameter_t **anchor = ¶meters;
4441 /* did we have an earlier prototype? */
4442 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4443 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4446 function_parameter_t *proto_parameter = NULL;
4447 if (proto_type != NULL) {
4448 type_t *proto_type_type = proto_type->declaration.type;
4449 proto_parameter = proto_type_type->function.parameters;
4450 /* If a K&R function definition has a variadic prototype earlier, then
4451 * make the function definition variadic, too. This should conform to
4452 * §6.7.5.3:15 and §6.9.1:8. */
4453 new_type->function.variadic = proto_type_type->function.variadic;
4455 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4457 new_type->function.unspecified_parameters = true;
4460 bool need_incompatible_warning = false;
4461 parameter = entity->function.parameters.entities;
4462 for (; parameter != NULL; parameter = parameter->base.next,
4464 proto_parameter == NULL ? NULL : proto_parameter->next) {
4465 if (parameter->kind != ENTITY_PARAMETER)
4468 type_t *parameter_type = parameter->declaration.type;
4469 if (parameter_type == NULL) {
4470 source_position_t const* const pos = ¶meter->base.source_position;
4472 errorf(pos, "no type specified for function '%N'", parameter);
4473 parameter_type = type_error_type;
4475 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4476 parameter_type = type_int;
4478 parameter->declaration.type = parameter_type;
4481 semantic_parameter_incomplete(parameter);
4483 /* we need the default promoted types for the function type */
4484 type_t *not_promoted = parameter_type;
4485 parameter_type = get_default_promoted_type(parameter_type);
4487 /* gcc special: if the type of the prototype matches the unpromoted
4488 * type don't promote */
4489 if (!strict_mode && proto_parameter != NULL) {
4490 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4491 type_t *promo_skip = skip_typeref(parameter_type);
4492 type_t *param_skip = skip_typeref(not_promoted);
4493 if (!types_compatible(proto_p_type, promo_skip)
4494 && types_compatible(proto_p_type, param_skip)) {
4496 need_incompatible_warning = true;
4497 parameter_type = not_promoted;
4500 function_parameter_t *const function_parameter
4501 = allocate_parameter(parameter_type);
4503 *anchor = function_parameter;
4504 anchor = &function_parameter->next;
4507 new_type->function.parameters = parameters;
4508 new_type = identify_new_type(new_type);
4510 if (need_incompatible_warning) {
4511 symbol_t const *const sym = entity->base.symbol;
4512 source_position_t const *const pos = &entity->base.source_position;
4513 source_position_t const *const ppos = &proto_type->base.source_position;
4514 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4516 entity->declaration.type = new_type;
4518 rem_anchor_token('{');
4521 static bool first_err = true;
4524 * When called with first_err set, prints the name of the current function,
4527 static void print_in_function(void)
4531 char const *const file = current_function->base.base.source_position.input_name;
4532 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4537 * Check if all labels are defined in the current function.
4538 * Check if all labels are used in the current function.
4540 static void check_labels(void)
4542 for (const goto_statement_t *goto_statement = goto_first;
4543 goto_statement != NULL;
4544 goto_statement = goto_statement->next) {
4545 label_t *label = goto_statement->label;
4546 if (label->base.source_position.input_name == NULL) {
4547 print_in_function();
4548 source_position_t const *const pos = &goto_statement->base.source_position;
4549 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4553 if (is_warn_on(WARN_UNUSED_LABEL)) {
4554 for (const label_statement_t *label_statement = label_first;
4555 label_statement != NULL;
4556 label_statement = label_statement->next) {
4557 label_t *label = label_statement->label;
4559 if (! label->used) {
4560 print_in_function();
4561 source_position_t const *const pos = &label_statement->base.source_position;
4562 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4568 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4570 entity_t const *const end = last != NULL ? last->base.next : NULL;
4571 for (; entity != end; entity = entity->base.next) {
4572 if (!is_declaration(entity))
4575 declaration_t *declaration = &entity->declaration;
4576 if (declaration->implicit)
4579 if (!declaration->used) {
4580 print_in_function();
4581 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4582 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4583 print_in_function();
4584 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4589 static void check_unused_variables(statement_t *const stmt, void *const env)
4593 switch (stmt->kind) {
4594 case STATEMENT_DECLARATION: {
4595 declaration_statement_t const *const decls = &stmt->declaration;
4596 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4601 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4610 * Check declarations of current_function for unused entities.
4612 static void check_declarations(void)
4614 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4615 const scope_t *scope = ¤t_function->parameters;
4616 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4618 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4619 walk_statements(current_function->statement, check_unused_variables,
4624 static int determine_truth(expression_t const* const cond)
4627 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4628 fold_constant_to_bool(cond) ? 1 :
4632 static void check_reachable(statement_t *);
4633 static bool reaches_end;
4635 static bool expression_returns(expression_t const *const expr)
4637 switch (expr->kind) {
4639 expression_t const *const func = expr->call.function;
4640 type_t const *const type = skip_typeref(func->base.type);
4641 if (type->kind == TYPE_POINTER) {
4642 type_t const *const points_to
4643 = skip_typeref(type->pointer.points_to);
4644 if (points_to->kind == TYPE_FUNCTION
4645 && points_to->function.modifiers & DM_NORETURN)
4649 if (!expression_returns(func))
4652 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4653 if (!expression_returns(arg->expression))
4660 case EXPR_REFERENCE:
4661 case EXPR_ENUM_CONSTANT:
4662 case EXPR_LITERAL_CASES:
4663 case EXPR_STRING_LITERAL:
4664 case EXPR_WIDE_STRING_LITERAL:
4665 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4666 case EXPR_LABEL_ADDRESS:
4667 case EXPR_CLASSIFY_TYPE:
4668 case EXPR_SIZEOF: // TODO handle obscure VLA case
4671 case EXPR_BUILTIN_CONSTANT_P:
4672 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4677 case EXPR_STATEMENT: {
4678 bool old_reaches_end = reaches_end;
4679 reaches_end = false;
4680 check_reachable(expr->statement.statement);
4681 bool returns = reaches_end;
4682 reaches_end = old_reaches_end;
4686 case EXPR_CONDITIONAL:
4687 // TODO handle constant expression
4689 if (!expression_returns(expr->conditional.condition))
4692 if (expr->conditional.true_expression != NULL
4693 && expression_returns(expr->conditional.true_expression))
4696 return expression_returns(expr->conditional.false_expression);
4699 return expression_returns(expr->select.compound);
4701 case EXPR_ARRAY_ACCESS:
4703 expression_returns(expr->array_access.array_ref) &&
4704 expression_returns(expr->array_access.index);
4707 return expression_returns(expr->va_starte.ap);
4710 return expression_returns(expr->va_arge.ap);
4713 return expression_returns(expr->va_copye.src);
4715 case EXPR_UNARY_CASES_MANDATORY:
4716 return expression_returns(expr->unary.value);
4718 case EXPR_UNARY_THROW:
4721 case EXPR_BINARY_CASES:
4722 // TODO handle constant lhs of && and ||
4724 expression_returns(expr->binary.left) &&
4725 expression_returns(expr->binary.right);
4728 panic("unhandled expression");
4731 static bool initializer_returns(initializer_t const *const init)
4733 switch (init->kind) {
4734 case INITIALIZER_VALUE:
4735 return expression_returns(init->value.value);
4737 case INITIALIZER_LIST: {
4738 initializer_t * const* i = init->list.initializers;
4739 initializer_t * const* const end = i + init->list.len;
4740 bool returns = true;
4741 for (; i != end; ++i) {
4742 if (!initializer_returns(*i))
4748 case INITIALIZER_STRING:
4749 case INITIALIZER_WIDE_STRING:
4750 case INITIALIZER_DESIGNATOR: // designators have no payload
4753 panic("unhandled initializer");
4756 static bool noreturn_candidate;
4758 static void check_reachable(statement_t *const stmt)
4760 if (stmt->base.reachable)
4762 if (stmt->kind != STATEMENT_DO_WHILE)
4763 stmt->base.reachable = true;
4765 statement_t *last = stmt;
4767 switch (stmt->kind) {
4768 case STATEMENT_ERROR:
4769 case STATEMENT_EMPTY:
4771 next = stmt->base.next;
4774 case STATEMENT_DECLARATION: {
4775 declaration_statement_t const *const decl = &stmt->declaration;
4776 entity_t const * ent = decl->declarations_begin;
4777 entity_t const *const last_decl = decl->declarations_end;
4779 for (;; ent = ent->base.next) {
4780 if (ent->kind == ENTITY_VARIABLE &&
4781 ent->variable.initializer != NULL &&
4782 !initializer_returns(ent->variable.initializer)) {
4785 if (ent == last_decl)
4789 next = stmt->base.next;
4793 case STATEMENT_COMPOUND:
4794 next = stmt->compound.statements;
4796 next = stmt->base.next;
4799 case STATEMENT_RETURN: {
4800 expression_t const *const val = stmt->returns.value;
4801 if (val == NULL || expression_returns(val))
4802 noreturn_candidate = false;
4806 case STATEMENT_IF: {
4807 if_statement_t const *const ifs = &stmt->ifs;
4808 expression_t const *const cond = ifs->condition;
4810 if (!expression_returns(cond))
4813 int const val = determine_truth(cond);
4816 check_reachable(ifs->true_statement);
4821 if (ifs->false_statement != NULL) {
4822 check_reachable(ifs->false_statement);
4826 next = stmt->base.next;
4830 case STATEMENT_SWITCH: {
4831 switch_statement_t const *const switchs = &stmt->switchs;
4832 expression_t const *const expr = switchs->expression;
4834 if (!expression_returns(expr))
4837 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4838 long const val = fold_constant_to_int(expr);
4839 case_label_statement_t * defaults = NULL;
4840 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4841 if (i->expression == NULL) {
4846 if (i->first_case <= val && val <= i->last_case) {
4847 check_reachable((statement_t*)i);
4852 if (defaults != NULL) {
4853 check_reachable((statement_t*)defaults);
4857 bool has_default = false;
4858 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4859 if (i->expression == NULL)
4862 check_reachable((statement_t*)i);
4869 next = stmt->base.next;
4873 case STATEMENT_EXPRESSION: {
4874 /* Check for noreturn function call */
4875 expression_t const *const expr = stmt->expression.expression;
4876 if (!expression_returns(expr))
4879 next = stmt->base.next;
4883 case STATEMENT_CONTINUE:
4884 for (statement_t *parent = stmt;;) {
4885 parent = parent->base.parent;
4886 if (parent == NULL) /* continue not within loop */
4890 switch (parent->kind) {
4891 case STATEMENT_WHILE: goto continue_while;
4892 case STATEMENT_DO_WHILE: goto continue_do_while;
4893 case STATEMENT_FOR: goto continue_for;
4899 case STATEMENT_BREAK:
4900 for (statement_t *parent = stmt;;) {
4901 parent = parent->base.parent;
4902 if (parent == NULL) /* break not within loop/switch */
4905 switch (parent->kind) {
4906 case STATEMENT_SWITCH:
4907 case STATEMENT_WHILE:
4908 case STATEMENT_DO_WHILE:
4911 next = parent->base.next;
4912 goto found_break_parent;
4920 case STATEMENT_COMPUTED_GOTO: {
4921 if (!expression_returns(stmt->computed_goto.expression))
4924 statement_t *parent = stmt->base.parent;
4925 if (parent == NULL) /* top level goto */
4931 case STATEMENT_GOTO:
4932 next = stmt->gotos.label->statement;
4933 if (next == NULL) /* missing label */
4937 case STATEMENT_LABEL:
4938 next = stmt->label.statement;
4941 case STATEMENT_CASE_LABEL:
4942 next = stmt->case_label.statement;
4945 case STATEMENT_WHILE: {
4946 while_statement_t const *const whiles = &stmt->whiles;
4947 expression_t const *const cond = whiles->condition;
4949 if (!expression_returns(cond))
4952 int const val = determine_truth(cond);
4955 check_reachable(whiles->body);
4960 next = stmt->base.next;
4964 case STATEMENT_DO_WHILE:
4965 next = stmt->do_while.body;
4968 case STATEMENT_FOR: {
4969 for_statement_t *const fors = &stmt->fors;
4971 if (fors->condition_reachable)
4973 fors->condition_reachable = true;
4975 expression_t const *const cond = fors->condition;
4980 } else if (expression_returns(cond)) {
4981 val = determine_truth(cond);
4987 check_reachable(fors->body);
4992 next = stmt->base.next;
4996 case STATEMENT_MS_TRY: {
4997 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4998 check_reachable(ms_try->try_statement);
4999 next = ms_try->final_statement;
5003 case STATEMENT_LEAVE: {
5004 statement_t *parent = stmt;
5006 parent = parent->base.parent;
5007 if (parent == NULL) /* __leave not within __try */
5010 if (parent->kind == STATEMENT_MS_TRY) {
5012 next = parent->ms_try.final_statement;
5020 panic("invalid statement kind");
5023 while (next == NULL) {
5024 next = last->base.parent;
5026 noreturn_candidate = false;
5028 type_t *const type = skip_typeref(current_function->base.type);
5029 assert(is_type_function(type));
5030 type_t *const ret = skip_typeref(type->function.return_type);
5031 if (!is_type_void(ret) &&
5032 is_type_valid(ret) &&
5033 !is_main(current_entity)) {
5034 source_position_t const *const pos = &stmt->base.source_position;
5035 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5040 switch (next->kind) {
5041 case STATEMENT_ERROR:
5042 case STATEMENT_EMPTY:
5043 case STATEMENT_DECLARATION:
5044 case STATEMENT_EXPRESSION:
5046 case STATEMENT_RETURN:
5047 case STATEMENT_CONTINUE:
5048 case STATEMENT_BREAK:
5049 case STATEMENT_COMPUTED_GOTO:
5050 case STATEMENT_GOTO:
5051 case STATEMENT_LEAVE:
5052 panic("invalid control flow in function");
5054 case STATEMENT_COMPOUND:
5055 if (next->compound.stmt_expr) {
5061 case STATEMENT_SWITCH:
5062 case STATEMENT_LABEL:
5063 case STATEMENT_CASE_LABEL:
5065 next = next->base.next;
5068 case STATEMENT_WHILE: {
5070 if (next->base.reachable)
5072 next->base.reachable = true;
5074 while_statement_t const *const whiles = &next->whiles;
5075 expression_t const *const cond = whiles->condition;
5077 if (!expression_returns(cond))
5080 int const val = determine_truth(cond);
5083 check_reachable(whiles->body);
5089 next = next->base.next;
5093 case STATEMENT_DO_WHILE: {
5095 if (next->base.reachable)
5097 next->base.reachable = true;
5099 do_while_statement_t const *const dw = &next->do_while;
5100 expression_t const *const cond = dw->condition;
5102 if (!expression_returns(cond))
5105 int const val = determine_truth(cond);
5108 check_reachable(dw->body);
5114 next = next->base.next;
5118 case STATEMENT_FOR: {
5120 for_statement_t *const fors = &next->fors;
5122 fors->step_reachable = true;
5124 if (fors->condition_reachable)
5126 fors->condition_reachable = true;
5128 expression_t const *const cond = fors->condition;
5133 } else if (expression_returns(cond)) {
5134 val = determine_truth(cond);
5140 check_reachable(fors->body);
5146 next = next->base.next;
5150 case STATEMENT_MS_TRY:
5152 next = next->ms_try.final_statement;
5157 check_reachable(next);
5160 static void check_unreachable(statement_t* const stmt, void *const env)
5164 switch (stmt->kind) {
5165 case STATEMENT_DO_WHILE:
5166 if (!stmt->base.reachable) {
5167 expression_t const *const cond = stmt->do_while.condition;
5168 if (determine_truth(cond) >= 0) {
5169 source_position_t const *const pos = &cond->base.source_position;
5170 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5175 case STATEMENT_FOR: {
5176 for_statement_t const* const fors = &stmt->fors;
5178 // if init and step are unreachable, cond is unreachable, too
5179 if (!stmt->base.reachable && !fors->step_reachable) {
5180 goto warn_unreachable;
5182 if (!stmt->base.reachable && fors->initialisation != NULL) {
5183 source_position_t const *const pos = &fors->initialisation->base.source_position;
5184 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5187 if (!fors->condition_reachable && fors->condition != NULL) {
5188 source_position_t const *const pos = &fors->condition->base.source_position;
5189 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5192 if (!fors->step_reachable && fors->step != NULL) {
5193 source_position_t const *const pos = &fors->step->base.source_position;
5194 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5200 case STATEMENT_COMPOUND:
5201 if (stmt->compound.statements != NULL)
5203 goto warn_unreachable;
5205 case STATEMENT_DECLARATION: {
5206 /* Only warn if there is at least one declarator with an initializer.
5207 * This typically occurs in switch statements. */
5208 declaration_statement_t const *const decl = &stmt->declaration;
5209 entity_t const * ent = decl->declarations_begin;
5210 entity_t const *const last = decl->declarations_end;
5212 for (;; ent = ent->base.next) {
5213 if (ent->kind == ENTITY_VARIABLE &&
5214 ent->variable.initializer != NULL) {
5215 goto warn_unreachable;
5225 if (!stmt->base.reachable) {
5226 source_position_t const *const pos = &stmt->base.source_position;
5227 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5233 static bool is_main(entity_t *entity)
5235 static symbol_t *sym_main = NULL;
5236 if (sym_main == NULL) {
5237 sym_main = symbol_table_insert("main");
5240 if (entity->base.symbol != sym_main)
5242 /* must be in outermost scope */
5243 if (entity->base.parent_scope != file_scope)
5249 static void prepare_main_collect2(entity_t*);
5251 static void parse_external_declaration(void)
5253 /* function-definitions and declarations both start with declaration
5255 add_anchor_token(';');
5256 declaration_specifiers_t specifiers;
5257 parse_declaration_specifiers(&specifiers);
5258 rem_anchor_token(';');
5260 /* must be a declaration */
5261 if (token.kind == ';') {
5262 parse_anonymous_declaration_rest(&specifiers);
5266 add_anchor_token(',');
5267 add_anchor_token('=');
5268 add_anchor_token(';');
5269 add_anchor_token('{');
5271 /* declarator is common to both function-definitions and declarations */
5272 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5274 rem_anchor_token('{');
5275 rem_anchor_token(';');
5276 rem_anchor_token('=');
5277 rem_anchor_token(',');
5279 /* must be a declaration */
5280 switch (token.kind) {
5284 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5289 /* must be a function definition */
5290 parse_kr_declaration_list(ndeclaration);
5292 if (token.kind != '{') {
5293 parse_error_expected("while parsing function definition", '{', NULL);
5294 eat_until_matching_token(';');
5298 assert(is_declaration(ndeclaration));
5299 type_t *const orig_type = ndeclaration->declaration.type;
5300 type_t * type = skip_typeref(orig_type);
5302 if (!is_type_function(type)) {
5303 if (is_type_valid(type)) {
5304 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5310 source_position_t const *const pos = &ndeclaration->base.source_position;
5311 if (is_typeref(orig_type)) {
5313 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5316 if (is_type_compound(skip_typeref(type->function.return_type))) {
5317 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5319 if (type->function.unspecified_parameters) {
5320 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5322 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5325 /* §6.7.5.3:14 a function definition with () means no
5326 * parameters (and not unspecified parameters) */
5327 if (type->function.unspecified_parameters &&
5328 type->function.parameters == NULL) {
5329 type_t *copy = duplicate_type(type);
5330 copy->function.unspecified_parameters = false;
5331 type = identify_new_type(copy);
5333 ndeclaration->declaration.type = type;
5336 entity_t *const entity = record_entity(ndeclaration, true);
5337 assert(entity->kind == ENTITY_FUNCTION);
5338 assert(ndeclaration->kind == ENTITY_FUNCTION);
5340 function_t *const function = &entity->function;
5341 if (ndeclaration != entity) {
5342 function->parameters = ndeclaration->function.parameters;
5345 PUSH_SCOPE(&function->parameters);
5347 entity_t *parameter = function->parameters.entities;
5348 for (; parameter != NULL; parameter = parameter->base.next) {
5349 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5350 parameter->base.parent_scope = current_scope;
5352 assert(parameter->base.parent_scope == NULL
5353 || parameter->base.parent_scope == current_scope);
5354 parameter->base.parent_scope = current_scope;
5355 if (parameter->base.symbol == NULL) {
5356 errorf(¶meter->base.source_position, "parameter name omitted");
5359 environment_push(parameter);
5362 if (function->statement != NULL) {
5363 parser_error_multiple_definition(entity, HERE);
5366 /* parse function body */
5367 int label_stack_top = label_top();
5368 function_t *old_current_function = current_function;
5369 current_function = function;
5370 PUSH_CURRENT_ENTITY(entity);
5374 goto_anchor = &goto_first;
5376 label_anchor = &label_first;
5378 statement_t *const body = parse_compound_statement(false);
5379 function->statement = body;
5382 check_declarations();
5383 if (is_warn_on(WARN_RETURN_TYPE) ||
5384 is_warn_on(WARN_UNREACHABLE_CODE) ||
5385 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5386 noreturn_candidate = true;
5387 check_reachable(body);
5388 if (is_warn_on(WARN_UNREACHABLE_CODE))
5389 walk_statements(body, check_unreachable, NULL);
5390 if (noreturn_candidate &&
5391 !(function->base.modifiers & DM_NORETURN)) {
5392 source_position_t const *const pos = &body->base.source_position;
5393 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5397 if (is_main(entity)) {
5398 /* Force main to C linkage. */
5399 type_t *const type = entity->declaration.type;
5400 assert(is_type_function(type));
5401 if (type->function.linkage != LINKAGE_C) {
5402 type_t *new_type = duplicate_type(type);
5403 new_type->function.linkage = LINKAGE_C;
5404 entity->declaration.type = identify_new_type(new_type);
5407 if (enable_main_collect2_hack)
5408 prepare_main_collect2(entity);
5411 POP_CURRENT_ENTITY();
5413 assert(current_function == function);
5414 current_function = old_current_function;
5415 label_pop_to(label_stack_top);
5421 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5423 entity_t *iter = compound->members.entities;
5424 for (; iter != NULL; iter = iter->base.next) {
5425 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5428 if (iter->base.symbol == symbol) {
5430 } else if (iter->base.symbol == NULL) {
5431 /* search in anonymous structs and unions */
5432 type_t *type = skip_typeref(iter->declaration.type);
5433 if (is_type_compound(type)) {
5434 if (find_compound_entry(type->compound.compound, symbol)
5445 static void check_deprecated(const source_position_t *source_position,
5446 const entity_t *entity)
5448 if (!is_declaration(entity))
5450 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5453 source_position_t const *const epos = &entity->base.source_position;
5454 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5456 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5458 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5463 static expression_t *create_select(const source_position_t *pos,
5465 type_qualifiers_t qualifiers,
5468 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5470 check_deprecated(pos, entry);
5472 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5473 select->select.compound = addr;
5474 select->select.compound_entry = entry;
5476 type_t *entry_type = entry->declaration.type;
5477 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5479 /* bitfields need special treatment */
5480 if (entry->compound_member.bitfield) {
5481 unsigned bit_size = entry->compound_member.bit_size;
5482 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5483 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5484 res_type = type_int;
5488 /* we always do the auto-type conversions; the & and sizeof parser contains
5489 * code to revert this! */
5490 select->base.type = automatic_type_conversion(res_type);
5497 * Find entry with symbol in compound. Search anonymous structs and unions and
5498 * creates implicit select expressions for them.
5499 * Returns the adress for the innermost compound.
5501 static expression_t *find_create_select(const source_position_t *pos,
5503 type_qualifiers_t qualifiers,
5504 compound_t *compound, symbol_t *symbol)
5506 entity_t *iter = compound->members.entities;
5507 for (; iter != NULL; iter = iter->base.next) {
5508 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5511 symbol_t *iter_symbol = iter->base.symbol;
5512 if (iter_symbol == NULL) {
5513 type_t *type = iter->declaration.type;
5514 if (type->kind != TYPE_COMPOUND_STRUCT
5515 && type->kind != TYPE_COMPOUND_UNION)
5518 compound_t *sub_compound = type->compound.compound;
5520 if (find_compound_entry(sub_compound, symbol) == NULL)
5523 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5524 sub_addr->base.source_position = *pos;
5525 sub_addr->base.implicit = true;
5526 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5530 if (iter_symbol == symbol) {
5531 return create_select(pos, addr, qualifiers, iter);
5538 static void parse_bitfield_member(entity_t *entity)
5542 expression_t *size = parse_constant_expression();
5545 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5546 type_t *type = entity->declaration.type;
5547 if (!is_type_integer(skip_typeref(type))) {
5548 errorf(HERE, "bitfield base type '%T' is not an integer type",
5552 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5553 /* error already reported by parse_constant_expression */
5554 size_long = get_type_size(type) * 8;
5556 size_long = fold_constant_to_int(size);
5558 const symbol_t *symbol = entity->base.symbol;
5559 const symbol_t *user_symbol
5560 = symbol == NULL ? sym_anonymous : symbol;
5561 unsigned bit_size = get_type_size(type) * 8;
5562 if (size_long < 0) {
5563 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5564 } else if (size_long == 0 && symbol != NULL) {
5565 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5566 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5567 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5570 /* hope that people don't invent crazy types with more bits
5571 * than our struct can hold */
5573 (1 << sizeof(entity->compound_member.bit_size)*8));
5577 entity->compound_member.bitfield = true;
5578 entity->compound_member.bit_size = (unsigned char)size_long;
5581 static void parse_compound_declarators(compound_t *compound,
5582 const declaration_specifiers_t *specifiers)
5584 add_anchor_token(';');
5585 add_anchor_token(',');
5589 if (token.kind == ':') {
5590 /* anonymous bitfield */
5591 type_t *type = specifiers->type;
5592 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5593 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5594 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5595 entity->declaration.type = type;
5597 parse_bitfield_member(entity);
5599 attribute_t *attributes = parse_attributes(NULL);
5600 attribute_t **anchor = &attributes;
5601 while (*anchor != NULL)
5602 anchor = &(*anchor)->next;
5603 *anchor = specifiers->attributes;
5604 if (attributes != NULL) {
5605 handle_entity_attributes(attributes, entity);
5607 entity->declaration.attributes = attributes;
5609 append_entity(&compound->members, entity);
5611 entity = parse_declarator(specifiers,
5612 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5613 source_position_t const *const pos = &entity->base.source_position;
5614 if (entity->kind == ENTITY_TYPEDEF) {
5615 errorf(pos, "typedef not allowed as compound member");
5617 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5619 /* make sure we don't define a symbol multiple times */
5620 symbol_t *symbol = entity->base.symbol;
5621 if (symbol != NULL) {
5622 entity_t *prev = find_compound_entry(compound, symbol);
5624 source_position_t const *const ppos = &prev->base.source_position;
5625 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5629 if (token.kind == ':') {
5630 parse_bitfield_member(entity);
5632 attribute_t *attributes = parse_attributes(NULL);
5633 handle_entity_attributes(attributes, entity);
5635 type_t *orig_type = entity->declaration.type;
5636 type_t *type = skip_typeref(orig_type);
5637 if (is_type_function(type)) {
5638 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5639 } else if (is_type_incomplete(type)) {
5640 /* §6.7.2.1:16 flexible array member */
5641 if (!is_type_array(type) ||
5642 token.kind != ';' ||
5643 look_ahead(1)->kind != '}') {
5644 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5645 } else if (compound->members.entities == NULL) {
5646 errorf(pos, "flexible array member in otherwise empty struct");
5651 append_entity(&compound->members, entity);
5654 } while (next_if(','));
5655 rem_anchor_token(',');
5656 rem_anchor_token(';');
5659 anonymous_entity = NULL;
5662 static void parse_compound_type_entries(compound_t *compound)
5665 add_anchor_token('}');
5668 switch (token.kind) {
5670 case T___extension__:
5671 case T_IDENTIFIER: {
5673 declaration_specifiers_t specifiers;
5674 parse_declaration_specifiers(&specifiers);
5675 parse_compound_declarators(compound, &specifiers);
5681 rem_anchor_token('}');
5684 compound->complete = true;
5690 static type_t *parse_typename(void)
5692 declaration_specifiers_t specifiers;
5693 parse_declaration_specifiers(&specifiers);
5694 if (specifiers.storage_class != STORAGE_CLASS_NONE
5695 || specifiers.thread_local) {
5696 /* TODO: improve error message, user does probably not know what a
5697 * storage class is...
5699 errorf(&specifiers.source_position, "typename must not have a storage class");
5702 type_t *result = parse_abstract_declarator(specifiers.type);
5710 typedef expression_t* (*parse_expression_function)(void);
5711 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5713 typedef struct expression_parser_function_t expression_parser_function_t;
5714 struct expression_parser_function_t {
5715 parse_expression_function parser;
5716 precedence_t infix_precedence;
5717 parse_expression_infix_function infix_parser;
5720 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5722 static type_t *get_string_type(void)
5724 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5727 static type_t *get_wide_string_type(void)
5729 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5733 * Parse a string constant.
5735 static expression_t *parse_string_literal(void)
5737 source_position_t begin = token.base.source_position;
5738 string_t res = token.string.string;
5739 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5742 while (token.kind == T_STRING_LITERAL
5743 || token.kind == T_WIDE_STRING_LITERAL) {
5744 warn_string_concat(&token.base.source_position);
5745 res = concat_strings(&res, &token.string.string);
5747 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5750 expression_t *literal;
5752 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5753 literal->base.type = get_wide_string_type();
5755 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5756 literal->base.type = get_string_type();
5758 literal->base.source_position = begin;
5759 literal->literal.value = res;
5765 * Parse a boolean constant.
5767 static expression_t *parse_boolean_literal(bool value)
5769 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5770 literal->base.type = type_bool;
5771 literal->literal.value.begin = value ? "true" : "false";
5772 literal->literal.value.size = value ? 4 : 5;
5778 static void warn_traditional_suffix(void)
5780 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5781 &token.number.suffix);
5784 static void check_integer_suffix(void)
5786 const string_t *suffix = &token.number.suffix;
5787 if (suffix->size == 0)
5790 bool not_traditional = false;
5791 const char *c = suffix->begin;
5792 if (*c == 'l' || *c == 'L') {
5795 not_traditional = true;
5797 if (*c == 'u' || *c == 'U') {
5800 } else if (*c == 'u' || *c == 'U') {
5801 not_traditional = true;
5804 } else if (*c == 'u' || *c == 'U') {
5805 not_traditional = true;
5807 if (*c == 'l' || *c == 'L') {
5815 errorf(&token.base.source_position,
5816 "invalid suffix '%S' on integer constant", suffix);
5817 } else if (not_traditional) {
5818 warn_traditional_suffix();
5822 static type_t *check_floatingpoint_suffix(void)
5824 const string_t *suffix = &token.number.suffix;
5825 type_t *type = type_double;
5826 if (suffix->size == 0)
5829 bool not_traditional = false;
5830 const char *c = suffix->begin;
5831 if (*c == 'f' || *c == 'F') {
5834 } else if (*c == 'l' || *c == 'L') {
5836 type = type_long_double;
5839 errorf(&token.base.source_position,
5840 "invalid suffix '%S' on floatingpoint constant", suffix);
5841 } else if (not_traditional) {
5842 warn_traditional_suffix();
5849 * Parse an integer constant.
5851 static expression_t *parse_number_literal(void)
5853 expression_kind_t kind;
5856 switch (token.kind) {
5858 case T_INTEGER_OCTAL:
5859 case T_INTEGER_HEXADECIMAL:
5860 kind = EXPR_LITERAL_INTEGER;
5861 check_integer_suffix();
5865 case T_FLOATINGPOINT:
5866 case T_FLOATINGPOINT_HEXADECIMAL:
5867 kind = EXPR_LITERAL_FLOATINGPOINT;
5868 type = check_floatingpoint_suffix();
5872 panic("unexpected token type in parse_number_literal");
5875 expression_t *literal = allocate_expression_zero(kind);
5876 literal->base.type = type;
5877 literal->literal.value = token.number.number;
5878 literal->literal.suffix = token.number.suffix;
5881 /* integer type depends on the size of the number and the size
5882 * representable by the types. The backend/codegeneration has to determine
5885 determine_literal_type(&literal->literal);
5890 * Parse a character constant.
5892 static expression_t *parse_character_constant(void)
5894 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5895 literal->base.type = c_mode & _CXX ? type_char : type_int;
5896 literal->literal.value = token.string.string;
5898 size_t len = literal->literal.value.size;
5900 if (!GNU_MODE && !(c_mode & _C99)) {
5901 errorf(HERE, "more than 1 character in character constant");
5903 literal->base.type = type_int;
5904 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5913 * Parse a wide character constant.
5915 static expression_t *parse_wide_character_constant(void)
5917 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5918 literal->base.type = type_int;
5919 literal->literal.value = token.string.string;
5921 size_t len = wstrlen(&literal->literal.value);
5923 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5930 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5932 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5933 ntype->function.return_type = type_int;
5934 ntype->function.unspecified_parameters = true;
5935 ntype->function.linkage = LINKAGE_C;
5936 type_t *type = identify_new_type(ntype);
5938 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5939 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5940 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5941 entity->declaration.type = type;
5942 entity->declaration.implicit = true;
5944 if (current_scope != NULL)
5945 record_entity(entity, false);
5951 * Performs automatic type cast as described in §6.3.2.1.
5953 * @param orig_type the original type
5955 static type_t *automatic_type_conversion(type_t *orig_type)
5957 type_t *type = skip_typeref(orig_type);
5958 if (is_type_array(type)) {
5959 array_type_t *array_type = &type->array;
5960 type_t *element_type = array_type->element_type;
5961 unsigned qualifiers = array_type->base.qualifiers;
5963 return make_pointer_type(element_type, qualifiers);
5966 if (is_type_function(type)) {
5967 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5974 * reverts the automatic casts of array to pointer types and function
5975 * to function-pointer types as defined §6.3.2.1
5977 type_t *revert_automatic_type_conversion(const expression_t *expression)
5979 switch (expression->kind) {
5980 case EXPR_REFERENCE: {
5981 entity_t *entity = expression->reference.entity;
5982 if (is_declaration(entity)) {
5983 return entity->declaration.type;
5984 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5985 return entity->enum_value.enum_type;
5987 panic("no declaration or enum in reference");
5992 entity_t *entity = expression->select.compound_entry;
5993 assert(is_declaration(entity));
5994 type_t *type = entity->declaration.type;
5995 return get_qualified_type(type, expression->base.type->base.qualifiers);
5998 case EXPR_UNARY_DEREFERENCE: {
5999 const expression_t *const value = expression->unary.value;
6000 type_t *const type = skip_typeref(value->base.type);
6001 if (!is_type_pointer(type))
6002 return type_error_type;
6003 return type->pointer.points_to;
6006 case EXPR_ARRAY_ACCESS: {
6007 const expression_t *array_ref = expression->array_access.array_ref;
6008 type_t *type_left = skip_typeref(array_ref->base.type);
6009 if (!is_type_pointer(type_left))
6010 return type_error_type;
6011 return type_left->pointer.points_to;
6014 case EXPR_STRING_LITERAL: {
6015 size_t size = expression->string_literal.value.size;
6016 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6019 case EXPR_WIDE_STRING_LITERAL: {
6020 size_t size = wstrlen(&expression->string_literal.value);
6021 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6024 case EXPR_COMPOUND_LITERAL:
6025 return expression->compound_literal.type;
6030 return expression->base.type;
6034 * Find an entity matching a symbol in a scope.
6035 * Uses current scope if scope is NULL
6037 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6038 namespace_tag_t namespc)
6040 if (scope == NULL) {
6041 return get_entity(symbol, namespc);
6044 /* we should optimize here, if scope grows above a certain size we should
6045 construct a hashmap here... */
6046 entity_t *entity = scope->entities;
6047 for ( ; entity != NULL; entity = entity->base.next) {
6048 if (entity->base.symbol == symbol
6049 && (namespace_tag_t)entity->base.namespc == namespc)
6056 static entity_t *parse_qualified_identifier(void)
6058 /* namespace containing the symbol */
6060 source_position_t pos;
6061 const scope_t *lookup_scope = NULL;
6063 if (next_if(T_COLONCOLON))
6064 lookup_scope = &unit->scope;
6068 symbol = expect_identifier("while parsing identifier", &pos);
6070 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6073 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6075 if (!next_if(T_COLONCOLON))
6078 switch (entity->kind) {
6079 case ENTITY_NAMESPACE:
6080 lookup_scope = &entity->namespacee.members;
6085 lookup_scope = &entity->compound.members;
6088 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6089 symbol, get_entity_kind_name(entity->kind));
6091 /* skip further qualifications */
6092 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6094 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6098 if (entity == NULL) {
6099 if (!strict_mode && token.kind == '(') {
6100 /* an implicitly declared function */
6101 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6102 "implicit declaration of function '%Y'", symbol);
6103 entity = create_implicit_function(symbol, &pos);
6105 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6106 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6113 static expression_t *parse_reference(void)
6115 source_position_t const pos = token.base.source_position;
6116 entity_t *const entity = parse_qualified_identifier();
6119 if (is_declaration(entity)) {
6120 orig_type = entity->declaration.type;
6121 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6122 orig_type = entity->enum_value.enum_type;
6124 panic("expected declaration or enum value in reference");
6127 /* we always do the auto-type conversions; the & and sizeof parser contains
6128 * code to revert this! */
6129 type_t *type = automatic_type_conversion(orig_type);
6131 expression_kind_t kind = EXPR_REFERENCE;
6132 if (entity->kind == ENTITY_ENUM_VALUE)
6133 kind = EXPR_ENUM_CONSTANT;
6135 expression_t *expression = allocate_expression_zero(kind);
6136 expression->base.source_position = pos;
6137 expression->base.type = type;
6138 expression->reference.entity = entity;
6140 /* this declaration is used */
6141 if (is_declaration(entity)) {
6142 entity->declaration.used = true;
6145 if (entity->base.parent_scope != file_scope
6146 && (current_function != NULL
6147 && entity->base.parent_scope->depth < current_function->parameters.depth)
6148 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6149 if (entity->kind == ENTITY_VARIABLE) {
6150 /* access of a variable from an outer function */
6151 entity->variable.address_taken = true;
6152 } else if (entity->kind == ENTITY_PARAMETER) {
6153 entity->parameter.address_taken = true;
6155 current_function->need_closure = true;
6158 check_deprecated(&pos, entity);
6163 static bool semantic_cast(expression_t *cast)
6165 expression_t *expression = cast->unary.value;
6166 type_t *orig_dest_type = cast->base.type;
6167 type_t *orig_type_right = expression->base.type;
6168 type_t const *dst_type = skip_typeref(orig_dest_type);
6169 type_t const *src_type = skip_typeref(orig_type_right);
6170 source_position_t const *pos = &cast->base.source_position;
6172 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6173 if (is_type_void(dst_type))
6176 /* only integer and pointer can be casted to pointer */
6177 if (is_type_pointer(dst_type) &&
6178 !is_type_pointer(src_type) &&
6179 !is_type_integer(src_type) &&
6180 is_type_valid(src_type)) {
6181 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6185 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6186 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6190 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6191 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6195 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6196 type_t *src = skip_typeref(src_type->pointer.points_to);
6197 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6198 unsigned missing_qualifiers =
6199 src->base.qualifiers & ~dst->base.qualifiers;
6200 if (missing_qualifiers != 0) {
6201 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6207 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6209 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6210 expression->base.source_position = *pos;
6212 parse_initializer_env_t env;
6215 env.must_be_constant = false;
6216 initializer_t *initializer = parse_initializer(&env);
6219 expression->compound_literal.initializer = initializer;
6220 expression->compound_literal.type = type;
6221 expression->base.type = automatic_type_conversion(type);
6227 * Parse a cast expression.
6229 static expression_t *parse_cast(void)
6231 source_position_t const pos = *HERE;
6234 add_anchor_token(')');
6236 type_t *type = parse_typename();
6238 rem_anchor_token(')');
6241 if (token.kind == '{') {
6242 return parse_compound_literal(&pos, type);
6245 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6246 cast->base.source_position = pos;
6248 expression_t *value = parse_subexpression(PREC_CAST);
6249 cast->base.type = type;
6250 cast->unary.value = value;
6252 if (! semantic_cast(cast)) {
6253 /* TODO: record the error in the AST. else it is impossible to detect it */
6260 * Parse a statement expression.
6262 static expression_t *parse_statement_expression(void)
6264 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6267 add_anchor_token(')');
6269 statement_t *statement = parse_compound_statement(true);
6270 statement->compound.stmt_expr = true;
6271 expression->statement.statement = statement;
6273 /* find last statement and use its type */
6274 type_t *type = type_void;
6275 const statement_t *stmt = statement->compound.statements;
6277 while (stmt->base.next != NULL)
6278 stmt = stmt->base.next;
6280 if (stmt->kind == STATEMENT_EXPRESSION) {
6281 type = stmt->expression.expression->base.type;
6284 source_position_t const *const pos = &expression->base.source_position;
6285 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6287 expression->base.type = type;
6289 rem_anchor_token(')');
6295 * Parse a parenthesized expression.
6297 static expression_t *parse_parenthesized_expression(void)
6299 token_t const* const la1 = look_ahead(1);
6300 switch (la1->kind) {
6302 /* gcc extension: a statement expression */
6303 return parse_statement_expression();
6306 if (is_typedef_symbol(la1->identifier.symbol)) {
6308 return parse_cast();
6313 add_anchor_token(')');
6314 expression_t *result = parse_expression();
6315 result->base.parenthesized = true;
6316 rem_anchor_token(')');
6322 static expression_t *parse_function_keyword(void)
6326 if (current_function == NULL) {
6327 errorf(HERE, "'__func__' used outside of a function");
6330 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6331 expression->base.type = type_char_ptr;
6332 expression->funcname.kind = FUNCNAME_FUNCTION;
6339 static expression_t *parse_pretty_function_keyword(void)
6341 if (current_function == NULL) {
6342 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6345 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6346 expression->base.type = type_char_ptr;
6347 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6349 eat(T___PRETTY_FUNCTION__);
6354 static expression_t *parse_funcsig_keyword(void)
6356 if (current_function == NULL) {
6357 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6360 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6361 expression->base.type = type_char_ptr;
6362 expression->funcname.kind = FUNCNAME_FUNCSIG;
6369 static expression_t *parse_funcdname_keyword(void)
6371 if (current_function == NULL) {
6372 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6375 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6376 expression->base.type = type_char_ptr;
6377 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6379 eat(T___FUNCDNAME__);
6384 static designator_t *parse_designator(void)
6386 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6387 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6388 if (!result->symbol)
6391 designator_t *last_designator = result;
6394 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6395 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6396 if (!designator->symbol)
6399 last_designator->next = designator;
6400 last_designator = designator;
6404 add_anchor_token(']');
6405 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6406 designator->source_position = *HERE;
6407 designator->array_index = parse_expression();
6408 rem_anchor_token(']');
6410 if (designator->array_index == NULL) {
6414 last_designator->next = designator;
6415 last_designator = designator;
6425 * Parse the __builtin_offsetof() expression.
6427 static expression_t *parse_offsetof(void)
6429 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6430 expression->base.type = type_size_t;
6432 eat(T___builtin_offsetof);
6435 add_anchor_token(')');
6436 add_anchor_token(',');
6437 type_t *type = parse_typename();
6438 rem_anchor_token(',');
6440 designator_t *designator = parse_designator();
6441 rem_anchor_token(')');
6444 expression->offsetofe.type = type;
6445 expression->offsetofe.designator = designator;
6448 memset(&path, 0, sizeof(path));
6449 path.top_type = type;
6450 path.path = NEW_ARR_F(type_path_entry_t, 0);
6452 descend_into_subtype(&path);
6454 if (!walk_designator(&path, designator, true)) {
6455 return create_error_expression();
6458 DEL_ARR_F(path.path);
6464 * Parses a _builtin_va_start() expression.
6466 static expression_t *parse_va_start(void)
6468 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6470 eat(T___builtin_va_start);
6473 add_anchor_token(')');
6474 add_anchor_token(',');
6475 expression->va_starte.ap = parse_assignment_expression();
6476 rem_anchor_token(',');
6478 expression_t *const expr = parse_assignment_expression();
6479 if (expr->kind == EXPR_REFERENCE) {
6480 entity_t *const entity = expr->reference.entity;
6481 if (!current_function->base.type->function.variadic) {
6482 errorf(&expr->base.source_position,
6483 "'va_start' used in non-variadic function");
6484 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6485 entity->base.next != NULL ||
6486 entity->kind != ENTITY_PARAMETER) {
6487 errorf(&expr->base.source_position,
6488 "second argument of 'va_start' must be last parameter of the current function");
6490 expression->va_starte.parameter = &entity->variable;
6493 expression = create_error_expression();
6495 rem_anchor_token(')');
6501 * Parses a __builtin_va_arg() expression.
6503 static expression_t *parse_va_arg(void)
6505 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6507 eat(T___builtin_va_arg);
6510 add_anchor_token(')');
6511 add_anchor_token(',');
6513 ap.expression = parse_assignment_expression();
6514 expression->va_arge.ap = ap.expression;
6515 check_call_argument(type_valist, &ap, 1);
6517 rem_anchor_token(',');
6519 expression->base.type = parse_typename();
6520 rem_anchor_token(')');
6527 * Parses a __builtin_va_copy() expression.
6529 static expression_t *parse_va_copy(void)
6531 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6533 eat(T___builtin_va_copy);
6536 add_anchor_token(')');
6537 add_anchor_token(',');
6538 expression_t *dst = parse_assignment_expression();
6539 assign_error_t error = semantic_assign(type_valist, dst);
6540 report_assign_error(error, type_valist, dst, "call argument 1",
6541 &dst->base.source_position);
6542 expression->va_copye.dst = dst;
6544 rem_anchor_token(',');
6547 call_argument_t src;
6548 src.expression = parse_assignment_expression();
6549 check_call_argument(type_valist, &src, 2);
6550 expression->va_copye.src = src.expression;
6551 rem_anchor_token(')');
6558 * Parses a __builtin_constant_p() expression.
6560 static expression_t *parse_builtin_constant(void)
6562 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6564 eat(T___builtin_constant_p);
6567 add_anchor_token(')');
6568 expression->builtin_constant.value = parse_assignment_expression();
6569 rem_anchor_token(')');
6571 expression->base.type = type_int;
6577 * Parses a __builtin_types_compatible_p() expression.
6579 static expression_t *parse_builtin_types_compatible(void)
6581 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6583 eat(T___builtin_types_compatible_p);
6586 add_anchor_token(')');
6587 add_anchor_token(',');
6588 expression->builtin_types_compatible.left = parse_typename();
6589 rem_anchor_token(',');
6591 expression->builtin_types_compatible.right = parse_typename();
6592 rem_anchor_token(')');
6594 expression->base.type = type_int;
6600 * Parses a __builtin_is_*() compare expression.
6602 static expression_t *parse_compare_builtin(void)
6604 expression_t *expression;
6606 switch (token.kind) {
6607 case T___builtin_isgreater:
6608 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6610 case T___builtin_isgreaterequal:
6611 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6613 case T___builtin_isless:
6614 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6616 case T___builtin_islessequal:
6617 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6619 case T___builtin_islessgreater:
6620 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6622 case T___builtin_isunordered:
6623 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6626 internal_errorf(HERE, "invalid compare builtin found");
6628 expression->base.source_position = *HERE;
6632 add_anchor_token(')');
6633 add_anchor_token(',');
6634 expression->binary.left = parse_assignment_expression();
6635 rem_anchor_token(',');
6637 expression->binary.right = parse_assignment_expression();
6638 rem_anchor_token(')');
6641 type_t *const orig_type_left = expression->binary.left->base.type;
6642 type_t *const orig_type_right = expression->binary.right->base.type;
6644 type_t *const type_left = skip_typeref(orig_type_left);
6645 type_t *const type_right = skip_typeref(orig_type_right);
6646 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6647 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6648 type_error_incompatible("invalid operands in comparison",
6649 &expression->base.source_position, orig_type_left, orig_type_right);
6652 semantic_comparison(&expression->binary);
6659 * Parses a MS assume() expression.
6661 static expression_t *parse_assume(void)
6663 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6668 add_anchor_token(')');
6669 expression->unary.value = parse_assignment_expression();
6670 rem_anchor_token(')');
6673 expression->base.type = type_void;
6678 * Return the label for the current symbol or create a new one.
6680 static label_t *get_label(void)
6682 assert(token.kind == T_IDENTIFIER);
6683 assert(current_function != NULL);
6685 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6686 /* If we find a local label, we already created the declaration. */
6687 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6688 if (label->base.parent_scope != current_scope) {
6689 assert(label->base.parent_scope->depth < current_scope->depth);
6690 current_function->goto_to_outer = true;
6692 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6693 /* There is no matching label in the same function, so create a new one. */
6694 source_position_t const nowhere = { NULL, 0, 0, false };
6695 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6700 return &label->label;
6704 * Parses a GNU && label address expression.
6706 static expression_t *parse_label_address(void)
6708 source_position_t source_position = token.base.source_position;
6710 if (token.kind != T_IDENTIFIER) {
6711 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6712 return create_error_expression();
6715 label_t *const label = get_label();
6717 label->address_taken = true;
6719 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6720 expression->base.source_position = source_position;
6722 /* label address is treated as a void pointer */
6723 expression->base.type = type_void_ptr;
6724 expression->label_address.label = label;
6729 * Parse a microsoft __noop expression.
6731 static expression_t *parse_noop_expression(void)
6733 /* the result is a (int)0 */
6734 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6735 literal->base.type = type_int;
6736 literal->literal.value.begin = "__noop";
6737 literal->literal.value.size = 6;
6741 if (token.kind == '(') {
6742 /* parse arguments */
6744 add_anchor_token(')');
6745 add_anchor_token(',');
6747 if (token.kind != ')') do {
6748 (void)parse_assignment_expression();
6749 } while (next_if(','));
6751 rem_anchor_token(',');
6752 rem_anchor_token(')');
6760 * Parses a primary expression.
6762 static expression_t *parse_primary_expression(void)
6764 switch (token.kind) {
6765 case T_false: return parse_boolean_literal(false);
6766 case T_true: return parse_boolean_literal(true);
6768 case T_INTEGER_OCTAL:
6769 case T_INTEGER_HEXADECIMAL:
6770 case T_FLOATINGPOINT:
6771 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6772 case T_CHARACTER_CONSTANT: return parse_character_constant();
6773 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6774 case T_STRING_LITERAL:
6775 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6776 case T___FUNCTION__:
6777 case T___func__: return parse_function_keyword();
6778 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6779 case T___FUNCSIG__: return parse_funcsig_keyword();
6780 case T___FUNCDNAME__: return parse_funcdname_keyword();
6781 case T___builtin_offsetof: return parse_offsetof();
6782 case T___builtin_va_start: return parse_va_start();
6783 case T___builtin_va_arg: return parse_va_arg();
6784 case T___builtin_va_copy: return parse_va_copy();
6785 case T___builtin_isgreater:
6786 case T___builtin_isgreaterequal:
6787 case T___builtin_isless:
6788 case T___builtin_islessequal:
6789 case T___builtin_islessgreater:
6790 case T___builtin_isunordered: return parse_compare_builtin();
6791 case T___builtin_constant_p: return parse_builtin_constant();
6792 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6793 case T__assume: return parse_assume();
6796 return parse_label_address();
6799 case '(': return parse_parenthesized_expression();
6800 case T___noop: return parse_noop_expression();
6802 /* Gracefully handle type names while parsing expressions. */
6804 return parse_reference();
6806 if (!is_typedef_symbol(token.identifier.symbol)) {
6807 return parse_reference();
6811 source_position_t const pos = *HERE;
6812 declaration_specifiers_t specifiers;
6813 parse_declaration_specifiers(&specifiers);
6814 type_t const *const type = parse_abstract_declarator(specifiers.type);
6815 errorf(&pos, "encountered type '%T' while parsing expression", type);
6816 return create_error_expression();
6820 errorf(HERE, "unexpected token %K, expected an expression", &token);
6822 return create_error_expression();
6825 static expression_t *parse_array_expression(expression_t *left)
6827 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6828 array_access_expression_t *const arr = &expr->array_access;
6831 add_anchor_token(']');
6833 expression_t *const inside = parse_expression();
6835 type_t *const orig_type_left = left->base.type;
6836 type_t *const orig_type_inside = inside->base.type;
6838 type_t *const type_left = skip_typeref(orig_type_left);
6839 type_t *const type_inside = skip_typeref(orig_type_inside);
6845 if (is_type_pointer(type_left)) {
6848 idx_type = type_inside;
6849 res_type = type_left->pointer.points_to;
6851 } else if (is_type_pointer(type_inside)) {
6852 arr->flipped = true;
6855 idx_type = type_left;
6856 res_type = type_inside->pointer.points_to;
6858 res_type = automatic_type_conversion(res_type);
6859 if (!is_type_integer(idx_type)) {
6860 errorf(&idx->base.source_position, "array subscript must have integer type");
6861 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6862 source_position_t const *const pos = &idx->base.source_position;
6863 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6866 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6867 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6869 res_type = type_error_type;
6874 arr->array_ref = ref;
6876 arr->base.type = res_type;
6878 rem_anchor_token(']');
6883 static bool is_bitfield(const expression_t *expression)
6885 return expression->kind == EXPR_SELECT
6886 && expression->select.compound_entry->compound_member.bitfield;
6889 static expression_t *parse_typeprop(expression_kind_t const kind)
6891 expression_t *tp_expression = allocate_expression_zero(kind);
6892 tp_expression->base.type = type_size_t;
6894 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6897 expression_t *expression;
6898 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6899 source_position_t const pos = *HERE;
6901 add_anchor_token(')');
6902 orig_type = parse_typename();
6903 rem_anchor_token(')');
6906 if (token.kind == '{') {
6907 /* It was not sizeof(type) after all. It is sizeof of an expression
6908 * starting with a compound literal */
6909 expression = parse_compound_literal(&pos, orig_type);
6910 goto typeprop_expression;
6913 expression = parse_subexpression(PREC_UNARY);
6915 typeprop_expression:
6916 if (is_bitfield(expression)) {
6917 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6918 errorf(&tp_expression->base.source_position,
6919 "operand of %s expression must not be a bitfield", what);
6922 tp_expression->typeprop.tp_expression = expression;
6924 orig_type = revert_automatic_type_conversion(expression);
6925 expression->base.type = orig_type;
6928 tp_expression->typeprop.type = orig_type;
6929 type_t const* const type = skip_typeref(orig_type);
6930 char const* wrong_type = NULL;
6931 if (is_type_incomplete(type)) {
6932 if (!is_type_void(type) || !GNU_MODE)
6933 wrong_type = "incomplete";
6934 } else if (type->kind == TYPE_FUNCTION) {
6936 /* function types are allowed (and return 1) */
6937 source_position_t const *const pos = &tp_expression->base.source_position;
6938 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6939 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6941 wrong_type = "function";
6945 if (wrong_type != NULL) {
6946 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6947 errorf(&tp_expression->base.source_position,
6948 "operand of %s expression must not be of %s type '%T'",
6949 what, wrong_type, orig_type);
6952 return tp_expression;
6955 static expression_t *parse_sizeof(void)
6957 return parse_typeprop(EXPR_SIZEOF);
6960 static expression_t *parse_alignof(void)
6962 return parse_typeprop(EXPR_ALIGNOF);
6965 static expression_t *parse_select_expression(expression_t *addr)
6967 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6968 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6969 source_position_t const pos = *HERE;
6972 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6974 return create_error_expression();
6976 type_t *const orig_type = addr->base.type;
6977 type_t *const type = skip_typeref(orig_type);
6980 bool saw_error = false;
6981 if (is_type_pointer(type)) {
6982 if (!select_left_arrow) {
6984 "request for member '%Y' in something not a struct or union, but '%T'",
6988 type_left = skip_typeref(type->pointer.points_to);
6990 if (select_left_arrow && is_type_valid(type)) {
6991 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6997 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6998 type_left->kind != TYPE_COMPOUND_UNION) {
7000 if (is_type_valid(type_left) && !saw_error) {
7002 "request for member '%Y' in something not a struct or union, but '%T'",
7005 return create_error_expression();
7008 compound_t *compound = type_left->compound.compound;
7009 if (!compound->complete) {
7010 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7012 return create_error_expression();
7015 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7016 expression_t *result =
7017 find_create_select(&pos, addr, qualifiers, compound, symbol);
7019 if (result == NULL) {
7020 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7021 return create_error_expression();
7027 static void check_call_argument(type_t *expected_type,
7028 call_argument_t *argument, unsigned pos)
7030 type_t *expected_type_skip = skip_typeref(expected_type);
7031 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7032 expression_t *arg_expr = argument->expression;
7033 type_t *arg_type = skip_typeref(arg_expr->base.type);
7035 /* handle transparent union gnu extension */
7036 if (is_type_union(expected_type_skip)
7037 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7038 compound_t *union_decl = expected_type_skip->compound.compound;
7039 type_t *best_type = NULL;
7040 entity_t *entry = union_decl->members.entities;
7041 for ( ; entry != NULL; entry = entry->base.next) {
7042 assert(is_declaration(entry));
7043 type_t *decl_type = entry->declaration.type;
7044 error = semantic_assign(decl_type, arg_expr);
7045 if (error == ASSIGN_ERROR_INCOMPATIBLE
7046 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7049 if (error == ASSIGN_SUCCESS) {
7050 best_type = decl_type;
7051 } else if (best_type == NULL) {
7052 best_type = decl_type;
7056 if (best_type != NULL) {
7057 expected_type = best_type;
7061 error = semantic_assign(expected_type, arg_expr);
7062 argument->expression = create_implicit_cast(arg_expr, expected_type);
7064 if (error != ASSIGN_SUCCESS) {
7065 /* report exact scope in error messages (like "in argument 3") */
7067 snprintf(buf, sizeof(buf), "call argument %u", pos);
7068 report_assign_error(error, expected_type, arg_expr, buf,
7069 &arg_expr->base.source_position);
7071 type_t *const promoted_type = get_default_promoted_type(arg_type);
7072 if (!types_compatible(expected_type_skip, promoted_type) &&
7073 !types_compatible(expected_type_skip, type_void_ptr) &&
7074 !types_compatible(type_void_ptr, promoted_type)) {
7075 /* Deliberately show the skipped types in this warning */
7076 source_position_t const *const apos = &arg_expr->base.source_position;
7077 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7083 * Handle the semantic restrictions of builtin calls
7085 static void handle_builtin_argument_restrictions(call_expression_t *call)
7087 entity_t *entity = call->function->reference.entity;
7088 switch (entity->function.btk) {
7090 switch (entity->function.b.firm_builtin_kind) {
7091 case ir_bk_return_address:
7092 case ir_bk_frame_address: {
7093 /* argument must be constant */
7094 call_argument_t *argument = call->arguments;
7096 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7097 errorf(&call->base.source_position,
7098 "argument of '%Y' must be a constant expression",
7099 call->function->reference.entity->base.symbol);
7103 case ir_bk_prefetch:
7104 /* second and third argument must be constant if existent */
7105 if (call->arguments == NULL)
7107 call_argument_t *rw = call->arguments->next;
7108 call_argument_t *locality = NULL;
7111 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7112 errorf(&call->base.source_position,
7113 "second argument of '%Y' must be a constant expression",
7114 call->function->reference.entity->base.symbol);
7116 locality = rw->next;
7118 if (locality != NULL) {
7119 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7120 errorf(&call->base.source_position,
7121 "third argument of '%Y' must be a constant expression",
7122 call->function->reference.entity->base.symbol);
7124 locality = rw->next;
7131 case BUILTIN_OBJECT_SIZE:
7132 if (call->arguments == NULL)
7135 call_argument_t *arg = call->arguments->next;
7136 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7137 errorf(&call->base.source_position,
7138 "second argument of '%Y' must be a constant expression",
7139 call->function->reference.entity->base.symbol);
7148 * Parse a call expression, ie. expression '( ... )'.
7150 * @param expression the function address
7152 static expression_t *parse_call_expression(expression_t *expression)
7154 expression_t *result = allocate_expression_zero(EXPR_CALL);
7155 call_expression_t *call = &result->call;
7156 call->function = expression;
7158 type_t *const orig_type = expression->base.type;
7159 type_t *const type = skip_typeref(orig_type);
7161 function_type_t *function_type = NULL;
7162 if (is_type_pointer(type)) {
7163 type_t *const to_type = skip_typeref(type->pointer.points_to);
7165 if (is_type_function(to_type)) {
7166 function_type = &to_type->function;
7167 call->base.type = function_type->return_type;
7171 if (function_type == NULL && is_type_valid(type)) {
7173 "called object '%E' (type '%T') is not a pointer to a function",
7174 expression, orig_type);
7177 /* parse arguments */
7179 add_anchor_token(')');
7180 add_anchor_token(',');
7182 if (token.kind != ')') {
7183 call_argument_t **anchor = &call->arguments;
7185 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7186 argument->expression = parse_assignment_expression();
7189 anchor = &argument->next;
7190 } while (next_if(','));
7192 rem_anchor_token(',');
7193 rem_anchor_token(')');
7196 if (function_type == NULL)
7199 /* check type and count of call arguments */
7200 function_parameter_t *parameter = function_type->parameters;
7201 call_argument_t *argument = call->arguments;
7202 if (!function_type->unspecified_parameters) {
7203 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7204 parameter = parameter->next, argument = argument->next) {
7205 check_call_argument(parameter->type, argument, ++pos);
7208 if (parameter != NULL) {
7209 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7210 } else if (argument != NULL && !function_type->variadic) {
7211 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7215 /* do default promotion for other arguments */
7216 for (; argument != NULL; argument = argument->next) {
7217 type_t *argument_type = argument->expression->base.type;
7218 if (!is_type_object(skip_typeref(argument_type))) {
7219 errorf(&argument->expression->base.source_position,
7220 "call argument '%E' must not be void", argument->expression);
7223 argument_type = get_default_promoted_type(argument_type);
7225 argument->expression
7226 = create_implicit_cast(argument->expression, argument_type);
7231 if (is_type_compound(skip_typeref(function_type->return_type))) {
7232 source_position_t const *const pos = &expression->base.source_position;
7233 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7236 if (expression->kind == EXPR_REFERENCE) {
7237 reference_expression_t *reference = &expression->reference;
7238 if (reference->entity->kind == ENTITY_FUNCTION &&
7239 reference->entity->function.btk != BUILTIN_NONE)
7240 handle_builtin_argument_restrictions(call);
7246 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7248 static bool same_compound_type(const type_t *type1, const type_t *type2)
7251 is_type_compound(type1) &&
7252 type1->kind == type2->kind &&
7253 type1->compound.compound == type2->compound.compound;
7256 static expression_t const *get_reference_address(expression_t const *expr)
7258 bool regular_take_address = true;
7260 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7261 expr = expr->unary.value;
7263 regular_take_address = false;
7266 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7269 expr = expr->unary.value;
7272 if (expr->kind != EXPR_REFERENCE)
7275 /* special case for functions which are automatically converted to a
7276 * pointer to function without an extra TAKE_ADDRESS operation */
7277 if (!regular_take_address &&
7278 expr->reference.entity->kind != ENTITY_FUNCTION) {
7285 static void warn_reference_address_as_bool(expression_t const* expr)
7287 expr = get_reference_address(expr);
7289 source_position_t const *const pos = &expr->base.source_position;
7290 entity_t const *const ent = expr->reference.entity;
7291 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7295 static void warn_assignment_in_condition(const expression_t *const expr)
7297 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7299 if (expr->base.parenthesized)
7301 source_position_t const *const pos = &expr->base.source_position;
7302 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7305 static void semantic_condition(expression_t const *const expr,
7306 char const *const context)
7308 type_t *const type = skip_typeref(expr->base.type);
7309 if (is_type_scalar(type)) {
7310 warn_reference_address_as_bool(expr);
7311 warn_assignment_in_condition(expr);
7312 } else if (is_type_valid(type)) {
7313 errorf(&expr->base.source_position,
7314 "%s must have scalar type", context);
7319 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7321 * @param expression the conditional expression
7323 static expression_t *parse_conditional_expression(expression_t *expression)
7325 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7327 conditional_expression_t *conditional = &result->conditional;
7328 conditional->condition = expression;
7331 add_anchor_token(':');
7333 /* §6.5.15:2 The first operand shall have scalar type. */
7334 semantic_condition(expression, "condition of conditional operator");
7336 expression_t *true_expression = expression;
7337 bool gnu_cond = false;
7338 if (GNU_MODE && token.kind == ':') {
7341 true_expression = parse_expression();
7343 rem_anchor_token(':');
7345 expression_t *false_expression =
7346 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7348 type_t *const orig_true_type = true_expression->base.type;
7349 type_t *const orig_false_type = false_expression->base.type;
7350 type_t *const true_type = skip_typeref(orig_true_type);
7351 type_t *const false_type = skip_typeref(orig_false_type);
7354 source_position_t const *const pos = &conditional->base.source_position;
7355 type_t *result_type;
7356 if (is_type_void(true_type) || is_type_void(false_type)) {
7357 /* ISO/IEC 14882:1998(E) §5.16:2 */
7358 if (true_expression->kind == EXPR_UNARY_THROW) {
7359 result_type = false_type;
7360 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7361 result_type = true_type;
7363 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7364 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7366 result_type = type_void;
7368 } else if (is_type_arithmetic(true_type)
7369 && is_type_arithmetic(false_type)) {
7370 result_type = semantic_arithmetic(true_type, false_type);
7371 } else if (same_compound_type(true_type, false_type)) {
7372 /* just take 1 of the 2 types */
7373 result_type = true_type;
7374 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7375 type_t *pointer_type;
7377 expression_t *other_expression;
7378 if (is_type_pointer(true_type) &&
7379 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7380 pointer_type = true_type;
7381 other_type = false_type;
7382 other_expression = false_expression;
7384 pointer_type = false_type;
7385 other_type = true_type;
7386 other_expression = true_expression;
7389 if (is_null_pointer_constant(other_expression)) {
7390 result_type = pointer_type;
7391 } else if (is_type_pointer(other_type)) {
7392 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7393 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7396 if (is_type_void(to1) || is_type_void(to2)) {
7398 } else if (types_compatible(get_unqualified_type(to1),
7399 get_unqualified_type(to2))) {
7402 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7406 type_t *const type =
7407 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7408 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7409 } else if (is_type_integer(other_type)) {
7410 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7411 result_type = pointer_type;
7413 goto types_incompatible;
7417 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7418 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7420 result_type = type_error_type;
7423 conditional->true_expression
7424 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7425 conditional->false_expression
7426 = create_implicit_cast(false_expression, result_type);
7427 conditional->base.type = result_type;
7432 * Parse an extension expression.
7434 static expression_t *parse_extension(void)
7437 expression_t *expression = parse_subexpression(PREC_UNARY);
7443 * Parse a __builtin_classify_type() expression.
7445 static expression_t *parse_builtin_classify_type(void)
7447 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7448 result->base.type = type_int;
7450 eat(T___builtin_classify_type);
7453 add_anchor_token(')');
7454 expression_t *expression = parse_expression();
7455 rem_anchor_token(')');
7457 result->classify_type.type_expression = expression;
7463 * Parse a delete expression
7464 * ISO/IEC 14882:1998(E) §5.3.5
7466 static expression_t *parse_delete(void)
7468 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7469 result->base.type = type_void;
7474 result->kind = EXPR_UNARY_DELETE_ARRAY;
7478 expression_t *const value = parse_subexpression(PREC_CAST);
7479 result->unary.value = value;
7481 type_t *const type = skip_typeref(value->base.type);
7482 if (!is_type_pointer(type)) {
7483 if (is_type_valid(type)) {
7484 errorf(&value->base.source_position,
7485 "operand of delete must have pointer type");
7487 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7488 source_position_t const *const pos = &value->base.source_position;
7489 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7496 * Parse a throw expression
7497 * ISO/IEC 14882:1998(E) §15:1
7499 static expression_t *parse_throw(void)
7501 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7502 result->base.type = type_void;
7506 expression_t *value = NULL;
7507 switch (token.kind) {
7509 value = parse_assignment_expression();
7510 /* ISO/IEC 14882:1998(E) §15.1:3 */
7511 type_t *const orig_type = value->base.type;
7512 type_t *const type = skip_typeref(orig_type);
7513 if (is_type_incomplete(type)) {
7514 errorf(&value->base.source_position,
7515 "cannot throw object of incomplete type '%T'", orig_type);
7516 } else if (is_type_pointer(type)) {
7517 type_t *const points_to = skip_typeref(type->pointer.points_to);
7518 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7519 errorf(&value->base.source_position,
7520 "cannot throw pointer to incomplete type '%T'", orig_type);
7528 result->unary.value = value;
7533 static bool check_pointer_arithmetic(const source_position_t *source_position,
7534 type_t *pointer_type,
7535 type_t *orig_pointer_type)
7537 type_t *points_to = pointer_type->pointer.points_to;
7538 points_to = skip_typeref(points_to);
7540 if (is_type_incomplete(points_to)) {
7541 if (!GNU_MODE || !is_type_void(points_to)) {
7542 errorf(source_position,
7543 "arithmetic with pointer to incomplete type '%T' not allowed",
7547 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7549 } else if (is_type_function(points_to)) {
7551 errorf(source_position,
7552 "arithmetic with pointer to function type '%T' not allowed",
7556 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7562 static bool is_lvalue(const expression_t *expression)
7564 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7565 switch (expression->kind) {
7566 case EXPR_ARRAY_ACCESS:
7567 case EXPR_COMPOUND_LITERAL:
7568 case EXPR_REFERENCE:
7570 case EXPR_UNARY_DEREFERENCE:
7574 type_t *type = skip_typeref(expression->base.type);
7576 /* ISO/IEC 14882:1998(E) §3.10:3 */
7577 is_type_reference(type) ||
7578 /* Claim it is an lvalue, if the type is invalid. There was a parse
7579 * error before, which maybe prevented properly recognizing it as
7581 !is_type_valid(type);
7586 static void semantic_incdec(unary_expression_t *expression)
7588 type_t *const orig_type = expression->value->base.type;
7589 type_t *const type = skip_typeref(orig_type);
7590 if (is_type_pointer(type)) {
7591 if (!check_pointer_arithmetic(&expression->base.source_position,
7595 } else if (!is_type_real(type) && is_type_valid(type)) {
7596 /* TODO: improve error message */
7597 errorf(&expression->base.source_position,
7598 "operation needs an arithmetic or pointer type");
7601 if (!is_lvalue(expression->value)) {
7602 /* TODO: improve error message */
7603 errorf(&expression->base.source_position, "lvalue required as operand");
7605 expression->base.type = orig_type;
7608 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7610 type_t *const res_type = promote_integer(type);
7611 expr->base.type = res_type;
7612 expr->value = create_implicit_cast(expr->value, res_type);
7615 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7617 type_t *const orig_type = expression->value->base.type;
7618 type_t *const type = skip_typeref(orig_type);
7619 if (!is_type_arithmetic(type)) {
7620 if (is_type_valid(type)) {
7621 /* TODO: improve error message */
7622 errorf(&expression->base.source_position,
7623 "operation needs an arithmetic type");
7626 } else if (is_type_integer(type)) {
7627 promote_unary_int_expr(expression, type);
7629 expression->base.type = orig_type;
7633 static void semantic_unexpr_plus(unary_expression_t *expression)
7635 semantic_unexpr_arithmetic(expression);
7636 source_position_t const *const pos = &expression->base.source_position;
7637 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7640 static void semantic_not(unary_expression_t *expression)
7642 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7643 semantic_condition(expression->value, "operand of !");
7644 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7647 static void semantic_unexpr_integer(unary_expression_t *expression)
7649 type_t *const orig_type = expression->value->base.type;
7650 type_t *const type = skip_typeref(orig_type);
7651 if (!is_type_integer(type)) {
7652 if (is_type_valid(type)) {
7653 errorf(&expression->base.source_position,
7654 "operand of ~ must be of integer type");
7659 promote_unary_int_expr(expression, type);
7662 static void semantic_dereference(unary_expression_t *expression)
7664 type_t *const orig_type = expression->value->base.type;
7665 type_t *const type = skip_typeref(orig_type);
7666 if (!is_type_pointer(type)) {
7667 if (is_type_valid(type)) {
7668 errorf(&expression->base.source_position,
7669 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7674 type_t *result_type = type->pointer.points_to;
7675 result_type = automatic_type_conversion(result_type);
7676 expression->base.type = result_type;
7680 * Record that an address is taken (expression represents an lvalue).
7682 * @param expression the expression
7683 * @param may_be_register if true, the expression might be an register
7685 static void set_address_taken(expression_t *expression, bool may_be_register)
7687 if (expression->kind != EXPR_REFERENCE)
7690 entity_t *const entity = expression->reference.entity;
7692 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7695 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7696 && !may_be_register) {
7697 source_position_t const *const pos = &expression->base.source_position;
7698 errorf(pos, "address of register '%N' requested", entity);
7701 if (entity->kind == ENTITY_VARIABLE) {
7702 entity->variable.address_taken = true;
7704 assert(entity->kind == ENTITY_PARAMETER);
7705 entity->parameter.address_taken = true;
7710 * Check the semantic of the address taken expression.
7712 static void semantic_take_addr(unary_expression_t *expression)
7714 expression_t *value = expression->value;
7715 value->base.type = revert_automatic_type_conversion(value);
7717 type_t *orig_type = value->base.type;
7718 type_t *type = skip_typeref(orig_type);
7719 if (!is_type_valid(type))
7723 if (!is_lvalue(value)) {
7724 errorf(&expression->base.source_position, "'&' requires an lvalue");
7726 if (is_bitfield(value)) {
7727 errorf(&expression->base.source_position,
7728 "'&' not allowed on bitfield");
7731 set_address_taken(value, false);
7733 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7736 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7737 static expression_t *parse_##unexpression_type(void) \
7739 expression_t *unary_expression \
7740 = allocate_expression_zero(unexpression_type); \
7742 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7744 sfunc(&unary_expression->unary); \
7746 return unary_expression; \
7749 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7750 semantic_unexpr_arithmetic)
7751 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7752 semantic_unexpr_plus)
7753 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7755 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7756 semantic_dereference)
7757 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7759 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7760 semantic_unexpr_integer)
7761 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7763 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7766 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7768 static expression_t *parse_##unexpression_type(expression_t *left) \
7770 expression_t *unary_expression \
7771 = allocate_expression_zero(unexpression_type); \
7773 unary_expression->unary.value = left; \
7775 sfunc(&unary_expression->unary); \
7777 return unary_expression; \
7780 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7781 EXPR_UNARY_POSTFIX_INCREMENT,
7783 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7784 EXPR_UNARY_POSTFIX_DECREMENT,
7787 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7789 /* TODO: handle complex + imaginary types */
7791 type_left = get_unqualified_type(type_left);
7792 type_right = get_unqualified_type(type_right);
7794 /* §6.3.1.8 Usual arithmetic conversions */
7795 if (type_left == type_long_double || type_right == type_long_double) {
7796 return type_long_double;
7797 } else if (type_left == type_double || type_right == type_double) {
7799 } else if (type_left == type_float || type_right == type_float) {
7803 type_left = promote_integer(type_left);
7804 type_right = promote_integer(type_right);
7806 if (type_left == type_right)
7809 bool const signed_left = is_type_signed(type_left);
7810 bool const signed_right = is_type_signed(type_right);
7811 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7812 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7814 if (signed_left == signed_right)
7815 return rank_left >= rank_right ? type_left : type_right;
7819 atomic_type_kind_t s_akind;
7820 atomic_type_kind_t u_akind;
7825 u_type = type_right;
7827 s_type = type_right;
7830 s_akind = get_akind(s_type);
7831 u_akind = get_akind(u_type);
7832 s_rank = get_akind_rank(s_akind);
7833 u_rank = get_akind_rank(u_akind);
7835 if (u_rank >= s_rank)
7838 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7842 case ATOMIC_TYPE_INT: return type_unsigned_int;
7843 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7844 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7846 default: panic("invalid atomic type");
7851 * Check the semantic restrictions for a binary expression.
7853 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7855 expression_t *const left = expression->left;
7856 expression_t *const right = expression->right;
7857 type_t *const orig_type_left = left->base.type;
7858 type_t *const orig_type_right = right->base.type;
7859 type_t *const type_left = skip_typeref(orig_type_left);
7860 type_t *const type_right = skip_typeref(orig_type_right);
7862 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7863 /* TODO: improve error message */
7864 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7865 errorf(&expression->base.source_position,
7866 "operation needs arithmetic types");
7871 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7872 expression->left = create_implicit_cast(left, arithmetic_type);
7873 expression->right = create_implicit_cast(right, arithmetic_type);
7874 expression->base.type = arithmetic_type;
7877 static void semantic_binexpr_integer(binary_expression_t *const expression)
7879 expression_t *const left = expression->left;
7880 expression_t *const right = expression->right;
7881 type_t *const orig_type_left = left->base.type;
7882 type_t *const orig_type_right = right->base.type;
7883 type_t *const type_left = skip_typeref(orig_type_left);
7884 type_t *const type_right = skip_typeref(orig_type_right);
7886 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7887 /* TODO: improve error message */
7888 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7889 errorf(&expression->base.source_position,
7890 "operation needs integer types");
7895 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7896 expression->left = create_implicit_cast(left, result_type);
7897 expression->right = create_implicit_cast(right, result_type);
7898 expression->base.type = result_type;
7901 static void warn_div_by_zero(binary_expression_t const *const expression)
7903 if (!is_type_integer(expression->base.type))
7906 expression_t const *const right = expression->right;
7907 /* The type of the right operand can be different for /= */
7908 if (is_type_integer(right->base.type) &&
7909 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7910 !fold_constant_to_bool(right)) {
7911 source_position_t const *const pos = &expression->base.source_position;
7912 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7917 * Check the semantic restrictions for a div/mod expression.
7919 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7921 semantic_binexpr_arithmetic(expression);
7922 warn_div_by_zero(expression);
7925 static void warn_addsub_in_shift(const expression_t *const expr)
7927 if (expr->base.parenthesized)
7931 switch (expr->kind) {
7932 case EXPR_BINARY_ADD: op = '+'; break;
7933 case EXPR_BINARY_SUB: op = '-'; break;
7937 source_position_t const *const pos = &expr->base.source_position;
7938 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7941 static bool semantic_shift(binary_expression_t *expression)
7943 expression_t *const left = expression->left;
7944 expression_t *const right = expression->right;
7945 type_t *const orig_type_left = left->base.type;
7946 type_t *const orig_type_right = right->base.type;
7947 type_t * type_left = skip_typeref(orig_type_left);
7948 type_t * type_right = skip_typeref(orig_type_right);
7950 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7951 /* TODO: improve error message */
7952 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7953 errorf(&expression->base.source_position,
7954 "operands of shift operation must have integer types");
7959 type_left = promote_integer(type_left);
7961 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7962 source_position_t const *const pos = &right->base.source_position;
7963 long const count = fold_constant_to_int(right);
7965 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7966 } else if ((unsigned long)count >=
7967 get_atomic_type_size(type_left->atomic.akind) * 8) {
7968 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7972 type_right = promote_integer(type_right);
7973 expression->right = create_implicit_cast(right, type_right);
7978 static void semantic_shift_op(binary_expression_t *expression)
7980 expression_t *const left = expression->left;
7981 expression_t *const right = expression->right;
7983 if (!semantic_shift(expression))
7986 warn_addsub_in_shift(left);
7987 warn_addsub_in_shift(right);
7989 type_t *const orig_type_left = left->base.type;
7990 type_t * type_left = skip_typeref(orig_type_left);
7992 type_left = promote_integer(type_left);
7993 expression->left = create_implicit_cast(left, type_left);
7994 expression->base.type = type_left;
7997 static void semantic_add(binary_expression_t *expression)
7999 expression_t *const left = expression->left;
8000 expression_t *const right = expression->right;
8001 type_t *const orig_type_left = left->base.type;
8002 type_t *const orig_type_right = right->base.type;
8003 type_t *const type_left = skip_typeref(orig_type_left);
8004 type_t *const type_right = skip_typeref(orig_type_right);
8007 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8008 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8009 expression->left = create_implicit_cast(left, arithmetic_type);
8010 expression->right = create_implicit_cast(right, arithmetic_type);
8011 expression->base.type = arithmetic_type;
8012 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8013 check_pointer_arithmetic(&expression->base.source_position,
8014 type_left, orig_type_left);
8015 expression->base.type = type_left;
8016 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8017 check_pointer_arithmetic(&expression->base.source_position,
8018 type_right, orig_type_right);
8019 expression->base.type = type_right;
8020 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8021 errorf(&expression->base.source_position,
8022 "invalid operands to binary + ('%T', '%T')",
8023 orig_type_left, orig_type_right);
8027 static void semantic_sub(binary_expression_t *expression)
8029 expression_t *const left = expression->left;
8030 expression_t *const right = expression->right;
8031 type_t *const orig_type_left = left->base.type;
8032 type_t *const orig_type_right = right->base.type;
8033 type_t *const type_left = skip_typeref(orig_type_left);
8034 type_t *const type_right = skip_typeref(orig_type_right);
8035 source_position_t const *const pos = &expression->base.source_position;
8038 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8039 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8040 expression->left = create_implicit_cast(left, arithmetic_type);
8041 expression->right = create_implicit_cast(right, arithmetic_type);
8042 expression->base.type = arithmetic_type;
8043 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8044 check_pointer_arithmetic(&expression->base.source_position,
8045 type_left, orig_type_left);
8046 expression->base.type = type_left;
8047 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8048 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8049 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8050 if (!types_compatible(unqual_left, unqual_right)) {
8052 "subtracting pointers to incompatible types '%T' and '%T'",
8053 orig_type_left, orig_type_right);
8054 } else if (!is_type_object(unqual_left)) {
8055 if (!is_type_void(unqual_left)) {
8056 errorf(pos, "subtracting pointers to non-object types '%T'",
8059 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8062 expression->base.type = type_ptrdiff_t;
8063 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8064 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8065 orig_type_left, orig_type_right);
8069 static void warn_string_literal_address(expression_t const* expr)
8071 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8072 expr = expr->unary.value;
8073 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8075 expr = expr->unary.value;
8078 if (expr->kind == EXPR_STRING_LITERAL
8079 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8080 source_position_t const *const pos = &expr->base.source_position;
8081 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8085 static bool maybe_negative(expression_t const *const expr)
8087 switch (is_constant_expression(expr)) {
8088 case EXPR_CLASS_ERROR: return false;
8089 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8090 default: return true;
8094 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8096 warn_string_literal_address(expr);
8098 expression_t const* const ref = get_reference_address(expr);
8099 if (ref != NULL && is_null_pointer_constant(other)) {
8100 entity_t const *const ent = ref->reference.entity;
8101 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8104 if (!expr->base.parenthesized) {
8105 switch (expr->base.kind) {
8106 case EXPR_BINARY_LESS:
8107 case EXPR_BINARY_GREATER:
8108 case EXPR_BINARY_LESSEQUAL:
8109 case EXPR_BINARY_GREATEREQUAL:
8110 case EXPR_BINARY_NOTEQUAL:
8111 case EXPR_BINARY_EQUAL:
8112 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8121 * Check the semantics of comparison expressions.
8123 * @param expression The expression to check.
8125 static void semantic_comparison(binary_expression_t *expression)
8127 source_position_t const *const pos = &expression->base.source_position;
8128 expression_t *const left = expression->left;
8129 expression_t *const right = expression->right;
8131 warn_comparison(pos, left, right);
8132 warn_comparison(pos, right, left);
8134 type_t *orig_type_left = left->base.type;
8135 type_t *orig_type_right = right->base.type;
8136 type_t *type_left = skip_typeref(orig_type_left);
8137 type_t *type_right = skip_typeref(orig_type_right);
8139 /* TODO non-arithmetic types */
8140 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8141 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8143 /* test for signed vs unsigned compares */
8144 if (is_type_integer(arithmetic_type)) {
8145 bool const signed_left = is_type_signed(type_left);
8146 bool const signed_right = is_type_signed(type_right);
8147 if (signed_left != signed_right) {
8148 /* FIXME long long needs better const folding magic */
8149 /* TODO check whether constant value can be represented by other type */
8150 if ((signed_left && maybe_negative(left)) ||
8151 (signed_right && maybe_negative(right))) {
8152 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8157 expression->left = create_implicit_cast(left, arithmetic_type);
8158 expression->right = create_implicit_cast(right, arithmetic_type);
8159 expression->base.type = arithmetic_type;
8160 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8161 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8162 is_type_float(arithmetic_type)) {
8163 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8165 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8166 /* TODO check compatibility */
8167 } else if (is_type_pointer(type_left)) {
8168 expression->right = create_implicit_cast(right, type_left);
8169 } else if (is_type_pointer(type_right)) {
8170 expression->left = create_implicit_cast(left, type_right);
8171 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8172 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8174 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8178 * Checks if a compound type has constant fields.
8180 static bool has_const_fields(const compound_type_t *type)
8182 compound_t *compound = type->compound;
8183 entity_t *entry = compound->members.entities;
8185 for (; entry != NULL; entry = entry->base.next) {
8186 if (!is_declaration(entry))
8189 const type_t *decl_type = skip_typeref(entry->declaration.type);
8190 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8197 static bool is_valid_assignment_lhs(expression_t const* const left)
8199 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8200 type_t *const type_left = skip_typeref(orig_type_left);
8202 if (!is_lvalue(left)) {
8203 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8208 if (left->kind == EXPR_REFERENCE
8209 && left->reference.entity->kind == ENTITY_FUNCTION) {
8210 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8214 if (is_type_array(type_left)) {
8215 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8218 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8219 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8223 if (is_type_incomplete(type_left)) {
8224 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8225 left, orig_type_left);
8228 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8229 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8230 left, orig_type_left);
8237 static void semantic_arithmetic_assign(binary_expression_t *expression)
8239 expression_t *left = expression->left;
8240 expression_t *right = expression->right;
8241 type_t *orig_type_left = left->base.type;
8242 type_t *orig_type_right = right->base.type;
8244 if (!is_valid_assignment_lhs(left))
8247 type_t *type_left = skip_typeref(orig_type_left);
8248 type_t *type_right = skip_typeref(orig_type_right);
8250 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8251 /* TODO: improve error message */
8252 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8253 errorf(&expression->base.source_position,
8254 "operation needs arithmetic types");
8259 /* combined instructions are tricky. We can't create an implicit cast on
8260 * the left side, because we need the uncasted form for the store.
8261 * The ast2firm pass has to know that left_type must be right_type
8262 * for the arithmetic operation and create a cast by itself */
8263 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8264 expression->right = create_implicit_cast(right, arithmetic_type);
8265 expression->base.type = type_left;
8268 static void semantic_divmod_assign(binary_expression_t *expression)
8270 semantic_arithmetic_assign(expression);
8271 warn_div_by_zero(expression);
8274 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8276 expression_t *const left = expression->left;
8277 expression_t *const right = expression->right;
8278 type_t *const orig_type_left = left->base.type;
8279 type_t *const orig_type_right = right->base.type;
8280 type_t *const type_left = skip_typeref(orig_type_left);
8281 type_t *const type_right = skip_typeref(orig_type_right);
8283 if (!is_valid_assignment_lhs(left))
8286 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8287 /* combined instructions are tricky. We can't create an implicit cast on
8288 * the left side, because we need the uncasted form for the store.
8289 * The ast2firm pass has to know that left_type must be right_type
8290 * for the arithmetic operation and create a cast by itself */
8291 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8292 expression->right = create_implicit_cast(right, arithmetic_type);
8293 expression->base.type = type_left;
8294 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8295 check_pointer_arithmetic(&expression->base.source_position,
8296 type_left, orig_type_left);
8297 expression->base.type = type_left;
8298 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8299 errorf(&expression->base.source_position,
8300 "incompatible types '%T' and '%T' in assignment",
8301 orig_type_left, orig_type_right);
8305 static void semantic_integer_assign(binary_expression_t *expression)
8307 expression_t *left = expression->left;
8308 expression_t *right = expression->right;
8309 type_t *orig_type_left = left->base.type;
8310 type_t *orig_type_right = right->base.type;
8312 if (!is_valid_assignment_lhs(left))
8315 type_t *type_left = skip_typeref(orig_type_left);
8316 type_t *type_right = skip_typeref(orig_type_right);
8318 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8319 /* TODO: improve error message */
8320 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8321 errorf(&expression->base.source_position,
8322 "operation needs integer types");
8327 /* combined instructions are tricky. We can't create an implicit cast on
8328 * the left side, because we need the uncasted form for the store.
8329 * The ast2firm pass has to know that left_type must be right_type
8330 * for the arithmetic operation and create a cast by itself */
8331 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8332 expression->right = create_implicit_cast(right, arithmetic_type);
8333 expression->base.type = type_left;
8336 static void semantic_shift_assign(binary_expression_t *expression)
8338 expression_t *left = expression->left;
8340 if (!is_valid_assignment_lhs(left))
8343 if (!semantic_shift(expression))
8346 expression->base.type = skip_typeref(left->base.type);
8349 static void warn_logical_and_within_or(const expression_t *const expr)
8351 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8353 if (expr->base.parenthesized)
8355 source_position_t const *const pos = &expr->base.source_position;
8356 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8360 * Check the semantic restrictions of a logical expression.
8362 static void semantic_logical_op(binary_expression_t *expression)
8364 /* §6.5.13:2 Each of the operands shall have scalar type.
8365 * §6.5.14:2 Each of the operands shall have scalar type. */
8366 semantic_condition(expression->left, "left operand of logical operator");
8367 semantic_condition(expression->right, "right operand of logical operator");
8368 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8369 warn_logical_and_within_or(expression->left);
8370 warn_logical_and_within_or(expression->right);
8372 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8376 * Check the semantic restrictions of a binary assign expression.
8378 static void semantic_binexpr_assign(binary_expression_t *expression)
8380 expression_t *left = expression->left;
8381 type_t *orig_type_left = left->base.type;
8383 if (!is_valid_assignment_lhs(left))
8386 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8387 report_assign_error(error, orig_type_left, expression->right,
8388 "assignment", &left->base.source_position);
8389 expression->right = create_implicit_cast(expression->right, orig_type_left);
8390 expression->base.type = orig_type_left;
8394 * Determine if the outermost operation (or parts thereof) of the given
8395 * expression has no effect in order to generate a warning about this fact.
8396 * Therefore in some cases this only examines some of the operands of the
8397 * expression (see comments in the function and examples below).
8399 * f() + 23; // warning, because + has no effect
8400 * x || f(); // no warning, because x controls execution of f()
8401 * x ? y : f(); // warning, because y has no effect
8402 * (void)x; // no warning to be able to suppress the warning
8403 * This function can NOT be used for an "expression has definitely no effect"-
8405 static bool expression_has_effect(const expression_t *const expr)
8407 switch (expr->kind) {
8408 case EXPR_ERROR: return true; /* do NOT warn */
8409 case EXPR_REFERENCE: return false;
8410 case EXPR_ENUM_CONSTANT: return false;
8411 case EXPR_LABEL_ADDRESS: return false;
8413 /* suppress the warning for microsoft __noop operations */
8414 case EXPR_LITERAL_MS_NOOP: return true;
8415 case EXPR_LITERAL_BOOLEAN:
8416 case EXPR_LITERAL_CHARACTER:
8417 case EXPR_LITERAL_WIDE_CHARACTER:
8418 case EXPR_LITERAL_INTEGER:
8419 case EXPR_LITERAL_FLOATINGPOINT:
8420 case EXPR_STRING_LITERAL: return false;
8421 case EXPR_WIDE_STRING_LITERAL: return false;
8424 const call_expression_t *const call = &expr->call;
8425 if (call->function->kind != EXPR_REFERENCE)
8428 switch (call->function->reference.entity->function.btk) {
8429 /* FIXME: which builtins have no effect? */
8430 default: return true;
8434 /* Generate the warning if either the left or right hand side of a
8435 * conditional expression has no effect */
8436 case EXPR_CONDITIONAL: {
8437 conditional_expression_t const *const cond = &expr->conditional;
8438 expression_t const *const t = cond->true_expression;
8440 (t == NULL || expression_has_effect(t)) &&
8441 expression_has_effect(cond->false_expression);
8444 case EXPR_SELECT: return false;
8445 case EXPR_ARRAY_ACCESS: return false;
8446 case EXPR_SIZEOF: return false;
8447 case EXPR_CLASSIFY_TYPE: return false;
8448 case EXPR_ALIGNOF: return false;
8450 case EXPR_FUNCNAME: return false;
8451 case EXPR_BUILTIN_CONSTANT_P: return false;
8452 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8453 case EXPR_OFFSETOF: return false;
8454 case EXPR_VA_START: return true;
8455 case EXPR_VA_ARG: return true;
8456 case EXPR_VA_COPY: return true;
8457 case EXPR_STATEMENT: return true; // TODO
8458 case EXPR_COMPOUND_LITERAL: return false;
8460 case EXPR_UNARY_NEGATE: return false;
8461 case EXPR_UNARY_PLUS: return false;
8462 case EXPR_UNARY_BITWISE_NEGATE: return false;
8463 case EXPR_UNARY_NOT: return false;
8464 case EXPR_UNARY_DEREFERENCE: return false;
8465 case EXPR_UNARY_TAKE_ADDRESS: return false;
8466 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8467 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8468 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8469 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8471 /* Treat void casts as if they have an effect in order to being able to
8472 * suppress the warning */
8473 case EXPR_UNARY_CAST: {
8474 type_t *const type = skip_typeref(expr->base.type);
8475 return is_type_void(type);
8478 case EXPR_UNARY_ASSUME: return true;
8479 case EXPR_UNARY_DELETE: return true;
8480 case EXPR_UNARY_DELETE_ARRAY: return true;
8481 case EXPR_UNARY_THROW: return true;
8483 case EXPR_BINARY_ADD: return false;
8484 case EXPR_BINARY_SUB: return false;
8485 case EXPR_BINARY_MUL: return false;
8486 case EXPR_BINARY_DIV: return false;
8487 case EXPR_BINARY_MOD: return false;
8488 case EXPR_BINARY_EQUAL: return false;
8489 case EXPR_BINARY_NOTEQUAL: return false;
8490 case EXPR_BINARY_LESS: return false;
8491 case EXPR_BINARY_LESSEQUAL: return false;
8492 case EXPR_BINARY_GREATER: return false;
8493 case EXPR_BINARY_GREATEREQUAL: return false;
8494 case EXPR_BINARY_BITWISE_AND: return false;
8495 case EXPR_BINARY_BITWISE_OR: return false;
8496 case EXPR_BINARY_BITWISE_XOR: return false;
8497 case EXPR_BINARY_SHIFTLEFT: return false;
8498 case EXPR_BINARY_SHIFTRIGHT: return false;
8499 case EXPR_BINARY_ASSIGN: return true;
8500 case EXPR_BINARY_MUL_ASSIGN: return true;
8501 case EXPR_BINARY_DIV_ASSIGN: return true;
8502 case EXPR_BINARY_MOD_ASSIGN: return true;
8503 case EXPR_BINARY_ADD_ASSIGN: return true;
8504 case EXPR_BINARY_SUB_ASSIGN: return true;
8505 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8506 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8507 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8508 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8509 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8511 /* Only examine the right hand side of && and ||, because the left hand
8512 * side already has the effect of controlling the execution of the right
8514 case EXPR_BINARY_LOGICAL_AND:
8515 case EXPR_BINARY_LOGICAL_OR:
8516 /* Only examine the right hand side of a comma expression, because the left
8517 * hand side has a separate warning */
8518 case EXPR_BINARY_COMMA:
8519 return expression_has_effect(expr->binary.right);
8521 case EXPR_BINARY_ISGREATER: return false;
8522 case EXPR_BINARY_ISGREATEREQUAL: return false;
8523 case EXPR_BINARY_ISLESS: return false;
8524 case EXPR_BINARY_ISLESSEQUAL: return false;
8525 case EXPR_BINARY_ISLESSGREATER: return false;
8526 case EXPR_BINARY_ISUNORDERED: return false;
8529 internal_errorf(HERE, "unexpected expression");
8532 static void semantic_comma(binary_expression_t *expression)
8534 const expression_t *const left = expression->left;
8535 if (!expression_has_effect(left)) {
8536 source_position_t const *const pos = &left->base.source_position;
8537 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8539 expression->base.type = expression->right->base.type;
8543 * @param prec_r precedence of the right operand
8545 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8546 static expression_t *parse_##binexpression_type(expression_t *left) \
8548 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8549 binexpr->binary.left = left; \
8552 expression_t *right = parse_subexpression(prec_r); \
8554 binexpr->binary.right = right; \
8555 sfunc(&binexpr->binary); \
8560 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8561 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8562 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8563 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8564 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8565 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8566 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8567 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8568 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8569 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8570 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8571 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8572 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8573 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8574 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8575 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8576 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8577 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8578 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8579 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8580 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8581 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8582 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8583 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8584 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8585 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8586 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8587 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8588 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8589 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8592 static expression_t *parse_subexpression(precedence_t precedence)
8594 expression_parser_function_t *parser
8595 = &expression_parsers[token.kind];
8598 if (parser->parser != NULL) {
8599 left = parser->parser();
8601 left = parse_primary_expression();
8603 assert(left != NULL);
8606 parser = &expression_parsers[token.kind];
8607 if (parser->infix_parser == NULL)
8609 if (parser->infix_precedence < precedence)
8612 left = parser->infix_parser(left);
8614 assert(left != NULL);
8621 * Parse an expression.
8623 static expression_t *parse_expression(void)
8625 return parse_subexpression(PREC_EXPRESSION);
8629 * Register a parser for a prefix-like operator.
8631 * @param parser the parser function
8632 * @param token_kind the token type of the prefix token
8634 static void register_expression_parser(parse_expression_function parser,
8637 expression_parser_function_t *entry = &expression_parsers[token_kind];
8639 if (entry->parser != NULL) {
8640 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8641 panic("trying to register multiple expression parsers for a token");
8643 entry->parser = parser;
8647 * Register a parser for an infix operator with given precedence.
8649 * @param parser the parser function
8650 * @param token_kind the token type of the infix operator
8651 * @param precedence the precedence of the operator
8653 static void register_infix_parser(parse_expression_infix_function parser,
8654 int token_kind, precedence_t precedence)
8656 expression_parser_function_t *entry = &expression_parsers[token_kind];
8658 if (entry->infix_parser != NULL) {
8659 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8660 panic("trying to register multiple infix expression parsers for a "
8663 entry->infix_parser = parser;
8664 entry->infix_precedence = precedence;
8668 * Initialize the expression parsers.
8670 static void init_expression_parsers(void)
8672 memset(&expression_parsers, 0, sizeof(expression_parsers));
8674 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8675 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8676 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8677 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8678 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8679 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8680 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8681 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8682 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8683 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8684 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8685 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8686 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8687 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8688 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8689 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8690 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8691 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8692 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8693 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8694 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8695 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8696 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8697 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8698 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8699 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8700 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8701 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8702 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8703 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8704 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8705 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8706 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8707 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8708 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8709 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8710 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8712 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8713 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8714 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8715 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8716 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8717 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8718 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8719 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8720 register_expression_parser(parse_sizeof, T_sizeof);
8721 register_expression_parser(parse_alignof, T___alignof__);
8722 register_expression_parser(parse_extension, T___extension__);
8723 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8724 register_expression_parser(parse_delete, T_delete);
8725 register_expression_parser(parse_throw, T_throw);
8729 * Parse a asm statement arguments specification.
8731 static asm_argument_t *parse_asm_arguments(bool is_out)
8733 asm_argument_t *result = NULL;
8734 asm_argument_t **anchor = &result;
8736 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8737 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8740 add_anchor_token(']');
8741 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8742 rem_anchor_token(']');
8744 if (!argument->symbol)
8748 argument->constraints = parse_string_literals();
8750 add_anchor_token(')');
8751 expression_t *expression = parse_expression();
8752 rem_anchor_token(')');
8754 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8755 * change size or type representation (e.g. int -> long is ok, but
8756 * int -> float is not) */
8757 if (expression->kind == EXPR_UNARY_CAST) {
8758 type_t *const type = expression->base.type;
8759 type_kind_t const kind = type->kind;
8760 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8763 if (kind == TYPE_ATOMIC) {
8764 atomic_type_kind_t const akind = type->atomic.akind;
8765 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8766 size = get_atomic_type_size(akind);
8768 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8769 size = get_type_size(type_void_ptr);
8773 expression_t *const value = expression->unary.value;
8774 type_t *const value_type = value->base.type;
8775 type_kind_t const value_kind = value_type->kind;
8777 unsigned value_flags;
8778 unsigned value_size;
8779 if (value_kind == TYPE_ATOMIC) {
8780 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8781 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8782 value_size = get_atomic_type_size(value_akind);
8783 } else if (value_kind == TYPE_POINTER) {
8784 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8785 value_size = get_type_size(type_void_ptr);
8790 if (value_flags != flags || value_size != size)
8794 } while (expression->kind == EXPR_UNARY_CAST);
8798 if (!is_lvalue(expression)) {
8799 errorf(&expression->base.source_position,
8800 "asm output argument is not an lvalue");
8803 if (argument->constraints.begin[0] == '=')
8804 determine_lhs_ent(expression, NULL);
8806 mark_vars_read(expression, NULL);
8808 mark_vars_read(expression, NULL);
8810 argument->expression = expression;
8813 set_address_taken(expression, true);
8816 anchor = &argument->next;
8826 * Parse a asm statement clobber specification.
8828 static asm_clobber_t *parse_asm_clobbers(void)
8830 asm_clobber_t *result = NULL;
8831 asm_clobber_t **anchor = &result;
8833 while (token.kind == T_STRING_LITERAL) {
8834 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8835 clobber->clobber = parse_string_literals();
8838 anchor = &clobber->next;
8848 * Parse an asm statement.
8850 static statement_t *parse_asm_statement(void)
8852 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8853 asm_statement_t *asm_statement = &statement->asms;
8857 if (next_if(T_volatile))
8858 asm_statement->is_volatile = true;
8861 add_anchor_token(')');
8862 if (token.kind != T_STRING_LITERAL) {
8863 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8866 asm_statement->asm_text = parse_string_literals();
8868 add_anchor_token(':');
8869 if (!next_if(':')) {
8870 rem_anchor_token(':');
8874 asm_statement->outputs = parse_asm_arguments(true);
8875 if (!next_if(':')) {
8876 rem_anchor_token(':');
8880 asm_statement->inputs = parse_asm_arguments(false);
8881 if (!next_if(':')) {
8882 rem_anchor_token(':');
8885 rem_anchor_token(':');
8887 asm_statement->clobbers = parse_asm_clobbers();
8890 rem_anchor_token(')');
8894 if (asm_statement->outputs == NULL) {
8895 /* GCC: An 'asm' instruction without any output operands will be treated
8896 * identically to a volatile 'asm' instruction. */
8897 asm_statement->is_volatile = true;
8903 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8905 statement_t *inner_stmt;
8906 switch (token.kind) {
8908 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8909 inner_stmt = create_error_statement();
8913 if (label->kind == STATEMENT_LABEL) {
8914 /* Eat an empty statement here, to avoid the warning about an empty
8915 * statement after a label. label:; is commonly used to have a label
8916 * before a closing brace. */
8917 inner_stmt = create_empty_statement();
8924 inner_stmt = parse_statement();
8925 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8926 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8927 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8928 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8936 * Parse a case statement.
8938 static statement_t *parse_case_statement(void)
8940 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8941 source_position_t *const pos = &statement->base.source_position;
8944 add_anchor_token(':');
8946 expression_t *expression = parse_expression();
8947 type_t *expression_type = expression->base.type;
8948 type_t *skipped = skip_typeref(expression_type);
8949 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8950 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8951 expression, expression_type);
8954 type_t *type = expression_type;
8955 if (current_switch != NULL) {
8956 type_t *switch_type = current_switch->expression->base.type;
8957 if (is_type_valid(switch_type)) {
8958 expression = create_implicit_cast(expression, switch_type);
8962 statement->case_label.expression = expression;
8963 expression_classification_t const expr_class = is_constant_expression(expression);
8964 if (expr_class != EXPR_CLASS_CONSTANT) {
8965 if (expr_class != EXPR_CLASS_ERROR) {
8966 errorf(pos, "case label does not reduce to an integer constant");
8968 statement->case_label.is_bad = true;
8970 long const val = fold_constant_to_int(expression);
8971 statement->case_label.first_case = val;
8972 statement->case_label.last_case = val;
8976 if (next_if(T_DOTDOTDOT)) {
8977 expression_t *end_range = parse_expression();
8978 expression_type = expression->base.type;
8979 skipped = skip_typeref(expression_type);
8980 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8981 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8982 expression, expression_type);
8985 end_range = create_implicit_cast(end_range, type);
8986 statement->case_label.end_range = end_range;
8987 expression_classification_t const end_class = is_constant_expression(end_range);
8988 if (end_class != EXPR_CLASS_CONSTANT) {
8989 if (end_class != EXPR_CLASS_ERROR) {
8990 errorf(pos, "case range does not reduce to an integer constant");
8992 statement->case_label.is_bad = true;
8994 long const val = fold_constant_to_int(end_range);
8995 statement->case_label.last_case = val;
8997 if (val < statement->case_label.first_case) {
8998 statement->case_label.is_empty_range = true;
8999 warningf(WARN_OTHER, pos, "empty range specified");
9005 PUSH_PARENT(statement);
9007 rem_anchor_token(':');
9010 if (current_switch != NULL) {
9011 if (! statement->case_label.is_bad) {
9012 /* Check for duplicate case values */
9013 case_label_statement_t *c = &statement->case_label;
9014 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9015 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9018 if (c->last_case < l->first_case || c->first_case > l->last_case)
9021 errorf(pos, "duplicate case value (previously used %P)",
9022 &l->base.source_position);
9026 /* link all cases into the switch statement */
9027 if (current_switch->last_case == NULL) {
9028 current_switch->first_case = &statement->case_label;
9030 current_switch->last_case->next = &statement->case_label;
9032 current_switch->last_case = &statement->case_label;
9034 errorf(pos, "case label not within a switch statement");
9037 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9044 * Parse a default statement.
9046 static statement_t *parse_default_statement(void)
9048 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9052 PUSH_PARENT(statement);
9056 if (current_switch != NULL) {
9057 const case_label_statement_t *def_label = current_switch->default_label;
9058 if (def_label != NULL) {
9059 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9061 current_switch->default_label = &statement->case_label;
9063 /* link all cases into the switch statement */
9064 if (current_switch->last_case == NULL) {
9065 current_switch->first_case = &statement->case_label;
9067 current_switch->last_case->next = &statement->case_label;
9069 current_switch->last_case = &statement->case_label;
9072 errorf(&statement->base.source_position,
9073 "'default' label not within a switch statement");
9076 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9083 * Parse a label statement.
9085 static statement_t *parse_label_statement(void)
9087 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9088 label_t *const label = get_label();
9089 statement->label.label = label;
9091 PUSH_PARENT(statement);
9093 /* if statement is already set then the label is defined twice,
9094 * otherwise it was just mentioned in a goto/local label declaration so far
9096 source_position_t const* const pos = &statement->base.source_position;
9097 if (label->statement != NULL) {
9098 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9100 label->base.source_position = *pos;
9101 label->statement = statement;
9106 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9107 parse_attributes(NULL); // TODO process attributes
9110 statement->label.statement = parse_label_inner_statement(statement, "label");
9112 /* remember the labels in a list for later checking */
9113 *label_anchor = &statement->label;
9114 label_anchor = &statement->label.next;
9120 static statement_t *parse_inner_statement(void)
9122 statement_t *const stmt = parse_statement();
9123 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9124 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9125 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9126 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9132 * Parse an expression in parentheses and mark its variables as read.
9134 static expression_t *parse_condition(void)
9137 add_anchor_token(')');
9138 expression_t *const expr = parse_expression();
9139 mark_vars_read(expr, NULL);
9140 rem_anchor_token(')');
9146 * Parse an if statement.
9148 static statement_t *parse_if(void)
9150 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9154 PUSH_PARENT(statement);
9155 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9157 add_anchor_token(T_else);
9159 expression_t *const expr = parse_condition();
9160 statement->ifs.condition = expr;
9161 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9163 semantic_condition(expr, "condition of 'if'-statment");
9165 statement_t *const true_stmt = parse_inner_statement();
9166 statement->ifs.true_statement = true_stmt;
9167 rem_anchor_token(T_else);
9169 if (true_stmt->kind == STATEMENT_EMPTY) {
9170 warningf(WARN_EMPTY_BODY, HERE,
9171 "suggest braces around empty body in an ‘if’ statement");
9174 if (next_if(T_else)) {
9175 statement->ifs.false_statement = parse_inner_statement();
9177 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9178 warningf(WARN_EMPTY_BODY, HERE,
9179 "suggest braces around empty body in an ‘if’ statement");
9181 } else if (true_stmt->kind == STATEMENT_IF &&
9182 true_stmt->ifs.false_statement != NULL) {
9183 source_position_t const *const pos = &true_stmt->base.source_position;
9184 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9193 * Check that all enums are handled in a switch.
9195 * @param statement the switch statement to check
9197 static void check_enum_cases(const switch_statement_t *statement)
9199 if (!is_warn_on(WARN_SWITCH_ENUM))
9201 const type_t *type = skip_typeref(statement->expression->base.type);
9202 if (! is_type_enum(type))
9204 const enum_type_t *enumt = &type->enumt;
9206 /* if we have a default, no warnings */
9207 if (statement->default_label != NULL)
9210 /* FIXME: calculation of value should be done while parsing */
9211 /* TODO: quadratic algorithm here. Change to an n log n one */
9212 long last_value = -1;
9213 const entity_t *entry = enumt->enume->base.next;
9214 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9215 entry = entry->base.next) {
9216 const expression_t *expression = entry->enum_value.value;
9217 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9219 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9220 if (l->expression == NULL)
9222 if (l->first_case <= value && value <= l->last_case) {
9228 source_position_t const *const pos = &statement->base.source_position;
9229 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9236 * Parse a switch statement.
9238 static statement_t *parse_switch(void)
9240 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9244 PUSH_PARENT(statement);
9245 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9247 expression_t *const expr = parse_condition();
9248 type_t * type = skip_typeref(expr->base.type);
9249 if (is_type_integer(type)) {
9250 type = promote_integer(type);
9251 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9252 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9254 } else if (is_type_valid(type)) {
9255 errorf(&expr->base.source_position,
9256 "switch quantity is not an integer, but '%T'", type);
9257 type = type_error_type;
9259 statement->switchs.expression = create_implicit_cast(expr, type);
9261 switch_statement_t *rem = current_switch;
9262 current_switch = &statement->switchs;
9263 statement->switchs.body = parse_inner_statement();
9264 current_switch = rem;
9266 if (statement->switchs.default_label == NULL) {
9267 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9269 check_enum_cases(&statement->switchs);
9276 static statement_t *parse_loop_body(statement_t *const loop)
9278 statement_t *const rem = current_loop;
9279 current_loop = loop;
9281 statement_t *const body = parse_inner_statement();
9288 * Parse a while statement.
9290 static statement_t *parse_while(void)
9292 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9296 PUSH_PARENT(statement);
9297 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9299 expression_t *const cond = parse_condition();
9300 statement->whiles.condition = cond;
9301 /* §6.8.5:2 The controlling expression of an iteration statement shall
9302 * have scalar type. */
9303 semantic_condition(cond, "condition of 'while'-statement");
9305 statement->whiles.body = parse_loop_body(statement);
9313 * Parse a do statement.
9315 static statement_t *parse_do(void)
9317 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9321 PUSH_PARENT(statement);
9322 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9324 add_anchor_token(T_while);
9325 statement->do_while.body = parse_loop_body(statement);
9326 rem_anchor_token(T_while);
9329 expression_t *const cond = parse_condition();
9330 statement->do_while.condition = cond;
9331 /* §6.8.5:2 The controlling expression of an iteration statement shall
9332 * have scalar type. */
9333 semantic_condition(cond, "condition of 'do-while'-statement");
9342 * Parse a for statement.
9344 static statement_t *parse_for(void)
9346 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9350 PUSH_PARENT(statement);
9351 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9354 add_anchor_token(')');
9359 } else if (is_declaration_specifier(&token)) {
9360 parse_declaration(record_entity, DECL_FLAGS_NONE);
9362 add_anchor_token(';');
9363 expression_t *const init = parse_expression();
9364 statement->fors.initialisation = init;
9365 mark_vars_read(init, ENT_ANY);
9366 if (!expression_has_effect(init)) {
9367 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9369 rem_anchor_token(';');
9375 if (token.kind != ';') {
9376 add_anchor_token(';');
9377 expression_t *const cond = parse_expression();
9378 statement->fors.condition = cond;
9379 /* §6.8.5:2 The controlling expression of an iteration statement
9380 * shall have scalar type. */
9381 semantic_condition(cond, "condition of 'for'-statement");
9382 mark_vars_read(cond, NULL);
9383 rem_anchor_token(';');
9386 if (token.kind != ')') {
9387 expression_t *const step = parse_expression();
9388 statement->fors.step = step;
9389 mark_vars_read(step, ENT_ANY);
9390 if (!expression_has_effect(step)) {
9391 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9394 rem_anchor_token(')');
9396 statement->fors.body = parse_loop_body(statement);
9404 * Parse a goto statement.
9406 static statement_t *parse_goto(void)
9408 statement_t *statement;
9409 if (GNU_MODE && look_ahead(1)->kind == '*') {
9410 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9414 expression_t *expression = parse_expression();
9415 mark_vars_read(expression, NULL);
9417 /* Argh: although documentation says the expression must be of type void*,
9418 * gcc accepts anything that can be casted into void* without error */
9419 type_t *type = expression->base.type;
9421 if (type != type_error_type) {
9422 if (!is_type_pointer(type) && !is_type_integer(type)) {
9423 errorf(&expression->base.source_position,
9424 "cannot convert to a pointer type");
9425 } else if (type != type_void_ptr) {
9426 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9428 expression = create_implicit_cast(expression, type_void_ptr);
9431 statement->computed_goto.expression = expression;
9433 statement = allocate_statement_zero(STATEMENT_GOTO);
9435 if (token.kind == T_IDENTIFIER) {
9436 label_t *const label = get_label();
9438 statement->gotos.label = label;
9440 /* remember the goto's in a list for later checking */
9441 *goto_anchor = &statement->gotos;
9442 goto_anchor = &statement->gotos.next;
9445 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9447 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9449 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9458 * Parse a continue statement.
9460 static statement_t *parse_continue(void)
9462 if (current_loop == NULL) {
9463 errorf(HERE, "continue statement not within loop");
9466 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9474 * Parse a break statement.
9476 static statement_t *parse_break(void)
9478 if (current_switch == NULL && current_loop == NULL) {
9479 errorf(HERE, "break statement not within loop or switch");
9482 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9490 * Parse a __leave statement.
9492 static statement_t *parse_leave_statement(void)
9494 if (current_try == NULL) {
9495 errorf(HERE, "__leave statement not within __try");
9498 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9506 * Check if a given entity represents a local variable.
9508 static bool is_local_variable(const entity_t *entity)
9510 if (entity->kind != ENTITY_VARIABLE)
9513 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9514 case STORAGE_CLASS_AUTO:
9515 case STORAGE_CLASS_REGISTER: {
9516 const type_t *type = skip_typeref(entity->declaration.type);
9517 if (is_type_function(type)) {
9529 * Check if a given expression represents a local variable.
9531 static bool expression_is_local_variable(const expression_t *expression)
9533 if (expression->base.kind != EXPR_REFERENCE) {
9536 const entity_t *entity = expression->reference.entity;
9537 return is_local_variable(entity);
9541 * Check if a given expression represents a local variable and
9542 * return its declaration then, else return NULL.
9544 entity_t *expression_is_variable(const expression_t *expression)
9546 if (expression->base.kind != EXPR_REFERENCE) {
9549 entity_t *entity = expression->reference.entity;
9550 if (entity->kind != ENTITY_VARIABLE)
9556 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9558 if (c_mode & _CXX || strict_mode) {
9561 warningf(WARN_OTHER, pos, msg);
9566 * Parse a return statement.
9568 static statement_t *parse_return(void)
9570 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9573 expression_t *return_value = NULL;
9574 if (token.kind != ';') {
9575 return_value = parse_expression();
9576 mark_vars_read(return_value, NULL);
9579 const type_t *const func_type = skip_typeref(current_function->base.type);
9580 assert(is_type_function(func_type));
9581 type_t *const return_type = skip_typeref(func_type->function.return_type);
9583 source_position_t const *const pos = &statement->base.source_position;
9584 if (return_value != NULL) {
9585 type_t *return_value_type = skip_typeref(return_value->base.type);
9587 if (is_type_void(return_type)) {
9588 if (!is_type_void(return_value_type)) {
9589 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9590 /* Only warn in C mode, because GCC does the same */
9591 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9592 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9593 /* Only warn in C mode, because GCC does the same */
9594 err_or_warn(pos, "'return' with expression in function returning 'void'");
9597 assign_error_t error = semantic_assign(return_type, return_value);
9598 report_assign_error(error, return_type, return_value, "'return'",
9601 return_value = create_implicit_cast(return_value, return_type);
9602 /* check for returning address of a local var */
9603 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9604 const expression_t *expression = return_value->unary.value;
9605 if (expression_is_local_variable(expression)) {
9606 warningf(WARN_OTHER, pos, "function returns address of local variable");
9609 } else if (!is_type_void(return_type)) {
9610 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9611 err_or_warn(pos, "'return' without value, in function returning non-void");
9613 statement->returns.value = return_value;
9620 * Parse a declaration statement.
9622 static statement_t *parse_declaration_statement(void)
9624 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9626 entity_t *before = current_scope->last_entity;
9628 parse_external_declaration();
9630 parse_declaration(record_entity, DECL_FLAGS_NONE);
9633 declaration_statement_t *const decl = &statement->declaration;
9634 entity_t *const begin =
9635 before != NULL ? before->base.next : current_scope->entities;
9636 decl->declarations_begin = begin;
9637 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9643 * Parse an expression statement, ie. expr ';'.
9645 static statement_t *parse_expression_statement(void)
9647 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9649 expression_t *const expr = parse_expression();
9650 statement->expression.expression = expr;
9651 mark_vars_read(expr, ENT_ANY);
9658 * Parse a microsoft __try { } __finally { } or
9659 * __try{ } __except() { }
9661 static statement_t *parse_ms_try_statment(void)
9663 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9666 PUSH_PARENT(statement);
9668 ms_try_statement_t *rem = current_try;
9669 current_try = &statement->ms_try;
9670 statement->ms_try.try_statement = parse_compound_statement(false);
9675 if (next_if(T___except)) {
9676 expression_t *const expr = parse_condition();
9677 type_t * type = skip_typeref(expr->base.type);
9678 if (is_type_integer(type)) {
9679 type = promote_integer(type);
9680 } else if (is_type_valid(type)) {
9681 errorf(&expr->base.source_position,
9682 "__expect expression is not an integer, but '%T'", type);
9683 type = type_error_type;
9685 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9686 } else if (!next_if(T__finally)) {
9687 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9689 statement->ms_try.final_statement = parse_compound_statement(false);
9693 static statement_t *parse_empty_statement(void)
9695 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9696 statement_t *const statement = create_empty_statement();
9701 static statement_t *parse_local_label_declaration(void)
9703 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9707 entity_t *begin = NULL;
9708 entity_t *end = NULL;
9709 entity_t **anchor = &begin;
9711 source_position_t pos;
9712 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9716 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9717 if (entity != NULL && entity->base.parent_scope == current_scope) {
9718 source_position_t const *const ppos = &entity->base.source_position;
9719 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9721 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9722 entity->base.parent_scope = current_scope;
9725 anchor = &entity->base.next;
9728 environment_push(entity);
9730 } while (next_if(','));
9733 statement->declaration.declarations_begin = begin;
9734 statement->declaration.declarations_end = end;
9738 static void parse_namespace_definition(void)
9742 entity_t *entity = NULL;
9743 symbol_t *symbol = NULL;
9745 if (token.kind == T_IDENTIFIER) {
9746 symbol = token.identifier.symbol;
9749 entity = get_entity(symbol, NAMESPACE_NORMAL);
9751 && entity->kind != ENTITY_NAMESPACE
9752 && entity->base.parent_scope == current_scope) {
9753 if (is_entity_valid(entity)) {
9754 error_redefined_as_different_kind(&token.base.source_position,
9755 entity, ENTITY_NAMESPACE);
9761 if (entity == NULL) {
9762 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9763 entity->base.parent_scope = current_scope;
9766 if (token.kind == '=') {
9767 /* TODO: parse namespace alias */
9768 panic("namespace alias definition not supported yet");
9771 environment_push(entity);
9772 append_entity(current_scope, entity);
9774 PUSH_SCOPE(&entity->namespacee.members);
9775 PUSH_CURRENT_ENTITY(entity);
9777 add_anchor_token('}');
9780 rem_anchor_token('}');
9783 POP_CURRENT_ENTITY();
9788 * Parse a statement.
9789 * There's also parse_statement() which additionally checks for
9790 * "statement has no effect" warnings
9792 static statement_t *intern_parse_statement(void)
9794 /* declaration or statement */
9795 statement_t *statement;
9796 switch (token.kind) {
9797 case T_IDENTIFIER: {
9798 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9799 if (la1_type == ':') {
9800 statement = parse_label_statement();
9801 } else if (is_typedef_symbol(token.identifier.symbol)) {
9802 statement = parse_declaration_statement();
9804 /* it's an identifier, the grammar says this must be an
9805 * expression statement. However it is common that users mistype
9806 * declaration types, so we guess a bit here to improve robustness
9807 * for incorrect programs */
9811 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9813 statement = parse_expression_statement();
9817 statement = parse_declaration_statement();
9825 case T___extension__: {
9826 /* This can be a prefix to a declaration or an expression statement.
9827 * We simply eat it now and parse the rest with tail recursion. */
9829 statement = intern_parse_statement();
9835 statement = parse_declaration_statement();
9839 statement = parse_local_label_declaration();
9842 case ';': statement = parse_empty_statement(); break;
9843 case '{': statement = parse_compound_statement(false); break;
9844 case T___leave: statement = parse_leave_statement(); break;
9845 case T___try: statement = parse_ms_try_statment(); break;
9846 case T_asm: statement = parse_asm_statement(); break;
9847 case T_break: statement = parse_break(); break;
9848 case T_case: statement = parse_case_statement(); break;
9849 case T_continue: statement = parse_continue(); break;
9850 case T_default: statement = parse_default_statement(); break;
9851 case T_do: statement = parse_do(); break;
9852 case T_for: statement = parse_for(); break;
9853 case T_goto: statement = parse_goto(); break;
9854 case T_if: statement = parse_if(); break;
9855 case T_return: statement = parse_return(); break;
9856 case T_switch: statement = parse_switch(); break;
9857 case T_while: statement = parse_while(); break;
9860 statement = parse_expression_statement();
9864 errorf(HERE, "unexpected token %K while parsing statement", &token);
9865 statement = create_error_statement();
9874 * parse a statement and emits "statement has no effect" warning if needed
9875 * (This is really a wrapper around intern_parse_statement with check for 1
9876 * single warning. It is needed, because for statement expressions we have
9877 * to avoid the warning on the last statement)
9879 static statement_t *parse_statement(void)
9881 statement_t *statement = intern_parse_statement();
9883 if (statement->kind == STATEMENT_EXPRESSION) {
9884 expression_t *expression = statement->expression.expression;
9885 if (!expression_has_effect(expression)) {
9886 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9894 * Parse a compound statement.
9896 static statement_t *parse_compound_statement(bool inside_expression_statement)
9898 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9900 PUSH_PARENT(statement);
9901 PUSH_SCOPE(&statement->compound.scope);
9904 add_anchor_token('}');
9905 /* tokens, which can start a statement */
9906 /* TODO MS, __builtin_FOO */
9907 add_anchor_token('!');
9908 add_anchor_token('&');
9909 add_anchor_token('(');
9910 add_anchor_token('*');
9911 add_anchor_token('+');
9912 add_anchor_token('-');
9913 add_anchor_token(';');
9914 add_anchor_token('{');
9915 add_anchor_token('~');
9916 add_anchor_token(T_CHARACTER_CONSTANT);
9917 add_anchor_token(T_COLONCOLON);
9918 add_anchor_token(T_FLOATINGPOINT);
9919 add_anchor_token(T_IDENTIFIER);
9920 add_anchor_token(T_INTEGER);
9921 add_anchor_token(T_MINUSMINUS);
9922 add_anchor_token(T_PLUSPLUS);
9923 add_anchor_token(T_STRING_LITERAL);
9924 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
9925 add_anchor_token(T_WIDE_STRING_LITERAL);
9926 add_anchor_token(T__Bool);
9927 add_anchor_token(T__Complex);
9928 add_anchor_token(T__Imaginary);
9929 add_anchor_token(T___FUNCTION__);
9930 add_anchor_token(T___PRETTY_FUNCTION__);
9931 add_anchor_token(T___alignof__);
9932 add_anchor_token(T___attribute__);
9933 add_anchor_token(T___builtin_va_start);
9934 add_anchor_token(T___extension__);
9935 add_anchor_token(T___func__);
9936 add_anchor_token(T___imag__);
9937 add_anchor_token(T___label__);
9938 add_anchor_token(T___real__);
9939 add_anchor_token(T___thread);
9940 add_anchor_token(T_asm);
9941 add_anchor_token(T_auto);
9942 add_anchor_token(T_bool);
9943 add_anchor_token(T_break);
9944 add_anchor_token(T_case);
9945 add_anchor_token(T_char);
9946 add_anchor_token(T_class);
9947 add_anchor_token(T_const);
9948 add_anchor_token(T_const_cast);
9949 add_anchor_token(T_continue);
9950 add_anchor_token(T_default);
9951 add_anchor_token(T_delete);
9952 add_anchor_token(T_double);
9953 add_anchor_token(T_do);
9954 add_anchor_token(T_dynamic_cast);
9955 add_anchor_token(T_enum);
9956 add_anchor_token(T_extern);
9957 add_anchor_token(T_false);
9958 add_anchor_token(T_float);
9959 add_anchor_token(T_for);
9960 add_anchor_token(T_goto);
9961 add_anchor_token(T_if);
9962 add_anchor_token(T_inline);
9963 add_anchor_token(T_int);
9964 add_anchor_token(T_long);
9965 add_anchor_token(T_new);
9966 add_anchor_token(T_operator);
9967 add_anchor_token(T_register);
9968 add_anchor_token(T_reinterpret_cast);
9969 add_anchor_token(T_restrict);
9970 add_anchor_token(T_return);
9971 add_anchor_token(T_short);
9972 add_anchor_token(T_signed);
9973 add_anchor_token(T_sizeof);
9974 add_anchor_token(T_static);
9975 add_anchor_token(T_static_cast);
9976 add_anchor_token(T_struct);
9977 add_anchor_token(T_switch);
9978 add_anchor_token(T_template);
9979 add_anchor_token(T_this);
9980 add_anchor_token(T_throw);
9981 add_anchor_token(T_true);
9982 add_anchor_token(T_try);
9983 add_anchor_token(T_typedef);
9984 add_anchor_token(T_typeid);
9985 add_anchor_token(T_typename);
9986 add_anchor_token(T_typeof);
9987 add_anchor_token(T_union);
9988 add_anchor_token(T_unsigned);
9989 add_anchor_token(T_using);
9990 add_anchor_token(T_void);
9991 add_anchor_token(T_volatile);
9992 add_anchor_token(T_wchar_t);
9993 add_anchor_token(T_while);
9995 statement_t **anchor = &statement->compound.statements;
9996 bool only_decls_so_far = true;
9997 while (token.kind != '}' && token.kind != T_EOF) {
9998 statement_t *sub_statement = intern_parse_statement();
9999 if (sub_statement->kind == STATEMENT_ERROR) {
10003 if (sub_statement->kind != STATEMENT_DECLARATION) {
10004 only_decls_so_far = false;
10005 } else if (!only_decls_so_far) {
10006 source_position_t const *const pos = &sub_statement->base.source_position;
10007 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10010 *anchor = sub_statement;
10011 anchor = &sub_statement->base.next;
10015 /* look over all statements again to produce no effect warnings */
10016 if (is_warn_on(WARN_UNUSED_VALUE)) {
10017 statement_t *sub_statement = statement->compound.statements;
10018 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10019 if (sub_statement->kind != STATEMENT_EXPRESSION)
10021 /* don't emit a warning for the last expression in an expression
10022 * statement as it has always an effect */
10023 if (inside_expression_statement && sub_statement->base.next == NULL)
10026 expression_t *expression = sub_statement->expression.expression;
10027 if (!expression_has_effect(expression)) {
10028 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10033 rem_anchor_token(T_while);
10034 rem_anchor_token(T_wchar_t);
10035 rem_anchor_token(T_volatile);
10036 rem_anchor_token(T_void);
10037 rem_anchor_token(T_using);
10038 rem_anchor_token(T_unsigned);
10039 rem_anchor_token(T_union);
10040 rem_anchor_token(T_typeof);
10041 rem_anchor_token(T_typename);
10042 rem_anchor_token(T_typeid);
10043 rem_anchor_token(T_typedef);
10044 rem_anchor_token(T_try);
10045 rem_anchor_token(T_true);
10046 rem_anchor_token(T_throw);
10047 rem_anchor_token(T_this);
10048 rem_anchor_token(T_template);
10049 rem_anchor_token(T_switch);
10050 rem_anchor_token(T_struct);
10051 rem_anchor_token(T_static_cast);
10052 rem_anchor_token(T_static);
10053 rem_anchor_token(T_sizeof);
10054 rem_anchor_token(T_signed);
10055 rem_anchor_token(T_short);
10056 rem_anchor_token(T_return);
10057 rem_anchor_token(T_restrict);
10058 rem_anchor_token(T_reinterpret_cast);
10059 rem_anchor_token(T_register);
10060 rem_anchor_token(T_operator);
10061 rem_anchor_token(T_new);
10062 rem_anchor_token(T_long);
10063 rem_anchor_token(T_int);
10064 rem_anchor_token(T_inline);
10065 rem_anchor_token(T_if);
10066 rem_anchor_token(T_goto);
10067 rem_anchor_token(T_for);
10068 rem_anchor_token(T_float);
10069 rem_anchor_token(T_false);
10070 rem_anchor_token(T_extern);
10071 rem_anchor_token(T_enum);
10072 rem_anchor_token(T_dynamic_cast);
10073 rem_anchor_token(T_do);
10074 rem_anchor_token(T_double);
10075 rem_anchor_token(T_delete);
10076 rem_anchor_token(T_default);
10077 rem_anchor_token(T_continue);
10078 rem_anchor_token(T_const_cast);
10079 rem_anchor_token(T_const);
10080 rem_anchor_token(T_class);
10081 rem_anchor_token(T_char);
10082 rem_anchor_token(T_case);
10083 rem_anchor_token(T_break);
10084 rem_anchor_token(T_bool);
10085 rem_anchor_token(T_auto);
10086 rem_anchor_token(T_asm);
10087 rem_anchor_token(T___thread);
10088 rem_anchor_token(T___real__);
10089 rem_anchor_token(T___label__);
10090 rem_anchor_token(T___imag__);
10091 rem_anchor_token(T___func__);
10092 rem_anchor_token(T___extension__);
10093 rem_anchor_token(T___builtin_va_start);
10094 rem_anchor_token(T___attribute__);
10095 rem_anchor_token(T___alignof__);
10096 rem_anchor_token(T___PRETTY_FUNCTION__);
10097 rem_anchor_token(T___FUNCTION__);
10098 rem_anchor_token(T__Imaginary);
10099 rem_anchor_token(T__Complex);
10100 rem_anchor_token(T__Bool);
10101 rem_anchor_token(T_WIDE_STRING_LITERAL);
10102 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10103 rem_anchor_token(T_STRING_LITERAL);
10104 rem_anchor_token(T_PLUSPLUS);
10105 rem_anchor_token(T_MINUSMINUS);
10106 rem_anchor_token(T_INTEGER);
10107 rem_anchor_token(T_IDENTIFIER);
10108 rem_anchor_token(T_FLOATINGPOINT);
10109 rem_anchor_token(T_COLONCOLON);
10110 rem_anchor_token(T_CHARACTER_CONSTANT);
10111 rem_anchor_token('~');
10112 rem_anchor_token('{');
10113 rem_anchor_token(';');
10114 rem_anchor_token('-');
10115 rem_anchor_token('+');
10116 rem_anchor_token('*');
10117 rem_anchor_token('(');
10118 rem_anchor_token('&');
10119 rem_anchor_token('!');
10120 rem_anchor_token('}');
10128 * Check for unused global static functions and variables
10130 static void check_unused_globals(void)
10132 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10135 for (const entity_t *entity = file_scope->entities; entity != NULL;
10136 entity = entity->base.next) {
10137 if (!is_declaration(entity))
10140 const declaration_t *declaration = &entity->declaration;
10141 if (declaration->used ||
10142 declaration->modifiers & DM_UNUSED ||
10143 declaration->modifiers & DM_USED ||
10144 declaration->storage_class != STORAGE_CLASS_STATIC)
10149 if (entity->kind == ENTITY_FUNCTION) {
10150 /* inhibit warning for static inline functions */
10151 if (entity->function.is_inline)
10154 why = WARN_UNUSED_FUNCTION;
10155 s = entity->function.statement != NULL ? "defined" : "declared";
10157 why = WARN_UNUSED_VARIABLE;
10161 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10165 static void parse_global_asm(void)
10167 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10170 add_anchor_token(';');
10171 add_anchor_token(')');
10172 add_anchor_token(T_STRING_LITERAL);
10175 rem_anchor_token(T_STRING_LITERAL);
10176 statement->asms.asm_text = parse_string_literals();
10177 statement->base.next = unit->global_asm;
10178 unit->global_asm = statement;
10180 rem_anchor_token(')');
10182 rem_anchor_token(';');
10186 static void parse_linkage_specification(void)
10190 source_position_t const pos = *HERE;
10191 char const *const linkage = parse_string_literals().begin;
10193 linkage_kind_t old_linkage = current_linkage;
10194 linkage_kind_t new_linkage;
10195 if (streq(linkage, "C")) {
10196 new_linkage = LINKAGE_C;
10197 } else if (streq(linkage, "C++")) {
10198 new_linkage = LINKAGE_CXX;
10200 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10201 new_linkage = LINKAGE_C;
10203 current_linkage = new_linkage;
10205 if (next_if('{')) {
10212 assert(current_linkage == new_linkage);
10213 current_linkage = old_linkage;
10216 static void parse_external(void)
10218 switch (token.kind) {
10220 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10221 parse_linkage_specification();
10223 DECLARATION_START_NO_EXTERN
10225 case T___extension__:
10226 /* tokens below are for implicit int */
10227 case '&': /* & x; -> int& x; (and error later, because C++ has no
10229 case '*': /* * x; -> int* x; */
10230 case '(': /* (x); -> int (x); */
10232 parse_external_declaration();
10238 parse_global_asm();
10242 parse_namespace_definition();
10246 if (!strict_mode) {
10247 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10254 errorf(HERE, "stray %K outside of function", &token);
10255 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10256 eat_until_matching_token(token.kind);
10262 static void parse_externals(void)
10264 add_anchor_token('}');
10265 add_anchor_token(T_EOF);
10268 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10269 unsigned short token_anchor_copy[T_LAST_TOKEN];
10270 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10273 while (token.kind != T_EOF && token.kind != '}') {
10275 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10276 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10278 /* the anchor set and its copy differs */
10279 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10282 if (in_gcc_extension) {
10283 /* an gcc extension scope was not closed */
10284 internal_errorf(HERE, "Leaked __extension__");
10291 rem_anchor_token(T_EOF);
10292 rem_anchor_token('}');
10296 * Parse a translation unit.
10298 static void parse_translation_unit(void)
10300 add_anchor_token(T_EOF);
10305 if (token.kind == T_EOF)
10308 errorf(HERE, "stray %K outside of function", &token);
10309 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10310 eat_until_matching_token(token.kind);
10315 void set_default_visibility(elf_visibility_tag_t visibility)
10317 default_visibility = visibility;
10323 * @return the translation unit or NULL if errors occurred.
10325 void start_parsing(void)
10327 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10328 label_stack = NEW_ARR_F(stack_entry_t, 0);
10329 diagnostic_count = 0;
10333 print_to_file(stderr);
10335 assert(unit == NULL);
10336 unit = allocate_ast_zero(sizeof(unit[0]));
10338 assert(file_scope == NULL);
10339 file_scope = &unit->scope;
10341 assert(current_scope == NULL);
10342 scope_push(&unit->scope);
10344 create_gnu_builtins();
10346 create_microsoft_intrinsics();
10349 translation_unit_t *finish_parsing(void)
10351 assert(current_scope == &unit->scope);
10354 assert(file_scope == &unit->scope);
10355 check_unused_globals();
10358 DEL_ARR_F(environment_stack);
10359 DEL_ARR_F(label_stack);
10361 translation_unit_t *result = unit;
10366 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10367 * are given length one. */
10368 static void complete_incomplete_arrays(void)
10370 size_t n = ARR_LEN(incomplete_arrays);
10371 for (size_t i = 0; i != n; ++i) {
10372 declaration_t *const decl = incomplete_arrays[i];
10373 type_t *const type = skip_typeref(decl->type);
10375 if (!is_type_incomplete(type))
10378 source_position_t const *const pos = &decl->base.source_position;
10379 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10381 type_t *const new_type = duplicate_type(type);
10382 new_type->array.size_constant = true;
10383 new_type->array.has_implicit_size = true;
10384 new_type->array.size = 1;
10386 type_t *const result = identify_new_type(new_type);
10388 decl->type = result;
10392 static void prepare_main_collect2(entity_t *const entity)
10394 PUSH_SCOPE(&entity->function.statement->compound.scope);
10396 // create call to __main
10397 symbol_t *symbol = symbol_table_insert("__main");
10398 entity_t *subsubmain_ent
10399 = create_implicit_function(symbol, &builtin_source_position);
10401 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10402 type_t *ftype = subsubmain_ent->declaration.type;
10403 ref->base.source_position = builtin_source_position;
10404 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10405 ref->reference.entity = subsubmain_ent;
10407 expression_t *call = allocate_expression_zero(EXPR_CALL);
10408 call->base.source_position = builtin_source_position;
10409 call->base.type = type_void;
10410 call->call.function = ref;
10412 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10413 expr_statement->base.source_position = builtin_source_position;
10414 expr_statement->expression.expression = call;
10416 statement_t *statement = entity->function.statement;
10417 assert(statement->kind == STATEMENT_COMPOUND);
10418 compound_statement_t *compounds = &statement->compound;
10420 expr_statement->base.next = compounds->statements;
10421 compounds->statements = expr_statement;
10428 lookahead_bufpos = 0;
10429 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10432 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10433 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10434 parse_translation_unit();
10435 complete_incomplete_arrays();
10436 DEL_ARR_F(incomplete_arrays);
10437 incomplete_arrays = NULL;
10441 * Initialize the parser.
10443 void init_parser(void)
10445 sym_anonymous = symbol_table_insert("<anonymous>");
10447 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10449 init_expression_parsers();
10450 obstack_init(&temp_obst);
10454 * Terminate the parser.
10456 void exit_parser(void)
10458 obstack_free(&temp_obst, NULL);