2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "adt/strutil.h"
29 #include "diagnostic.h"
30 #include "format_check.h"
31 #include "preprocessor.h"
36 #include "type_hash.h"
39 #include "attribute_t.h"
40 #include "lang_features.h"
45 #include "adt/bitfiddle.h"
46 #include "adt/error.h"
47 #include "adt/array.h"
49 //#define PRINT_TOKENS
50 #define MAX_LOOKAHEAD 1
55 entity_namespace_t namespc;
58 typedef struct declaration_specifiers_t declaration_specifiers_t;
59 struct declaration_specifiers_t {
61 storage_class_t storage_class;
62 unsigned char alignment; /**< Alignment, 0 if not set. */
64 bool thread_local : 1;
65 attribute_t *attributes; /**< list of attributes */
70 * An environment for parsing initializers (and compound literals).
72 typedef struct parse_initializer_env_t {
73 type_t *type; /**< the type of the initializer. In case of an
74 array type with unspecified size this gets
75 adjusted to the actual size. */
76 entity_t *entity; /**< the variable that is initialized if any */
77 bool must_be_constant;
78 } parse_initializer_env_t;
80 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
82 /** The current token. */
84 /** The lookahead ring-buffer. */
85 static token_t lookahead_buffer[MAX_LOOKAHEAD];
86 /** Position of the next token in the lookahead buffer. */
87 static size_t lookahead_bufpos;
88 static stack_entry_t *environment_stack = NULL;
89 static stack_entry_t *label_stack = NULL;
90 static scope_t *file_scope = NULL;
91 static scope_t *current_scope = NULL;
92 /** Point to the current function declaration if inside a function. */
93 static function_t *current_function = NULL;
94 static entity_t *current_entity = NULL;
95 static switch_statement_t *current_switch = NULL;
96 static statement_t *current_loop = NULL;
97 static statement_t *current_parent = NULL;
98 static ms_try_statement_t *current_try = NULL;
99 static linkage_kind_t current_linkage;
100 static goto_statement_t *goto_first = NULL;
101 static goto_statement_t **goto_anchor = NULL;
102 static label_statement_t *label_first = NULL;
103 static label_statement_t **label_anchor = NULL;
104 /** current translation unit. */
105 static translation_unit_t *unit = NULL;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_CURRENT_ENTITY(entity) \
115 entity_t *const new_current_entity = (entity); \
116 entity_t *const old_current_entity = current_entity; \
117 ((void)(current_entity = new_current_entity))
118 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
120 #define PUSH_PARENT(stmt) \
121 statement_t *const new_parent = (stmt); \
122 statement_t *const old_parent = current_parent; \
123 ((void)(current_parent = new_parent))
124 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
126 #define PUSH_SCOPE(scope) \
127 size_t const top = environment_top(); \
128 scope_t *const new_scope = (scope); \
129 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
130 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
131 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
133 #define PUSH_EXTENSION() \
135 bool const old_gcc_extension = in_gcc_extension; \
136 while (accept(T___extension__)) { \
137 in_gcc_extension = true; \
140 #define POP_EXTENSION() \
141 ((void)(in_gcc_extension = old_gcc_extension))
143 /** The token anchor set */
144 static unsigned short token_anchor_set[T_LAST_TOKEN];
146 /** The current source position. */
147 #define HERE (&token.base.pos)
149 /** true if we are in GCC mode. */
150 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
152 static statement_t *parse_compound_statement(bool inside_expression_statement);
153 static statement_t *parse_statement(void);
155 static expression_t *parse_subexpression(precedence_t);
156 static expression_t *parse_expression(void);
157 static type_t *parse_typename(void);
158 static void parse_externals(void);
159 static void parse_external(void);
161 static void parse_compound_type_entries(compound_t *compound_declaration);
163 static void check_call_argument(type_t *expected_type,
164 call_argument_t *argument, unsigned pos);
166 typedef enum declarator_flags_t {
168 DECL_MAY_BE_ABSTRACT = 1U << 0,
169 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
170 DECL_IS_PARAMETER = 1U << 2
171 } declarator_flags_t;
173 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
174 declarator_flags_t flags);
176 static void semantic_comparison(binary_expression_t *expression);
178 #define STORAGE_CLASSES \
179 STORAGE_CLASSES_NO_EXTERN \
182 #define STORAGE_CLASSES_NO_EXTERN \
187 case T__Thread_local:
189 #define TYPE_QUALIFIERS \
194 case T__forceinline: \
195 case T___attribute__:
197 #define COMPLEX_SPECIFIERS \
199 #define IMAGINARY_SPECIFIERS \
202 #define TYPE_SPECIFIERS \
204 case T___builtin_va_list: \
229 #define DECLARATION_START \
234 #define DECLARATION_START_NO_EXTERN \
235 STORAGE_CLASSES_NO_EXTERN \
239 #define EXPRESSION_START \
248 case T_CHARACTER_CONSTANT: \
252 case T_STRING_LITERAL: \
254 case T___FUNCDNAME__: \
255 case T___FUNCSIG__: \
256 case T___PRETTY_FUNCTION__: \
257 case T___builtin_classify_type: \
258 case T___builtin_constant_p: \
259 case T___builtin_isgreater: \
260 case T___builtin_isgreaterequal: \
261 case T___builtin_isless: \
262 case T___builtin_islessequal: \
263 case T___builtin_islessgreater: \
264 case T___builtin_isunordered: \
265 case T___builtin_offsetof: \
266 case T___builtin_va_arg: \
267 case T___builtin_va_copy: \
268 case T___builtin_va_start: \
281 * Returns the size of a statement node.
283 * @param kind the statement kind
285 static size_t get_statement_struct_size(statement_kind_t kind)
287 static const size_t sizes[] = {
288 [STATEMENT_ERROR] = sizeof(statement_base_t),
289 [STATEMENT_EMPTY] = sizeof(statement_base_t),
290 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
291 [STATEMENT_RETURN] = sizeof(return_statement_t),
292 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
293 [STATEMENT_IF] = sizeof(if_statement_t),
294 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
295 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
296 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
297 [STATEMENT_BREAK] = sizeof(statement_base_t),
298 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
299 [STATEMENT_GOTO] = sizeof(goto_statement_t),
300 [STATEMENT_LABEL] = sizeof(label_statement_t),
301 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
302 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
303 [STATEMENT_FOR] = sizeof(for_statement_t),
304 [STATEMENT_ASM] = sizeof(asm_statement_t),
305 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
306 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
308 assert((size_t)kind < lengthof(sizes));
309 assert(sizes[kind] != 0);
314 * Returns the size of an expression node.
316 * @param kind the expression kind
318 static size_t get_expression_struct_size(expression_kind_t kind)
320 static const size_t sizes[] = {
321 [EXPR_ERROR] = sizeof(expression_base_t),
322 [EXPR_REFERENCE] = sizeof(reference_expression_t),
323 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
324 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_CHARACTER] = sizeof(string_literal_expression_t),
328 [EXPR_LITERAL_MS_NOOP] = sizeof(literal_expression_t),
329 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
330 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
331 [EXPR_CALL] = sizeof(call_expression_t),
332 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
333 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
334 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
335 [EXPR_SELECT] = sizeof(select_expression_t),
336 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
337 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
338 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
339 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
340 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
341 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
342 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
343 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
344 [EXPR_VA_START] = sizeof(va_start_expression_t),
345 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
346 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
347 [EXPR_STATEMENT] = sizeof(statement_expression_t),
348 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
350 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
351 return sizes[EXPR_UNARY_FIRST];
353 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
354 return sizes[EXPR_BINARY_FIRST];
356 assert((size_t)kind < lengthof(sizes));
357 assert(sizes[kind] != 0);
362 * Allocate a statement node of given kind and initialize all
363 * fields with zero. Sets its source position to the position
364 * of the current token.
366 static statement_t *allocate_statement_zero(statement_kind_t kind)
368 size_t size = get_statement_struct_size(kind);
369 statement_t *res = allocate_ast_zero(size);
371 res->base.kind = kind;
372 res->base.parent = current_parent;
373 res->base.pos = *HERE;
378 * Allocate an expression node of given kind and initialize all
381 * @param kind the kind of the expression to allocate
383 static expression_t *allocate_expression_zero(expression_kind_t kind)
385 size_t size = get_expression_struct_size(kind);
386 expression_t *res = allocate_ast_zero(size);
388 res->base.kind = kind;
389 res->base.type = type_error_type;
390 res->base.pos = *HERE;
395 * Creates a new invalid expression at the source position
396 * of the current token.
398 static expression_t *create_error_expression(void)
400 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
401 expression->base.type = type_error_type;
406 * Creates a new invalid statement.
408 static statement_t *create_error_statement(void)
410 return allocate_statement_zero(STATEMENT_ERROR);
414 * Allocate a new empty statement.
416 static statement_t *create_empty_statement(void)
418 return allocate_statement_zero(STATEMENT_EMPTY);
422 * Returns the size of an initializer node.
424 * @param kind the initializer kind
426 static size_t get_initializer_size(initializer_kind_t kind)
428 static const size_t sizes[] = {
429 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
430 [INITIALIZER_STRING] = sizeof(initializer_value_t),
431 [INITIALIZER_LIST] = sizeof(initializer_list_t),
432 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
434 assert((size_t)kind < lengthof(sizes));
435 assert(sizes[kind] != 0);
440 * Allocate an initializer node of given kind and initialize all
443 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
445 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
452 * Returns the index of the top element of the environment stack.
454 static size_t environment_top(void)
456 return ARR_LEN(environment_stack);
460 * Returns the index of the top element of the global label stack.
462 static size_t label_top(void)
464 return ARR_LEN(label_stack);
468 * Return the next token.
470 static inline void next_token(void)
472 token = lookahead_buffer[lookahead_bufpos];
473 lookahead_buffer[lookahead_bufpos] = pp_token;
474 next_preprocessing_token();
476 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
479 print_token(stderr, &token);
480 fprintf(stderr, "\n");
484 static inline void eat(token_kind_t const kind)
486 assert(token.kind == kind);
492 * Consume the current token, if it is of the expected kind.
494 * @param kind The kind of token to consume.
495 * @return Whether the token was consumed.
497 static inline bool accept(token_kind_t const kind)
499 if (token.kind == kind) {
508 * Return the next token with a given lookahead.
510 static inline const token_t *look_ahead(size_t num)
512 assert(0 < num && num <= MAX_LOOKAHEAD);
513 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
514 return &lookahead_buffer[pos];
518 * Adds a token type to the token type anchor set (a multi-set).
520 static void add_anchor_token(token_kind_t const token_kind)
522 assert(token_kind < T_LAST_TOKEN);
523 ++token_anchor_set[token_kind];
527 * Remove a token type from the token type anchor set (a multi-set).
529 static void rem_anchor_token(token_kind_t const token_kind)
531 assert(token_kind < T_LAST_TOKEN);
532 assert(token_anchor_set[token_kind] != 0);
533 --token_anchor_set[token_kind];
537 * Eat tokens until a matching token type is found.
539 static void eat_until_matching_token(token_kind_t const type)
541 token_kind_t end_token;
543 case '(': end_token = ')'; break;
544 case '{': end_token = '}'; break;
545 case '[': end_token = ']'; break;
546 default: end_token = type; break;
549 unsigned parenthesis_count = 0;
550 unsigned brace_count = 0;
551 unsigned bracket_count = 0;
552 while (token.kind != end_token ||
553 parenthesis_count != 0 ||
555 bracket_count != 0) {
556 switch (token.kind) {
558 case '(': ++parenthesis_count; break;
559 case '{': ++brace_count; break;
560 case '[': ++bracket_count; break;
563 if (parenthesis_count > 0)
573 if (bracket_count > 0)
576 if (token.kind == end_token &&
577 parenthesis_count == 0 &&
591 * Eat input tokens until an anchor is found.
593 static void eat_until_anchor(void)
595 while (token_anchor_set[token.kind] == 0) {
596 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
597 eat_until_matching_token(token.kind);
603 * Eat a whole block from input tokens.
605 static void eat_block(void)
607 eat_until_matching_token('{');
612 * Report a parse error because an expected token was not found.
615 #if defined __GNUC__ && __GNUC__ >= 4
616 __attribute__((sentinel))
618 void parse_error_expected(const char *message, ...)
620 if (message != NULL) {
621 errorf(HERE, "%s", message);
624 va_start(ap, message);
625 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
630 * Report an incompatible type.
632 static void type_error_incompatible(const char *msg,
633 const position_t *pos, type_t *type1, type_t *type2)
635 errorf(pos, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
638 static bool skip_till(token_kind_t const expected, char const *const context)
640 if (UNLIKELY(token.kind != expected)) {
641 parse_error_expected(context, expected, NULL);
642 add_anchor_token(expected);
644 rem_anchor_token(expected);
645 if (token.kind != expected)
652 * Expect the current token is the expected token.
653 * If not, generate an error and skip until the next anchor.
655 static void expect(token_kind_t const expected)
657 if (skip_till(expected, NULL))
661 static symbol_t *expect_identifier(char const *const context,
662 position_t *const pos)
664 if (!skip_till(T_IDENTIFIER, context))
666 symbol_t *const sym = token.base.symbol;
674 * Push a given scope on the scope stack and make it the
677 static scope_t *scope_push(scope_t *new_scope)
679 if (current_scope != NULL) {
680 new_scope->depth = current_scope->depth + 1;
683 scope_t *old_scope = current_scope;
684 current_scope = new_scope;
689 * Pop the current scope from the scope stack.
691 static void scope_pop(scope_t *old_scope)
693 current_scope = old_scope;
697 * Search an entity by its symbol in a given namespace.
699 static entity_t *get_entity(const symbol_t *const symbol,
700 namespace_tag_t namespc)
702 entity_t *entity = symbol->entity;
703 for (; entity != NULL; entity = entity->base.symbol_next) {
704 if ((namespace_tag_t)entity->base.namespc == namespc)
711 /* §6.2.3:1 24) There is only one name space for tags even though three are
713 static entity_t *get_tag(symbol_t const *const symbol,
714 entity_kind_tag_t const kind)
716 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
717 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
719 "'%Y' defined as wrong kind of tag (previous definition %P)",
720 symbol, &entity->base.pos);
727 * pushs an entity on the environment stack and links the corresponding symbol
730 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
732 symbol_t *symbol = entity->base.symbol;
733 entity_namespace_t namespc = entity->base.namespc;
734 assert(namespc != 0);
736 /* replace/add entity into entity list of the symbol */
739 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
744 /* replace an entry? */
745 if (iter->base.namespc == namespc) {
746 entity->base.symbol_next = iter->base.symbol_next;
752 /* remember old declaration */
754 entry.symbol = symbol;
755 entry.old_entity = iter;
756 entry.namespc = namespc;
757 ARR_APP1(stack_entry_t, *stack_ptr, entry);
761 * Push an entity on the environment stack.
763 static void environment_push(entity_t *entity)
765 assert(entity->base.pos.input_name != NULL);
766 assert(entity->base.parent_scope != NULL);
767 stack_push(&environment_stack, entity);
771 * Push a declaration on the global label stack.
773 * @param declaration the declaration
775 static void label_push(entity_t *label)
777 /* we abuse the parameters scope as parent for the labels */
778 label->base.parent_scope = ¤t_function->parameters;
779 stack_push(&label_stack, label);
783 * pops symbols from the environment stack until @p new_top is the top element
785 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
787 stack_entry_t *stack = *stack_ptr;
788 size_t top = ARR_LEN(stack);
791 assert(new_top <= top);
795 for (i = top; i > new_top; --i) {
796 stack_entry_t *entry = &stack[i - 1];
798 entity_t *old_entity = entry->old_entity;
799 symbol_t *symbol = entry->symbol;
800 entity_namespace_t namespc = entry->namespc;
802 /* replace with old_entity/remove */
805 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
807 assert(iter != NULL);
808 /* replace an entry? */
809 if (iter->base.namespc == namespc)
813 /* restore definition from outer scopes (if there was one) */
814 if (old_entity != NULL) {
815 old_entity->base.symbol_next = iter->base.symbol_next;
816 *anchor = old_entity;
818 /* remove entry from list */
819 *anchor = iter->base.symbol_next;
823 ARR_SHRINKLEN(*stack_ptr, new_top);
827 * Pop all entries from the environment stack until the new_top
830 * @param new_top the new stack top
832 static void environment_pop_to(size_t new_top)
834 stack_pop_to(&environment_stack, new_top);
838 * Pop all entries from the global label stack until the new_top
841 * @param new_top the new stack top
843 static void label_pop_to(size_t new_top)
845 stack_pop_to(&label_stack, new_top);
849 * §6.3.1.1:2 Do integer promotion for a given type.
851 * @param type the type to promote
852 * @return the promoted type
854 static type_t *promote_integer(type_t *type)
856 atomic_type_kind_t akind = get_arithmetic_akind(type);
857 if (get_akind_rank(akind) < get_akind_rank(ATOMIC_TYPE_INT))
864 * Check if a given expression represents a null pointer constant.
866 * @param expression the expression to check
868 static bool is_null_pointer_constant(const expression_t *expression)
870 /* skip void* cast */
871 if (expression->kind == EXPR_UNARY_CAST) {
872 type_t *const type = skip_typeref(expression->base.type);
873 if (types_compatible(type, type_void_ptr))
874 expression = expression->unary.value;
877 type_t *const type = skip_typeref(expression->base.type);
878 if (!is_type_integer(type))
880 switch (is_constant_expression(expression)) {
881 case EXPR_CLASS_ERROR: return true;
882 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
883 default: return false;
888 * Create an implicit cast expression.
890 * @param expression the expression to cast
891 * @param dest_type the destination type
893 static expression_t *create_implicit_cast(expression_t *expression,
896 type_t *const source_type = skip_typeref(expression->base.type);
897 if (source_type == skip_typeref(dest_type))
900 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
901 cast->unary.value = expression;
902 cast->base.type = dest_type;
903 cast->base.implicit = true;
908 typedef enum assign_error_t {
910 ASSIGN_ERROR_INCOMPATIBLE,
911 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
912 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
913 ASSIGN_WARNING_POINTER_FROM_INT,
914 ASSIGN_WARNING_INT_FROM_POINTER
917 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, position_t const *const pos)
919 type_t *const orig_type_right = right->base.type;
920 type_t *const type_left = skip_typeref(orig_type_left);
921 type_t *const type_right = skip_typeref(orig_type_right);
926 case ASSIGN_ERROR_INCOMPATIBLE:
927 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
930 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
931 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
932 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
934 /* the left type has all qualifiers from the right type */
935 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
936 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);
940 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
941 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
944 case ASSIGN_WARNING_POINTER_FROM_INT:
945 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
948 case ASSIGN_WARNING_INT_FROM_POINTER:
949 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
953 panic("invalid error value");
957 /** Implements the rules from §6.5.16.1 */
958 static assign_error_t semantic_assign(type_t *orig_type_left,
959 const expression_t *const right)
961 type_t *const orig_type_right = right->base.type;
962 type_t *const type_left = skip_typeref(orig_type_left);
963 type_t *const type_right = skip_typeref(orig_type_right);
965 if (is_type_pointer(type_left)) {
966 if (is_null_pointer_constant(right)) {
967 return ASSIGN_SUCCESS;
968 } else if (is_type_pointer(type_right)) {
969 type_t *points_to_left
970 = skip_typeref(type_left->pointer.points_to);
971 type_t *points_to_right
972 = skip_typeref(type_right->pointer.points_to);
973 assign_error_t res = ASSIGN_SUCCESS;
975 /* the left type has all qualifiers from the right type */
976 unsigned missing_qualifiers
977 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
978 if (missing_qualifiers != 0) {
979 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
982 points_to_left = get_unqualified_type(points_to_left);
983 points_to_right = get_unqualified_type(points_to_right);
985 if (is_type_void(points_to_left))
988 if (is_type_void(points_to_right)) {
989 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
990 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
993 if (!types_compatible(points_to_left, points_to_right)) {
994 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
998 } else if (is_type_integer(type_right)) {
999 return ASSIGN_WARNING_POINTER_FROM_INT;
1001 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1002 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1003 && is_type_pointer(type_right))) {
1004 return ASSIGN_SUCCESS;
1005 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1006 type_t *const unqual_type_left = get_unqualified_type(type_left);
1007 type_t *const unqual_type_right = get_unqualified_type(type_right);
1008 if (types_compatible(unqual_type_left, unqual_type_right)) {
1009 return ASSIGN_SUCCESS;
1011 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1012 return ASSIGN_WARNING_INT_FROM_POINTER;
1015 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1016 return ASSIGN_SUCCESS;
1018 return ASSIGN_ERROR_INCOMPATIBLE;
1021 static expression_t *parse_constant_expression(void)
1023 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1025 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1026 errorf(&result->base.pos, "expression '%E' is not constant", result);
1032 static expression_t *parse_assignment_expression(void)
1034 return parse_subexpression(PREC_ASSIGNMENT);
1037 static void append_string(string_t const *const s)
1039 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1040 * possible, because other tokens are grown there alongside. */
1041 obstack_grow(&ast_obstack, s->begin, s->size);
1044 static string_t finish_string(string_encoding_t const enc)
1046 obstack_1grow(&ast_obstack, '\0');
1047 size_t const size = obstack_object_size(&ast_obstack) - 1;
1048 char const *const string = obstack_finish(&ast_obstack);
1049 return (string_t){ string, size, enc };
1052 static string_t concat_string_literals(void)
1054 assert(token.kind == T_STRING_LITERAL);
1057 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1058 append_string(&token.literal.string);
1059 eat(T_STRING_LITERAL);
1060 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1061 string_encoding_t enc = token.literal.string.encoding;
1063 string_encoding_t const new_enc = token.literal.string.encoding;
1064 if (new_enc != enc && new_enc != STRING_ENCODING_CHAR) {
1065 if (enc == STRING_ENCODING_CHAR) {
1068 errorf(HERE, "concatenating string literals with encodings %s and %s", get_string_encoding_prefix(enc), get_string_encoding_prefix(new_enc));
1071 append_string(&token.literal.string);
1072 eat(T_STRING_LITERAL);
1073 } while (token.kind == T_STRING_LITERAL);
1074 result = finish_string(enc);
1076 result = token.literal.string;
1077 eat(T_STRING_LITERAL);
1083 static string_t parse_string_literals(char const *const context)
1085 if (!skip_till(T_STRING_LITERAL, context))
1086 return (string_t){ "", 0, STRING_ENCODING_CHAR };
1088 position_t const pos = *HERE;
1089 string_t const res = concat_string_literals();
1091 if (res.encoding != STRING_ENCODING_CHAR) {
1092 errorf(&pos, "expected plain string literal, got %s string literal", get_string_encoding_prefix(res.encoding));
1098 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1100 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1101 attribute->kind = kind;
1102 attribute->pos = *HERE;
1107 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1110 * __attribute__ ( ( attribute-list ) )
1114 * attribute_list , attrib
1119 * any-word ( identifier )
1120 * any-word ( identifier , nonempty-expr-list )
1121 * any-word ( expr-list )
1123 * where the "identifier" must not be declared as a type, and
1124 * "any-word" may be any identifier (including one declared as a
1125 * type), a reserved word storage class specifier, type specifier or
1126 * type qualifier. ??? This still leaves out most reserved keywords
1127 * (following the old parser), shouldn't we include them, and why not
1128 * allow identifiers declared as types to start the arguments?
1130 * Matze: this all looks confusing and little systematic, so we're even less
1131 * strict and parse any list of things which are identifiers or
1132 * (assignment-)expressions.
1134 static attribute_argument_t *parse_attribute_arguments(void)
1136 attribute_argument_t *first = NULL;
1137 attribute_argument_t **anchor = &first;
1138 if (token.kind != ')') do {
1139 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1141 /* is it an identifier */
1142 if (token.kind == T_IDENTIFIER
1143 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1144 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1145 argument->v.symbol = token.base.symbol;
1148 /* must be an expression */
1149 expression_t *expression = parse_assignment_expression();
1151 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1152 argument->v.expression = expression;
1155 /* append argument */
1157 anchor = &argument->next;
1158 } while (accept(','));
1163 static attribute_t *parse_attribute_asm(void)
1165 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1168 attribute->a.arguments = parse_attribute_arguments();
1172 static attribute_t *parse_attribute_gnu_single(void)
1174 /* parse "any-word" */
1175 symbol_t *const symbol = token.base.symbol;
1176 if (symbol == NULL) {
1177 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1181 attribute_kind_t kind;
1182 char const *const name = symbol->string;
1183 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1184 if (kind > ATTRIBUTE_GNU_LAST) {
1185 /* special case for "__const" */
1186 if (token.kind == T_const) {
1187 kind = ATTRIBUTE_GNU_CONST;
1191 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1192 /* TODO: we should still save the attribute in the list... */
1193 kind = ATTRIBUTE_UNKNOWN;
1197 const char *attribute_name = get_attribute_name(kind);
1198 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1202 attribute_t *attribute = allocate_attribute_zero(kind);
1205 /* parse arguments */
1207 attribute->a.arguments = parse_attribute_arguments();
1212 static attribute_t *parse_attribute_gnu(void)
1214 attribute_t *first = NULL;
1215 attribute_t **anchor = &first;
1217 eat(T___attribute__);
1218 add_anchor_token(')');
1219 add_anchor_token(',');
1223 if (token.kind != ')') do {
1224 attribute_t *attribute = parse_attribute_gnu_single();
1226 *anchor = attribute;
1227 anchor = &attribute->next;
1229 } while (accept(','));
1230 rem_anchor_token(',');
1231 rem_anchor_token(')');
1238 /** Parse attributes. */
1239 static attribute_t *parse_attributes(attribute_t *first)
1241 attribute_t **anchor = &first;
1243 while (*anchor != NULL)
1244 anchor = &(*anchor)->next;
1246 attribute_t *attribute;
1247 switch (token.kind) {
1248 case T___attribute__:
1249 attribute = parse_attribute_gnu();
1250 if (attribute == NULL)
1255 attribute = parse_attribute_asm();
1259 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1264 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1268 case T__forceinline:
1269 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1270 eat(T__forceinline);
1274 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1279 /* TODO record modifier */
1280 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1281 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1289 *anchor = attribute;
1290 anchor = &attribute->next;
1294 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1296 static entity_t *determine_lhs_ent(expression_t *const expr,
1299 switch (expr->kind) {
1300 case EXPR_REFERENCE: {
1301 entity_t *const entity = expr->reference.entity;
1302 /* we should only find variables as lvalues... */
1303 if (entity->base.kind != ENTITY_VARIABLE
1304 && entity->base.kind != ENTITY_PARAMETER)
1310 case EXPR_ARRAY_ACCESS: {
1311 expression_t *const ref = expr->array_access.array_ref;
1312 entity_t * ent = NULL;
1313 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1314 ent = determine_lhs_ent(ref, lhs_ent);
1317 mark_vars_read(ref, lhs_ent);
1319 mark_vars_read(expr->array_access.index, lhs_ent);
1324 mark_vars_read(expr->select.compound, lhs_ent);
1325 if (is_type_compound(skip_typeref(expr->base.type)))
1326 return determine_lhs_ent(expr->select.compound, lhs_ent);
1330 case EXPR_UNARY_DEREFERENCE: {
1331 expression_t *const val = expr->unary.value;
1332 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1334 return determine_lhs_ent(val->unary.value, lhs_ent);
1336 mark_vars_read(val, NULL);
1342 mark_vars_read(expr, NULL);
1347 #define ENT_ANY ((entity_t*)-1)
1350 * Mark declarations, which are read. This is used to detect variables, which
1354 * x is not marked as "read", because it is only read to calculate its own new
1358 * x and y are not detected as "not read", because multiple variables are
1361 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1363 switch (expr->kind) {
1364 case EXPR_REFERENCE: {
1365 entity_t *const entity = expr->reference.entity;
1366 if (entity->kind != ENTITY_VARIABLE
1367 && entity->kind != ENTITY_PARAMETER)
1370 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1371 entity->variable.read = true;
1377 // TODO respect pure/const
1378 mark_vars_read(expr->call.function, NULL);
1379 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1380 mark_vars_read(arg->expression, NULL);
1384 case EXPR_CONDITIONAL:
1385 // TODO lhs_decl should depend on whether true/false have an effect
1386 mark_vars_read(expr->conditional.condition, NULL);
1387 if (expr->conditional.true_expression != NULL)
1388 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1389 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1393 if (lhs_ent == ENT_ANY
1394 && !is_type_compound(skip_typeref(expr->base.type)))
1396 mark_vars_read(expr->select.compound, lhs_ent);
1399 case EXPR_ARRAY_ACCESS: {
1400 mark_vars_read(expr->array_access.index, lhs_ent);
1401 expression_t *const ref = expr->array_access.array_ref;
1402 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1403 if (lhs_ent == ENT_ANY)
1406 mark_vars_read(ref, lhs_ent);
1411 mark_vars_read(expr->va_arge.ap, lhs_ent);
1415 mark_vars_read(expr->va_copye.src, lhs_ent);
1418 case EXPR_UNARY_CAST:
1419 /* Special case: Use void cast to mark a variable as "read" */
1420 if (is_type_void(skip_typeref(expr->base.type)))
1425 case EXPR_UNARY_THROW:
1426 if (expr->unary.value == NULL)
1429 case EXPR_UNARY_DEREFERENCE:
1430 case EXPR_UNARY_DELETE:
1431 case EXPR_UNARY_DELETE_ARRAY:
1432 if (lhs_ent == ENT_ANY)
1436 case EXPR_UNARY_NEGATE:
1437 case EXPR_UNARY_PLUS:
1438 case EXPR_UNARY_COMPLEMENT:
1439 case EXPR_UNARY_NOT:
1440 case EXPR_UNARY_TAKE_ADDRESS:
1441 case EXPR_UNARY_POSTFIX_INCREMENT:
1442 case EXPR_UNARY_POSTFIX_DECREMENT:
1443 case EXPR_UNARY_PREFIX_INCREMENT:
1444 case EXPR_UNARY_PREFIX_DECREMENT:
1445 case EXPR_UNARY_ASSUME:
1446 case EXPR_UNARY_IMAG:
1447 case EXPR_UNARY_REAL:
1449 mark_vars_read(expr->unary.value, lhs_ent);
1452 case EXPR_BINARY_ADD:
1453 case EXPR_BINARY_SUB:
1454 case EXPR_BINARY_MUL:
1455 case EXPR_BINARY_DIV:
1456 case EXPR_BINARY_MOD:
1457 case EXPR_BINARY_EQUAL:
1458 case EXPR_BINARY_NOTEQUAL:
1459 case EXPR_BINARY_LESS:
1460 case EXPR_BINARY_LESSEQUAL:
1461 case EXPR_BINARY_GREATER:
1462 case EXPR_BINARY_GREATEREQUAL:
1463 case EXPR_BINARY_BITWISE_AND:
1464 case EXPR_BINARY_BITWISE_OR:
1465 case EXPR_BINARY_BITWISE_XOR:
1466 case EXPR_BINARY_LOGICAL_AND:
1467 case EXPR_BINARY_LOGICAL_OR:
1468 case EXPR_BINARY_SHIFTLEFT:
1469 case EXPR_BINARY_SHIFTRIGHT:
1470 case EXPR_BINARY_COMMA:
1471 case EXPR_BINARY_ISGREATER:
1472 case EXPR_BINARY_ISGREATEREQUAL:
1473 case EXPR_BINARY_ISLESS:
1474 case EXPR_BINARY_ISLESSEQUAL:
1475 case EXPR_BINARY_ISLESSGREATER:
1476 case EXPR_BINARY_ISUNORDERED:
1477 mark_vars_read(expr->binary.left, lhs_ent);
1478 mark_vars_read(expr->binary.right, lhs_ent);
1481 case EXPR_BINARY_ASSIGN:
1482 case EXPR_BINARY_MUL_ASSIGN:
1483 case EXPR_BINARY_DIV_ASSIGN:
1484 case EXPR_BINARY_MOD_ASSIGN:
1485 case EXPR_BINARY_ADD_ASSIGN:
1486 case EXPR_BINARY_SUB_ASSIGN:
1487 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1488 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1489 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1490 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1491 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1492 if (lhs_ent == ENT_ANY)
1494 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1495 mark_vars_read(expr->binary.right, lhs_ent);
1500 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1503 case EXPR_LITERAL_CASES:
1504 case EXPR_LITERAL_CHARACTER:
1506 case EXPR_STRING_LITERAL:
1507 case EXPR_COMPOUND_LITERAL: // TODO init?
1509 case EXPR_CLASSIFY_TYPE:
1512 case EXPR_BUILTIN_CONSTANT_P:
1513 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1515 case EXPR_STATEMENT: // TODO
1516 case EXPR_LABEL_ADDRESS:
1517 case EXPR_ENUM_CONSTANT:
1521 panic("unhandled expression");
1524 static designator_t *parse_designation(void)
1526 designator_t *result = NULL;
1527 designator_t **anchor = &result;
1530 designator_t *designator;
1531 switch (token.kind) {
1533 designator = allocate_ast_zero(sizeof(designator[0]));
1534 designator->pos = *HERE;
1536 add_anchor_token(']');
1537 designator->array_index = parse_constant_expression();
1538 rem_anchor_token(']');
1542 designator = allocate_ast_zero(sizeof(designator[0]));
1543 designator->pos = *HERE;
1545 designator->symbol = expect_identifier("while parsing designator", NULL);
1546 if (!designator->symbol)
1554 assert(designator != NULL);
1555 *anchor = designator;
1556 anchor = &designator->next;
1561 * Build an initializer from a given expression.
1563 static initializer_t *initializer_from_expression(type_t *orig_type,
1564 expression_t *expression)
1566 /* TODO check that expression is a constant expression */
1568 type_t *const type = skip_typeref(orig_type);
1570 /* §6.7.8.14/15 char array may be initialized by string literals */
1571 if (expression->kind == EXPR_STRING_LITERAL && is_type_array(type)) {
1572 array_type_t *const array_type = &type->array;
1573 type_t *const element_type = skip_typeref(array_type->element_type);
1574 switch (expression->string_literal.value.encoding) {
1575 case STRING_ENCODING_CHAR:
1576 case STRING_ENCODING_UTF8: {
1577 if (is_type_atomic(element_type, ATOMIC_TYPE_CHAR) ||
1578 is_type_atomic(element_type, ATOMIC_TYPE_SCHAR) ||
1579 is_type_atomic(element_type, ATOMIC_TYPE_UCHAR)) {
1580 goto make_string_init;
1585 case STRING_ENCODING_CHAR16:
1586 case STRING_ENCODING_CHAR32:
1587 case STRING_ENCODING_WIDE: {
1588 assert(is_type_pointer(expression->base.type));
1589 type_t *const init_type = get_unqualified_type(expression->base.type->pointer.points_to);
1590 if (types_compatible(get_unqualified_type(element_type), init_type)) {
1592 initializer_t *const init = allocate_initializer_zero(INITIALIZER_STRING);
1593 init->value.value = expression;
1601 assign_error_t error = semantic_assign(type, expression);
1602 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1604 report_assign_error(error, type, expression, "initializer",
1605 &expression->base.pos);
1607 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1608 result->value.value = create_implicit_cast(expression, type);
1614 * Parses an scalar initializer.
1616 * §6.7.8.11; eat {} without warning
1618 static initializer_t *parse_scalar_initializer(type_t *type,
1619 bool must_be_constant)
1621 /* there might be extra {} hierarchies */
1623 if (token.kind == '{') {
1624 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1628 } while (token.kind == '{');
1631 expression_t *expression = parse_assignment_expression();
1632 mark_vars_read(expression, NULL);
1633 if (must_be_constant && !is_linker_constant(expression)) {
1634 errorf(&expression->base.pos,
1635 "initialisation expression '%E' is not constant",
1639 initializer_t *initializer = initializer_from_expression(type, expression);
1641 if (initializer == NULL) {
1642 errorf(&expression->base.pos,
1643 "expression '%E' (type '%T') doesn't match expected type '%T'",
1644 expression, expression->base.type, type);
1649 bool additional_warning_displayed = false;
1650 while (braces > 0) {
1652 if (token.kind != '}') {
1653 if (!additional_warning_displayed) {
1654 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1655 additional_warning_displayed = true;
1666 * An entry in the type path.
1668 typedef struct type_path_entry_t type_path_entry_t;
1669 struct type_path_entry_t {
1670 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1672 size_t index; /**< For array types: the current index. */
1673 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1678 * A type path expression a position inside compound or array types.
1680 typedef struct type_path_t type_path_t;
1681 struct type_path_t {
1682 type_path_entry_t *path; /**< An flexible array containing the current path. */
1683 type_t *top_type; /**< type of the element the path points */
1684 size_t max_index; /**< largest index in outermost array */
1688 * Prints a type path for debugging.
1690 static __attribute__((unused)) void debug_print_type_path(
1691 const type_path_t *path)
1693 size_t len = ARR_LEN(path->path);
1695 for (size_t i = 0; i < len; ++i) {
1696 const type_path_entry_t *entry = & path->path[i];
1698 type_t *type = skip_typeref(entry->type);
1699 if (is_type_compound(type)) {
1700 /* in gcc mode structs can have no members */
1701 if (entry->v.compound_entry == NULL) {
1705 fprintf(stderr, ".%s",
1706 entry->v.compound_entry->base.symbol->string);
1707 } else if (is_type_array(type)) {
1708 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1710 fprintf(stderr, "-INVALID-");
1713 if (path->top_type != NULL) {
1714 fprintf(stderr, " (");
1715 print_type(path->top_type);
1716 fprintf(stderr, ")");
1721 * Return the top type path entry, i.e. in a path
1722 * (type).a.b returns the b.
1724 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1726 size_t len = ARR_LEN(path->path);
1728 return &path->path[len-1];
1732 * Enlarge the type path by an (empty) element.
1734 static type_path_entry_t *append_to_type_path(type_path_t *path)
1736 size_t len = ARR_LEN(path->path);
1737 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1739 type_path_entry_t *result = & path->path[len];
1740 memset(result, 0, sizeof(result[0]));
1745 * Descending into a sub-type. Enter the scope of the current top_type.
1747 static void descend_into_subtype(type_path_t *path)
1749 type_t *orig_top_type = path->top_type;
1750 type_t *top_type = skip_typeref(orig_top_type);
1752 type_path_entry_t *top = append_to_type_path(path);
1753 top->type = top_type;
1755 if (is_type_compound(top_type)) {
1756 compound_t *const compound = top_type->compound.compound;
1757 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1759 if (entry != NULL) {
1760 top->v.compound_entry = &entry->declaration;
1761 path->top_type = entry->declaration.type;
1763 path->top_type = NULL;
1765 } else if (is_type_array(top_type)) {
1767 path->top_type = top_type->array.element_type;
1769 assert(!is_type_valid(top_type));
1774 * Pop an entry from the given type path, i.e. returning from
1775 * (type).a.b to (type).a
1777 static void ascend_from_subtype(type_path_t *path)
1779 type_path_entry_t *top = get_type_path_top(path);
1781 path->top_type = top->type;
1783 size_t len = ARR_LEN(path->path);
1784 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1788 * Pop entries from the given type path until the given
1789 * path level is reached.
1791 static void ascend_to(type_path_t *path, size_t top_path_level)
1793 size_t len = ARR_LEN(path->path);
1795 while (len > top_path_level) {
1796 ascend_from_subtype(path);
1797 len = ARR_LEN(path->path);
1801 static bool walk_designator(type_path_t *path, const designator_t *designator,
1802 bool used_in_offsetof)
1804 for (; designator != NULL; designator = designator->next) {
1805 type_path_entry_t *top = get_type_path_top(path);
1806 type_t *orig_type = top->type;
1808 type_t *type = skip_typeref(orig_type);
1810 if (designator->symbol != NULL) {
1811 symbol_t *symbol = designator->symbol;
1812 if (!is_type_compound(type)) {
1813 if (is_type_valid(type)) {
1814 errorf(&designator->pos,
1815 "'.%Y' designator used for non-compound type '%T'",
1819 top->type = type_error_type;
1820 top->v.compound_entry = NULL;
1821 orig_type = type_error_type;
1823 compound_t *compound = type->compound.compound;
1824 entity_t *iter = compound->members.entities;
1825 for (; iter != NULL; iter = iter->base.next) {
1826 if (iter->base.symbol == symbol) {
1831 errorf(&designator->pos,
1832 "'%T' has no member named '%Y'", orig_type, symbol);
1835 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1836 if (used_in_offsetof && iter->compound_member.bitfield) {
1837 errorf(&designator->pos,
1838 "offsetof designator '%Y' must not specify bitfield",
1843 top->type = orig_type;
1844 top->v.compound_entry = &iter->declaration;
1845 orig_type = iter->declaration.type;
1848 expression_t *array_index = designator->array_index;
1849 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1852 if (!is_type_array(type)) {
1853 if (is_type_valid(type)) {
1854 errorf(&designator->pos,
1855 "[%E] designator used for non-array type '%T'",
1856 array_index, orig_type);
1861 long index = fold_constant_to_int(array_index);
1862 if (!used_in_offsetof) {
1864 errorf(&designator->pos,
1865 "array index [%E] must be positive", array_index);
1866 } else if (type->array.size_constant) {
1867 long array_size = type->array.size;
1868 if (index >= array_size) {
1869 errorf(&designator->pos,
1870 "designator [%E] (%d) exceeds array size %d",
1871 array_index, index, array_size);
1876 top->type = orig_type;
1877 top->v.index = (size_t) index;
1878 orig_type = type->array.element_type;
1880 path->top_type = orig_type;
1882 if (designator->next != NULL) {
1883 descend_into_subtype(path);
1889 static void advance_current_object(type_path_t *path, size_t top_path_level)
1891 type_path_entry_t *top = get_type_path_top(path);
1893 type_t *type = skip_typeref(top->type);
1894 if (is_type_union(type)) {
1895 /* in unions only the first element is initialized */
1896 top->v.compound_entry = NULL;
1897 } else if (is_type_struct(type)) {
1898 declaration_t *entry = top->v.compound_entry;
1900 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1901 if (next_entity != NULL) {
1902 assert(is_declaration(next_entity));
1903 entry = &next_entity->declaration;
1908 top->v.compound_entry = entry;
1909 if (entry != NULL) {
1910 path->top_type = entry->type;
1913 } else if (is_type_array(type)) {
1914 assert(is_type_array(type));
1918 if (!type->array.size_constant || top->v.index < type->array.size) {
1922 assert(!is_type_valid(type));
1926 /* we're past the last member of the current sub-aggregate, try if we
1927 * can ascend in the type hierarchy and continue with another subobject */
1928 size_t len = ARR_LEN(path->path);
1930 if (len > top_path_level) {
1931 ascend_from_subtype(path);
1932 advance_current_object(path, top_path_level);
1934 path->top_type = NULL;
1939 * skip any {...} blocks until a closing bracket is reached.
1941 static void skip_initializers(void)
1945 while (token.kind != '}') {
1946 if (token.kind == T_EOF)
1948 if (token.kind == '{') {
1956 static initializer_t *create_empty_initializer(void)
1958 static initializer_t empty_initializer
1959 = { .list = { { INITIALIZER_LIST }, 0 } };
1960 return &empty_initializer;
1964 * Parse a part of an initialiser for a struct or union,
1966 static initializer_t *parse_sub_initializer(type_path_t *path,
1967 type_t *outer_type, size_t top_path_level,
1968 parse_initializer_env_t *env)
1970 if (token.kind == '}') {
1971 /* empty initializer */
1972 return create_empty_initializer();
1975 initializer_t *result = NULL;
1977 type_t *orig_type = path->top_type;
1978 type_t *type = NULL;
1980 if (orig_type == NULL) {
1981 /* We are initializing an empty compound. */
1983 type = skip_typeref(orig_type);
1986 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1989 designator_t *designator = NULL;
1990 if (token.kind == '.' || token.kind == '[') {
1991 designator = parse_designation();
1992 goto finish_designator;
1993 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1994 /* GNU-style designator ("identifier: value") */
1995 designator = allocate_ast_zero(sizeof(designator[0]));
1996 designator->pos = *HERE;
1997 designator->symbol = token.base.symbol;
2002 /* reset path to toplevel, evaluate designator from there */
2003 ascend_to(path, top_path_level);
2004 if (!walk_designator(path, designator, false)) {
2005 /* can't continue after designation error */
2009 initializer_t *designator_initializer
2010 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2011 designator_initializer->designator.designator = designator;
2012 ARR_APP1(initializer_t*, initializers, designator_initializer);
2014 orig_type = path->top_type;
2015 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2020 if (token.kind == '{') {
2021 if (type != NULL && is_type_scalar(type)) {
2022 sub = parse_scalar_initializer(type, env->must_be_constant);
2025 if (env->entity != NULL) {
2026 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2028 errorf(HERE, "extra brace group at end of initializer");
2033 descend_into_subtype(path);
2036 add_anchor_token('}');
2037 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2039 rem_anchor_token('}');
2044 goto error_parse_next;
2046 ascend_from_subtype(path);
2049 /* must be an expression */
2050 expression_t *expression = parse_assignment_expression();
2051 mark_vars_read(expression, NULL);
2053 if (env->must_be_constant && !is_linker_constant(expression)) {
2054 errorf(&expression->base.pos,
2055 "Initialisation expression '%E' is not constant",
2060 /* we are already outside, ... */
2061 if (outer_type == NULL)
2062 goto error_parse_next;
2063 type_t *const outer_type_skip = skip_typeref(outer_type);
2064 if (is_type_compound(outer_type_skip) &&
2065 !outer_type_skip->compound.compound->complete) {
2066 goto error_parse_next;
2069 position_t const* const pos = &expression->base.pos;
2070 if (env->entity != NULL) {
2071 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2073 warningf(WARN_OTHER, pos, "excess elements in initializer");
2075 goto error_parse_next;
2078 /* handle { "string" } special case */
2079 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2080 result = initializer_from_expression(outer_type, expression);
2081 if (result != NULL) {
2083 if (token.kind != '}') {
2084 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", outer_type);
2086 /* TODO: eat , ... */
2091 /* descend into subtypes until expression matches type */
2093 orig_type = path->top_type;
2094 type = skip_typeref(orig_type);
2096 sub = initializer_from_expression(orig_type, expression);
2100 if (!is_type_valid(type)) {
2103 if (is_type_scalar(type)) {
2104 errorf(&expression->base.pos,
2105 "expression '%E' doesn't match expected type '%T'",
2106 expression, orig_type);
2110 descend_into_subtype(path);
2114 /* update largest index of top array */
2115 const type_path_entry_t *first = &path->path[0];
2116 type_t *first_type = first->type;
2117 first_type = skip_typeref(first_type);
2118 if (is_type_array(first_type)) {
2119 size_t index = first->v.index;
2120 if (index > path->max_index)
2121 path->max_index = index;
2124 /* append to initializers list */
2125 ARR_APP1(initializer_t*, initializers, sub);
2130 if (token.kind == '}') {
2135 /* advance to the next declaration if we are not at the end */
2136 advance_current_object(path, top_path_level);
2137 orig_type = path->top_type;
2138 if (orig_type != NULL)
2139 type = skip_typeref(orig_type);
2145 size_t len = ARR_LEN(initializers);
2146 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2147 result = allocate_ast_zero(size);
2148 result->kind = INITIALIZER_LIST;
2149 result->list.len = len;
2150 memcpy(&result->list.initializers, initializers,
2151 len * sizeof(initializers[0]));
2155 skip_initializers();
2157 DEL_ARR_F(initializers);
2158 ascend_to(path, top_path_level+1);
2162 static expression_t *make_size_literal(size_t value)
2164 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2165 literal->base.type = type_size_t;
2168 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2169 literal->literal.value = make_string(buf);
2175 * Parses an initializer. Parsers either a compound literal
2176 * (env->declaration == NULL) or an initializer of a declaration.
2178 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2180 type_t *type = skip_typeref(env->type);
2181 size_t max_index = 0;
2182 initializer_t *result;
2184 if (is_type_scalar(type)) {
2185 result = parse_scalar_initializer(type, env->must_be_constant);
2186 } else if (token.kind == '{') {
2190 memset(&path, 0, sizeof(path));
2191 path.top_type = env->type;
2192 path.path = NEW_ARR_F(type_path_entry_t, 0);
2194 descend_into_subtype(&path);
2196 add_anchor_token('}');
2197 result = parse_sub_initializer(&path, env->type, 1, env);
2198 rem_anchor_token('}');
2200 max_index = path.max_index;
2201 DEL_ARR_F(path.path);
2205 /* parse_scalar_initializer() also works in this case: we simply
2206 * have an expression without {} around it */
2207 result = parse_scalar_initializer(type, env->must_be_constant);
2210 /* §6.7.8:22 array initializers for arrays with unknown size determine
2211 * the array type size */
2212 if (is_type_array(type) && type->array.size_expression == NULL
2213 && result != NULL) {
2215 switch (result->kind) {
2216 case INITIALIZER_LIST:
2217 assert(max_index != 0xdeadbeaf);
2218 size = max_index + 1;
2221 case INITIALIZER_STRING: {
2222 size = get_string_len(&get_init_string(result)->value) + 1;
2226 case INITIALIZER_DESIGNATOR:
2227 case INITIALIZER_VALUE:
2228 /* can happen for parse errors */
2233 internal_errorf(HERE, "invalid initializer type");
2236 type_t *new_type = duplicate_type(type);
2238 new_type->array.size_expression = make_size_literal(size);
2239 new_type->array.size_constant = true;
2240 new_type->array.has_implicit_size = true;
2241 new_type->array.size = size;
2242 env->type = new_type;
2248 static void append_entity(scope_t *scope, entity_t *entity)
2250 if (scope->last_entity != NULL) {
2251 scope->last_entity->base.next = entity;
2253 scope->entities = entity;
2255 entity->base.parent_entity = current_entity;
2256 scope->last_entity = entity;
2260 static compound_t *parse_compound_type_specifier(bool is_struct)
2262 position_t const pos = *HERE;
2263 eat(is_struct ? T_struct : T_union);
2265 symbol_t *symbol = NULL;
2266 entity_t *entity = NULL;
2267 attribute_t *attributes = NULL;
2269 if (token.kind == T___attribute__) {
2270 attributes = parse_attributes(NULL);
2273 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2274 if (token.kind == T_IDENTIFIER) {
2275 /* the compound has a name, check if we have seen it already */
2276 symbol = token.base.symbol;
2277 entity = get_tag(symbol, kind);
2280 if (entity != NULL) {
2281 if (entity->base.parent_scope != current_scope &&
2282 (token.kind == '{' || token.kind == ';')) {
2283 /* we're in an inner scope and have a definition. Shadow
2284 * existing definition in outer scope */
2286 } else if (entity->compound.complete && token.kind == '{') {
2287 position_t const *const ppos = &entity->base.pos;
2288 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2289 /* clear members in the hope to avoid further errors */
2290 entity->compound.members.entities = NULL;
2293 } else if (token.kind != '{') {
2294 char const *const msg =
2295 is_struct ? "while parsing struct type specifier" :
2296 "while parsing union type specifier";
2297 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2302 if (entity == NULL) {
2303 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2304 entity->compound.alignment = 1;
2305 entity->base.parent_scope = current_scope;
2306 if (symbol != NULL) {
2307 environment_push(entity);
2309 append_entity(current_scope, entity);
2312 if (token.kind == '{') {
2313 parse_compound_type_entries(&entity->compound);
2315 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2316 if (symbol == NULL) {
2317 assert(anonymous_entity == NULL);
2318 anonymous_entity = entity;
2322 if (attributes != NULL) {
2323 entity->compound.attributes = attributes;
2324 handle_entity_attributes(attributes, entity);
2327 return &entity->compound;
2330 static void parse_enum_entries(type_t *const enum_type)
2334 if (token.kind == '}') {
2335 errorf(HERE, "empty enum not allowed");
2340 add_anchor_token('}');
2341 add_anchor_token(',');
2343 add_anchor_token('=');
2345 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2346 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2347 entity->enum_value.enum_type = enum_type;
2348 rem_anchor_token('=');
2351 expression_t *value = parse_constant_expression();
2353 value = create_implicit_cast(value, enum_type);
2354 entity->enum_value.value = value;
2359 record_entity(entity, false);
2360 } while (accept(',') && token.kind != '}');
2361 rem_anchor_token(',');
2362 rem_anchor_token('}');
2367 static type_t *parse_enum_specifier(void)
2369 position_t const pos = *HERE;
2374 switch (token.kind) {
2376 symbol = token.base.symbol;
2377 entity = get_tag(symbol, ENTITY_ENUM);
2380 if (entity != NULL) {
2381 if (entity->base.parent_scope != current_scope &&
2382 (token.kind == '{' || token.kind == ';')) {
2383 /* we're in an inner scope and have a definition. Shadow
2384 * existing definition in outer scope */
2386 } else if (entity->enume.complete && token.kind == '{') {
2387 position_t const *const ppos = &entity->base.pos;
2388 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2399 parse_error_expected("while parsing enum type specifier",
2400 T_IDENTIFIER, '{', NULL);
2404 if (entity == NULL) {
2405 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2406 entity->base.parent_scope = current_scope;
2409 type_t *const type = allocate_type_zero(TYPE_ENUM);
2410 type->enumt.enume = &entity->enume;
2411 type->enumt.base.akind = ATOMIC_TYPE_INT;
2413 if (token.kind == '{') {
2414 if (symbol != NULL) {
2415 environment_push(entity);
2417 append_entity(current_scope, entity);
2418 entity->enume.complete = true;
2420 parse_enum_entries(type);
2421 parse_attributes(NULL);
2423 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2424 if (symbol == NULL) {
2425 assert(anonymous_entity == NULL);
2426 anonymous_entity = entity;
2428 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2429 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2436 * if a symbol is a typedef to another type, return true
2438 static bool is_typedef_symbol(symbol_t *symbol)
2440 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2441 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2444 static type_t *parse_typeof(void)
2450 add_anchor_token(')');
2453 expression_t *expression = NULL;
2455 switch (token.kind) {
2457 if (is_typedef_symbol(token.base.symbol)) {
2459 type = parse_typename();
2462 expression = parse_expression();
2463 type = revert_automatic_type_conversion(expression);
2468 rem_anchor_token(')');
2471 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2472 typeof_type->typeoft.expression = expression;
2473 typeof_type->typeoft.typeof_type = type;
2478 typedef enum specifiers_t {
2480 SPECIFIER_SIGNED = 1 << 0,
2481 SPECIFIER_UNSIGNED = 1 << 1,
2482 SPECIFIER_LONG = 1 << 2,
2483 SPECIFIER_INT = 1 << 3,
2484 SPECIFIER_DOUBLE = 1 << 4,
2485 SPECIFIER_CHAR = 1 << 5,
2486 SPECIFIER_WCHAR_T = 1 << 6,
2487 SPECIFIER_SHORT = 1 << 7,
2488 SPECIFIER_LONG_LONG = 1 << 8,
2489 SPECIFIER_FLOAT = 1 << 9,
2490 SPECIFIER_BOOL = 1 << 10,
2491 SPECIFIER_VOID = 1 << 11,
2492 SPECIFIER_INT8 = 1 << 12,
2493 SPECIFIER_INT16 = 1 << 13,
2494 SPECIFIER_INT32 = 1 << 14,
2495 SPECIFIER_INT64 = 1 << 15,
2496 SPECIFIER_INT128 = 1 << 16,
2497 SPECIFIER_COMPLEX = 1 << 17,
2498 SPECIFIER_IMAGINARY = 1 << 18,
2501 static type_t *get_typedef_type(symbol_t *symbol)
2503 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2504 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2507 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2508 type->typedeft.typedefe = &entity->typedefe;
2513 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2515 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2517 add_anchor_token(')');
2518 add_anchor_token(',');
2522 add_anchor_token('=');
2524 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2525 rem_anchor_token('=');
2527 symbol_t **prop = NULL;
2529 if (streq(prop_sym->string, "put")) {
2530 prop = &property->put_symbol;
2531 } else if (streq(prop_sym->string, "get")) {
2532 prop = &property->get_symbol;
2534 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2538 add_anchor_token(T_IDENTIFIER);
2540 rem_anchor_token(T_IDENTIFIER);
2542 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2544 *prop = sym ? sym : sym_anonymous;
2545 } while (accept(','));
2546 rem_anchor_token(',');
2547 rem_anchor_token(')');
2549 attribute->a.property = property;
2555 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2557 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2558 if (accept(T_restrict)) {
2559 kind = ATTRIBUTE_MS_RESTRICT;
2560 } else if (token.kind == T_IDENTIFIER) {
2561 char const *const name = token.base.symbol->string;
2562 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2564 const char *attribute_name = get_attribute_name(k);
2565 if (attribute_name != NULL && streq(attribute_name, name)) {
2571 if (kind == ATTRIBUTE_UNKNOWN) {
2572 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2575 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2579 attribute_t *attribute = allocate_attribute_zero(kind);
2582 if (kind == ATTRIBUTE_MS_PROPERTY) {
2583 return parse_attribute_ms_property(attribute);
2586 /* parse arguments */
2588 attribute->a.arguments = parse_attribute_arguments();
2593 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2597 add_anchor_token(')');
2599 if (token.kind != ')') {
2600 attribute_t **anchor = &first;
2602 while (*anchor != NULL)
2603 anchor = &(*anchor)->next;
2605 attribute_t *attribute
2606 = parse_microsoft_extended_decl_modifier_single();
2607 if (attribute == NULL)
2610 *anchor = attribute;
2611 anchor = &attribute->next;
2612 } while (accept(','));
2614 rem_anchor_token(')');
2619 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2621 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2622 if (is_declaration(entity)) {
2623 entity->declaration.type = type_error_type;
2624 entity->declaration.implicit = true;
2625 } else if (kind == ENTITY_TYPEDEF) {
2626 entity->typedefe.type = type_error_type;
2627 entity->typedefe.builtin = true;
2629 if (kind != ENTITY_COMPOUND_MEMBER)
2630 record_entity(entity, false);
2634 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2636 type_t *type = NULL;
2637 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2638 unsigned type_specifiers = 0;
2639 bool newtype = false;
2640 bool saw_error = false;
2642 memset(specifiers, 0, sizeof(*specifiers));
2643 specifiers->pos = *HERE;
2646 specifiers->attributes = parse_attributes(specifiers->attributes);
2648 switch (token.kind) {
2650 #define MATCH_STORAGE_CLASS(token, class) \
2652 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2653 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2655 specifiers->storage_class = class; \
2656 if (specifiers->thread_local) \
2657 goto check_thread_storage_class; \
2661 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2662 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2663 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2664 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2665 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2668 specifiers->attributes
2669 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2672 case T__Thread_local:
2673 if (specifiers->thread_local) {
2674 errorf(HERE, "duplicate %K", &token);
2676 specifiers->thread_local = true;
2677 check_thread_storage_class:
2678 switch (specifiers->storage_class) {
2679 case STORAGE_CLASS_EXTERN:
2680 case STORAGE_CLASS_NONE:
2681 case STORAGE_CLASS_STATIC:
2685 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2686 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2687 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2688 wrong_thread_storage_class:
2689 errorf(HERE, "%K used with '%s'", &token, wrong);
2696 /* type qualifiers */
2697 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2699 qualifiers |= qualifier; \
2703 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2704 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2705 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2706 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2707 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2708 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2709 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2710 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2712 /* type specifiers */
2713 #define MATCH_SPECIFIER(token, specifier, name) \
2715 if (type_specifiers & specifier) { \
2716 errorf(HERE, "multiple " name " type specifiers given"); \
2718 type_specifiers |= specifier; \
2723 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2724 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2725 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2726 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2727 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2728 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2729 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2730 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2731 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2732 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2733 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2734 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2735 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2736 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2737 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2738 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2739 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2740 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2744 specifiers->is_inline = true;
2748 case T__forceinline:
2749 eat(T__forceinline);
2750 specifiers->modifiers |= DM_FORCEINLINE;
2755 if (type_specifiers & SPECIFIER_LONG_LONG) {
2756 errorf(HERE, "too many long type specifiers given");
2757 } else if (type_specifiers & SPECIFIER_LONG) {
2758 type_specifiers |= SPECIFIER_LONG_LONG;
2760 type_specifiers |= SPECIFIER_LONG;
2765 #define CHECK_DOUBLE_TYPE() \
2766 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2769 CHECK_DOUBLE_TYPE();
2770 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2772 type->compound.compound = parse_compound_type_specifier(true);
2775 CHECK_DOUBLE_TYPE();
2776 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2777 type->compound.compound = parse_compound_type_specifier(false);
2780 CHECK_DOUBLE_TYPE();
2781 type = parse_enum_specifier();
2784 CHECK_DOUBLE_TYPE();
2785 type = parse_typeof();
2787 case T___builtin_va_list:
2788 CHECK_DOUBLE_TYPE();
2789 type = duplicate_type(type_valist);
2790 eat(T___builtin_va_list);
2793 case T_IDENTIFIER: {
2794 /* only parse identifier if we haven't found a type yet */
2795 if (type != NULL || type_specifiers != 0) {
2796 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2797 * declaration, so it doesn't generate errors about expecting '(' or
2799 switch (look_ahead(1)->kind) {
2806 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2810 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2815 goto finish_specifiers;
2819 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2820 if (typedef_type == NULL) {
2821 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2822 * declaration, so it doesn't generate 'implicit int' followed by more
2823 * errors later on. */
2824 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2830 errorf(HERE, "%K does not name a type", &token);
2832 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2834 type = allocate_type_zero(TYPE_TYPEDEF);
2835 type->typedeft.typedefe = &entity->typedefe;
2843 goto finish_specifiers;
2848 type = typedef_type;
2852 /* function specifier */
2854 goto finish_specifiers;
2859 specifiers->attributes = parse_attributes(specifiers->attributes);
2861 if (type == NULL || (saw_error && type_specifiers != 0)) {
2862 position_t const* const pos = &specifiers->pos;
2863 atomic_type_kind_t atomic_type;
2865 /* match valid basic types */
2866 switch (type_specifiers & ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2867 case SPECIFIER_VOID:
2868 if (type_specifiers & (SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2869 if (type_specifiers & SPECIFIER_COMPLEX)
2870 errorf(pos, "_Complex specifier is invalid for void");
2871 if (type_specifiers & SPECIFIER_IMAGINARY)
2872 errorf(pos, "_Imaginary specifier is invalid for void");
2873 type_specifiers &= ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY);
2875 atomic_type = ATOMIC_TYPE_VOID;
2877 case SPECIFIER_WCHAR_T:
2878 atomic_type = ATOMIC_TYPE_WCHAR_T;
2880 case SPECIFIER_CHAR:
2881 atomic_type = ATOMIC_TYPE_CHAR;
2883 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2884 atomic_type = ATOMIC_TYPE_SCHAR;
2886 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2887 atomic_type = ATOMIC_TYPE_UCHAR;
2889 case SPECIFIER_SHORT:
2890 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2891 case SPECIFIER_SHORT | SPECIFIER_INT:
2892 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2893 atomic_type = ATOMIC_TYPE_SHORT;
2895 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2896 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2897 atomic_type = ATOMIC_TYPE_USHORT;
2900 case SPECIFIER_SIGNED:
2901 case SPECIFIER_SIGNED | SPECIFIER_INT:
2902 atomic_type = ATOMIC_TYPE_INT;
2904 case SPECIFIER_UNSIGNED:
2905 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2906 atomic_type = ATOMIC_TYPE_UINT;
2908 case SPECIFIER_LONG:
2909 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2910 case SPECIFIER_LONG | SPECIFIER_INT:
2911 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2912 atomic_type = ATOMIC_TYPE_LONG;
2914 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2915 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2916 atomic_type = ATOMIC_TYPE_ULONG;
2919 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2920 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2921 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2922 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2924 atomic_type = ATOMIC_TYPE_LONGLONG;
2925 goto warn_about_long_long;
2927 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2928 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2930 atomic_type = ATOMIC_TYPE_ULONGLONG;
2931 warn_about_long_long:
2932 warningf(WARN_LONG_LONG, &specifiers->pos, "ISO C90 does not support 'long long'");
2935 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2936 atomic_type = unsigned_int8_type_kind;
2939 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2940 atomic_type = unsigned_int16_type_kind;
2943 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2944 atomic_type = unsigned_int32_type_kind;
2947 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2948 atomic_type = unsigned_int64_type_kind;
2951 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2952 atomic_type = unsigned_int128_type_kind;
2955 case SPECIFIER_INT8:
2956 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2957 atomic_type = int8_type_kind;
2960 case SPECIFIER_INT16:
2961 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2962 atomic_type = int16_type_kind;
2965 case SPECIFIER_INT32:
2966 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2967 atomic_type = int32_type_kind;
2970 case SPECIFIER_INT64:
2971 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2972 atomic_type = int64_type_kind;
2975 case SPECIFIER_INT128:
2976 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2977 atomic_type = int128_type_kind;
2980 case SPECIFIER_FLOAT:
2981 atomic_type = ATOMIC_TYPE_FLOAT;
2983 case SPECIFIER_DOUBLE:
2984 atomic_type = ATOMIC_TYPE_DOUBLE;
2986 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2987 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2989 case SPECIFIER_BOOL:
2990 if (type_specifiers & (SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2991 if (type_specifiers & SPECIFIER_COMPLEX)
2992 errorf(pos, "_Complex specifier is invalid for _Bool");
2993 if (type_specifiers & SPECIFIER_IMAGINARY)
2994 errorf(pos, "_Imaginary specifier is invalid for _Bool");
2995 type_specifiers &= ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY);
2997 atomic_type = ATOMIC_TYPE_BOOL;
3000 /* invalid specifier combination, give an error message */
3001 if (type_specifiers == 0) {
3003 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3004 if (!(c_mode & _CXX) && !strict_mode) {
3005 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3006 atomic_type = ATOMIC_TYPE_INT;
3009 errorf(pos, "no type specifiers given in declaration");
3012 } else if (type_specifiers == SPECIFIER_COMPLEX) {
3013 warningf(WARN_OTHER, pos, "_Complex requires a type specifier; assuming '_Complex double'");
3014 atomic_type = ATOMIC_TYPE_DOUBLE;
3016 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3017 (type_specifiers & SPECIFIER_UNSIGNED)) {
3018 errorf(pos, "signed and unsigned specifiers given");
3019 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3020 errorf(pos, "only integer types can be signed or unsigned");
3022 errorf(pos, "multiple datatypes in declaration");
3024 specifiers->type = type_error_type;
3029 if (type_specifiers & SPECIFIER_COMPLEX) {
3030 type = allocate_type_zero(TYPE_COMPLEX);
3031 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3032 type = allocate_type_zero(TYPE_IMAGINARY);
3034 type = allocate_type_zero(TYPE_ATOMIC);
3036 type->atomic.akind = atomic_type;
3038 } else if (type_specifiers != 0) {
3039 errorf(&specifiers->pos, "multiple datatypes in declaration");
3042 /* FIXME: check type qualifiers here */
3043 type->base.qualifiers = qualifiers;
3046 type = identify_new_type(type);
3048 type = typehash_insert(type);
3051 if (specifiers->attributes != NULL)
3052 type = handle_type_attributes(specifiers->attributes, type);
3053 specifiers->type = type;
3056 static type_qualifiers_t parse_type_qualifiers(void)
3058 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3061 switch (token.kind) {
3062 /* type qualifiers */
3063 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3064 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3065 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3066 /* microsoft extended type modifiers */
3067 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3068 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3069 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3070 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3071 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3080 * Parses an K&R identifier list
3082 static void parse_identifier_list(scope_t *scope)
3084 assert(token.kind == T_IDENTIFIER);
3086 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3087 /* a K&R parameter has no type, yet */
3091 append_entity(scope, entity);
3092 } while (accept(',') && token.kind == T_IDENTIFIER);
3095 static entity_t *parse_parameter(void)
3097 declaration_specifiers_t specifiers;
3098 parse_declaration_specifiers(&specifiers);
3100 entity_t *entity = parse_declarator(&specifiers,
3101 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3102 anonymous_entity = NULL;
3106 static void semantic_parameter_incomplete(const entity_t *entity)
3108 assert(entity->kind == ENTITY_PARAMETER);
3110 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3111 * list in a function declarator that is part of a
3112 * definition of that function shall not have
3113 * incomplete type. */
3114 type_t *type = skip_typeref(entity->declaration.type);
3115 if (is_type_incomplete(type)) {
3116 errorf(&entity->base.pos, "'%N' has incomplete type", entity);
3120 static bool has_parameters(void)
3122 /* func(void) is not a parameter */
3123 if (look_ahead(1)->kind != ')')
3125 if (token.kind == T_IDENTIFIER) {
3126 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3129 if (entity->kind != ENTITY_TYPEDEF)
3131 type_t const *const type = skip_typeref(entity->typedefe.type);
3132 if (!is_type_void(type))
3134 if (c_mode & _CXX) {
3135 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3136 * is not allowed. */
3137 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3138 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3139 /* §6.7.5.3:10 Qualification is not allowed here. */
3140 errorf(HERE, "'void' as parameter must not have type qualifiers");
3142 } else if (token.kind != T_void) {
3150 * Parses function type parameters (and optionally creates variable_t entities
3151 * for them in a scope)
3153 static void parse_parameters(function_type_t *type, scope_t *scope)
3155 add_anchor_token(')');
3158 if (token.kind == T_IDENTIFIER &&
3159 !is_typedef_symbol(token.base.symbol) &&
3160 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3161 type->kr_style_parameters = true;
3162 parse_identifier_list(scope);
3163 } else if (token.kind == ')') {
3164 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3165 if (!(c_mode & _CXX))
3166 type->unspecified_parameters = true;
3167 } else if (has_parameters()) {
3168 function_parameter_t **anchor = &type->parameters;
3169 add_anchor_token(',');
3171 switch (token.kind) {
3174 type->variadic = true;
3175 goto parameters_finished;
3180 entity_t *entity = parse_parameter();
3181 if (entity->kind == ENTITY_TYPEDEF) {
3182 errorf(&entity->base.pos,
3183 "typedef not allowed as function parameter");
3186 assert(is_declaration(entity));
3188 semantic_parameter_incomplete(entity);
3190 function_parameter_t *const parameter =
3191 allocate_parameter(entity->declaration.type);
3193 if (scope != NULL) {
3194 append_entity(scope, entity);
3197 *anchor = parameter;
3198 anchor = ¶meter->next;
3203 goto parameters_finished;
3205 } while (accept(','));
3206 parameters_finished:
3207 rem_anchor_token(',');
3210 rem_anchor_token(')');
3214 typedef enum construct_type_kind_t {
3215 CONSTRUCT_POINTER = 1,
3216 CONSTRUCT_REFERENCE,
3219 } construct_type_kind_t;
3221 typedef union construct_type_t construct_type_t;
3223 typedef struct construct_type_base_t {
3224 construct_type_kind_t kind;
3226 construct_type_t *next;
3227 } construct_type_base_t;
3229 typedef struct parsed_pointer_t {
3230 construct_type_base_t base;
3231 type_qualifiers_t type_qualifiers;
3232 variable_t *base_variable; /**< MS __based extension. */
3235 typedef struct parsed_reference_t {
3236 construct_type_base_t base;
3237 } parsed_reference_t;
3239 typedef struct construct_function_type_t {
3240 construct_type_base_t base;
3241 type_t *function_type;
3242 } construct_function_type_t;
3244 typedef struct parsed_array_t {
3245 construct_type_base_t base;
3246 type_qualifiers_t type_qualifiers;
3252 union construct_type_t {
3253 construct_type_kind_t kind;
3254 construct_type_base_t base;
3255 parsed_pointer_t pointer;
3256 parsed_reference_t reference;
3257 construct_function_type_t function;
3258 parsed_array_t array;
3261 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3263 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3264 memset(cons, 0, size);
3266 cons->base.pos = *HERE;
3271 static construct_type_t *parse_pointer_declarator(void)
3273 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3275 cons->pointer.type_qualifiers = parse_type_qualifiers();
3276 //cons->pointer.base_variable = base_variable;
3281 /* ISO/IEC 14882:1998(E) §8.3.2 */
3282 static construct_type_t *parse_reference_declarator(void)
3284 if (!(c_mode & _CXX))
3285 errorf(HERE, "references are only available for C++");
3287 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3294 static construct_type_t *parse_array_declarator(void)
3296 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3297 parsed_array_t *const array = &cons->array;
3300 add_anchor_token(']');
3302 bool is_static = accept(T_static);
3304 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3307 is_static = accept(T_static);
3309 array->type_qualifiers = type_qualifiers;
3310 array->is_static = is_static;
3312 expression_t *size = NULL;
3313 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3314 array->is_variable = true;
3316 } else if (token.kind != ']') {
3317 size = parse_assignment_expression();
3319 /* §6.7.5.2:1 Array size must have integer type */
3320 type_t *const orig_type = size->base.type;
3321 type_t *const type = skip_typeref(orig_type);
3322 if (!is_type_integer(type) && is_type_valid(type)) {
3323 errorf(&size->base.pos,
3324 "array size '%E' must have integer type but has type '%T'",
3329 mark_vars_read(size, NULL);
3332 if (is_static && size == NULL)
3333 errorf(&array->base.pos, "static array parameters require a size");
3335 rem_anchor_token(']');
3341 static construct_type_t *parse_function_declarator(scope_t *scope)
3343 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3345 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3346 function_type_t *ftype = &type->function;
3348 ftype->linkage = current_linkage;
3349 ftype->calling_convention = CC_DEFAULT;
3351 parse_parameters(ftype, scope);
3353 cons->function.function_type = type;
3358 typedef struct parse_declarator_env_t {
3359 bool may_be_abstract : 1;
3360 bool must_be_abstract : 1;
3361 decl_modifiers_t modifiers;
3365 attribute_t *attributes;
3366 } parse_declarator_env_t;
3369 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3371 /* construct a single linked list of construct_type_t's which describe
3372 * how to construct the final declarator type */
3373 construct_type_t *first = NULL;
3374 construct_type_t **anchor = &first;
3376 env->attributes = parse_attributes(env->attributes);
3379 construct_type_t *type;
3380 //variable_t *based = NULL; /* MS __based extension */
3381 switch (token.kind) {
3383 type = parse_reference_declarator();
3387 panic("based not supported anymore");
3392 type = parse_pointer_declarator();
3396 goto ptr_operator_end;
3400 anchor = &type->base.next;
3402 /* TODO: find out if this is correct */
3403 env->attributes = parse_attributes(env->attributes);
3407 construct_type_t *inner_types = NULL;
3409 switch (token.kind) {
3411 if (env->must_be_abstract) {
3412 errorf(HERE, "no identifier expected in typename");
3414 env->symbol = token.base.symbol;
3421 /* Parenthesized declarator or function declarator? */
3422 token_t const *const la1 = look_ahead(1);
3423 switch (la1->kind) {
3425 if (is_typedef_symbol(la1->base.symbol)) {
3427 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3428 * interpreted as ``function with no parameter specification'', rather
3429 * than redundant parentheses around the omitted identifier. */
3431 /* Function declarator. */
3432 if (!env->may_be_abstract) {
3433 errorf(HERE, "function declarator must have a name");
3440 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3441 /* Paranthesized declarator. */
3443 add_anchor_token(')');
3444 inner_types = parse_inner_declarator(env);
3445 if (inner_types != NULL) {
3446 /* All later declarators only modify the return type */
3447 env->must_be_abstract = true;
3449 rem_anchor_token(')');
3458 if (env->may_be_abstract)
3460 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3465 construct_type_t **const p = anchor;
3468 construct_type_t *type;
3469 switch (token.kind) {
3471 scope_t *scope = NULL;
3472 if (!env->must_be_abstract) {
3473 scope = &env->parameters;
3476 type = parse_function_declarator(scope);
3480 type = parse_array_declarator();
3483 goto declarator_finished;
3486 /* insert in the middle of the list (at p) */
3487 type->base.next = *p;
3490 anchor = &type->base.next;
3493 declarator_finished:
3494 /* append inner_types at the end of the list, we don't to set anchor anymore
3495 * as it's not needed anymore */
3496 *anchor = inner_types;
3501 static type_t *construct_declarator_type(construct_type_t *construct_list,
3504 construct_type_t *iter = construct_list;
3505 for (; iter != NULL; iter = iter->base.next) {
3506 position_t const* const pos = &iter->base.pos;
3507 switch (iter->kind) {
3508 case CONSTRUCT_FUNCTION: {
3509 construct_function_type_t *function = &iter->function;
3510 type_t *function_type = function->function_type;
3512 function_type->function.return_type = type;
3514 type_t *skipped_return_type = skip_typeref(type);
3516 if (is_type_function(skipped_return_type)) {
3517 errorf(pos, "function returning function is not allowed");
3518 } else if (is_type_array(skipped_return_type)) {
3519 errorf(pos, "function returning array is not allowed");
3521 if (skipped_return_type->base.qualifiers != 0) {
3522 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3526 /* The function type was constructed earlier. Freeing it here will
3527 * destroy other types. */
3528 type = typehash_insert(function_type);
3532 case CONSTRUCT_POINTER: {
3533 if (is_type_reference(skip_typeref(type)))
3534 errorf(pos, "cannot declare a pointer to reference");
3536 parsed_pointer_t *pointer = &iter->pointer;
3537 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3541 case CONSTRUCT_REFERENCE:
3542 if (is_type_reference(skip_typeref(type)))
3543 errorf(pos, "cannot declare a reference to reference");
3545 type = make_reference_type(type);
3548 case CONSTRUCT_ARRAY: {
3549 if (is_type_reference(skip_typeref(type)))
3550 errorf(pos, "cannot declare an array of references");
3552 parsed_array_t *array = &iter->array;
3553 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3555 expression_t *size_expression = array->size;
3556 if (size_expression != NULL) {
3558 = create_implicit_cast(size_expression, type_size_t);
3561 array_type->base.qualifiers = array->type_qualifiers;
3562 array_type->array.element_type = type;
3563 array_type->array.is_static = array->is_static;
3564 array_type->array.is_variable = array->is_variable;
3565 array_type->array.size_expression = size_expression;
3567 if (size_expression != NULL) {
3568 switch (is_constant_expression(size_expression)) {
3569 case EXPR_CLASS_CONSTANT: {
3570 long const size = fold_constant_to_int(size_expression);
3571 array_type->array.size = size;
3572 array_type->array.size_constant = true;
3573 /* §6.7.5.2:1 If the expression is a constant expression,
3574 * it shall have a value greater than zero. */
3576 errorf(&size_expression->base.pos,
3577 "size of array must be greater than zero");
3578 } else if (size == 0 && !GNU_MODE) {
3579 errorf(&size_expression->base.pos,
3580 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3585 case EXPR_CLASS_VARIABLE:
3586 array_type->array.is_vla = true;
3589 case EXPR_CLASS_ERROR:
3594 type_t *skipped_type = skip_typeref(type);
3596 if (is_type_incomplete(skipped_type)) {
3597 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3598 } else if (is_type_function(skipped_type)) {
3599 errorf(pos, "array of functions is not allowed");
3601 type = identify_new_type(array_type);
3605 internal_errorf(pos, "invalid type construction found");
3611 static type_t *automatic_type_conversion(type_t *orig_type);
3613 static type_t *semantic_parameter(const position_t *pos, type_t *type,
3614 const declaration_specifiers_t *specifiers,
3615 entity_t const *const param)
3617 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3618 * shall be adjusted to ``qualified pointer to type'',
3620 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3621 * type'' shall be adjusted to ``pointer to function
3622 * returning type'', as in 6.3.2.1. */
3623 type = automatic_type_conversion(type);
3625 if (specifiers->is_inline && is_type_valid(type)) {
3626 errorf(pos, "'%N' declared 'inline'", param);
3629 /* §6.9.1:6 The declarations in the declaration list shall contain
3630 * no storage-class specifier other than register and no
3631 * initializations. */
3632 if (specifiers->thread_local || (
3633 specifiers->storage_class != STORAGE_CLASS_NONE &&
3634 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3636 errorf(pos, "invalid storage class for '%N'", param);
3639 /* delay test for incomplete type, because we might have (void)
3640 * which is legal but incomplete... */
3645 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3646 declarator_flags_t flags)
3648 parse_declarator_env_t env;
3649 memset(&env, 0, sizeof(env));
3650 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3652 construct_type_t *construct_type = parse_inner_declarator(&env);
3654 construct_declarator_type(construct_type, specifiers->type);
3655 type_t *type = skip_typeref(orig_type);
3657 if (construct_type != NULL) {
3658 obstack_free(&temp_obst, construct_type);
3661 attribute_t *attributes = parse_attributes(env.attributes);
3662 /* append (shared) specifier attribute behind attributes of this
3664 attribute_t **anchor = &attributes;
3665 while (*anchor != NULL)
3666 anchor = &(*anchor)->next;
3667 *anchor = specifiers->attributes;
3670 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3671 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.pos);
3672 entity->typedefe.type = orig_type;
3674 if (anonymous_entity != NULL) {
3675 if (is_type_compound(type)) {
3676 assert(anonymous_entity->compound.alias == NULL);
3677 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3678 anonymous_entity->kind == ENTITY_UNION);
3679 anonymous_entity->compound.alias = entity;
3680 anonymous_entity = NULL;
3681 } else if (is_type_enum(type)) {
3682 assert(anonymous_entity->enume.alias == NULL);
3683 assert(anonymous_entity->kind == ENTITY_ENUM);
3684 anonymous_entity->enume.alias = entity;
3685 anonymous_entity = NULL;
3689 /* create a declaration type entity */
3690 position_t const *const pos = env.symbol ? &env.pos : &specifiers->pos;
3691 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3692 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3694 if (env.symbol != NULL) {
3695 if (specifiers->is_inline && is_type_valid(type)) {
3696 errorf(&env.pos, "'%N' declared 'inline'", entity);
3699 if (specifiers->thread_local ||
3700 specifiers->storage_class != STORAGE_CLASS_NONE) {
3701 errorf(&env.pos, "'%N' must have no storage class", entity);
3704 } else if (flags & DECL_IS_PARAMETER) {
3705 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3706 orig_type = semantic_parameter(&env.pos, orig_type, specifiers, entity);
3707 } else if (is_type_function(type)) {
3708 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3709 entity->function.is_inline = specifiers->is_inline;
3710 entity->function.elf_visibility = default_visibility;
3711 entity->function.parameters = env.parameters;
3713 if (env.symbol != NULL) {
3714 /* this needs fixes for C++ */
3715 bool in_function_scope = current_function != NULL;
3717 if (specifiers->thread_local || (
3718 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3719 specifiers->storage_class != STORAGE_CLASS_NONE &&
3720 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3722 errorf(&env.pos, "invalid storage class for '%N'", entity);
3726 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3727 entity->variable.elf_visibility = default_visibility;
3728 entity->variable.thread_local = specifiers->thread_local;
3730 if (env.symbol != NULL) {
3731 if (specifiers->is_inline && is_type_valid(type)) {
3732 errorf(&env.pos, "'%N' declared 'inline'", entity);
3735 bool invalid_storage_class = false;
3736 if (current_scope == file_scope) {
3737 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3738 specifiers->storage_class != STORAGE_CLASS_NONE &&
3739 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3740 invalid_storage_class = true;
3743 if (specifiers->thread_local &&
3744 specifiers->storage_class == STORAGE_CLASS_NONE) {
3745 invalid_storage_class = true;
3748 if (invalid_storage_class) {
3749 errorf(&env.pos, "invalid storage class for '%N'", entity);
3754 entity->declaration.type = orig_type;
3755 entity->declaration.alignment = get_type_alignment(orig_type);
3756 entity->declaration.modifiers = env.modifiers;
3757 entity->declaration.attributes = attributes;
3759 storage_class_t storage_class = specifiers->storage_class;
3760 entity->declaration.declared_storage_class = storage_class;
3762 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3763 storage_class = STORAGE_CLASS_AUTO;
3764 entity->declaration.storage_class = storage_class;
3767 if (attributes != NULL) {
3768 handle_entity_attributes(attributes, entity);
3771 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3772 adapt_special_functions(&entity->function);
3778 static type_t *parse_abstract_declarator(type_t *base_type)
3780 parse_declarator_env_t env;
3781 memset(&env, 0, sizeof(env));
3782 env.may_be_abstract = true;
3783 env.must_be_abstract = true;
3785 construct_type_t *construct_type = parse_inner_declarator(&env);
3787 type_t *result = construct_declarator_type(construct_type, base_type);
3788 if (construct_type != NULL) {
3789 obstack_free(&temp_obst, construct_type);
3791 result = handle_type_attributes(env.attributes, result);
3797 * Check if the declaration of main is suspicious. main should be a
3798 * function with external linkage, returning int, taking either zero
3799 * arguments, two, or three arguments of appropriate types, ie.
3801 * int main([ int argc, char **argv [, char **env ] ]).
3803 * @param decl the declaration to check
3804 * @param type the function type of the declaration
3806 static void check_main(const entity_t *entity)
3808 const position_t *pos = &entity->base.pos;
3809 if (entity->kind != ENTITY_FUNCTION) {
3810 warningf(WARN_MAIN, pos, "'main' is not a function");
3814 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3815 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3818 type_t *type = skip_typeref(entity->declaration.type);
3819 assert(is_type_function(type));
3821 function_type_t const *const func_type = &type->function;
3822 type_t *const ret_type = func_type->return_type;
3823 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3824 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3826 const function_parameter_t *parm = func_type->parameters;
3828 type_t *const first_type = skip_typeref(parm->type);
3829 type_t *const first_type_unqual = get_unqualified_type(first_type);
3830 if (!types_compatible(first_type_unqual, type_int)) {
3831 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3835 type_t *const second_type = skip_typeref(parm->type);
3836 type_t *const second_type_unqual
3837 = get_unqualified_type(second_type);
3838 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3839 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3843 type_t *const third_type = skip_typeref(parm->type);
3844 type_t *const third_type_unqual
3845 = get_unqualified_type(third_type);
3846 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3847 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3851 goto warn_arg_count;
3855 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3860 static void error_redefined_as_different_kind(const position_t *pos,
3861 const entity_t *old, entity_kind_t new_kind)
3863 char const *const what = get_entity_kind_name(new_kind);
3864 position_t const *const ppos = &old->base.pos;
3865 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3868 static bool is_entity_valid(entity_t *const ent)
3870 if (is_declaration(ent)) {
3871 return is_type_valid(skip_typeref(ent->declaration.type));
3872 } else if (ent->kind == ENTITY_TYPEDEF) {
3873 return is_type_valid(skip_typeref(ent->typedefe.type));
3878 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3880 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3881 if (attributes_equal(tattr, attr))
3888 * Tests whether new_list contains any attributes not included in old_list
3890 static bool has_new_attributes(const attribute_t *old_list,
3891 const attribute_t *new_list)
3893 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3894 if (!contains_attribute(old_list, attr))
3901 * Merge in attributes from an attribute list (probably from a previous
3902 * declaration with the same name). Warning: destroys the old structure
3903 * of the attribute list - don't reuse attributes after this call.
3905 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3908 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3910 if (contains_attribute(decl->attributes, attr))
3913 /* move attribute to new declarations attributes list */
3914 attr->next = decl->attributes;
3915 decl->attributes = attr;
3919 static bool is_main(entity_t*);
3922 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3923 * for various problems that occur for multiple definitions
3925 entity_t *record_entity(entity_t *entity, const bool is_definition)
3927 const symbol_t *const symbol = entity->base.symbol;
3928 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3929 const position_t *pos = &entity->base.pos;
3931 /* can happen in error cases */
3935 assert(!entity->base.parent_scope);
3936 assert(current_scope);
3937 entity->base.parent_scope = current_scope;
3939 entity_t *const previous_entity = get_entity(symbol, namespc);
3940 /* pushing the same entity twice will break the stack structure */
3941 assert(previous_entity != entity);
3943 if (entity->kind == ENTITY_FUNCTION) {
3944 type_t *const orig_type = entity->declaration.type;
3945 type_t *const type = skip_typeref(orig_type);
3947 assert(is_type_function(type));
3948 if (type->function.unspecified_parameters &&
3949 previous_entity == NULL &&
3950 !entity->declaration.implicit) {
3951 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3954 if (is_main(entity)) {
3959 if (is_declaration(entity) &&
3960 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3961 current_scope != file_scope &&
3962 !entity->declaration.implicit) {
3963 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3966 if (previous_entity != NULL) {
3967 position_t const *const ppos = &previous_entity->base.pos;
3969 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3970 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3971 assert(previous_entity->kind == ENTITY_PARAMETER);
3972 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3976 if (previous_entity->base.parent_scope == current_scope) {
3977 if (previous_entity->kind != entity->kind) {
3978 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3979 error_redefined_as_different_kind(pos, previous_entity,
3984 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3985 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3988 if (previous_entity->kind == ENTITY_TYPEDEF) {
3989 type_t *const type = skip_typeref(entity->typedefe.type);
3990 type_t *const prev_type
3991 = skip_typeref(previous_entity->typedefe.type);
3992 if (c_mode & _CXX) {
3993 /* C++ allows double typedef if they are identical
3994 * (after skipping typedefs) */
3995 if (type == prev_type)
3998 /* GCC extension: redef in system headers is allowed */
3999 if ((pos->is_system_header || ppos->is_system_header) &&
4000 types_compatible(type, prev_type))
4003 errorf(pos, "redefinition of '%N' (declared %P)",
4008 /* at this point we should have only VARIABLES or FUNCTIONS */
4009 assert(is_declaration(previous_entity) && is_declaration(entity));
4011 declaration_t *const prev_decl = &previous_entity->declaration;
4012 declaration_t *const decl = &entity->declaration;
4014 /* can happen for K&R style declarations */
4015 if (prev_decl->type == NULL &&
4016 previous_entity->kind == ENTITY_PARAMETER &&
4017 entity->kind == ENTITY_PARAMETER) {
4018 prev_decl->type = decl->type;
4019 prev_decl->storage_class = decl->storage_class;
4020 prev_decl->declared_storage_class = decl->declared_storage_class;
4021 prev_decl->modifiers = decl->modifiers;
4022 return previous_entity;
4025 type_t *const type = skip_typeref(decl->type);
4026 type_t *const prev_type = skip_typeref(prev_decl->type);
4028 if (!types_compatible(type, prev_type)) {
4029 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4031 unsigned old_storage_class = prev_decl->storage_class;
4033 if (is_definition &&
4035 !(prev_decl->modifiers & DM_USED) &&
4036 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4037 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4040 storage_class_t new_storage_class = decl->storage_class;
4042 /* pretend no storage class means extern for function
4043 * declarations (except if the previous declaration is neither
4044 * none nor extern) */
4045 if (entity->kind == ENTITY_FUNCTION) {
4046 /* the previous declaration could have unspecified parameters or
4047 * be a typedef, so use the new type */
4048 if (prev_type->function.unspecified_parameters || is_definition)
4049 prev_decl->type = type;
4051 switch (old_storage_class) {
4052 case STORAGE_CLASS_NONE:
4053 old_storage_class = STORAGE_CLASS_EXTERN;
4056 case STORAGE_CLASS_EXTERN:
4057 if (is_definition) {
4058 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4059 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4061 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4062 new_storage_class = STORAGE_CLASS_EXTERN;
4069 } else if (is_type_incomplete(prev_type)) {
4070 prev_decl->type = type;
4073 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4074 new_storage_class == STORAGE_CLASS_EXTERN) {
4076 warn_redundant_declaration: ;
4078 = has_new_attributes(prev_decl->attributes,
4080 if (has_new_attrs) {
4081 merge_in_attributes(decl, prev_decl->attributes);
4082 } else if (!is_definition &&
4083 is_type_valid(prev_type) &&
4084 !pos->is_system_header) {
4085 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4087 } else if (current_function == NULL) {
4088 if (old_storage_class != STORAGE_CLASS_STATIC &&
4089 new_storage_class == STORAGE_CLASS_STATIC) {
4090 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4091 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4092 prev_decl->storage_class = STORAGE_CLASS_NONE;
4093 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4095 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4097 goto error_redeclaration;
4098 goto warn_redundant_declaration;
4100 } else if (is_type_valid(prev_type)) {
4101 if (old_storage_class == new_storage_class) {
4102 error_redeclaration:
4103 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4105 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4110 prev_decl->modifiers |= decl->modifiers;
4111 if (entity->kind == ENTITY_FUNCTION) {
4112 previous_entity->function.is_inline |= entity->function.is_inline;
4114 return previous_entity;
4118 if (is_warn_on(why = WARN_SHADOW) ||
4119 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4120 char const *const what = get_entity_kind_name(previous_entity->kind);
4121 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4125 if (entity->kind == ENTITY_FUNCTION) {
4126 if (is_definition &&
4127 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4129 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4130 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4132 goto warn_missing_declaration;
4135 } else if (entity->kind == ENTITY_VARIABLE) {
4136 if (current_scope == file_scope &&
4137 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4138 !entity->declaration.implicit) {
4139 warn_missing_declaration:
4140 if (is_type_valid(skip_typeref(entity->declaration.type)))
4141 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4146 environment_push(entity);
4147 append_entity(current_scope, entity);
4152 static void parser_error_multiple_definition(entity_t *entity,
4153 const position_t *pos)
4155 errorf(pos, "redefinition of '%N' (declared %P)", entity, &entity->base.pos);
4158 static bool is_declaration_specifier(const token_t *token)
4160 switch (token->kind) {
4164 return is_typedef_symbol(token->base.symbol);
4171 static void parse_init_declarator_rest(entity_t *entity)
4173 type_t *orig_type = type_error_type;
4175 if (entity->base.kind == ENTITY_TYPEDEF) {
4176 position_t const *const pos = &entity->base.pos;
4177 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4179 assert(is_declaration(entity));
4180 orig_type = entity->declaration.type;
4183 type_t *type = skip_typeref(orig_type);
4185 if (entity->kind == ENTITY_VARIABLE
4186 && entity->variable.initializer != NULL) {
4187 parser_error_multiple_definition(entity, HERE);
4191 declaration_t *const declaration = &entity->declaration;
4192 bool must_be_constant = false;
4193 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4194 entity->base.parent_scope == file_scope) {
4195 must_be_constant = true;
4198 if (is_type_function(type)) {
4199 position_t const *const pos = &entity->base.pos;
4200 errorf(pos, "'%N' is initialized like a variable", entity);
4201 orig_type = type_error_type;
4204 parse_initializer_env_t env;
4205 env.type = orig_type;
4206 env.must_be_constant = must_be_constant;
4207 env.entity = entity;
4209 initializer_t *initializer = parse_initializer(&env);
4211 if (entity->kind == ENTITY_VARIABLE) {
4212 /* §6.7.5:22 array initializers for arrays with unknown size
4213 * determine the array type size */
4214 declaration->type = env.type;
4215 entity->variable.initializer = initializer;
4219 /* parse rest of a declaration without any declarator */
4220 static void parse_anonymous_declaration_rest(
4221 const declaration_specifiers_t *specifiers)
4224 anonymous_entity = NULL;
4226 position_t const *const pos = &specifiers->pos;
4227 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4228 specifiers->thread_local) {
4229 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4232 type_t *type = specifiers->type;
4233 switch (type->kind) {
4234 case TYPE_COMPOUND_STRUCT:
4235 case TYPE_COMPOUND_UNION: {
4236 if (type->compound.compound->base.symbol == NULL) {
4237 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4246 warningf(WARN_OTHER, pos, "empty declaration");
4251 static void check_variable_type_complete(entity_t *ent)
4253 if (ent->kind != ENTITY_VARIABLE)
4256 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4257 * type for the object shall be complete [...] */
4258 declaration_t *decl = &ent->declaration;
4259 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4260 decl->storage_class == STORAGE_CLASS_STATIC)
4263 type_t *const type = skip_typeref(decl->type);
4264 if (!is_type_incomplete(type))
4267 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4268 * are given length one. */
4269 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4270 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4274 errorf(&ent->base.pos, "variable '%#N' has incomplete type", ent);
4278 static void parse_declaration_rest(entity_t *ndeclaration,
4279 const declaration_specifiers_t *specifiers,
4280 parsed_declaration_func finished_declaration,
4281 declarator_flags_t flags)
4283 add_anchor_token(';');
4284 add_anchor_token(',');
4286 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4288 if (token.kind == '=') {
4289 parse_init_declarator_rest(entity);
4290 } else if (entity->kind == ENTITY_VARIABLE) {
4291 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4292 * [...] where the extern specifier is explicitly used. */
4293 declaration_t *decl = &entity->declaration;
4294 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4295 is_type_reference(skip_typeref(decl->type))) {
4296 position_t const *const pos = &entity->base.pos;
4297 errorf(pos, "reference '%#N' must be initialized", entity);
4301 check_variable_type_complete(entity);
4306 add_anchor_token('=');
4307 ndeclaration = parse_declarator(specifiers, flags);
4308 rem_anchor_token('=');
4310 rem_anchor_token(',');
4311 rem_anchor_token(';');
4314 anonymous_entity = NULL;
4317 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4319 symbol_t *symbol = entity->base.symbol;
4323 assert(entity->base.namespc == NAMESPACE_NORMAL);
4324 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4325 if (previous_entity == NULL
4326 || previous_entity->base.parent_scope != current_scope) {
4327 errorf(&entity->base.pos, "expected declaration of a function parameter, found '%Y'",
4332 if (is_definition) {
4333 errorf(HERE, "'%N' is initialised", entity);
4336 return record_entity(entity, false);
4339 static void parse_declaration(parsed_declaration_func finished_declaration,
4340 declarator_flags_t flags)
4342 add_anchor_token(';');
4343 declaration_specifiers_t specifiers;
4344 parse_declaration_specifiers(&specifiers);
4345 rem_anchor_token(';');
4347 if (token.kind == ';') {
4348 parse_anonymous_declaration_rest(&specifiers);
4350 entity_t *entity = parse_declarator(&specifiers, flags);
4351 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4356 static type_t *get_default_promoted_type(type_t *orig_type)
4358 type_t *result = orig_type;
4360 type_t *type = skip_typeref(orig_type);
4361 if (is_type_integer(type)) {
4362 result = promote_integer(type);
4363 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4364 result = type_double;
4370 static void parse_kr_declaration_list(entity_t *entity)
4372 if (entity->kind != ENTITY_FUNCTION)
4375 type_t *type = skip_typeref(entity->declaration.type);
4376 assert(is_type_function(type));
4377 if (!type->function.kr_style_parameters)
4380 add_anchor_token('{');
4382 PUSH_SCOPE(&entity->function.parameters);
4384 entity_t *parameter = entity->function.parameters.entities;
4385 for ( ; parameter != NULL; parameter = parameter->base.next) {
4386 assert(parameter->base.parent_scope == NULL);
4387 parameter->base.parent_scope = current_scope;
4388 environment_push(parameter);
4391 /* parse declaration list */
4393 switch (token.kind) {
4395 /* This covers symbols, which are no type, too, and results in
4396 * better error messages. The typical cases are misspelled type
4397 * names and missing includes. */
4399 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4409 /* update function type */
4410 type_t *new_type = duplicate_type(type);
4412 function_parameter_t *parameters = NULL;
4413 function_parameter_t **anchor = ¶meters;
4415 /* did we have an earlier prototype? */
4416 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4417 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4420 function_parameter_t *proto_parameter = NULL;
4421 if (proto_type != NULL) {
4422 type_t *proto_type_type = proto_type->declaration.type;
4423 proto_parameter = proto_type_type->function.parameters;
4424 /* If a K&R function definition has a variadic prototype earlier, then
4425 * make the function definition variadic, too. This should conform to
4426 * §6.7.5.3:15 and §6.9.1:8. */
4427 new_type->function.variadic = proto_type_type->function.variadic;
4429 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4431 new_type->function.unspecified_parameters = true;
4434 bool need_incompatible_warning = false;
4435 parameter = entity->function.parameters.entities;
4436 for (; parameter != NULL; parameter = parameter->base.next,
4438 proto_parameter == NULL ? NULL : proto_parameter->next) {
4439 if (parameter->kind != ENTITY_PARAMETER)
4442 type_t *parameter_type = parameter->declaration.type;
4443 if (parameter_type == NULL) {
4444 position_t const* const pos = ¶meter->base.pos;
4446 errorf(pos, "no type specified for function '%N'", parameter);
4447 parameter_type = type_error_type;
4449 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4450 parameter_type = type_int;
4452 parameter->declaration.type = parameter_type;
4455 semantic_parameter_incomplete(parameter);
4457 /* we need the default promoted types for the function type */
4458 type_t *not_promoted = parameter_type;
4459 parameter_type = get_default_promoted_type(parameter_type);
4461 /* gcc special: if the type of the prototype matches the unpromoted
4462 * type don't promote */
4463 if (!strict_mode && proto_parameter != NULL) {
4464 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4465 type_t *promo_skip = skip_typeref(parameter_type);
4466 type_t *param_skip = skip_typeref(not_promoted);
4467 if (!types_compatible(proto_p_type, promo_skip)
4468 && types_compatible(proto_p_type, param_skip)) {
4470 need_incompatible_warning = true;
4471 parameter_type = not_promoted;
4474 function_parameter_t *const function_parameter
4475 = allocate_parameter(parameter_type);
4477 *anchor = function_parameter;
4478 anchor = &function_parameter->next;
4481 new_type->function.parameters = parameters;
4482 new_type = identify_new_type(new_type);
4484 if (need_incompatible_warning) {
4485 symbol_t const *const sym = entity->base.symbol;
4486 position_t const *const pos = &entity->base.pos;
4487 position_t const *const ppos = &proto_type->base.pos;
4488 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4490 entity->declaration.type = new_type;
4492 rem_anchor_token('{');
4495 static bool first_err = true;
4498 * When called with first_err set, prints the name of the current function,
4501 static void print_in_function(void)
4505 char const *const file = current_function->base.base.pos.input_name;
4506 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4511 * Check if all labels are defined in the current function.
4512 * Check if all labels are used in the current function.
4514 static void check_labels(void)
4516 for (const goto_statement_t *goto_statement = goto_first;
4517 goto_statement != NULL;
4518 goto_statement = goto_statement->next) {
4519 label_t *label = goto_statement->label;
4520 if (label->base.pos.input_name == NULL) {
4521 print_in_function();
4522 position_t const *const pos = &goto_statement->base.pos;
4523 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4527 if (is_warn_on(WARN_UNUSED_LABEL)) {
4528 for (const label_statement_t *label_statement = label_first;
4529 label_statement != NULL;
4530 label_statement = label_statement->next) {
4531 label_t *label = label_statement->label;
4533 if (! label->used) {
4534 print_in_function();
4535 position_t const *const pos = &label_statement->base.pos;
4536 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4542 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4544 entity_t const *const end = last != NULL ? last->base.next : NULL;
4545 for (; entity != end; entity = entity->base.next) {
4546 if (!is_declaration(entity))
4549 declaration_t *declaration = &entity->declaration;
4550 if (declaration->implicit)
4553 if (!declaration->used) {
4554 print_in_function();
4555 warningf(why, &entity->base.pos, "'%N' is unused", entity);
4556 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4557 print_in_function();
4558 warningf(why, &entity->base.pos, "'%N' is never read", entity);
4563 static void check_unused_variables(statement_t *const stmt, void *const env)
4567 switch (stmt->kind) {
4568 case STATEMENT_DECLARATION: {
4569 declaration_statement_t const *const decls = &stmt->declaration;
4570 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4575 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4584 * Check declarations of current_function for unused entities.
4586 static void check_declarations(void)
4588 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4589 const scope_t *scope = ¤t_function->parameters;
4590 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4592 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4593 walk_statements(current_function->body, check_unused_variables, NULL);
4597 static int determine_truth(expression_t const* const cond)
4600 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4601 fold_constant_to_bool(cond) ? 1 :
4605 static void check_reachable(statement_t *);
4606 static bool reaches_end;
4608 static bool expression_returns(expression_t const *const expr)
4610 switch (expr->kind) {
4612 expression_t const *const func = expr->call.function;
4613 type_t const *const type = skip_typeref(func->base.type);
4614 if (type->kind == TYPE_POINTER) {
4615 type_t const *const points_to
4616 = skip_typeref(type->pointer.points_to);
4617 if (points_to->kind == TYPE_FUNCTION
4618 && points_to->function.modifiers & DM_NORETURN)
4622 if (!expression_returns(func))
4625 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4626 if (!expression_returns(arg->expression))
4633 case EXPR_REFERENCE:
4634 case EXPR_ENUM_CONSTANT:
4635 case EXPR_LITERAL_CASES:
4636 case EXPR_LITERAL_CHARACTER:
4637 case EXPR_STRING_LITERAL:
4638 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4639 case EXPR_LABEL_ADDRESS:
4640 case EXPR_CLASSIFY_TYPE:
4641 case EXPR_SIZEOF: // TODO handle obscure VLA case
4644 case EXPR_BUILTIN_CONSTANT_P:
4645 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4650 case EXPR_STATEMENT: {
4651 bool old_reaches_end = reaches_end;
4652 reaches_end = false;
4653 check_reachable(expr->statement.statement);
4654 bool returns = reaches_end;
4655 reaches_end = old_reaches_end;
4659 case EXPR_CONDITIONAL:
4660 // TODO handle constant expression
4662 if (!expression_returns(expr->conditional.condition))
4665 if (expr->conditional.true_expression != NULL
4666 && expression_returns(expr->conditional.true_expression))
4669 return expression_returns(expr->conditional.false_expression);
4672 return expression_returns(expr->select.compound);
4674 case EXPR_ARRAY_ACCESS:
4676 expression_returns(expr->array_access.array_ref) &&
4677 expression_returns(expr->array_access.index);
4680 return expression_returns(expr->va_starte.ap);
4683 return expression_returns(expr->va_arge.ap);
4686 return expression_returns(expr->va_copye.src);
4688 case EXPR_UNARY_CASES_MANDATORY:
4689 return expression_returns(expr->unary.value);
4691 case EXPR_UNARY_THROW:
4694 case EXPR_BINARY_CASES:
4695 // TODO handle constant lhs of && and ||
4697 expression_returns(expr->binary.left) &&
4698 expression_returns(expr->binary.right);
4701 panic("unhandled expression");
4704 static bool initializer_returns(initializer_t const *const init)
4706 switch (init->kind) {
4707 case INITIALIZER_VALUE:
4708 return expression_returns(init->value.value);
4710 case INITIALIZER_LIST: {
4711 initializer_t * const* i = init->list.initializers;
4712 initializer_t * const* const end = i + init->list.len;
4713 bool returns = true;
4714 for (; i != end; ++i) {
4715 if (!initializer_returns(*i))
4721 case INITIALIZER_STRING:
4722 case INITIALIZER_DESIGNATOR: // designators have no payload
4725 panic("unhandled initializer");
4728 static bool noreturn_candidate;
4730 static void check_reachable(statement_t *const stmt)
4732 if (stmt->base.reachable)
4734 if (stmt->kind != STATEMENT_DO_WHILE)
4735 stmt->base.reachable = true;
4737 statement_t *last = stmt;
4739 switch (stmt->kind) {
4740 case STATEMENT_ERROR:
4741 case STATEMENT_EMPTY:
4743 next = stmt->base.next;
4746 case STATEMENT_DECLARATION: {
4747 declaration_statement_t const *const decl = &stmt->declaration;
4748 entity_t const * ent = decl->declarations_begin;
4749 entity_t const *const last_decl = decl->declarations_end;
4751 for (;; ent = ent->base.next) {
4752 if (ent->kind == ENTITY_VARIABLE &&
4753 ent->variable.initializer != NULL &&
4754 !initializer_returns(ent->variable.initializer)) {
4757 if (ent == last_decl)
4761 next = stmt->base.next;
4765 case STATEMENT_COMPOUND:
4766 next = stmt->compound.statements;
4768 next = stmt->base.next;
4771 case STATEMENT_RETURN: {
4772 expression_t const *const val = stmt->returns.value;
4773 if (val == NULL || expression_returns(val))
4774 noreturn_candidate = false;
4778 case STATEMENT_IF: {
4779 if_statement_t const *const ifs = &stmt->ifs;
4780 expression_t const *const cond = ifs->condition;
4782 if (!expression_returns(cond))
4785 int const val = determine_truth(cond);
4788 check_reachable(ifs->true_statement);
4793 if (ifs->false_statement != NULL) {
4794 check_reachable(ifs->false_statement);
4798 next = stmt->base.next;
4802 case STATEMENT_SWITCH: {
4803 switch_statement_t const *const switchs = &stmt->switchs;
4804 expression_t const *const expr = switchs->expression;
4806 if (!expression_returns(expr))
4809 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4810 ir_tarval *const val = fold_constant_to_tarval(expr);
4811 case_label_statement_t * defaults = NULL;
4812 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4813 if (i->expression == NULL) {
4818 if (i->first_case == val || i->last_case == val ||
4819 ((tarval_cmp(i->first_case, val) & ir_relation_less_equal)
4820 && (tarval_cmp(val, i->last_case) & ir_relation_less_equal))) {
4821 check_reachable((statement_t*)i);
4826 if (defaults != NULL) {
4827 check_reachable((statement_t*)defaults);
4831 bool has_default = false;
4832 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4833 if (i->expression == NULL)
4836 check_reachable((statement_t*)i);
4843 next = stmt->base.next;
4847 case STATEMENT_EXPRESSION: {
4848 /* Check for noreturn function call */
4849 expression_t const *const expr = stmt->expression.expression;
4850 if (!expression_returns(expr))
4853 next = stmt->base.next;
4857 case STATEMENT_CONTINUE:
4858 for (statement_t *parent = stmt;;) {
4859 parent = parent->base.parent;
4860 if (parent == NULL) /* continue not within loop */
4864 switch (parent->kind) {
4865 case STATEMENT_DO_WHILE: goto continue_do_while;
4866 case STATEMENT_FOR: goto continue_for;
4872 case STATEMENT_BREAK:
4873 for (statement_t *parent = stmt;;) {
4874 parent = parent->base.parent;
4875 if (parent == NULL) /* break not within loop/switch */
4878 switch (parent->kind) {
4879 case STATEMENT_SWITCH:
4880 case STATEMENT_DO_WHILE:
4883 next = parent->base.next;
4884 goto found_break_parent;
4892 case STATEMENT_COMPUTED_GOTO: {
4893 if (!expression_returns(stmt->computed_goto.expression))
4896 statement_t *parent = stmt->base.parent;
4897 if (parent == NULL) /* top level goto */
4903 case STATEMENT_GOTO:
4904 next = stmt->gotos.label->statement;
4905 if (next == NULL) /* missing label */
4909 case STATEMENT_LABEL:
4910 next = stmt->label.statement;
4913 case STATEMENT_CASE_LABEL:
4914 next = stmt->case_label.statement;
4917 case STATEMENT_DO_WHILE:
4918 next = stmt->do_while.body;
4921 case STATEMENT_FOR: {
4922 for_statement_t *const fors = &stmt->fors;
4924 if (fors->condition_reachable)
4926 fors->condition_reachable = true;
4928 expression_t const *const cond = fors->condition;
4933 } else if (expression_returns(cond)) {
4934 val = determine_truth(cond);
4940 check_reachable(fors->body);
4945 next = stmt->base.next;
4949 case STATEMENT_MS_TRY: {
4950 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4951 check_reachable(ms_try->try_statement);
4952 next = ms_try->final_statement;
4956 case STATEMENT_LEAVE: {
4957 statement_t *parent = stmt;
4959 parent = parent->base.parent;
4960 if (parent == NULL) /* __leave not within __try */
4963 if (parent->kind == STATEMENT_MS_TRY) {
4965 next = parent->ms_try.final_statement;
4973 panic("invalid statement kind");
4976 while (next == NULL) {
4977 next = last->base.parent;
4979 noreturn_candidate = false;
4981 type_t *const type = skip_typeref(current_function->base.type);
4982 assert(is_type_function(type));
4983 type_t *const ret = skip_typeref(type->function.return_type);
4984 if (!is_type_void(ret) &&
4985 is_type_valid(ret) &&
4986 !is_main(current_entity)) {
4987 position_t const *const pos = &stmt->base.pos;
4988 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4993 switch (next->kind) {
4994 case STATEMENT_ERROR:
4995 case STATEMENT_EMPTY:
4996 case STATEMENT_DECLARATION:
4997 case STATEMENT_EXPRESSION:
4999 case STATEMENT_RETURN:
5000 case STATEMENT_CONTINUE:
5001 case STATEMENT_BREAK:
5002 case STATEMENT_COMPUTED_GOTO:
5003 case STATEMENT_GOTO:
5004 case STATEMENT_LEAVE:
5005 panic("invalid control flow in function");
5007 case STATEMENT_COMPOUND:
5008 if (next->compound.stmt_expr) {
5014 case STATEMENT_SWITCH:
5015 case STATEMENT_LABEL:
5016 case STATEMENT_CASE_LABEL:
5018 next = next->base.next;
5021 case STATEMENT_DO_WHILE: {
5023 if (next->base.reachable)
5025 next->base.reachable = true;
5027 do_while_statement_t const *const dw = &next->do_while;
5028 expression_t const *const cond = dw->condition;
5030 if (!expression_returns(cond))
5033 int const val = determine_truth(cond);
5036 check_reachable(dw->body);
5042 next = next->base.next;
5046 case STATEMENT_FOR: {
5048 for_statement_t *const fors = &next->fors;
5050 fors->step_reachable = true;
5052 if (fors->condition_reachable)
5054 fors->condition_reachable = true;
5056 expression_t const *const cond = fors->condition;
5061 } else if (expression_returns(cond)) {
5062 val = determine_truth(cond);
5068 check_reachable(fors->body);
5074 next = next->base.next;
5078 case STATEMENT_MS_TRY:
5080 next = next->ms_try.final_statement;
5085 check_reachable(next);
5088 static void check_unreachable(statement_t* const stmt, void *const env)
5092 switch (stmt->kind) {
5093 case STATEMENT_DO_WHILE:
5094 if (!stmt->base.reachable) {
5095 expression_t const *const cond = stmt->do_while.condition;
5096 if (determine_truth(cond) >= 0) {
5097 position_t const *const pos = &cond->base.pos;
5098 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5103 case STATEMENT_FOR: {
5104 for_statement_t const* const fors = &stmt->fors;
5106 // if init and step are unreachable, cond is unreachable, too
5107 if (!stmt->base.reachable && !fors->step_reachable) {
5108 goto warn_unreachable;
5110 if (!stmt->base.reachable && fors->initialisation != NULL) {
5111 position_t const *const pos = &fors->initialisation->base.pos;
5112 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5115 if (!fors->condition_reachable && fors->condition != NULL) {
5116 position_t const *const pos = &fors->condition->base.pos;
5117 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5120 if (!fors->step_reachable && fors->step != NULL) {
5121 position_t const *const pos = &fors->step->base.pos;
5122 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5128 case STATEMENT_COMPOUND:
5129 if (stmt->compound.statements != NULL)
5131 goto warn_unreachable;
5133 case STATEMENT_DECLARATION: {
5134 /* Only warn if there is at least one declarator with an initializer.
5135 * This typically occurs in switch statements. */
5136 declaration_statement_t const *const decl = &stmt->declaration;
5137 entity_t const * ent = decl->declarations_begin;
5138 entity_t const *const last = decl->declarations_end;
5140 for (;; ent = ent->base.next) {
5141 if (ent->kind == ENTITY_VARIABLE &&
5142 ent->variable.initializer != NULL) {
5143 goto warn_unreachable;
5153 if (!stmt->base.reachable) {
5154 position_t const *const pos = &stmt->base.pos;
5155 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5161 static bool is_main(entity_t *entity)
5163 static symbol_t *sym_main = NULL;
5164 if (sym_main == NULL) {
5165 sym_main = symbol_table_insert("main");
5168 if (entity->base.symbol != sym_main)
5170 /* must be in outermost scope */
5171 if (entity->base.parent_scope != file_scope)
5177 static void prepare_main_collect2(entity_t*);
5179 static void parse_external_declaration(void)
5181 /* function-definitions and declarations both start with declaration
5183 add_anchor_token(';');
5184 declaration_specifiers_t specifiers;
5185 parse_declaration_specifiers(&specifiers);
5186 rem_anchor_token(';');
5188 /* must be a declaration */
5189 if (token.kind == ';') {
5190 parse_anonymous_declaration_rest(&specifiers);
5194 add_anchor_token(',');
5195 add_anchor_token('=');
5196 add_anchor_token(';');
5197 add_anchor_token('{');
5199 /* declarator is common to both function-definitions and declarations */
5200 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5202 rem_anchor_token('{');
5203 rem_anchor_token(';');
5204 rem_anchor_token('=');
5205 rem_anchor_token(',');
5207 /* must be a declaration */
5208 switch (token.kind) {
5212 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5217 /* must be a function definition */
5218 parse_kr_declaration_list(ndeclaration);
5220 if (token.kind != '{') {
5221 parse_error_expected("while parsing function definition", '{', NULL);
5222 eat_until_matching_token(';');
5226 assert(is_declaration(ndeclaration));
5227 type_t *const orig_type = ndeclaration->declaration.type;
5228 type_t * type = skip_typeref(orig_type);
5230 if (!is_type_function(type)) {
5231 if (is_type_valid(type)) {
5232 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5238 position_t const *const pos = &ndeclaration->base.pos;
5239 if (is_typeref(orig_type)) {
5241 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5244 if (is_type_compound(skip_typeref(type->function.return_type))) {
5245 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5247 if (type->function.unspecified_parameters) {
5248 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5250 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5253 /* §6.7.5.3:14 a function definition with () means no
5254 * parameters (and not unspecified parameters) */
5255 if (type->function.unspecified_parameters &&
5256 type->function.parameters == NULL) {
5257 type_t *copy = duplicate_type(type);
5258 copy->function.unspecified_parameters = false;
5259 type = identify_new_type(copy);
5261 ndeclaration->declaration.type = type;
5264 entity_t *const entity = record_entity(ndeclaration, true);
5265 assert(entity->kind == ENTITY_FUNCTION);
5266 assert(ndeclaration->kind == ENTITY_FUNCTION);
5268 function_t *const function = &entity->function;
5269 if (ndeclaration != entity) {
5270 function->parameters = ndeclaration->function.parameters;
5273 PUSH_SCOPE(&function->parameters);
5275 entity_t *parameter = function->parameters.entities;
5276 for (; parameter != NULL; parameter = parameter->base.next) {
5277 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5278 parameter->base.parent_scope = current_scope;
5280 assert(parameter->base.parent_scope == NULL
5281 || parameter->base.parent_scope == current_scope);
5282 parameter->base.parent_scope = current_scope;
5283 if (parameter->base.symbol == NULL) {
5284 errorf(¶meter->base.pos, "parameter name omitted");
5287 environment_push(parameter);
5290 if (function->body != NULL) {
5291 parser_error_multiple_definition(entity, HERE);
5294 /* parse function body */
5295 int label_stack_top = label_top();
5296 function_t *old_current_function = current_function;
5297 current_function = function;
5298 PUSH_CURRENT_ENTITY(entity);
5302 goto_anchor = &goto_first;
5304 label_anchor = &label_first;
5306 statement_t *const body = parse_compound_statement(false);
5307 function->body = body;
5310 check_declarations();
5311 if (is_warn_on(WARN_RETURN_TYPE) ||
5312 is_warn_on(WARN_UNREACHABLE_CODE) ||
5313 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5314 noreturn_candidate = true;
5315 check_reachable(body);
5316 if (is_warn_on(WARN_UNREACHABLE_CODE))
5317 walk_statements(body, check_unreachable, NULL);
5318 if (noreturn_candidate &&
5319 !(function->base.modifiers & DM_NORETURN)) {
5320 position_t const *const pos = &body->base.pos;
5321 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5325 if (is_main(entity)) {
5326 /* Force main to C linkage. */
5327 type_t *const type = entity->declaration.type;
5328 assert(is_type_function(type));
5329 if (type->function.linkage != LINKAGE_C) {
5330 type_t *new_type = duplicate_type(type);
5331 new_type->function.linkage = LINKAGE_C;
5332 entity->declaration.type = identify_new_type(new_type);
5335 if (enable_main_collect2_hack)
5336 prepare_main_collect2(entity);
5339 POP_CURRENT_ENTITY();
5341 assert(current_function == function);
5342 current_function = old_current_function;
5343 label_pop_to(label_stack_top);
5349 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5351 entity_t *iter = compound->members.entities;
5352 for (; iter != NULL; iter = iter->base.next) {
5353 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5356 if (iter->base.symbol == symbol) {
5358 } else if (iter->base.symbol == NULL) {
5359 /* search in anonymous structs and unions */
5360 type_t *type = skip_typeref(iter->declaration.type);
5361 if (is_type_compound(type)) {
5362 if (find_compound_entry(type->compound.compound, symbol)
5373 static void check_deprecated(const position_t *pos, const entity_t *entity)
5375 if (!is_declaration(entity))
5377 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5380 position_t const *const epos = &entity->base.pos;
5381 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5383 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5385 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P)", entity, epos);
5390 static expression_t *create_select(const position_t *pos, expression_t *addr,
5391 type_qualifiers_t qualifiers,
5394 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5396 check_deprecated(pos, entry);
5398 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5399 select->select.compound = addr;
5400 select->select.compound_entry = entry;
5402 type_t *entry_type = entry->declaration.type;
5403 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5405 /* bitfields need special treatment */
5406 if (entry->compound_member.bitfield) {
5407 unsigned bit_size = entry->compound_member.bit_size;
5408 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5409 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5410 res_type = type_int;
5414 /* we always do the auto-type conversions; the & and sizeof parser contains
5415 * code to revert this! */
5416 select->base.type = automatic_type_conversion(res_type);
5423 * Find entry with symbol in compound. Search anonymous structs and unions and
5424 * creates implicit select expressions for them.
5425 * Returns the adress for the innermost compound.
5427 static expression_t *find_create_select(const position_t *pos,
5429 type_qualifiers_t qualifiers,
5430 compound_t *compound, symbol_t *symbol)
5432 entity_t *iter = compound->members.entities;
5433 for (; iter != NULL; iter = iter->base.next) {
5434 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5437 symbol_t *iter_symbol = iter->base.symbol;
5438 if (iter_symbol == NULL) {
5439 type_t *type = iter->declaration.type;
5440 if (!is_type_compound(type))
5443 compound_t *sub_compound = type->compound.compound;
5445 if (find_compound_entry(sub_compound, symbol) == NULL)
5448 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5449 sub_addr->base.pos = *pos;
5450 sub_addr->base.implicit = true;
5451 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5455 if (iter_symbol == symbol) {
5456 return create_select(pos, addr, qualifiers, iter);
5463 static void parse_bitfield_member(entity_t *entity)
5467 expression_t *size = parse_constant_expression();
5470 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5471 type_t *type = entity->declaration.type;
5472 if (!is_type_integer(skip_typeref(type))) {
5473 errorf(HERE, "bitfield base type '%T' is not an integer type",
5477 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5478 /* error already reported by parse_constant_expression */
5479 size_long = get_type_size(type) * 8;
5481 size_long = fold_constant_to_int(size);
5483 const symbol_t *symbol = entity->base.symbol;
5484 const symbol_t *user_symbol
5485 = symbol == NULL ? sym_anonymous : symbol;
5486 unsigned bit_size = get_type_size(type) * 8;
5487 if (size_long < 0) {
5488 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5489 } else if (size_long == 0 && symbol != NULL) {
5490 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5491 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5492 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5495 /* hope that people don't invent crazy types with more bits
5496 * than our struct can hold */
5498 (1 << sizeof(entity->compound_member.bit_size)*8));
5502 entity->compound_member.bitfield = true;
5503 entity->compound_member.bit_size = (unsigned char)size_long;
5506 static void parse_compound_declarators(compound_t *compound,
5507 const declaration_specifiers_t *specifiers)
5509 add_anchor_token(';');
5510 add_anchor_token(',');
5514 if (token.kind == ':') {
5515 /* anonymous bitfield */
5516 type_t *type = specifiers->type;
5517 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5518 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5519 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5520 entity->declaration.type = type;
5522 parse_bitfield_member(entity);
5524 attribute_t *attributes = parse_attributes(NULL);
5525 attribute_t **anchor = &attributes;
5526 while (*anchor != NULL)
5527 anchor = &(*anchor)->next;
5528 *anchor = specifiers->attributes;
5529 if (attributes != NULL) {
5530 handle_entity_attributes(attributes, entity);
5532 entity->declaration.attributes = attributes;
5534 append_entity(&compound->members, entity);
5536 entity = parse_declarator(specifiers,
5537 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5538 position_t const *const pos = &entity->base.pos;
5539 if (entity->kind == ENTITY_TYPEDEF) {
5540 errorf(pos, "typedef not allowed as compound member");
5542 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5544 /* make sure we don't define a symbol multiple times */
5545 symbol_t *symbol = entity->base.symbol;
5546 if (symbol != NULL) {
5547 entity_t *prev = find_compound_entry(compound, symbol);
5549 position_t const *const ppos = &prev->base.pos;
5550 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5554 if (token.kind == ':') {
5555 parse_bitfield_member(entity);
5557 attribute_t *attributes = parse_attributes(NULL);
5558 handle_entity_attributes(attributes, entity);
5560 type_t *orig_type = entity->declaration.type;
5561 type_t *type = skip_typeref(orig_type);
5562 if (is_type_function(type)) {
5563 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5564 } else if (is_type_incomplete(type)) {
5565 /* §6.7.2.1:16 flexible array member */
5566 if (!is_type_array(type) ||
5567 token.kind != ';' ||
5568 look_ahead(1)->kind != '}') {
5569 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5570 } else if (compound->members.entities == NULL) {
5571 errorf(pos, "flexible array member in otherwise empty struct");
5576 append_entity(&compound->members, entity);
5579 } while (accept(','));
5580 rem_anchor_token(',');
5581 rem_anchor_token(';');
5584 anonymous_entity = NULL;
5587 static void parse_compound_type_entries(compound_t *compound)
5590 add_anchor_token('}');
5593 switch (token.kind) {
5595 case T___extension__:
5596 case T_IDENTIFIER: {
5598 declaration_specifiers_t specifiers;
5599 parse_declaration_specifiers(&specifiers);
5600 parse_compound_declarators(compound, &specifiers);
5606 rem_anchor_token('}');
5609 compound->complete = true;
5615 static type_t *parse_typename(void)
5617 declaration_specifiers_t specifiers;
5618 parse_declaration_specifiers(&specifiers);
5619 if (specifiers.storage_class != STORAGE_CLASS_NONE
5620 || specifiers.thread_local) {
5621 /* TODO: improve error message, user does probably not know what a
5622 * storage class is...
5624 errorf(&specifiers.pos, "typename must not have a storage class");
5627 type_t *result = parse_abstract_declarator(specifiers.type);
5635 typedef expression_t* (*parse_expression_function)(void);
5636 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5638 typedef struct expression_parser_function_t expression_parser_function_t;
5639 struct expression_parser_function_t {
5640 parse_expression_function parser;
5641 precedence_t infix_precedence;
5642 parse_expression_infix_function infix_parser;
5645 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5647 static type_t *get_string_type(string_encoding_t const enc)
5649 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5651 case STRING_ENCODING_CHAR:
5652 case STRING_ENCODING_UTF8: return warn ? type_const_char_ptr : type_char_ptr;
5653 case STRING_ENCODING_CHAR16: return warn ? type_char16_t_const_ptr : type_char16_t_ptr;
5654 case STRING_ENCODING_CHAR32: return warn ? type_char32_t_const_ptr : type_char32_t_ptr;
5655 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5657 panic("invalid string encoding");
5661 * Parse a string constant.
5663 static expression_t *parse_string_literal(void)
5665 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5666 expr->string_literal.value = concat_string_literals();
5667 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5672 * Parse a boolean constant.
5674 static expression_t *parse_boolean_literal(bool value)
5676 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5677 literal->base.type = type_bool;
5678 literal->literal.value.begin = value ? "true" : "false";
5679 literal->literal.value.size = value ? 4 : 5;
5681 eat(value ? T_true : T_false);
5685 static void warn_traditional_suffix(char const *const suffix)
5687 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5690 static void check_integer_suffix(expression_t *const expr, char const *const suffix)
5692 unsigned spec = SPECIFIER_NONE;
5693 char const *c = suffix;
5694 while (*c != '\0') {
5699 add = SPECIFIER_LONG;
5701 add |= SPECIFIER_LONG_LONG;
5707 add = SPECIFIER_UNSIGNED;
5715 add = SPECIFIER_COMPLEX;
5729 switch (spec & ~SPECIFIER_COMPLEX) {
5730 case SPECIFIER_NONE: type = type_int; break;
5731 case SPECIFIER_LONG: type = type_long; break;
5732 case SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long; break;
5733 case SPECIFIER_UNSIGNED: type = type_unsigned_int; break;
5734 case SPECIFIER_UNSIGNED | SPECIFIER_LONG: type = type_unsigned_long; break;
5735 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5736 default: panic("inconsistent suffix");
5738 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG) {
5739 warn_traditional_suffix(suffix);
5741 if (spec & SPECIFIER_COMPLEX) {
5742 assert(type->kind == TYPE_ATOMIC);
5743 type = make_complex_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
5745 expr->base.type = type;
5746 /* Integer type depends on the size of the number and the size
5747 * representable by the types. The backend/codegeneration has to
5748 * determine that. */
5749 determine_literal_type(&expr->literal);
5752 errorf(HERE, "invalid suffix '%s' on integer constant", suffix);
5756 static void check_floatingpoint_suffix(expression_t *const expr, char const *const suffix)
5759 char const *c = suffix;
5760 bool is_complex = false;
5764 case 'f': type = type_float; ++c; break;
5766 case 'l': type = type_long_double; ++c; break;
5776 default: type = type_double; break;
5781 assert(type->kind == TYPE_ATOMIC);
5782 type = make_complex_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
5785 expr->base.type = type;
5786 if (suffix[0] != '\0') {
5787 warn_traditional_suffix(suffix);
5790 errorf(HERE, "invalid suffix '%s' on floatingpoint constant", suffix);
5794 static expression_t *parse_number_literal(void)
5796 string_t const *const str = &token.literal.string;
5797 char const * i = str->begin;
5798 unsigned digits = 0;
5799 bool is_float = false;
5801 /* Parse base prefix. */
5805 case 'B': case 'b': base = 2; ++i; break;
5806 case 'X': case 'x': base = 16; ++i; break;
5807 default: base = 8; digits |= 1U << 0; break;
5813 /* Parse mantissa. */
5819 errorf(HERE, "multiple decimal points in %K", &token);
5828 case '0': digit = 0; break;
5829 case '1': digit = 1; break;
5830 case '2': digit = 2; break;
5831 case '3': digit = 3; break;
5832 case '4': digit = 4; break;
5833 case '5': digit = 5; break;
5834 case '6': digit = 6; break;
5835 case '7': digit = 7; break;
5836 case '8': digit = 8; break;
5837 case '9': digit = 9; break;
5838 case 'A': case 'a': digit = 10; break;
5839 case 'B': case 'b': digit = 11; break;
5840 case 'C': case 'c': digit = 12; break;
5841 case 'D': case 'd': digit = 13; break;
5842 case 'E': case 'e': digit = 14; break;
5843 case 'F': case 'f': digit = 15; break;
5845 default: goto done_mantissa;
5848 if (digit >= 10 && base != 16)
5851 digits |= 1U << digit;
5855 /* Parse exponent. */
5859 errorf(HERE, "binary floating %K not allowed", &token);
5864 if (*i == 'E' || *i == 'e') {
5866 goto parse_exponent;
5871 if (*i == 'P' || *i == 'p') {
5876 if (*i == '-' || *i == '+')
5882 } while (isdigit(*i));
5884 errorf(HERE, "exponent of %K has no digits", &token);
5886 } else if (is_float) {
5887 errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5893 panic("invalid base");
5897 expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5898 expr->literal.value = *str;
5902 errorf(HERE, "%K has no digits", &token);
5903 } else if (digits & ~((1U << base) - 1)) {
5904 errorf(HERE, "invalid digit in %K", &token);
5906 expr->literal.suffix = i;
5908 check_floatingpoint_suffix(expr, i);
5910 check_integer_suffix(expr, i);
5920 * Parse a character constant.
5922 static expression_t *parse_character_constant(void)
5924 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5925 literal->string_literal.value = token.literal.string;
5927 size_t const size = get_string_len(&token.literal.string);
5928 switch (token.literal.string.encoding) {
5929 case STRING_ENCODING_CHAR:
5930 case STRING_ENCODING_UTF8:
5931 literal->base.type = c_mode & _CXX ? type_char : type_int;
5933 if (!GNU_MODE && !(c_mode & _C99)) {
5934 errorf(HERE, "more than 1 character in character constant");
5936 literal->base.type = type_int;
5937 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5942 case STRING_ENCODING_CHAR16: literal->base.type = type_char16_t; goto warn_multi;
5943 case STRING_ENCODING_CHAR32: literal->base.type = type_char32_t; goto warn_multi;
5944 case STRING_ENCODING_WIDE: literal->base.type = type_wchar_t; goto warn_multi;
5947 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5952 eat(T_CHARACTER_CONSTANT);
5956 static entity_t *create_implicit_function(symbol_t *symbol, position_t const *const pos)
5958 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5959 ntype->function.return_type = type_int;
5960 ntype->function.unspecified_parameters = true;
5961 ntype->function.linkage = LINKAGE_C;
5962 type_t *type = identify_new_type(ntype);
5964 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5965 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5966 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5967 entity->declaration.type = type;
5968 entity->declaration.implicit = true;
5970 if (current_scope != NULL)
5971 record_entity(entity, false);
5977 * Performs automatic type cast as described in §6.3.2.1.
5979 * @param orig_type the original type
5981 static type_t *automatic_type_conversion(type_t *orig_type)
5983 type_t *type = skip_typeref(orig_type);
5984 if (is_type_array(type)) {
5985 array_type_t *array_type = &type->array;
5986 type_t *element_type = array_type->element_type;
5987 unsigned qualifiers = array_type->base.qualifiers;
5989 return make_pointer_type(element_type, qualifiers);
5992 if (is_type_function(type)) {
5993 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6000 * reverts the automatic casts of array to pointer types and function
6001 * to function-pointer types as defined §6.3.2.1
6003 type_t *revert_automatic_type_conversion(const expression_t *expression)
6005 switch (expression->kind) {
6006 case EXPR_REFERENCE: {
6007 entity_t *entity = expression->reference.entity;
6008 if (is_declaration(entity)) {
6009 return entity->declaration.type;
6010 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6011 return entity->enum_value.enum_type;
6013 panic("no declaration or enum in reference");
6018 entity_t *entity = expression->select.compound_entry;
6019 assert(is_declaration(entity));
6020 type_t *type = entity->declaration.type;
6021 return get_qualified_type(type, expression->base.type->base.qualifiers);
6024 case EXPR_UNARY_DEREFERENCE: {
6025 const expression_t *const value = expression->unary.value;
6026 type_t *const type = skip_typeref(value->base.type);
6027 if (!is_type_pointer(type))
6028 return type_error_type;
6029 return type->pointer.points_to;
6032 case EXPR_ARRAY_ACCESS: {
6033 const expression_t *array_ref = expression->array_access.array_ref;
6034 type_t *type_left = skip_typeref(array_ref->base.type);
6035 if (!is_type_pointer(type_left))
6036 return type_error_type;
6037 return type_left->pointer.points_to;
6040 case EXPR_STRING_LITERAL: {
6041 size_t const size = get_string_len(&expression->string_literal.value) + 1;
6042 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
6043 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
6046 case EXPR_COMPOUND_LITERAL:
6047 return expression->compound_literal.type;
6052 return expression->base.type;
6056 * Find an entity matching a symbol in a scope.
6057 * Uses current scope if scope is NULL
6059 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6060 namespace_tag_t namespc)
6062 if (scope == NULL) {
6063 return get_entity(symbol, namespc);
6066 /* we should optimize here, if scope grows above a certain size we should
6067 construct a hashmap here... */
6068 entity_t *entity = scope->entities;
6069 for ( ; entity != NULL; entity = entity->base.next) {
6070 if (entity->base.symbol == symbol
6071 && (namespace_tag_t)entity->base.namespc == namespc)
6078 static entity_t *parse_qualified_identifier(void)
6080 /* namespace containing the symbol */
6083 const scope_t *lookup_scope = NULL;
6085 if (accept(T_COLONCOLON))
6086 lookup_scope = &unit->scope;
6090 symbol = expect_identifier("while parsing identifier", &pos);
6092 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6095 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6097 if (!accept(T_COLONCOLON))
6100 switch (entity->kind) {
6101 case ENTITY_NAMESPACE:
6102 lookup_scope = &entity->namespacee.members;
6107 lookup_scope = &entity->compound.members;
6110 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6111 symbol, get_entity_kind_name(entity->kind));
6113 /* skip further qualifications */
6114 while (accept(T_IDENTIFIER) && accept(T_COLONCOLON)) {}
6116 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6120 if (entity == NULL) {
6121 if (!strict_mode && token.kind == '(') {
6122 /* an implicitly declared function */
6123 entity = create_implicit_function(symbol, &pos);
6124 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6126 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6127 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6134 static expression_t *parse_reference(void)
6136 position_t const pos = *HERE;
6137 entity_t *const entity = parse_qualified_identifier();
6140 if (is_declaration(entity)) {
6141 orig_type = entity->declaration.type;
6142 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6143 orig_type = entity->enum_value.enum_type;
6145 panic("expected declaration or enum value in reference");
6148 /* we always do the auto-type conversions; the & and sizeof parser contains
6149 * code to revert this! */
6150 type_t *type = automatic_type_conversion(orig_type);
6152 expression_kind_t kind = EXPR_REFERENCE;
6153 if (entity->kind == ENTITY_ENUM_VALUE)
6154 kind = EXPR_ENUM_CONSTANT;
6156 expression_t *expression = allocate_expression_zero(kind);
6157 expression->base.pos = pos;
6158 expression->base.type = type;
6159 expression->reference.entity = entity;
6161 /* this declaration is used */
6162 if (is_declaration(entity)) {
6163 entity->declaration.used = true;
6166 if (entity->base.parent_scope != file_scope
6167 && (current_function != NULL
6168 && entity->base.parent_scope->depth < current_function->parameters.depth)
6169 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6170 /* access of a variable from an outer function */
6171 entity->variable.address_taken = true;
6172 current_function->need_closure = true;
6175 check_deprecated(&pos, entity);
6180 static bool semantic_cast(expression_t *cast)
6182 expression_t *expression = cast->unary.value;
6183 type_t *orig_dest_type = cast->base.type;
6184 type_t *orig_type_right = expression->base.type;
6185 type_t const *dst_type = skip_typeref(orig_dest_type);
6186 type_t const *src_type = skip_typeref(orig_type_right);
6187 position_t const *pos = &cast->base.pos;
6189 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation
6190 * than for utility. */
6191 if (is_type_void(dst_type))
6194 /* only integer and pointer can be casted to pointer */
6195 if (is_type_pointer(dst_type) &&
6196 !is_type_pointer(src_type) &&
6197 !is_type_integer(src_type) &&
6198 is_type_valid(src_type)) {
6199 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6203 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6204 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6208 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6209 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6213 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6214 type_t *src = skip_typeref(src_type->pointer.points_to);
6215 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6216 unsigned missing_qualifiers =
6217 src->base.qualifiers & ~dst->base.qualifiers;
6218 if (missing_qualifiers != 0) {
6219 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6225 static void semantic_complex_extract(unary_expression_t *extract)
6227 type_t *orig_value_type = extract->value->base.type;
6228 type_t *value_type = skip_typeref(orig_value_type);
6229 if (!is_type_valid(value_type)) {
6230 extract->base.type = type_error_type;
6234 type_t *type = value_type;
6235 if (!is_type_complex(type)) {
6236 if (!is_type_arithmetic(type)) {
6237 errorf(&extract->base.pos,
6238 "%s requires an argument with complex or arithmetic type, got '%T'",
6239 extract->base.kind == EXPR_UNARY_IMAG ? "__imag__" : "__real__",
6241 extract->base.type = type_error_type;
6244 atomic_type_kind_t const akind = get_arithmetic_akind(type);
6245 type = make_complex_type(akind, TYPE_QUALIFIER_NONE);
6246 extract->value = create_implicit_cast(extract->value, type);
6248 assert(type->kind == TYPE_COMPLEX);
6249 type = make_atomic_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
6250 extract->base.type = type;
6253 static expression_t *parse_compound_literal(position_t const *const pos,
6256 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6257 expression->base.pos = *pos;
6258 bool global_scope = current_scope == file_scope;
6260 parse_initializer_env_t env;
6263 env.must_be_constant = global_scope;
6264 initializer_t *initializer = parse_initializer(&env);
6267 expression->base.type = automatic_type_conversion(type);
6268 expression->compound_literal.initializer = initializer;
6269 expression->compound_literal.type = type;
6270 expression->compound_literal.global_scope = global_scope;
6276 * Parse a cast expression.
6278 static expression_t *parse_cast(void)
6280 position_t const pos = *HERE;
6283 add_anchor_token(')');
6285 type_t *type = parse_typename();
6287 rem_anchor_token(')');
6290 if (token.kind == '{') {
6291 return parse_compound_literal(&pos, type);
6294 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6295 cast->base.pos = pos;
6297 expression_t *value = parse_subexpression(PREC_CAST);
6298 cast->base.type = type;
6299 cast->unary.value = value;
6301 if (!semantic_cast(cast)) {
6302 cast->base.type = type_error_type;
6308 static expression_t *parse_complex_extract_expression(void)
6310 expression_kind_t kind;
6311 if (token.kind == T___imag__) {
6312 kind = EXPR_UNARY_IMAG;
6314 assert(token.kind == T___real__);
6315 kind = EXPR_UNARY_REAL;
6317 expression_t *extract = allocate_expression_zero(kind);
6318 extract->base.pos = *HERE;
6321 extract->unary.value = parse_subexpression(PREC_CAST);
6322 semantic_complex_extract(&extract->unary);
6327 * Parse a statement expression.
6329 static expression_t *parse_statement_expression(void)
6331 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6334 add_anchor_token(')');
6336 statement_t *statement = parse_compound_statement(true);
6337 statement->compound.stmt_expr = true;
6338 expression->statement.statement = statement;
6340 /* find last statement and use its type */
6341 type_t *type = type_void;
6342 const statement_t *stmt = statement->compound.statements;
6344 while (stmt->base.next != NULL)
6345 stmt = stmt->base.next;
6347 if (stmt->kind == STATEMENT_EXPRESSION) {
6348 type = stmt->expression.expression->base.type;
6351 position_t const *const pos = &expression->base.pos;
6352 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6354 expression->base.type = type;
6356 rem_anchor_token(')');
6362 * Parse a parenthesized expression.
6364 static expression_t *parse_parenthesized_expression(void)
6366 token_t const* const la1 = look_ahead(1);
6367 switch (la1->kind) {
6369 /* gcc extension: a statement expression */
6370 return parse_statement_expression();
6373 if (is_typedef_symbol(la1->base.symbol)) {
6375 return parse_cast();
6380 add_anchor_token(')');
6381 expression_t *result = parse_expression();
6382 result->base.parenthesized = true;
6383 rem_anchor_token(')');
6389 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6391 if (current_function == NULL) {
6392 errorf(HERE, "%K used outside of a function", &token);
6395 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6396 expression->base.type = type_char_ptr;
6397 expression->funcname.kind = kind;
6404 static designator_t *parse_designator(void)
6406 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6407 result->symbol = expect_identifier("while parsing member designator", &result->pos);
6408 if (!result->symbol)
6411 designator_t *last_designator = result;
6414 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6415 designator->symbol = expect_identifier("while parsing member designator", &designator->pos);
6416 if (!designator->symbol)
6419 last_designator->next = designator;
6420 last_designator = designator;
6424 add_anchor_token(']');
6425 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6426 designator->pos = *HERE;
6427 designator->array_index = parse_expression();
6428 rem_anchor_token(']');
6430 if (designator->array_index == NULL) {
6434 last_designator->next = designator;
6435 last_designator = designator;
6445 * Parse the __builtin_offsetof() expression.
6447 static expression_t *parse_offsetof(void)
6449 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6450 expression->base.type = type_size_t;
6452 eat(T___builtin_offsetof);
6454 add_anchor_token(')');
6455 add_anchor_token(',');
6457 type_t *type = parse_typename();
6458 rem_anchor_token(',');
6460 designator_t *designator = parse_designator();
6461 rem_anchor_token(')');
6464 expression->offsetofe.type = type;
6465 expression->offsetofe.designator = designator;
6468 memset(&path, 0, sizeof(path));
6469 path.top_type = type;
6470 path.path = NEW_ARR_F(type_path_entry_t, 0);
6472 descend_into_subtype(&path);
6474 if (!walk_designator(&path, designator, true)) {
6475 return create_error_expression();
6478 DEL_ARR_F(path.path);
6483 static bool is_last_parameter(expression_t *const param)
6485 if (param->kind == EXPR_REFERENCE) {
6486 entity_t *const entity = param->reference.entity;
6487 if (entity->kind == ENTITY_PARAMETER &&
6488 !entity->base.next &&
6489 entity->base.parent_scope == ¤t_function->parameters) {
6494 if (!is_type_valid(skip_typeref(param->base.type)))
6501 * Parses a __builtin_va_start() expression.
6503 static expression_t *parse_va_start(void)
6505 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6507 eat(T___builtin_va_start);
6509 add_anchor_token(')');
6510 add_anchor_token(',');
6512 expression->va_starte.ap = parse_assignment_expression();
6513 rem_anchor_token(',');
6515 expression_t *const param = parse_assignment_expression();
6516 expression->va_starte.parameter = param;
6517 rem_anchor_token(')');
6520 if (!current_function) {
6521 errorf(&expression->base.pos, "'va_start' used outside of function");
6522 } else if (!current_function->base.type->function.variadic) {
6523 errorf(&expression->base.pos, "'va_start' used in non-variadic function");
6524 } else if (!is_last_parameter(param)) {
6525 errorf(¶m->base.pos, "second argument of 'va_start' must be last parameter of the current function");
6532 * Parses a __builtin_va_arg() expression.
6534 static expression_t *parse_va_arg(void)
6536 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6538 eat(T___builtin_va_arg);
6540 add_anchor_token(')');
6541 add_anchor_token(',');
6544 ap.expression = parse_assignment_expression();
6545 expression->va_arge.ap = ap.expression;
6546 check_call_argument(type_valist, &ap, 1);
6548 rem_anchor_token(',');
6550 expression->base.type = parse_typename();
6551 rem_anchor_token(')');
6558 * Parses a __builtin_va_copy() expression.
6560 static expression_t *parse_va_copy(void)
6562 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6564 eat(T___builtin_va_copy);
6566 add_anchor_token(')');
6567 add_anchor_token(',');
6569 expression_t *dst = parse_assignment_expression();
6570 assign_error_t error = semantic_assign(type_valist, dst);
6571 report_assign_error(error, type_valist, dst, "call argument 1",
6573 expression->va_copye.dst = dst;
6575 rem_anchor_token(',');
6578 call_argument_t src;
6579 src.expression = parse_assignment_expression();
6580 check_call_argument(type_valist, &src, 2);
6581 expression->va_copye.src = src.expression;
6582 rem_anchor_token(')');
6589 * Parses a __builtin_constant_p() expression.
6591 static expression_t *parse_builtin_constant(void)
6593 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6595 eat(T___builtin_constant_p);
6597 add_anchor_token(')');
6599 expression->builtin_constant.value = parse_assignment_expression();
6600 rem_anchor_token(')');
6602 expression->base.type = type_int;
6608 * Parses a __builtin_types_compatible_p() expression.
6610 static expression_t *parse_builtin_types_compatible(void)
6612 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6614 eat(T___builtin_types_compatible_p);
6616 add_anchor_token(')');
6617 add_anchor_token(',');
6619 expression->builtin_types_compatible.left = parse_typename();
6620 rem_anchor_token(',');
6622 expression->builtin_types_compatible.right = parse_typename();
6623 rem_anchor_token(')');
6625 expression->base.type = type_int;
6631 * Parses a __builtin_is_*() compare expression.
6633 static expression_t *parse_compare_builtin(void)
6635 expression_kind_t kind;
6636 switch (token.kind) {
6637 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6638 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6639 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6640 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6641 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6642 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6643 default: internal_errorf(HERE, "invalid compare builtin found");
6645 expression_t *const expression = allocate_expression_zero(kind);
6648 add_anchor_token(')');
6649 add_anchor_token(',');
6651 expression->binary.left = parse_assignment_expression();
6652 rem_anchor_token(',');
6654 expression->binary.right = parse_assignment_expression();
6655 rem_anchor_token(')');
6658 type_t *const orig_type_left = expression->binary.left->base.type;
6659 type_t *const orig_type_right = expression->binary.right->base.type;
6661 type_t *const type_left = skip_typeref(orig_type_left);
6662 type_t *const type_right = skip_typeref(orig_type_right);
6663 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6664 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6665 type_error_incompatible("invalid operands in comparison",
6666 &expression->base.pos, orig_type_left, orig_type_right);
6669 semantic_comparison(&expression->binary);
6676 * Parses a MS assume() expression.
6678 static expression_t *parse_assume(void)
6680 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6684 add_anchor_token(')');
6686 expression->unary.value = parse_assignment_expression();
6687 rem_anchor_token(')');
6690 expression->base.type = type_void;
6695 * Return the label for the current symbol or create a new one.
6697 static label_t *get_label(char const *const context)
6699 assert(current_function != NULL);
6701 symbol_t *const sym = expect_identifier(context, NULL);
6705 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6706 /* If we find a local label, we already created the declaration. */
6707 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6708 if (label->base.parent_scope != current_scope) {
6709 assert(label->base.parent_scope->depth < current_scope->depth);
6710 current_function->goto_to_outer = true;
6712 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6713 /* There is no matching label in the same function, so create a new one. */
6714 position_t const nowhere = { NULL, 0, 0, false };
6715 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6719 return &label->label;
6723 * Parses a GNU && label address expression.
6725 static expression_t *parse_label_address(void)
6727 position_t const pos = *HERE;
6730 label_t *const label = get_label("while parsing label address");
6732 return create_error_expression();
6735 label->address_taken = true;
6737 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6738 expression->base.pos = pos;
6740 /* label address is treated as a void pointer */
6741 expression->base.type = type_void_ptr;
6742 expression->label_address.label = label;
6747 * Parse a microsoft __noop expression.
6749 static expression_t *parse_noop_expression(void)
6751 /* the result is a (int)0 */
6752 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6753 literal->base.type = type_int;
6754 literal->literal.value.begin = "__noop";
6755 literal->literal.value.size = 6;
6759 if (token.kind == '(') {
6760 /* parse arguments */
6762 add_anchor_token(')');
6763 add_anchor_token(',');
6765 if (token.kind != ')') do {
6766 (void)parse_assignment_expression();
6767 } while (accept(','));
6769 rem_anchor_token(',');
6770 rem_anchor_token(')');
6778 * Parses a primary expression.
6780 static expression_t *parse_primary_expression(void)
6782 switch (token.kind) {
6783 case T_false: return parse_boolean_literal(false);
6784 case T_true: return parse_boolean_literal(true);
6785 case T_NUMBER: return parse_number_literal();
6786 case T_CHARACTER_CONSTANT: return parse_character_constant();
6787 case T_STRING_LITERAL: return parse_string_literal();
6788 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6789 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6790 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6791 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6792 case T___builtin_offsetof: return parse_offsetof();
6793 case T___builtin_va_start: return parse_va_start();
6794 case T___builtin_va_arg: return parse_va_arg();
6795 case T___builtin_va_copy: return parse_va_copy();
6796 case T___builtin_isgreater:
6797 case T___builtin_isgreaterequal:
6798 case T___builtin_isless:
6799 case T___builtin_islessequal:
6800 case T___builtin_islessgreater:
6801 case T___builtin_isunordered: return parse_compare_builtin();
6802 case T___builtin_constant_p: return parse_builtin_constant();
6803 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6804 case T__assume: return parse_assume();
6807 return parse_label_address();
6810 case '(': return parse_parenthesized_expression();
6811 case T___noop: return parse_noop_expression();
6813 case T___imag__: return parse_complex_extract_expression();
6815 /* Gracefully handle type names while parsing expressions. */
6817 return parse_reference();
6819 if (!is_typedef_symbol(token.base.symbol)) {
6820 return parse_reference();
6824 position_t const pos = *HERE;
6825 declaration_specifiers_t specifiers;
6826 parse_declaration_specifiers(&specifiers);
6827 type_t const *const type = parse_abstract_declarator(specifiers.type);
6828 errorf(&pos, "encountered type '%T' while parsing expression", type);
6829 return create_error_expression();
6833 errorf(HERE, "unexpected token %K, expected an expression", &token);
6835 return create_error_expression();
6838 static expression_t *parse_array_expression(expression_t *left)
6840 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6841 array_access_expression_t *const arr = &expr->array_access;
6844 add_anchor_token(']');
6846 expression_t *const inside = parse_expression();
6848 type_t *const orig_type_left = left->base.type;
6849 type_t *const orig_type_inside = inside->base.type;
6851 type_t *const type_left = skip_typeref(orig_type_left);
6852 type_t *const type_inside = skip_typeref(orig_type_inside);
6858 if (is_type_pointer(type_left)) {
6861 idx_type = type_inside;
6862 res_type = type_left->pointer.points_to;
6864 } else if (is_type_pointer(type_inside)) {
6865 arr->flipped = true;
6868 idx_type = type_left;
6869 res_type = type_inside->pointer.points_to;
6871 res_type = automatic_type_conversion(res_type);
6872 if (!is_type_integer(idx_type)) {
6873 if (is_type_valid(idx_type))
6874 errorf(&idx->base.pos, "array subscript must have integer type");
6875 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6876 position_t const *const pos = &idx->base.pos;
6877 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6880 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6881 errorf(&expr->base.pos, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6883 res_type = type_error_type;
6888 arr->array_ref = ref;
6890 arr->base.type = res_type;
6892 rem_anchor_token(']');
6897 static bool is_bitfield(const expression_t *expression)
6899 return expression->kind == EXPR_SELECT
6900 && expression->select.compound_entry->compound_member.bitfield;
6903 static expression_t *parse_typeprop(expression_kind_t const kind)
6905 expression_t *tp_expression = allocate_expression_zero(kind);
6906 tp_expression->base.type = type_size_t;
6908 eat(kind == EXPR_SIZEOF ? T_sizeof : T__Alignof);
6911 expression_t *expression;
6912 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6913 position_t const pos = *HERE;
6915 add_anchor_token(')');
6916 orig_type = parse_typename();
6917 rem_anchor_token(')');
6920 if (token.kind == '{') {
6921 /* It was not sizeof(type) after all. It is sizeof of an expression
6922 * starting with a compound literal */
6923 expression = parse_compound_literal(&pos, orig_type);
6924 goto typeprop_expression;
6927 expression = parse_subexpression(PREC_UNARY);
6929 typeprop_expression:
6930 if (is_bitfield(expression)) {
6931 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6932 errorf(&tp_expression->base.pos,
6933 "operand of %s expression must not be a bitfield", what);
6936 tp_expression->typeprop.tp_expression = expression;
6938 orig_type = revert_automatic_type_conversion(expression);
6939 expression->base.type = orig_type;
6942 tp_expression->typeprop.type = orig_type;
6943 type_t const* const type = skip_typeref(orig_type);
6944 char const* wrong_type = NULL;
6945 if (is_type_incomplete(type)) {
6946 if (!is_type_void(type) || !GNU_MODE)
6947 wrong_type = "incomplete";
6948 } else if (type->kind == TYPE_FUNCTION) {
6950 /* function types are allowed (and return 1) */
6951 position_t const *const pos = &tp_expression->base.pos;
6952 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6953 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6955 wrong_type = "function";
6959 if (wrong_type != NULL) {
6960 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6961 errorf(&tp_expression->base.pos,
6962 "operand of %s expression must not be of %s type '%T'",
6963 what, wrong_type, orig_type);
6966 return tp_expression;
6969 static expression_t *parse_sizeof(void)
6971 return parse_typeprop(EXPR_SIZEOF);
6974 static expression_t *parse_alignof(void)
6976 return parse_typeprop(EXPR_ALIGNOF);
6979 static expression_t *parse_select_expression(expression_t *addr)
6981 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6982 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6983 position_t const pos = *HERE;
6986 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6988 return create_error_expression();
6990 type_t *const orig_type = addr->base.type;
6991 type_t *const type = skip_typeref(orig_type);
6994 bool saw_error = false;
6995 if (is_type_pointer(type)) {
6996 if (!select_left_arrow) {
6998 "request for member '%Y' in something not a struct or union, but '%T'",
7002 type_left = skip_typeref(type->pointer.points_to);
7004 if (select_left_arrow && is_type_valid(type)) {
7005 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7011 if (!is_type_compound(type_left)) {
7012 if (is_type_valid(type_left) && !saw_error) {
7014 "request for member '%Y' in something not a struct or union, but '%T'",
7017 return create_error_expression();
7020 compound_t *compound = type_left->compound.compound;
7021 if (!compound->complete) {
7022 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7024 return create_error_expression();
7027 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7028 expression_t *result =
7029 find_create_select(&pos, addr, qualifiers, compound, symbol);
7031 if (result == NULL) {
7032 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7033 return create_error_expression();
7039 static void check_call_argument(type_t *expected_type,
7040 call_argument_t *argument, unsigned pos)
7042 type_t *expected_type_skip = skip_typeref(expected_type);
7043 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7044 expression_t *arg_expr = argument->expression;
7045 type_t *arg_type = skip_typeref(arg_expr->base.type);
7047 /* handle transparent union gnu extension */
7048 if (is_type_union(expected_type_skip)
7049 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7050 compound_t *union_decl = expected_type_skip->compound.compound;
7051 type_t *best_type = NULL;
7052 entity_t *entry = union_decl->members.entities;
7053 for ( ; entry != NULL; entry = entry->base.next) {
7054 assert(is_declaration(entry));
7055 type_t *decl_type = entry->declaration.type;
7056 error = semantic_assign(decl_type, arg_expr);
7057 if (error == ASSIGN_ERROR_INCOMPATIBLE
7058 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7061 if (error == ASSIGN_SUCCESS) {
7062 best_type = decl_type;
7063 } else if (best_type == NULL) {
7064 best_type = decl_type;
7068 if (best_type != NULL) {
7069 expected_type = best_type;
7073 error = semantic_assign(expected_type, arg_expr);
7074 argument->expression = create_implicit_cast(arg_expr, expected_type);
7076 if (error != ASSIGN_SUCCESS) {
7077 /* report exact scope in error messages (like "in argument 3") */
7079 snprintf(buf, sizeof(buf), "call argument %u", pos);
7080 report_assign_error(error, expected_type, arg_expr, buf,
7081 &arg_expr->base.pos);
7083 type_t *const promoted_type = get_default_promoted_type(arg_type);
7084 if (!types_compatible(expected_type_skip, promoted_type) &&
7085 !types_compatible(expected_type_skip, type_void_ptr) &&
7086 !types_compatible(type_void_ptr, promoted_type)) {
7087 /* Deliberately show the skipped types in this warning */
7088 position_t const *const apos = &arg_expr->base.pos;
7089 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7095 * Handle the semantic restrictions of builtin calls
7097 static void handle_builtin_argument_restrictions(call_expression_t *call)
7099 entity_t *entity = call->function->reference.entity;
7100 switch (entity->function.btk) {
7102 switch (entity->function.b.firm_builtin_kind) {
7103 case ir_bk_return_address:
7104 case ir_bk_frame_address: {
7105 /* argument must be constant */
7106 call_argument_t *argument = call->arguments;
7108 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7109 errorf(&call->base.pos,
7110 "argument of '%Y' must be a constant expression",
7111 call->function->reference.entity->base.symbol);
7115 case ir_bk_prefetch:
7116 /* second and third argument must be constant if existent */
7117 if (call->arguments == NULL)
7119 call_argument_t *rw = call->arguments->next;
7120 call_argument_t *locality = NULL;
7123 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7124 errorf(&call->base.pos,
7125 "second argument of '%Y' must be a constant expression",
7126 call->function->reference.entity->base.symbol);
7128 locality = rw->next;
7130 if (locality != NULL) {
7131 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7132 errorf(&call->base.pos,
7133 "third argument of '%Y' must be a constant expression",
7134 call->function->reference.entity->base.symbol);
7142 case BUILTIN_OBJECT_SIZE:
7143 if (call->arguments == NULL)
7146 call_argument_t *arg = call->arguments->next;
7147 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7148 errorf(&call->base.pos,
7149 "second argument of '%Y' must be a constant expression",
7150 call->function->reference.entity->base.symbol);
7159 * Parse a call expression, i.e. expression '( ... )'.
7161 * @param expression the function address
7163 static expression_t *parse_call_expression(expression_t *expression)
7165 expression_t *result = allocate_expression_zero(EXPR_CALL);
7166 call_expression_t *call = &result->call;
7167 call->function = expression;
7169 type_t *const orig_type = expression->base.type;
7170 type_t *const type = skip_typeref(orig_type);
7172 function_type_t *function_type = NULL;
7173 if (is_type_pointer(type)) {
7174 type_t *const to_type = skip_typeref(type->pointer.points_to);
7176 if (is_type_function(to_type)) {
7177 function_type = &to_type->function;
7178 call->base.type = function_type->return_type;
7182 if (function_type == NULL && is_type_valid(type)) {
7184 "called object '%E' (type '%T') is not a pointer to a function",
7185 expression, orig_type);
7188 /* parse arguments */
7190 add_anchor_token(')');
7191 add_anchor_token(',');
7193 if (token.kind != ')') {
7194 call_argument_t **anchor = &call->arguments;
7196 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7197 argument->expression = parse_assignment_expression();
7200 anchor = &argument->next;
7201 } while (accept(','));
7203 rem_anchor_token(',');
7204 rem_anchor_token(')');
7207 if (function_type == NULL)
7210 /* check type and count of call arguments */
7211 function_parameter_t *parameter = function_type->parameters;
7212 call_argument_t *argument = call->arguments;
7213 if (!function_type->unspecified_parameters) {
7214 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7215 parameter = parameter->next, argument = argument->next) {
7216 check_call_argument(parameter->type, argument, ++pos);
7219 if (parameter != NULL) {
7220 errorf(&expression->base.pos, "too few arguments to function '%E'",
7222 } else if (argument != NULL && !function_type->variadic) {
7223 errorf(&argument->expression->base.pos,
7224 "too many arguments to function '%E'", expression);
7228 /* do default promotion for other arguments */
7229 for (; argument != NULL; argument = argument->next) {
7230 type_t *argument_type = argument->expression->base.type;
7231 if (!is_type_object(skip_typeref(argument_type))) {
7232 errorf(&argument->expression->base.pos,
7233 "call argument '%E' must not be void", argument->expression);
7236 argument_type = get_default_promoted_type(argument_type);
7238 argument->expression
7239 = create_implicit_cast(argument->expression, argument_type);
7244 if (is_type_compound(skip_typeref(function_type->return_type))) {
7245 position_t const *const pos = &expression->base.pos;
7246 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7249 if (expression->kind == EXPR_REFERENCE) {
7250 reference_expression_t *reference = &expression->reference;
7251 if (reference->entity->kind == ENTITY_FUNCTION &&
7252 reference->entity->function.btk != BUILTIN_NONE)
7253 handle_builtin_argument_restrictions(call);
7259 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7261 static bool same_compound_type(const type_t *type1, const type_t *type2)
7264 is_type_compound(type1) &&
7265 type1->kind == type2->kind &&
7266 type1->compound.compound == type2->compound.compound;
7269 static expression_t const *get_reference_address(expression_t const *expr)
7271 bool regular_take_address = true;
7273 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7274 expr = expr->unary.value;
7276 regular_take_address = false;
7279 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7282 expr = expr->unary.value;
7285 if (expr->kind != EXPR_REFERENCE)
7288 /* special case for functions which are automatically converted to a
7289 * pointer to function without an extra TAKE_ADDRESS operation */
7290 if (!regular_take_address &&
7291 expr->reference.entity->kind != ENTITY_FUNCTION) {
7298 static void warn_reference_address_as_bool(expression_t const* expr)
7300 expr = get_reference_address(expr);
7302 position_t const *const pos = &expr->base.pos;
7303 entity_t const *const ent = expr->reference.entity;
7304 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7308 static void warn_assignment_in_condition(const expression_t *const expr)
7310 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7312 if (expr->base.parenthesized)
7314 position_t const *const pos = &expr->base.pos;
7315 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7318 static void semantic_condition(expression_t const *const expr,
7319 char const *const context)
7321 type_t *const type = skip_typeref(expr->base.type);
7322 if (is_type_scalar(type)) {
7323 warn_reference_address_as_bool(expr);
7324 warn_assignment_in_condition(expr);
7325 } else if (is_type_valid(type)) {
7326 errorf(&expr->base.pos, "%s must have scalar type", context);
7331 * Parse a conditional expression, i.e. 'expression ? ... : ...'.
7333 * @param expression the conditional expression
7335 static expression_t *parse_conditional_expression(expression_t *expression)
7337 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7339 conditional_expression_t *conditional = &result->conditional;
7340 conditional->condition = expression;
7343 add_anchor_token(':');
7345 /* §6.5.15:2 The first operand shall have scalar type. */
7346 semantic_condition(expression, "condition of conditional operator");
7348 expression_t *true_expression = expression;
7349 bool gnu_cond = false;
7350 if (GNU_MODE && token.kind == ':') {
7353 true_expression = parse_expression();
7355 rem_anchor_token(':');
7357 expression_t *false_expression =
7358 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7360 type_t *const orig_true_type = true_expression->base.type;
7361 type_t *const orig_false_type = false_expression->base.type;
7362 type_t *const true_type = skip_typeref(orig_true_type);
7363 type_t *const false_type = skip_typeref(orig_false_type);
7366 position_t const *const pos = &conditional->base.pos;
7367 type_t *result_type;
7368 if (is_type_void(true_type) || is_type_void(false_type)) {
7369 /* ISO/IEC 14882:1998(E) §5.16:2 */
7370 if (true_expression->kind == EXPR_UNARY_THROW) {
7371 result_type = false_type;
7372 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7373 result_type = true_type;
7375 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7376 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7378 result_type = type_void;
7380 } else if (is_type_arithmetic(true_type)
7381 && is_type_arithmetic(false_type)) {
7382 result_type = semantic_arithmetic(true_type, false_type);
7383 } else if (same_compound_type(true_type, false_type)) {
7384 /* just take 1 of the 2 types */
7385 result_type = true_type;
7386 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7387 type_t *pointer_type;
7389 expression_t *other_expression;
7390 if (is_type_pointer(true_type) &&
7391 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7392 pointer_type = true_type;
7393 other_type = false_type;
7394 other_expression = false_expression;
7396 pointer_type = false_type;
7397 other_type = true_type;
7398 other_expression = true_expression;
7401 if (is_null_pointer_constant(other_expression)) {
7402 result_type = pointer_type;
7403 } else if (is_type_pointer(other_type)) {
7404 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7405 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7408 if (is_type_void(to1) || is_type_void(to2)) {
7410 } else if (types_compatible(get_unqualified_type(to1),
7411 get_unqualified_type(to2))) {
7414 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7418 type_t *const type =
7419 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7420 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7421 } else if (is_type_integer(other_type)) {
7422 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7423 result_type = pointer_type;
7425 goto types_incompatible;
7429 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7430 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7432 result_type = type_error_type;
7435 conditional->true_expression
7436 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7437 conditional->false_expression
7438 = create_implicit_cast(false_expression, result_type);
7439 conditional->base.type = result_type;
7444 * Parse an extension expression.
7446 static expression_t *parse_extension(void)
7449 expression_t *expression = parse_subexpression(PREC_UNARY);
7455 * Parse a __builtin_classify_type() expression.
7457 static expression_t *parse_builtin_classify_type(void)
7459 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7460 result->base.type = type_int;
7462 eat(T___builtin_classify_type);
7464 add_anchor_token(')');
7466 expression_t *expression = parse_expression();
7467 rem_anchor_token(')');
7469 result->classify_type.type_expression = expression;
7475 * Parse a delete expression
7476 * ISO/IEC 14882:1998(E) §5.3.5
7478 static expression_t *parse_delete(void)
7480 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7481 result->base.type = type_void;
7486 result->kind = EXPR_UNARY_DELETE_ARRAY;
7490 expression_t *const value = parse_subexpression(PREC_CAST);
7491 result->unary.value = value;
7493 type_t *const type = skip_typeref(value->base.type);
7494 if (!is_type_pointer(type)) {
7495 if (is_type_valid(type)) {
7496 errorf(&value->base.pos,
7497 "operand of delete must have pointer type");
7499 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7500 position_t const *const pos = &value->base.pos;
7501 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7508 * Parse a throw expression
7509 * ISO/IEC 14882:1998(E) §15:1
7511 static expression_t *parse_throw(void)
7513 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7514 result->base.type = type_void;
7518 expression_t *value = NULL;
7519 switch (token.kind) {
7521 value = parse_assignment_expression();
7522 /* ISO/IEC 14882:1998(E) §15.1:3 */
7523 type_t *const orig_type = value->base.type;
7524 type_t *const type = skip_typeref(orig_type);
7525 if (is_type_incomplete(type)) {
7526 errorf(&value->base.pos,
7527 "cannot throw object of incomplete type '%T'", orig_type);
7528 } else if (is_type_pointer(type)) {
7529 type_t *const points_to = skip_typeref(type->pointer.points_to);
7530 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7531 errorf(&value->base.pos,
7532 "cannot throw pointer to incomplete type '%T'", orig_type);
7540 result->unary.value = value;
7545 static bool check_pointer_arithmetic(const position_t *pos,
7546 type_t *pointer_type,
7547 type_t *orig_pointer_type)
7549 type_t *points_to = pointer_type->pointer.points_to;
7550 points_to = skip_typeref(points_to);
7552 if (is_type_incomplete(points_to)) {
7553 if (!GNU_MODE || !is_type_void(points_to)) {
7555 "arithmetic with pointer to incomplete type '%T' not allowed",
7559 warningf(WARN_POINTER_ARITH, pos, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7561 } else if (is_type_function(points_to)) {
7564 "arithmetic with pointer to function type '%T' not allowed",
7568 warningf(WARN_POINTER_ARITH, pos,
7569 "pointer to a function '%T' used in arithmetic",
7576 static bool is_lvalue(const expression_t *expression)
7578 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7579 switch (expression->kind) {
7580 case EXPR_ARRAY_ACCESS:
7581 case EXPR_COMPOUND_LITERAL:
7582 case EXPR_REFERENCE:
7584 case EXPR_UNARY_DEREFERENCE:
7588 type_t *type = skip_typeref(expression->base.type);
7590 /* ISO/IEC 14882:1998(E) §3.10:3 */
7591 is_type_reference(type) ||
7592 /* Claim it is an lvalue, if the type is invalid. There was a parse
7593 * error before, which maybe prevented properly recognizing it as
7595 !is_type_valid(type);
7600 static void semantic_incdec(unary_expression_t *expression)
7602 type_t *orig_type = expression->value->base.type;
7603 type_t *type = skip_typeref(orig_type);
7604 if (is_type_pointer(type)) {
7605 if (!check_pointer_arithmetic(&expression->base.pos, type, orig_type)) {
7608 } else if (!is_type_real(type) &&
7609 (!GNU_MODE || !is_type_complex(type)) && is_type_valid(type)) {
7610 /* TODO: improve error message */
7611 errorf(&expression->base.pos,
7612 "operation needs an arithmetic or pointer type");
7613 orig_type = type = type_error_type;
7615 if (!is_lvalue(expression->value)) {
7616 /* TODO: improve error message */
7617 errorf(&expression->base.pos, "lvalue required as operand");
7619 expression->base.type = orig_type;
7622 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7624 atomic_type_kind_t akind = get_arithmetic_akind(type);
7626 if (get_akind_rank(akind) < get_akind_rank(ATOMIC_TYPE_INT)) {
7627 if (type->kind == TYPE_COMPLEX)
7628 res_type = make_complex_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
7630 res_type = type_int;
7634 expr->base.type = res_type;
7635 expr->value = create_implicit_cast(expr->value, res_type);
7638 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7640 type_t *const orig_type = expression->value->base.type;
7641 type_t *const type = skip_typeref(orig_type);
7642 if (!is_type_arithmetic(type)) {
7643 if (is_type_valid(type)) {
7644 position_t const *const pos = &expression->base.pos;
7645 errorf(pos, "operand of unary expression must have arithmetic type, but is '%T'", orig_type);
7648 } else if (is_type_integer(type)) {
7649 promote_unary_int_expr(expression, type);
7651 expression->base.type = orig_type;
7655 static void semantic_unexpr_plus(unary_expression_t *expression)
7657 semantic_unexpr_arithmetic(expression);
7658 position_t const *const pos = &expression->base.pos;
7659 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7662 static void semantic_not(unary_expression_t *expression)
7664 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7665 semantic_condition(expression->value, "operand of !");
7666 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7669 static void semantic_complement(unary_expression_t *expression)
7671 type_t *const orig_type = expression->value->base.type;
7672 type_t *const type = skip_typeref(orig_type);
7673 if (!is_type_integer(type) && (!GNU_MODE || !is_type_complex(type))) {
7674 if (is_type_valid(type)) {
7675 errorf(&expression->base.pos, "operand of ~ must be of integer type");
7680 if (is_type_integer(type)) {
7681 promote_unary_int_expr(expression, type);
7683 expression->base.type = orig_type;
7687 static void semantic_dereference(unary_expression_t *expression)
7689 type_t *const orig_type = expression->value->base.type;
7690 type_t *const type = skip_typeref(orig_type);
7691 if (!is_type_pointer(type)) {
7692 if (is_type_valid(type)) {
7693 errorf(&expression->base.pos,
7694 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7699 type_t *result_type = type->pointer.points_to;
7700 result_type = automatic_type_conversion(result_type);
7701 expression->base.type = result_type;
7705 * Record that an address is taken (expression represents an lvalue).
7707 * @param expression the expression
7708 * @param may_be_register if true, the expression might be an register
7710 static void set_address_taken(expression_t *expression, bool may_be_register)
7712 if (expression->kind != EXPR_REFERENCE)
7715 entity_t *const entity = expression->reference.entity;
7717 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7720 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7721 && !may_be_register) {
7722 position_t const *const pos = &expression->base.pos;
7723 errorf(pos, "address of register '%N' requested", entity);
7726 entity->variable.address_taken = true;
7730 * Check the semantic of the address taken expression.
7732 static void semantic_take_addr(unary_expression_t *expression)
7734 expression_t *value = expression->value;
7735 value->base.type = revert_automatic_type_conversion(value);
7737 type_t *orig_type = value->base.type;
7738 type_t *type = skip_typeref(orig_type);
7739 if (!is_type_valid(type))
7743 if (!is_lvalue(value)) {
7744 errorf(&expression->base.pos, "'&' requires an lvalue");
7746 if (is_bitfield(value)) {
7747 errorf(&expression->base.pos, "'&' not allowed on bitfield");
7750 set_address_taken(value, false);
7752 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7755 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7756 static expression_t *parse_##unexpression_type(void) \
7758 expression_t *unary_expression \
7759 = allocate_expression_zero(unexpression_type); \
7761 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7763 sfunc(&unary_expression->unary); \
7765 return unary_expression; \
7768 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7769 semantic_unexpr_arithmetic)
7770 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7771 semantic_unexpr_plus)
7772 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7774 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7775 semantic_dereference)
7776 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7778 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_COMPLEMENT,
7779 semantic_complement)
7780 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7782 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7785 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7787 static expression_t *parse_##unexpression_type(expression_t *left) \
7789 expression_t *unary_expression \
7790 = allocate_expression_zero(unexpression_type); \
7792 unary_expression->unary.value = left; \
7794 sfunc(&unary_expression->unary); \
7796 return unary_expression; \
7799 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7800 EXPR_UNARY_POSTFIX_INCREMENT,
7802 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7803 EXPR_UNARY_POSTFIX_DECREMENT,
7806 static atomic_type_kind_t semantic_arithmetic_(atomic_type_kind_t kind_left,
7807 atomic_type_kind_t kind_right)
7809 /* §6.3.1.8 Usual arithmetic conversions */
7810 if (kind_left == ATOMIC_TYPE_LONG_DOUBLE
7811 || kind_right == ATOMIC_TYPE_LONG_DOUBLE) {
7812 return ATOMIC_TYPE_LONG_DOUBLE;
7813 } else if (kind_left == ATOMIC_TYPE_DOUBLE
7814 || kind_right == ATOMIC_TYPE_DOUBLE) {
7815 return ATOMIC_TYPE_DOUBLE;
7816 } else if (kind_left == ATOMIC_TYPE_FLOAT
7817 || kind_right == ATOMIC_TYPE_FLOAT) {
7818 return ATOMIC_TYPE_FLOAT;
7821 unsigned rank_left = get_akind_rank(kind_left);
7822 unsigned rank_right = get_akind_rank(kind_right);
7823 unsigned const rank_int = get_akind_rank(ATOMIC_TYPE_INT);
7824 if (rank_left < rank_int) {
7825 kind_left = ATOMIC_TYPE_INT;
7826 rank_left = rank_int;
7828 if (rank_right < rank_int) {
7829 kind_right = ATOMIC_TYPE_INT;
7830 rank_right = rank_int;
7832 if (kind_left == kind_right)
7835 bool const signed_left = is_akind_signed(kind_left);
7836 bool const signed_right = is_akind_signed(kind_right);
7837 if (signed_left == signed_right)
7838 return rank_left >= rank_right ? kind_left : kind_right;
7842 atomic_type_kind_t s_kind;
7843 atomic_type_kind_t u_kind;
7847 u_kind = kind_right;
7848 u_rank = rank_right;
7850 s_kind = kind_right;
7851 s_rank = rank_right;
7855 if (u_rank >= s_rank)
7857 if (get_atomic_type_size(s_kind) > get_atomic_type_size(u_kind))
7861 case ATOMIC_TYPE_INT: return ATOMIC_TYPE_UINT;
7862 case ATOMIC_TYPE_LONG: return ATOMIC_TYPE_ULONG;
7863 case ATOMIC_TYPE_LONGLONG: return ATOMIC_TYPE_ULONGLONG;
7864 default: panic("invalid atomic type");
7868 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7870 atomic_type_kind_t kind_left = get_arithmetic_akind(type_left);
7871 atomic_type_kind_t kind_right = get_arithmetic_akind(type_right);
7872 atomic_type_kind_t kind_res = semantic_arithmetic_(kind_left, kind_right);
7874 if (type_left->kind == TYPE_COMPLEX || type_right->kind == TYPE_COMPLEX) {
7875 return make_complex_type(kind_res, TYPE_QUALIFIER_NONE);
7877 return make_atomic_type(kind_res, TYPE_QUALIFIER_NONE);
7881 * Check the semantic restrictions for a binary expression.
7883 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7885 expression_t *const left = expression->left;
7886 expression_t *const right = expression->right;
7887 type_t *const orig_type_left = left->base.type;
7888 type_t *const orig_type_right = right->base.type;
7889 type_t *const type_left = skip_typeref(orig_type_left);
7890 type_t *const type_right = skip_typeref(orig_type_right);
7892 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7893 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7894 position_t const *const pos = &expression->base.pos;
7895 errorf(pos, "operands of binary expression must have arithmetic types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7900 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7901 expression->left = create_implicit_cast(left, arithmetic_type);
7902 expression->right = create_implicit_cast(right, arithmetic_type);
7903 expression->base.type = arithmetic_type;
7906 static void semantic_binexpr_integer(binary_expression_t *const expression)
7908 expression_t *const left = expression->left;
7909 expression_t *const right = expression->right;
7910 type_t *const orig_type_left = left->base.type;
7911 type_t *const orig_type_right = right->base.type;
7912 type_t *const type_left = skip_typeref(orig_type_left);
7913 type_t *const type_right = skip_typeref(orig_type_right);
7915 if (!is_type_integer(type_left) || !is_type_integer(type_right)
7916 || is_type_complex(type_left) || is_type_complex(type_right)) {
7917 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7918 position_t const *const pos = &expression->base.pos;
7919 errorf(pos, "operands of binary expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7924 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7925 expression->left = create_implicit_cast(left, result_type);
7926 expression->right = create_implicit_cast(right, result_type);
7927 expression->base.type = result_type;
7930 static void warn_div_by_zero(binary_expression_t const *const expression)
7932 if (!is_type_integer(expression->base.type))
7935 expression_t const *const right = expression->right;
7936 /* The type of the right operand can be different for /= */
7937 if (is_type_integer(skip_typeref(right->base.type)) &&
7938 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7939 !fold_constant_to_bool(right)) {
7940 position_t const *const pos = &expression->base.pos;
7941 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7946 * Check the semantic restrictions for a div expression.
7948 static void semantic_div(binary_expression_t *expression)
7950 semantic_binexpr_arithmetic(expression);
7951 warn_div_by_zero(expression);
7955 * Check the semantic restrictions for a mod expression.
7957 static void semantic_mod(binary_expression_t *expression)
7959 semantic_binexpr_integer(expression);
7960 warn_div_by_zero(expression);
7963 static void warn_addsub_in_shift(const expression_t *const expr)
7965 if (expr->base.parenthesized)
7969 switch (expr->kind) {
7970 case EXPR_BINARY_ADD: op = '+'; break;
7971 case EXPR_BINARY_SUB: op = '-'; break;
7975 position_t const *const pos = &expr->base.pos;
7976 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7979 static bool semantic_shift(binary_expression_t *expression)
7981 expression_t *const left = expression->left;
7982 expression_t *const right = expression->right;
7983 type_t *const orig_type_left = left->base.type;
7984 type_t *const orig_type_right = right->base.type;
7985 type_t * type_left = skip_typeref(orig_type_left);
7986 type_t * type_right = skip_typeref(orig_type_right);
7988 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7989 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7990 position_t const *const pos = &expression->base.pos;
7991 errorf(pos, "operands of shift expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7996 type_left = promote_integer(type_left);
7998 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7999 position_t const *const pos = &right->base.pos;
8000 long const count = fold_constant_to_int(right);
8002 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8003 } else if ((unsigned long)count >=
8004 get_atomic_type_size(type_left->atomic.akind) * 8) {
8005 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8009 type_right = promote_integer(type_right);
8010 expression->right = create_implicit_cast(right, type_right);
8015 static void semantic_shift_op(binary_expression_t *expression)
8017 expression_t *const left = expression->left;
8018 expression_t *const right = expression->right;
8020 if (!semantic_shift(expression))
8023 warn_addsub_in_shift(left);
8024 warn_addsub_in_shift(right);
8026 type_t *const orig_type_left = left->base.type;
8027 type_t * type_left = skip_typeref(orig_type_left);
8029 type_left = promote_integer(type_left);
8030 expression->left = create_implicit_cast(left, type_left);
8031 expression->base.type = type_left;
8034 static void semantic_add(binary_expression_t *expression)
8036 expression_t *const left = expression->left;
8037 expression_t *const right = expression->right;
8038 type_t *const orig_type_left = left->base.type;
8039 type_t *const orig_type_right = right->base.type;
8040 type_t *const type_left = skip_typeref(orig_type_left);
8041 type_t *const type_right = skip_typeref(orig_type_right);
8044 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8045 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8046 expression->left = create_implicit_cast(left, arithmetic_type);
8047 expression->right = create_implicit_cast(right, arithmetic_type);
8048 expression->base.type = arithmetic_type;
8049 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8050 check_pointer_arithmetic(&expression->base.pos, type_left,
8052 expression->base.type = type_left;
8053 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8054 check_pointer_arithmetic(&expression->base.pos, type_right,
8056 expression->base.type = type_right;
8057 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8058 errorf(&expression->base.pos,
8059 "invalid operands to binary + ('%T', '%T')",
8060 orig_type_left, orig_type_right);
8064 static void semantic_sub(binary_expression_t *expression)
8066 expression_t *const left = expression->left;
8067 expression_t *const right = expression->right;
8068 type_t *const orig_type_left = left->base.type;
8069 type_t *const orig_type_right = right->base.type;
8070 type_t *const type_left = skip_typeref(orig_type_left);
8071 type_t *const type_right = skip_typeref(orig_type_right);
8072 position_t const *const pos = &expression->base.pos;
8075 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8076 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8077 expression->left = create_implicit_cast(left, arithmetic_type);
8078 expression->right = create_implicit_cast(right, arithmetic_type);
8079 expression->base.type = arithmetic_type;
8080 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8081 check_pointer_arithmetic(&expression->base.pos, type_left,
8083 expression->base.type = type_left;
8084 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8085 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8086 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8087 if (!types_compatible(unqual_left, unqual_right)) {
8089 "subtracting pointers to incompatible types '%T' and '%T'",
8090 orig_type_left, orig_type_right);
8091 } else if (!is_type_object(unqual_left)) {
8092 if (!is_type_void(unqual_left)) {
8093 errorf(pos, "subtracting pointers to non-object types '%T'",
8096 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8099 expression->base.type = type_ptrdiff_t;
8100 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8101 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8102 orig_type_left, orig_type_right);
8106 static void warn_string_literal_address(expression_t const* expr)
8108 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8109 expr = expr->unary.value;
8110 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8112 expr = expr->unary.value;
8115 if (expr->kind == EXPR_STRING_LITERAL) {
8116 position_t const *const pos = &expr->base.pos;
8117 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8121 static bool maybe_negative(expression_t const *const expr)
8123 switch (is_constant_expression(expr)) {
8124 case EXPR_CLASS_ERROR: return false;
8125 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8126 default: return true;
8130 static void warn_comparison(position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8132 warn_string_literal_address(expr);
8134 expression_t const* const ref = get_reference_address(expr);
8135 if (ref != NULL && is_null_pointer_constant(other)) {
8136 entity_t const *const ent = ref->reference.entity;
8137 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8140 if (!expr->base.parenthesized) {
8141 switch (expr->base.kind) {
8142 case EXPR_BINARY_LESS:
8143 case EXPR_BINARY_GREATER:
8144 case EXPR_BINARY_LESSEQUAL:
8145 case EXPR_BINARY_GREATEREQUAL:
8146 case EXPR_BINARY_NOTEQUAL:
8147 case EXPR_BINARY_EQUAL:
8148 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8157 * Check the semantics of comparison expressions.
8159 * @param expression The expression to check.
8161 static void semantic_comparison(binary_expression_t *expression)
8163 position_t const *const pos = &expression->base.pos;
8164 expression_t *const left = expression->left;
8165 expression_t *const right = expression->right;
8167 warn_comparison(pos, left, right);
8168 warn_comparison(pos, right, left);
8170 type_t *orig_type_left = left->base.type;
8171 type_t *orig_type_right = right->base.type;
8172 type_t *type_left = skip_typeref(orig_type_left);
8173 type_t *type_right = skip_typeref(orig_type_right);
8175 /* TODO non-arithmetic types */
8176 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8177 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8179 /* test for signed vs unsigned compares */
8180 if (is_type_integer(arithmetic_type)) {
8181 bool const signed_left = is_type_signed(type_left);
8182 bool const signed_right = is_type_signed(type_right);
8183 if (signed_left != signed_right) {
8184 /* FIXME long long needs better const folding magic */
8185 /* TODO check whether constant value can be represented by other type */
8186 if ((signed_left && maybe_negative(left)) ||
8187 (signed_right && maybe_negative(right))) {
8188 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8193 expression->left = create_implicit_cast(left, arithmetic_type);
8194 expression->right = create_implicit_cast(right, arithmetic_type);
8195 expression->base.type = arithmetic_type;
8196 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8197 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8198 is_type_float(arithmetic_type)) {
8199 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8201 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8202 /* TODO check compatibility */
8203 } else if (is_type_pointer(type_left)) {
8204 expression->right = create_implicit_cast(right, type_left);
8205 } else if (is_type_pointer(type_right)) {
8206 expression->left = create_implicit_cast(left, type_right);
8207 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8208 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8210 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8214 * Checks if a compound type has constant fields.
8216 static bool has_const_fields(const compound_type_t *type)
8218 compound_t *compound = type->compound;
8219 entity_t *entry = compound->members.entities;
8221 for (; entry != NULL; entry = entry->base.next) {
8222 if (!is_declaration(entry))
8225 const type_t *decl_type = skip_typeref(entry->declaration.type);
8226 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8233 static bool is_valid_assignment_lhs(expression_t const* const left)
8235 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8236 type_t *const type_left = skip_typeref(orig_type_left);
8238 if (!is_lvalue(left)) {
8239 errorf(&left->base.pos,
8240 "left hand side '%E' of assignment is not an lvalue", left);
8244 if (left->kind == EXPR_REFERENCE
8245 && left->reference.entity->kind == ENTITY_FUNCTION) {
8246 errorf(&left->base.pos, "cannot assign to function '%E'", left);
8250 if (is_type_array(type_left)) {
8251 errorf(&left->base.pos, "cannot assign to array '%E'", left);
8254 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8255 errorf(&left->base.pos,
8256 "assignment to read-only location '%E' (type '%T')", left,
8260 if (is_type_incomplete(type_left)) {
8261 errorf(&left->base.pos, "left-hand side '%E' of assignment has incomplete type '%T'",
8262 left, orig_type_left);
8265 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8266 errorf(&left->base.pos, "cannot assign to '%E' because compound type '%T' has read-only fields",
8267 left, orig_type_left);
8274 static void semantic_arithmetic_assign(binary_expression_t *expression)
8276 expression_t *left = expression->left;
8277 expression_t *right = expression->right;
8278 type_t *orig_type_left = left->base.type;
8279 type_t *orig_type_right = right->base.type;
8281 if (!is_valid_assignment_lhs(left))
8284 type_t *type_left = skip_typeref(orig_type_left);
8285 type_t *type_right = skip_typeref(orig_type_right);
8287 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8288 /* TODO: improve error message */
8289 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8290 errorf(&expression->base.pos, "operation needs arithmetic types");
8295 /* combined instructions are tricky. We can't create an implicit cast on
8296 * the left side, because we need the uncasted form for the store.
8297 * The ast2firm pass has to know that left_type must be right_type
8298 * for the arithmetic operation and create a cast by itself */
8299 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8300 expression->right = create_implicit_cast(right, arithmetic_type);
8301 expression->base.type = type_left;
8304 static void semantic_divmod_assign(binary_expression_t *expression)
8306 semantic_arithmetic_assign(expression);
8307 warn_div_by_zero(expression);
8310 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8312 expression_t *const left = expression->left;
8313 expression_t *const right = expression->right;
8314 type_t *const orig_type_left = left->base.type;
8315 type_t *const orig_type_right = right->base.type;
8316 type_t *const type_left = skip_typeref(orig_type_left);
8317 type_t *const type_right = skip_typeref(orig_type_right);
8319 if (!is_valid_assignment_lhs(left))
8322 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8323 /* combined instructions are tricky. We can't create an implicit cast on
8324 * the left side, because we need the uncasted form for the store.
8325 * The ast2firm pass has to know that left_type must be right_type
8326 * for the arithmetic operation and create a cast by itself */
8327 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8328 expression->right = create_implicit_cast(right, arithmetic_type);
8329 expression->base.type = type_left;
8330 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8331 check_pointer_arithmetic(&expression->base.pos, type_left,
8333 expression->base.type = type_left;
8334 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8335 errorf(&expression->base.pos,
8336 "incompatible types '%T' and '%T' in assignment",
8337 orig_type_left, orig_type_right);
8341 static void semantic_integer_assign(binary_expression_t *expression)
8343 expression_t *left = expression->left;
8344 expression_t *right = expression->right;
8345 type_t *orig_type_left = left->base.type;
8346 type_t *orig_type_right = right->base.type;
8348 if (!is_valid_assignment_lhs(left))
8351 type_t *type_left = skip_typeref(orig_type_left);
8352 type_t *type_right = skip_typeref(orig_type_right);
8354 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8355 /* TODO: improve error message */
8356 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8357 errorf(&expression->base.pos, "operation needs integer types");
8362 /* combined instructions are tricky. We can't create an implicit cast on
8363 * the left side, because we need the uncasted form for the store.
8364 * The ast2firm pass has to know that left_type must be right_type
8365 * for the arithmetic operation and create a cast by itself */
8366 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8367 expression->right = create_implicit_cast(right, arithmetic_type);
8368 expression->base.type = type_left;
8371 static void semantic_shift_assign(binary_expression_t *expression)
8373 expression_t *left = expression->left;
8375 if (!is_valid_assignment_lhs(left))
8378 if (!semantic_shift(expression))
8381 expression->base.type = skip_typeref(left->base.type);
8384 static void warn_logical_and_within_or(const expression_t *const expr)
8386 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8388 if (expr->base.parenthesized)
8390 position_t const *const pos = &expr->base.pos;
8391 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8395 * Check the semantic restrictions of a logical expression.
8397 static void semantic_logical_op(binary_expression_t *expression)
8399 /* §6.5.13:2 Each of the operands shall have scalar type.
8400 * §6.5.14:2 Each of the operands shall have scalar type. */
8401 semantic_condition(expression->left, "left operand of logical operator");
8402 semantic_condition(expression->right, "right operand of logical operator");
8403 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8404 warn_logical_and_within_or(expression->left);
8405 warn_logical_and_within_or(expression->right);
8407 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8411 * Check the semantic restrictions of a binary assign expression.
8413 static void semantic_binexpr_assign(binary_expression_t *expression)
8415 expression_t *left = expression->left;
8416 type_t *orig_type_left = left->base.type;
8418 if (!is_valid_assignment_lhs(left))
8421 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8422 report_assign_error(error, orig_type_left, expression->right,
8423 "assignment", &left->base.pos);
8424 expression->right = create_implicit_cast(expression->right, orig_type_left);
8425 expression->base.type = orig_type_left;
8429 * Determine if the outermost operation (or parts thereof) of the given
8430 * expression has no effect in order to generate a warning about this fact.
8431 * Therefore in some cases this only examines some of the operands of the
8432 * expression (see comments in the function and examples below).
8434 * f() + 23; // warning, because + has no effect
8435 * x || f(); // no warning, because x controls execution of f()
8436 * x ? y : f(); // warning, because y has no effect
8437 * (void)x; // no warning to be able to suppress the warning
8438 * This function can NOT be used for an "expression has definitely no effect"-
8440 static bool expression_has_effect(const expression_t *const expr)
8442 switch (expr->kind) {
8443 case EXPR_ERROR: return true; /* do NOT warn */
8444 case EXPR_REFERENCE: return false;
8445 case EXPR_ENUM_CONSTANT: return false;
8446 case EXPR_LABEL_ADDRESS: return false;
8448 /* suppress the warning for microsoft __noop operations */
8449 case EXPR_LITERAL_MS_NOOP: return true;
8450 case EXPR_LITERAL_BOOLEAN:
8451 case EXPR_LITERAL_CHARACTER:
8452 case EXPR_LITERAL_INTEGER:
8453 case EXPR_LITERAL_FLOATINGPOINT:
8454 case EXPR_STRING_LITERAL: return false;
8457 const call_expression_t *const call = &expr->call;
8458 if (call->function->kind != EXPR_REFERENCE)
8461 switch (call->function->reference.entity->function.btk) {
8462 /* FIXME: which builtins have no effect? */
8463 default: return true;
8467 /* Generate the warning if either the left or right hand side of a
8468 * conditional expression has no effect */
8469 case EXPR_CONDITIONAL: {
8470 conditional_expression_t const *const cond = &expr->conditional;
8471 expression_t const *const t = cond->true_expression;
8473 (t == NULL || expression_has_effect(t)) &&
8474 expression_has_effect(cond->false_expression);
8477 case EXPR_SELECT: return false;
8478 case EXPR_ARRAY_ACCESS: return false;
8479 case EXPR_SIZEOF: return false;
8480 case EXPR_CLASSIFY_TYPE: return false;
8481 case EXPR_ALIGNOF: return false;
8483 case EXPR_FUNCNAME: return false;
8484 case EXPR_BUILTIN_CONSTANT_P: return false;
8485 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8486 case EXPR_OFFSETOF: return false;
8487 case EXPR_VA_START: return true;
8488 case EXPR_VA_ARG: return true;
8489 case EXPR_VA_COPY: return true;
8490 case EXPR_STATEMENT: return true; // TODO
8491 case EXPR_COMPOUND_LITERAL: return false;
8493 case EXPR_UNARY_NEGATE: return false;
8494 case EXPR_UNARY_PLUS: return false;
8495 case EXPR_UNARY_COMPLEMENT: return false;
8496 case EXPR_UNARY_NOT: return false;
8497 case EXPR_UNARY_DEREFERENCE: return false;
8498 case EXPR_UNARY_TAKE_ADDRESS: return false;
8499 case EXPR_UNARY_REAL: return false;
8500 case EXPR_UNARY_IMAG: return false;
8501 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8502 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8503 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8504 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8506 /* Treat void casts as if they have an effect in order to being able to
8507 * suppress the warning */
8508 case EXPR_UNARY_CAST: {
8509 type_t *const type = skip_typeref(expr->base.type);
8510 return is_type_void(type);
8513 case EXPR_UNARY_ASSUME: return true;
8514 case EXPR_UNARY_DELETE: return true;
8515 case EXPR_UNARY_DELETE_ARRAY: return true;
8516 case EXPR_UNARY_THROW: return true;
8518 case EXPR_BINARY_ADD: return false;
8519 case EXPR_BINARY_SUB: return false;
8520 case EXPR_BINARY_MUL: return false;
8521 case EXPR_BINARY_DIV: return false;
8522 case EXPR_BINARY_MOD: return false;
8523 case EXPR_BINARY_EQUAL: return false;
8524 case EXPR_BINARY_NOTEQUAL: return false;
8525 case EXPR_BINARY_LESS: return false;
8526 case EXPR_BINARY_LESSEQUAL: return false;
8527 case EXPR_BINARY_GREATER: return false;
8528 case EXPR_BINARY_GREATEREQUAL: return false;
8529 case EXPR_BINARY_BITWISE_AND: return false;
8530 case EXPR_BINARY_BITWISE_OR: return false;
8531 case EXPR_BINARY_BITWISE_XOR: return false;
8532 case EXPR_BINARY_SHIFTLEFT: return false;
8533 case EXPR_BINARY_SHIFTRIGHT: return false;
8534 case EXPR_BINARY_ASSIGN: return true;
8535 case EXPR_BINARY_MUL_ASSIGN: return true;
8536 case EXPR_BINARY_DIV_ASSIGN: return true;
8537 case EXPR_BINARY_MOD_ASSIGN: return true;
8538 case EXPR_BINARY_ADD_ASSIGN: return true;
8539 case EXPR_BINARY_SUB_ASSIGN: return true;
8540 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8541 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8542 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8543 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8544 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8546 /* Only examine the right hand side of && and ||, because the left hand
8547 * side already has the effect of controlling the execution of the right
8549 case EXPR_BINARY_LOGICAL_AND:
8550 case EXPR_BINARY_LOGICAL_OR:
8551 /* Only examine the right hand side of a comma expression, because the left
8552 * hand side has a separate warning */
8553 case EXPR_BINARY_COMMA:
8554 return expression_has_effect(expr->binary.right);
8556 case EXPR_BINARY_ISGREATER: return false;
8557 case EXPR_BINARY_ISGREATEREQUAL: return false;
8558 case EXPR_BINARY_ISLESS: return false;
8559 case EXPR_BINARY_ISLESSEQUAL: return false;
8560 case EXPR_BINARY_ISLESSGREATER: return false;
8561 case EXPR_BINARY_ISUNORDERED: return false;
8564 internal_errorf(HERE, "unexpected expression");
8567 static void semantic_comma(binary_expression_t *expression)
8569 const expression_t *const left = expression->left;
8570 if (!expression_has_effect(left)) {
8571 position_t const *const pos = &left->base.pos;
8572 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8574 expression->base.type = expression->right->base.type;
8578 * @param prec_r precedence of the right operand
8580 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8581 static expression_t *parse_##binexpression_type(expression_t *left) \
8583 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8584 binexpr->binary.left = left; \
8587 expression_t *right = parse_subexpression(prec_r); \
8589 binexpr->binary.right = right; \
8590 sfunc(&binexpr->binary); \
8595 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8596 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_div)
8597 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_mod)
8598 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8599 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8600 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8601 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8602 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8603 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8604 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8605 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8606 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8607 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8608 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8609 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8610 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8611 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8612 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8613 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8614 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8615 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8616 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8617 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8618 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8619 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8620 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8621 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8622 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8623 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8624 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8627 static expression_t *parse_subexpression(precedence_t precedence)
8629 expression_parser_function_t *parser
8630 = &expression_parsers[token.kind];
8633 if (parser->parser != NULL) {
8634 left = parser->parser();
8636 left = parse_primary_expression();
8638 assert(left != NULL);
8641 parser = &expression_parsers[token.kind];
8642 if (parser->infix_parser == NULL)
8644 if (parser->infix_precedence < precedence)
8647 left = parser->infix_parser(left);
8649 assert(left != NULL);
8656 * Parse an expression.
8658 static expression_t *parse_expression(void)
8660 return parse_subexpression(PREC_EXPRESSION);
8664 * Register a parser for a prefix-like operator.
8666 * @param parser the parser function
8667 * @param token_kind the token type of the prefix token
8669 static void register_expression_parser(parse_expression_function parser,
8672 expression_parser_function_t *entry = &expression_parsers[token_kind];
8674 assert(!entry->parser);
8675 entry->parser = parser;
8679 * Register a parser for an infix operator with given precedence.
8681 * @param parser the parser function
8682 * @param token_kind the token type of the infix operator
8683 * @param precedence the precedence of the operator
8685 static void register_infix_parser(parse_expression_infix_function parser,
8686 int token_kind, precedence_t precedence)
8688 expression_parser_function_t *entry = &expression_parsers[token_kind];
8690 assert(!entry->infix_parser);
8691 entry->infix_parser = parser;
8692 entry->infix_precedence = precedence;
8696 * Initialize the expression parsers.
8698 static void init_expression_parsers(void)
8700 memset(&expression_parsers, 0, sizeof(expression_parsers));
8702 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8703 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8704 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8705 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8706 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8707 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8708 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8709 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8710 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8711 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8712 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8713 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8714 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8715 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8716 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8717 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8718 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8719 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8720 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8721 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8722 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8723 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8724 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8725 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8726 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8727 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8728 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8729 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8730 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8731 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8732 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8733 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8734 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8735 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8736 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8737 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8738 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8740 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8741 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8742 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8743 register_expression_parser(parse_EXPR_UNARY_COMPLEMENT, '~');
8744 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8745 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8746 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8747 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8748 register_expression_parser(parse_sizeof, T_sizeof);
8749 register_expression_parser(parse_alignof, T__Alignof);
8750 register_expression_parser(parse_extension, T___extension__);
8751 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8752 register_expression_parser(parse_delete, T_delete);
8753 register_expression_parser(parse_throw, T_throw);
8757 * Parse a asm statement arguments specification.
8759 static void parse_asm_arguments(asm_argument_t **anchor, bool const is_out)
8761 if (token.kind == T_STRING_LITERAL || token.kind == '[') {
8762 add_anchor_token(',');
8764 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8766 add_anchor_token(')');
8767 add_anchor_token('(');
8768 add_anchor_token(T_STRING_LITERAL);
8771 add_anchor_token(']');
8772 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8773 rem_anchor_token(']');
8777 rem_anchor_token(T_STRING_LITERAL);
8778 argument->constraints = parse_string_literals("asm argument");
8779 rem_anchor_token('(');
8781 expression_t *expression = parse_expression();
8783 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8784 * change size or type representation (e.g. int -> long is ok, but
8785 * int -> float is not) */
8786 if (expression->kind == EXPR_UNARY_CAST) {
8787 type_t *const type = expression->base.type;
8788 type_kind_t const kind = type->kind;
8789 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8792 if (kind == TYPE_ATOMIC) {
8793 atomic_type_kind_t const akind = type->atomic.akind;
8794 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8795 size = get_atomic_type_size(akind);
8797 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8798 size = get_type_size(type_void_ptr);
8802 expression_t *const value = expression->unary.value;
8803 type_t *const value_type = value->base.type;
8804 type_kind_t const value_kind = value_type->kind;
8806 unsigned value_flags;
8807 unsigned value_size;
8808 if (value_kind == TYPE_ATOMIC) {
8809 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8810 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8811 value_size = get_atomic_type_size(value_akind);
8812 } else if (value_kind == TYPE_POINTER) {
8813 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8814 value_size = get_type_size(type_void_ptr);
8819 if (value_flags != flags || value_size != size)
8823 } while (expression->kind == EXPR_UNARY_CAST);
8827 if (!is_lvalue(expression))
8828 errorf(&expression->base.pos,
8829 "asm output argument is not an lvalue");
8831 if (argument->constraints.begin[0] == '=')
8832 determine_lhs_ent(expression, NULL);
8834 mark_vars_read(expression, NULL);
8836 mark_vars_read(expression, NULL);
8838 argument->expression = expression;
8839 rem_anchor_token(')');
8842 set_address_taken(expression, true);
8845 anchor = &argument->next;
8846 } while (accept(','));
8847 rem_anchor_token(',');
8852 * Parse a asm statement clobber specification.
8854 static void parse_asm_clobbers(asm_clobber_t **anchor)
8856 if (token.kind == T_STRING_LITERAL) {
8857 add_anchor_token(',');
8859 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8860 clobber->clobber = parse_string_literals(NULL);
8863 anchor = &clobber->next;
8864 } while (accept(','));
8865 rem_anchor_token(',');
8869 static void parse_asm_labels(asm_label_t **anchor)
8871 if (token.kind == T_IDENTIFIER) {
8872 add_anchor_token(',');
8874 label_t *const label = get_label("while parsing 'asm goto' labels");
8876 asm_label_t *const asm_label = allocate_ast_zero(sizeof(*asm_label));
8877 asm_label->label = label;
8879 *anchor = asm_label;
8880 anchor = &asm_label->next;
8882 } while (accept(','));
8883 rem_anchor_token(',');
8888 * Parse an asm statement.
8890 static statement_t *parse_asm_statement(void)
8892 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8893 asm_statement_t *asm_statement = &statement->asms;
8896 add_anchor_token(')');
8897 add_anchor_token(':');
8898 add_anchor_token(T_STRING_LITERAL);
8900 if (accept(T_volatile))
8901 asm_statement->is_volatile = true;
8903 bool const asm_goto = accept(T_goto);
8906 rem_anchor_token(T_STRING_LITERAL);
8907 asm_statement->asm_text = parse_string_literals("asm statement");
8909 if (accept(':')) parse_asm_arguments(&asm_statement->outputs, true);
8910 if (accept(':')) parse_asm_arguments(&asm_statement->inputs, false);
8911 if (accept(':')) parse_asm_clobbers( &asm_statement->clobbers);
8913 rem_anchor_token(':');
8916 warningf(WARN_OTHER, &statement->base.pos, "assembler statement with labels should be 'asm goto'");
8917 parse_asm_labels(&asm_statement->labels);
8918 if (asm_statement->labels)
8919 errorf(&statement->base.pos, "'asm goto' not supported");
8922 warningf(WARN_OTHER, &statement->base.pos, "'asm goto' without labels");
8925 rem_anchor_token(')');
8929 if (asm_statement->outputs == NULL) {
8930 /* GCC: An 'asm' instruction without any output operands will be treated
8931 * identically to a volatile 'asm' instruction. */
8932 asm_statement->is_volatile = true;
8938 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8940 statement_t *inner_stmt;
8941 switch (token.kind) {
8943 errorf(&label->base.pos, "%s at end of compound statement", label_kind);
8944 inner_stmt = create_error_statement();
8948 if (label->kind == STATEMENT_LABEL) {
8949 /* Eat an empty statement here, to avoid the warning about an empty
8950 * statement after a label. label:; is commonly used to have a label
8951 * before a closing brace. */
8952 inner_stmt = create_empty_statement();
8959 inner_stmt = parse_statement();
8960 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8961 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8962 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8963 errorf(&inner_stmt->base.pos, "declaration after %s", label_kind);
8971 * Parse a case statement.
8973 static statement_t *parse_case_statement(void)
8975 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8976 position_t *const pos = &statement->base.pos;
8979 add_anchor_token(':');
8981 expression_t *expression = parse_expression();
8982 type_t *expression_type = expression->base.type;
8983 type_t *skipped = skip_typeref(expression_type);
8984 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8985 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8986 expression, expression_type);
8989 type_t *type = expression_type;
8990 if (current_switch != NULL) {
8991 type_t *switch_type = current_switch->expression->base.type;
8992 if (is_type_valid(skip_typeref(switch_type))) {
8993 expression = create_implicit_cast(expression, switch_type);
8997 statement->case_label.expression = expression;
8998 expression_classification_t const expr_class = is_constant_expression(expression);
8999 if (expr_class != EXPR_CLASS_CONSTANT) {
9000 if (expr_class != EXPR_CLASS_ERROR) {
9001 errorf(pos, "case label does not reduce to an integer constant");
9003 statement->case_label.is_bad = true;
9005 ir_tarval *val = fold_constant_to_tarval(expression);
9006 statement->case_label.first_case = val;
9007 statement->case_label.last_case = val;
9011 if (accept(T_DOTDOTDOT)) {
9012 expression_t *end_range = parse_expression();
9013 expression_type = expression->base.type;
9014 skipped = skip_typeref(expression_type);
9015 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9016 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9017 expression, expression_type);
9020 end_range = create_implicit_cast(end_range, type);
9021 statement->case_label.end_range = end_range;
9022 expression_classification_t const end_class = is_constant_expression(end_range);
9023 if (end_class != EXPR_CLASS_CONSTANT) {
9024 if (end_class != EXPR_CLASS_ERROR) {
9025 errorf(pos, "case range does not reduce to an integer constant");
9027 statement->case_label.is_bad = true;
9029 ir_tarval *val = fold_constant_to_tarval(end_range);
9030 statement->case_label.last_case = val;
9032 if (tarval_cmp(val, statement->case_label.first_case)
9033 == ir_relation_less) {
9034 statement->case_label.is_empty_range = true;
9035 warningf(WARN_OTHER, pos, "empty range specified");
9041 PUSH_PARENT(statement);
9043 rem_anchor_token(':');
9046 if (current_switch != NULL) {
9047 if (! statement->case_label.is_bad) {
9048 /* Check for duplicate case values */
9049 case_label_statement_t *c = &statement->case_label;
9050 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9051 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9054 if (c->last_case < l->first_case || c->first_case > l->last_case)
9057 errorf(pos, "duplicate case value (previously used %P)",
9062 /* link all cases into the switch statement */
9063 if (current_switch->last_case == NULL) {
9064 current_switch->first_case = &statement->case_label;
9066 current_switch->last_case->next = &statement->case_label;
9068 current_switch->last_case = &statement->case_label;
9070 errorf(pos, "case label not within a switch statement");
9073 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9080 * Parse a default statement.
9082 static statement_t *parse_default_statement(void)
9084 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9088 PUSH_PARENT(statement);
9092 if (current_switch != NULL) {
9093 const case_label_statement_t *def_label = current_switch->default_label;
9094 if (def_label != NULL) {
9095 errorf(&statement->base.pos, "multiple default labels in one switch (previous declared %P)", &def_label->base.pos);
9097 current_switch->default_label = &statement->case_label;
9099 /* link all cases into the switch statement */
9100 if (current_switch->last_case == NULL) {
9101 current_switch->first_case = &statement->case_label;
9103 current_switch->last_case->next = &statement->case_label;
9105 current_switch->last_case = &statement->case_label;
9108 errorf(&statement->base.pos,
9109 "'default' label not within a switch statement");
9112 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9119 * Parse a label statement.
9121 static statement_t *parse_label_statement(void)
9123 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9124 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9125 statement->label.label = label;
9127 PUSH_PARENT(statement);
9129 /* if statement is already set then the label is defined twice,
9130 * otherwise it was just mentioned in a goto/local label declaration so far
9132 position_t const* const pos = &statement->base.pos;
9133 if (label->statement != NULL) {
9134 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.pos);
9136 label->base.pos = *pos;
9137 label->statement = statement;
9138 label->n_users += 1;
9143 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9144 parse_attributes(NULL); // TODO process attributes
9147 statement->label.statement = parse_label_inner_statement(statement, "label");
9149 /* remember the labels in a list for later checking */
9150 *label_anchor = &statement->label;
9151 label_anchor = &statement->label.next;
9157 static statement_t *parse_inner_statement(void)
9159 statement_t *const stmt = parse_statement();
9160 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9161 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9162 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9163 errorf(&stmt->base.pos, "declaration as inner statement, use {}");
9169 * Parse an expression in parentheses and mark its variables as read.
9171 static expression_t *parse_condition(void)
9173 add_anchor_token(')');
9175 expression_t *const expr = parse_expression();
9176 mark_vars_read(expr, NULL);
9177 rem_anchor_token(')');
9183 * Parse an if statement.
9185 static statement_t *parse_if(void)
9187 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9191 PUSH_PARENT(statement);
9192 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9194 add_anchor_token(T_else);
9196 expression_t *const expr = parse_condition();
9197 statement->ifs.condition = expr;
9198 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9200 semantic_condition(expr, "condition of 'if'-statment");
9202 statement_t *const true_stmt = parse_inner_statement();
9203 statement->ifs.true_statement = true_stmt;
9204 rem_anchor_token(T_else);
9206 if (true_stmt->kind == STATEMENT_EMPTY) {
9207 warningf(WARN_EMPTY_BODY, HERE,
9208 "suggest braces around empty body in an ‘if’ statement");
9211 if (accept(T_else)) {
9212 statement->ifs.false_statement = parse_inner_statement();
9214 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9215 warningf(WARN_EMPTY_BODY, HERE,
9216 "suggest braces around empty body in an ‘if’ statement");
9218 } else if (true_stmt->kind == STATEMENT_IF &&
9219 true_stmt->ifs.false_statement != NULL) {
9220 position_t const *const pos = &true_stmt->base.pos;
9221 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9230 * Check that all enums are handled in a switch.
9232 * @param statement the switch statement to check
9234 static void check_enum_cases(const switch_statement_t *statement)
9236 if (!is_warn_on(WARN_SWITCH_ENUM))
9238 type_t *type = skip_typeref(statement->expression->base.type);
9239 if (! is_type_enum(type))
9241 enum_type_t *enumt = &type->enumt;
9243 /* if we have a default, no warnings */
9244 if (statement->default_label != NULL)
9247 determine_enum_values(enumt);
9249 /* FIXME: calculation of value should be done while parsing */
9250 /* TODO: quadratic algorithm here. Change to an n log n one */
9251 const entity_t *entry = enumt->enume->base.next;
9252 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9253 entry = entry->base.next) {
9254 ir_tarval *value = entry->enum_value.tv;
9256 for (const case_label_statement_t *l = statement->first_case; l != NULL;
9258 if (l->expression == NULL)
9260 if (l->first_case == l->last_case && l->first_case != value)
9262 if ((tarval_cmp(l->first_case, value) & ir_relation_less_equal)
9263 && (tarval_cmp(value, l->last_case) & ir_relation_less_equal)) {
9269 position_t const *const pos = &statement->base.pos;
9270 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9276 * Parse a switch statement.
9278 static statement_t *parse_switch(void)
9280 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9284 PUSH_PARENT(statement);
9285 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9287 expression_t *const expr = parse_condition();
9288 type_t * type = skip_typeref(expr->base.type);
9289 if (is_type_integer(type)) {
9290 type = promote_integer(type);
9291 if (get_akind_rank(get_arithmetic_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9292 warningf(WARN_TRADITIONAL, &expr->base.pos,
9293 "'%T' switch expression not converted to '%T' in ISO C",
9296 } else if (is_type_valid(type)) {
9297 errorf(&expr->base.pos, "switch quantity is not an integer, but '%T'",
9299 type = type_error_type;
9301 statement->switchs.expression = create_implicit_cast(expr, type);
9303 switch_statement_t *rem = current_switch;
9304 current_switch = &statement->switchs;
9305 statement->switchs.body = parse_inner_statement();
9306 current_switch = rem;
9308 if (statement->switchs.default_label == NULL) {
9309 warningf(WARN_SWITCH_DEFAULT, &statement->base.pos, "switch has no default case");
9311 check_enum_cases(&statement->switchs);
9318 static statement_t *parse_loop_body(statement_t *const loop)
9320 statement_t *const rem = current_loop;
9321 current_loop = loop;
9323 statement_t *const body = parse_inner_statement();
9330 * Parse a while statement.
9332 static statement_t *parse_while(void)
9334 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9338 PUSH_PARENT(statement);
9339 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9341 expression_t *const cond = parse_condition();
9342 statement->fors.condition = cond;
9343 /* §6.8.5:2 The controlling expression of an iteration statement shall
9344 * have scalar type. */
9345 semantic_condition(cond, "condition of 'while'-statement");
9347 statement->fors.body = parse_loop_body(statement);
9355 * Parse a do statement.
9357 static statement_t *parse_do(void)
9359 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9363 PUSH_PARENT(statement);
9364 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9366 add_anchor_token(T_while);
9367 statement->do_while.body = parse_loop_body(statement);
9368 rem_anchor_token(T_while);
9371 expression_t *const cond = parse_condition();
9372 statement->do_while.condition = cond;
9373 /* §6.8.5:2 The controlling expression of an iteration statement shall
9374 * have scalar type. */
9375 semantic_condition(cond, "condition of 'do-while'-statement");
9384 * Parse a for statement.
9386 static statement_t *parse_for(void)
9388 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9392 PUSH_PARENT(statement);
9393 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9395 add_anchor_token(')');
9401 } else if (is_declaration_specifier(&token)) {
9402 parse_declaration(record_entity, DECL_FLAGS_NONE);
9404 add_anchor_token(';');
9405 expression_t *const init = parse_expression();
9406 statement->fors.initialisation = init;
9407 mark_vars_read(init, ENT_ANY);
9408 if (!expression_has_effect(init)) {
9409 warningf(WARN_UNUSED_VALUE, &init->base.pos, "initialisation of 'for'-statement has no effect");
9411 rem_anchor_token(';');
9417 if (token.kind != ';') {
9418 add_anchor_token(';');
9419 expression_t *const cond = parse_expression();
9420 statement->fors.condition = cond;
9421 /* §6.8.5:2 The controlling expression of an iteration statement
9422 * shall have scalar type. */
9423 semantic_condition(cond, "condition of 'for'-statement");
9424 mark_vars_read(cond, NULL);
9425 rem_anchor_token(';');
9428 if (token.kind != ')') {
9429 expression_t *const step = parse_expression();
9430 statement->fors.step = step;
9431 mark_vars_read(step, ENT_ANY);
9432 if (!expression_has_effect(step)) {
9433 warningf(WARN_UNUSED_VALUE, &step->base.pos, "step of 'for'-statement has no effect");
9436 rem_anchor_token(')');
9438 statement->fors.body = parse_loop_body(statement);
9446 * Parse a goto statement.
9448 static statement_t *parse_goto(void)
9450 statement_t *statement;
9451 if (GNU_MODE && look_ahead(1)->kind == '*') {
9452 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9456 expression_t *expression = parse_expression();
9457 mark_vars_read(expression, NULL);
9459 /* Argh: although documentation says the expression must be of type void*,
9460 * gcc accepts anything that can be casted into void* without error */
9461 type_t *type = expression->base.type;
9463 if (type != type_error_type) {
9464 if (!is_type_pointer(type) && !is_type_integer(type)) {
9465 errorf(&expression->base.pos, "cannot convert to a pointer type");
9466 } else if (type != type_void_ptr) {
9467 warningf(WARN_OTHER, &expression->base.pos, "type of computed goto expression should be 'void*' not '%T'", type);
9469 expression = create_implicit_cast(expression, type_void_ptr);
9472 statement->computed_goto.expression = expression;
9474 statement = allocate_statement_zero(STATEMENT_GOTO);
9477 label_t *const label = get_label("while parsing goto");
9479 label->n_users += 1;
9481 statement->gotos.label = label;
9483 /* remember the goto's in a list for later checking */
9484 *goto_anchor = &statement->gotos;
9485 goto_anchor = &statement->gotos.next;
9487 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_position)->label;
9496 * Parse a continue statement.
9498 static statement_t *parse_continue(void)
9500 if (current_loop == NULL) {
9501 errorf(HERE, "continue statement not within loop");
9504 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9512 * Parse a break statement.
9514 static statement_t *parse_break(void)
9516 if (current_switch == NULL && current_loop == NULL) {
9517 errorf(HERE, "break statement not within loop or switch");
9520 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9528 * Parse a __leave statement.
9530 static statement_t *parse_leave_statement(void)
9532 if (current_try == NULL) {
9533 errorf(HERE, "__leave statement not within __try");
9536 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9544 * Check if a given entity represents a local variable.
9546 static bool is_local_variable(const entity_t *entity)
9548 if (entity->kind != ENTITY_VARIABLE)
9551 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9552 case STORAGE_CLASS_AUTO:
9553 case STORAGE_CLASS_REGISTER: {
9554 const type_t *type = skip_typeref(entity->declaration.type);
9555 if (is_type_function(type)) {
9567 * Check if a given expression represents a local variable.
9569 static bool expression_is_local_variable(const expression_t *expression)
9571 if (expression->base.kind != EXPR_REFERENCE) {
9574 const entity_t *entity = expression->reference.entity;
9575 return is_local_variable(entity);
9578 static void err_or_warn(position_t const *const pos, char const *const msg)
9580 if (c_mode & _CXX || strict_mode) {
9583 warningf(WARN_OTHER, pos, msg);
9588 * Parse a return statement.
9590 static statement_t *parse_return(void)
9592 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9595 expression_t *return_value = NULL;
9596 if (token.kind != ';') {
9597 return_value = parse_expression();
9598 mark_vars_read(return_value, NULL);
9601 const type_t *const func_type = skip_typeref(current_function->base.type);
9602 assert(is_type_function(func_type));
9603 type_t *const return_type = skip_typeref(func_type->function.return_type);
9605 position_t const *const pos = &statement->base.pos;
9606 if (return_value != NULL) {
9607 type_t *return_value_type = skip_typeref(return_value->base.type);
9609 if (is_type_void(return_type)) {
9610 if (!is_type_void(return_value_type)) {
9611 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9612 /* Only warn in C mode, because GCC does the same */
9613 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9614 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9615 /* Only warn in C mode, because GCC does the same */
9616 err_or_warn(pos, "'return' with expression in function returning 'void'");
9619 assign_error_t error = semantic_assign(return_type, return_value);
9620 report_assign_error(error, return_type, return_value, "'return'",
9623 return_value = create_implicit_cast(return_value, return_type);
9624 /* check for returning address of a local var */
9625 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9626 const expression_t *expression = return_value->unary.value;
9627 if (expression_is_local_variable(expression)) {
9628 warningf(WARN_OTHER, pos, "function returns address of local variable");
9631 } else if (!is_type_void(return_type)) {
9632 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9633 err_or_warn(pos, "'return' without value, in function returning non-void");
9635 statement->returns.value = return_value;
9642 * Parse a declaration statement.
9644 static statement_t *parse_declaration_statement(void)
9646 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9648 entity_t *before = current_scope->last_entity;
9650 parse_external_declaration();
9652 parse_declaration(record_entity, DECL_FLAGS_NONE);
9655 declaration_statement_t *const decl = &statement->declaration;
9656 entity_t *const begin =
9657 before != NULL ? before->base.next : current_scope->entities;
9658 decl->declarations_begin = begin;
9659 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9665 * Parse an expression statement, i.e. expr ';'.
9667 static statement_t *parse_expression_statement(void)
9669 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9671 expression_t *const expr = parse_expression();
9672 statement->expression.expression = expr;
9673 mark_vars_read(expr, ENT_ANY);
9680 * Parse a microsoft __try { } __finally { } or
9681 * __try{ } __except() { }
9683 static statement_t *parse_ms_try_statment(void)
9685 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9688 PUSH_PARENT(statement);
9690 ms_try_statement_t *rem = current_try;
9691 current_try = &statement->ms_try;
9692 statement->ms_try.try_statement = parse_compound_statement(false);
9697 if (accept(T___except)) {
9698 expression_t *const expr = parse_condition();
9699 type_t * type = skip_typeref(expr->base.type);
9700 if (is_type_integer(type)) {
9701 type = promote_integer(type);
9702 } else if (is_type_valid(type)) {
9703 errorf(&expr->base.pos,
9704 "__expect expression is not an integer, but '%T'", type);
9705 type = type_error_type;
9707 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9708 } else if (!accept(T__finally)) {
9709 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9711 statement->ms_try.final_statement = parse_compound_statement(false);
9715 static statement_t *parse_empty_statement(void)
9717 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9718 statement_t *const statement = create_empty_statement();
9723 static statement_t *parse_local_label_declaration(void)
9725 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9729 entity_t *begin = NULL;
9730 entity_t *end = NULL;
9731 entity_t **anchor = &begin;
9732 add_anchor_token(';');
9733 add_anchor_token(',');
9736 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9738 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9739 if (entity != NULL && entity->base.parent_scope == current_scope) {
9740 position_t const *const ppos = &entity->base.pos;
9741 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9743 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9744 entity->base.parent_scope = current_scope;
9747 anchor = &entity->base.next;
9750 environment_push(entity);
9753 } while (accept(','));
9754 rem_anchor_token(',');
9755 rem_anchor_token(';');
9757 statement->declaration.declarations_begin = begin;
9758 statement->declaration.declarations_end = end;
9762 static void parse_namespace_definition(void)
9766 entity_t *entity = NULL;
9767 symbol_t *symbol = NULL;
9769 if (token.kind == T_IDENTIFIER) {
9770 symbol = token.base.symbol;
9771 entity = get_entity(symbol, NAMESPACE_NORMAL);
9772 if (entity && entity->kind != ENTITY_NAMESPACE) {
9774 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9775 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9781 if (entity == NULL) {
9782 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9783 entity->base.parent_scope = current_scope;
9786 if (token.kind == '=') {
9787 /* TODO: parse namespace alias */
9788 panic("namespace alias definition not supported yet");
9791 environment_push(entity);
9792 append_entity(current_scope, entity);
9794 PUSH_SCOPE(&entity->namespacee.members);
9795 PUSH_CURRENT_ENTITY(entity);
9797 add_anchor_token('}');
9800 rem_anchor_token('}');
9803 POP_CURRENT_ENTITY();
9808 * Parse a statement.
9809 * There's also parse_statement() which additionally checks for
9810 * "statement has no effect" warnings
9812 static statement_t *intern_parse_statement(void)
9814 /* declaration or statement */
9815 statement_t *statement;
9816 switch (token.kind) {
9817 case T_IDENTIFIER: {
9818 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9819 if (la1_type == ':') {
9820 statement = parse_label_statement();
9821 } else if (is_typedef_symbol(token.base.symbol)) {
9822 statement = parse_declaration_statement();
9824 /* it's an identifier, the grammar says this must be an
9825 * expression statement. However it is common that users mistype
9826 * declaration types, so we guess a bit here to improve robustness
9827 * for incorrect programs */
9831 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9833 statement = parse_expression_statement();
9837 statement = parse_declaration_statement();
9845 case T___extension__: {
9846 /* This can be a prefix to a declaration or an expression statement.
9847 * We simply eat it now and parse the rest with tail recursion. */
9849 statement = intern_parse_statement();
9855 statement = parse_declaration_statement();
9859 statement = parse_local_label_declaration();
9862 case ';': statement = parse_empty_statement(); break;
9863 case '{': statement = parse_compound_statement(false); break;
9864 case T___leave: statement = parse_leave_statement(); break;
9865 case T___try: statement = parse_ms_try_statment(); break;
9866 case T_asm: statement = parse_asm_statement(); break;
9867 case T_break: statement = parse_break(); break;
9868 case T_case: statement = parse_case_statement(); break;
9869 case T_continue: statement = parse_continue(); break;
9870 case T_default: statement = parse_default_statement(); break;
9871 case T_do: statement = parse_do(); break;
9872 case T_for: statement = parse_for(); break;
9873 case T_goto: statement = parse_goto(); break;
9874 case T_if: statement = parse_if(); break;
9875 case T_return: statement = parse_return(); break;
9876 case T_switch: statement = parse_switch(); break;
9877 case T_while: statement = parse_while(); break;
9880 statement = parse_expression_statement();
9884 errorf(HERE, "unexpected token %K while parsing statement", &token);
9885 statement = create_error_statement();
9894 * parse a statement and emits "statement has no effect" warning if needed
9895 * (This is really a wrapper around intern_parse_statement with check for 1
9896 * single warning. It is needed, because for statement expressions we have
9897 * to avoid the warning on the last statement)
9899 static statement_t *parse_statement(void)
9901 statement_t *statement = intern_parse_statement();
9903 if (statement->kind == STATEMENT_EXPRESSION) {
9904 expression_t *expression = statement->expression.expression;
9905 if (!expression_has_effect(expression)) {
9906 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
9907 "statement has no effect");
9915 * Parse a compound statement.
9917 static statement_t *parse_compound_statement(bool inside_expression_statement)
9919 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9921 PUSH_PARENT(statement);
9922 PUSH_SCOPE(&statement->compound.scope);
9925 add_anchor_token('}');
9926 /* tokens, which can start a statement */
9927 /* TODO MS, __builtin_FOO */
9928 add_anchor_token('!');
9929 add_anchor_token('&');
9930 add_anchor_token('(');
9931 add_anchor_token('*');
9932 add_anchor_token('+');
9933 add_anchor_token('-');
9934 add_anchor_token(';');
9935 add_anchor_token('{');
9936 add_anchor_token('~');
9937 add_anchor_token(T_CHARACTER_CONSTANT);
9938 add_anchor_token(T_COLONCOLON);
9939 add_anchor_token(T_IDENTIFIER);
9940 add_anchor_token(T_MINUSMINUS);
9941 add_anchor_token(T_NUMBER);
9942 add_anchor_token(T_PLUSPLUS);
9943 add_anchor_token(T_STRING_LITERAL);
9944 add_anchor_token(T__Alignof);
9945 add_anchor_token(T__Bool);
9946 add_anchor_token(T__Complex);
9947 add_anchor_token(T__Imaginary);
9948 add_anchor_token(T__Thread_local);
9949 add_anchor_token(T___PRETTY_FUNCTION__);
9950 add_anchor_token(T___attribute__);
9951 add_anchor_token(T___builtin_va_start);
9952 add_anchor_token(T___extension__);
9953 add_anchor_token(T___func__);
9954 add_anchor_token(T___imag__);
9955 add_anchor_token(T___label__);
9956 add_anchor_token(T___real__);
9957 add_anchor_token(T_asm);
9958 add_anchor_token(T_auto);
9959 add_anchor_token(T_bool);
9960 add_anchor_token(T_break);
9961 add_anchor_token(T_case);
9962 add_anchor_token(T_char);
9963 add_anchor_token(T_class);
9964 add_anchor_token(T_const);
9965 add_anchor_token(T_const_cast);
9966 add_anchor_token(T_continue);
9967 add_anchor_token(T_default);
9968 add_anchor_token(T_delete);
9969 add_anchor_token(T_double);
9970 add_anchor_token(T_do);
9971 add_anchor_token(T_dynamic_cast);
9972 add_anchor_token(T_enum);
9973 add_anchor_token(T_extern);
9974 add_anchor_token(T_false);
9975 add_anchor_token(T_float);
9976 add_anchor_token(T_for);
9977 add_anchor_token(T_goto);
9978 add_anchor_token(T_if);
9979 add_anchor_token(T_inline);
9980 add_anchor_token(T_int);
9981 add_anchor_token(T_long);
9982 add_anchor_token(T_new);
9983 add_anchor_token(T_operator);
9984 add_anchor_token(T_register);
9985 add_anchor_token(T_reinterpret_cast);
9986 add_anchor_token(T_restrict);
9987 add_anchor_token(T_return);
9988 add_anchor_token(T_short);
9989 add_anchor_token(T_signed);
9990 add_anchor_token(T_sizeof);
9991 add_anchor_token(T_static);
9992 add_anchor_token(T_static_cast);
9993 add_anchor_token(T_struct);
9994 add_anchor_token(T_switch);
9995 add_anchor_token(T_template);
9996 add_anchor_token(T_this);
9997 add_anchor_token(T_throw);
9998 add_anchor_token(T_true);
9999 add_anchor_token(T_try);
10000 add_anchor_token(T_typedef);
10001 add_anchor_token(T_typeid);
10002 add_anchor_token(T_typename);
10003 add_anchor_token(T_typeof);
10004 add_anchor_token(T_union);
10005 add_anchor_token(T_unsigned);
10006 add_anchor_token(T_using);
10007 add_anchor_token(T_void);
10008 add_anchor_token(T_volatile);
10009 add_anchor_token(T_wchar_t);
10010 add_anchor_token(T_while);
10012 statement_t **anchor = &statement->compound.statements;
10013 bool only_decls_so_far = true;
10014 while (token.kind != '}' && token.kind != T_EOF) {
10015 statement_t *sub_statement = intern_parse_statement();
10016 if (sub_statement->kind == STATEMENT_ERROR) {
10020 if (sub_statement->kind != STATEMENT_DECLARATION) {
10021 only_decls_so_far = false;
10022 } else if (!only_decls_so_far) {
10023 position_t const *const pos = &sub_statement->base.pos;
10024 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10027 *anchor = sub_statement;
10028 anchor = &sub_statement->base.next;
10032 /* look over all statements again to produce no effect warnings */
10033 if (is_warn_on(WARN_UNUSED_VALUE)) {
10034 statement_t *sub_statement = statement->compound.statements;
10035 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10036 if (sub_statement->kind != STATEMENT_EXPRESSION)
10038 /* don't emit a warning for the last expression in an expression
10039 * statement as it has always an effect */
10040 if (inside_expression_statement && sub_statement->base.next == NULL)
10043 expression_t *expression = sub_statement->expression.expression;
10044 if (!expression_has_effect(expression)) {
10045 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
10046 "statement has no effect");
10051 rem_anchor_token(T_while);
10052 rem_anchor_token(T_wchar_t);
10053 rem_anchor_token(T_volatile);
10054 rem_anchor_token(T_void);
10055 rem_anchor_token(T_using);
10056 rem_anchor_token(T_unsigned);
10057 rem_anchor_token(T_union);
10058 rem_anchor_token(T_typeof);
10059 rem_anchor_token(T_typename);
10060 rem_anchor_token(T_typeid);
10061 rem_anchor_token(T_typedef);
10062 rem_anchor_token(T_try);
10063 rem_anchor_token(T_true);
10064 rem_anchor_token(T_throw);
10065 rem_anchor_token(T_this);
10066 rem_anchor_token(T_template);
10067 rem_anchor_token(T_switch);
10068 rem_anchor_token(T_struct);
10069 rem_anchor_token(T_static_cast);
10070 rem_anchor_token(T_static);
10071 rem_anchor_token(T_sizeof);
10072 rem_anchor_token(T_signed);
10073 rem_anchor_token(T_short);
10074 rem_anchor_token(T_return);
10075 rem_anchor_token(T_restrict);
10076 rem_anchor_token(T_reinterpret_cast);
10077 rem_anchor_token(T_register);
10078 rem_anchor_token(T_operator);
10079 rem_anchor_token(T_new);
10080 rem_anchor_token(T_long);
10081 rem_anchor_token(T_int);
10082 rem_anchor_token(T_inline);
10083 rem_anchor_token(T_if);
10084 rem_anchor_token(T_goto);
10085 rem_anchor_token(T_for);
10086 rem_anchor_token(T_float);
10087 rem_anchor_token(T_false);
10088 rem_anchor_token(T_extern);
10089 rem_anchor_token(T_enum);
10090 rem_anchor_token(T_dynamic_cast);
10091 rem_anchor_token(T_do);
10092 rem_anchor_token(T_double);
10093 rem_anchor_token(T_delete);
10094 rem_anchor_token(T_default);
10095 rem_anchor_token(T_continue);
10096 rem_anchor_token(T_const_cast);
10097 rem_anchor_token(T_const);
10098 rem_anchor_token(T_class);
10099 rem_anchor_token(T_char);
10100 rem_anchor_token(T_case);
10101 rem_anchor_token(T_break);
10102 rem_anchor_token(T_bool);
10103 rem_anchor_token(T_auto);
10104 rem_anchor_token(T_asm);
10105 rem_anchor_token(T___real__);
10106 rem_anchor_token(T___label__);
10107 rem_anchor_token(T___imag__);
10108 rem_anchor_token(T___func__);
10109 rem_anchor_token(T___extension__);
10110 rem_anchor_token(T___builtin_va_start);
10111 rem_anchor_token(T___attribute__);
10112 rem_anchor_token(T___PRETTY_FUNCTION__);
10113 rem_anchor_token(T__Thread_local);
10114 rem_anchor_token(T__Imaginary);
10115 rem_anchor_token(T__Complex);
10116 rem_anchor_token(T__Bool);
10117 rem_anchor_token(T__Alignof);
10118 rem_anchor_token(T_STRING_LITERAL);
10119 rem_anchor_token(T_PLUSPLUS);
10120 rem_anchor_token(T_NUMBER);
10121 rem_anchor_token(T_MINUSMINUS);
10122 rem_anchor_token(T_IDENTIFIER);
10123 rem_anchor_token(T_COLONCOLON);
10124 rem_anchor_token(T_CHARACTER_CONSTANT);
10125 rem_anchor_token('~');
10126 rem_anchor_token('{');
10127 rem_anchor_token(';');
10128 rem_anchor_token('-');
10129 rem_anchor_token('+');
10130 rem_anchor_token('*');
10131 rem_anchor_token('(');
10132 rem_anchor_token('&');
10133 rem_anchor_token('!');
10134 rem_anchor_token('}');
10142 * Check for unused global static functions and variables
10144 static void check_unused_globals(void)
10146 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10149 for (const entity_t *entity = file_scope->entities; entity != NULL;
10150 entity = entity->base.next) {
10151 if (!is_declaration(entity))
10154 const declaration_t *declaration = &entity->declaration;
10155 if (declaration->used ||
10156 declaration->modifiers & DM_UNUSED ||
10157 declaration->modifiers & DM_USED ||
10158 declaration->storage_class != STORAGE_CLASS_STATIC)
10163 if (entity->kind == ENTITY_FUNCTION) {
10164 /* inhibit warning for static inline functions */
10165 if (entity->function.is_inline)
10168 why = WARN_UNUSED_FUNCTION;
10169 s = entity->function.body != NULL ? "defined" : "declared";
10171 why = WARN_UNUSED_VARIABLE;
10175 warningf(why, &declaration->base.pos, "'%#N' %s but not used", entity, s);
10179 static void parse_global_asm(void)
10181 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10184 add_anchor_token(';');
10185 add_anchor_token(')');
10186 add_anchor_token(T_STRING_LITERAL);
10189 rem_anchor_token(T_STRING_LITERAL);
10190 statement->asms.asm_text = parse_string_literals("global asm");
10191 statement->base.next = unit->global_asm;
10192 unit->global_asm = statement;
10194 rem_anchor_token(')');
10196 rem_anchor_token(';');
10200 static void parse_linkage_specification(void)
10204 position_t const pos = *HERE;
10205 char const *const linkage = parse_string_literals(NULL).begin;
10207 linkage_kind_t old_linkage = current_linkage;
10208 linkage_kind_t new_linkage;
10209 if (streq(linkage, "C")) {
10210 new_linkage = LINKAGE_C;
10211 } else if (streq(linkage, "C++")) {
10212 new_linkage = LINKAGE_CXX;
10214 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10215 new_linkage = LINKAGE_C;
10217 current_linkage = new_linkage;
10226 assert(current_linkage == new_linkage);
10227 current_linkage = old_linkage;
10230 static void parse_external(void)
10232 switch (token.kind) {
10234 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10235 parse_linkage_specification();
10237 DECLARATION_START_NO_EXTERN
10239 case T___extension__:
10240 /* tokens below are for implicit int */
10241 case '&': /* & x; -> int& x; (and error later, because C++ has no
10243 case '*': /* * x; -> int* x; */
10244 case '(': /* (x); -> int (x); */
10246 parse_external_declaration();
10252 parse_global_asm();
10256 parse_namespace_definition();
10260 if (!strict_mode) {
10261 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10268 errorf(HERE, "stray %K outside of function", &token);
10269 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10270 eat_until_matching_token(token.kind);
10276 static void parse_externals(void)
10278 add_anchor_token('}');
10279 add_anchor_token(T_EOF);
10282 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10283 unsigned short token_anchor_copy[T_LAST_TOKEN];
10284 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10287 while (token.kind != T_EOF && token.kind != '}') {
10289 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10290 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10292 /* the anchor set and its copy differs */
10293 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10296 if (in_gcc_extension) {
10297 /* an gcc extension scope was not closed */
10298 internal_errorf(HERE, "Leaked __extension__");
10305 rem_anchor_token(T_EOF);
10306 rem_anchor_token('}');
10310 * Parse a translation unit.
10312 static void parse_translation_unit(void)
10314 add_anchor_token(T_EOF);
10319 if (token.kind == T_EOF)
10322 errorf(HERE, "stray %K outside of function", &token);
10323 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10324 eat_until_matching_token(token.kind);
10329 void set_default_visibility(elf_visibility_tag_t visibility)
10331 default_visibility = visibility;
10337 * @return the translation unit or NULL if errors occurred.
10339 void start_parsing(void)
10341 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10342 label_stack = NEW_ARR_F(stack_entry_t, 0);
10344 print_to_file(stderr);
10346 assert(unit == NULL);
10347 unit = allocate_ast_zero(sizeof(unit[0]));
10349 assert(file_scope == NULL);
10350 file_scope = &unit->scope;
10352 assert(current_scope == NULL);
10353 scope_push(&unit->scope);
10355 create_gnu_builtins();
10357 create_microsoft_intrinsics();
10360 translation_unit_t *finish_parsing(void)
10362 assert(current_scope == &unit->scope);
10365 assert(file_scope == &unit->scope);
10366 check_unused_globals();
10369 DEL_ARR_F(environment_stack);
10370 DEL_ARR_F(label_stack);
10372 translation_unit_t *result = unit;
10377 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10378 * are given length one. */
10379 static void complete_incomplete_arrays(void)
10381 size_t n = ARR_LEN(incomplete_arrays);
10382 for (size_t i = 0; i != n; ++i) {
10383 declaration_t *const decl = incomplete_arrays[i];
10384 type_t *const type = skip_typeref(decl->type);
10386 if (!is_type_incomplete(type))
10389 position_t const *const pos = &decl->base.pos;
10390 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10392 type_t *const new_type = duplicate_type(type);
10393 new_type->array.size_constant = true;
10394 new_type->array.has_implicit_size = true;
10395 new_type->array.size = 1;
10397 type_t *const result = identify_new_type(new_type);
10399 decl->type = result;
10403 static void prepare_main_collect2(entity_t *const entity)
10405 PUSH_SCOPE(&entity->function.body->compound.scope);
10407 // create call to __main
10408 symbol_t *symbol = symbol_table_insert("__main");
10409 entity_t *subsubmain_ent
10410 = create_implicit_function(symbol, &builtin_position);
10412 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10413 type_t *ftype = subsubmain_ent->declaration.type;
10414 ref->base.pos = builtin_position;
10415 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10416 ref->reference.entity = subsubmain_ent;
10418 expression_t *call = allocate_expression_zero(EXPR_CALL);
10419 call->base.pos = builtin_position;
10420 call->base.type = type_void;
10421 call->call.function = ref;
10423 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10424 expr_statement->base.pos = builtin_position;
10425 expr_statement->expression.expression = call;
10427 statement_t *const body = entity->function.body;
10428 assert(body->kind == STATEMENT_COMPOUND);
10429 compound_statement_t *compounds = &body->compound;
10431 expr_statement->base.next = compounds->statements;
10432 compounds->statements = expr_statement;
10439 lookahead_bufpos = 0;
10440 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10443 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10444 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10445 parse_translation_unit();
10446 complete_incomplete_arrays();
10447 DEL_ARR_F(incomplete_arrays);
10448 incomplete_arrays = NULL;
10452 * Initialize the parser.
10454 void init_parser(void)
10456 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10458 init_expression_parsers();
10459 obstack_init(&temp_obst);
10463 * Terminate the parser.
10465 void exit_parser(void)
10467 obstack_free(&temp_obst, NULL);