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,
179 #define STORAGE_CLASSES \
180 STORAGE_CLASSES_NO_EXTERN \
183 #define STORAGE_CLASSES_NO_EXTERN \
188 case T__Thread_local:
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #define COMPLEX_SPECIFIERS \
200 #define IMAGINARY_SPECIFIERS \
203 #define TYPE_SPECIFIERS \
205 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define DECLARATION_START_NO_EXTERN \
236 STORAGE_CLASSES_NO_EXTERN \
240 #define EXPRESSION_START \
249 case T_CHARACTER_CONSTANT: \
253 case T_STRING_LITERAL: \
255 case T___FUNCDNAME__: \
256 case T___FUNCSIG__: \
257 case T___PRETTY_FUNCTION__: \
258 case T___builtin_classify_type: \
259 case T___builtin_constant_p: \
260 case T___builtin_isgreater: \
261 case T___builtin_isgreaterequal: \
262 case T___builtin_isless: \
263 case T___builtin_islessequal: \
264 case T___builtin_islessgreater: \
265 case T___builtin_isunordered: \
266 case T___builtin_offsetof: \
267 case T___builtin_va_arg: \
268 case T___builtin_va_copy: \
269 case T___builtin_va_start: \
282 * Returns the size of a statement node.
284 * @param kind the statement kind
286 static size_t get_statement_struct_size(statement_kind_t kind)
288 static const size_t sizes[] = {
289 [STATEMENT_ERROR] = sizeof(statement_base_t),
290 [STATEMENT_EMPTY] = sizeof(statement_base_t),
291 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
292 [STATEMENT_RETURN] = sizeof(return_statement_t),
293 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
294 [STATEMENT_IF] = sizeof(if_statement_t),
295 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
296 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
297 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
298 [STATEMENT_BREAK] = sizeof(statement_base_t),
299 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
300 [STATEMENT_GOTO] = sizeof(goto_statement_t),
301 [STATEMENT_LABEL] = sizeof(label_statement_t),
302 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
303 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
304 [STATEMENT_FOR] = sizeof(for_statement_t),
305 [STATEMENT_ASM] = sizeof(asm_statement_t),
306 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
307 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
309 assert((size_t)kind < lengthof(sizes));
310 assert(sizes[kind] != 0);
315 * Returns the size of an expression node.
317 * @param kind the expression kind
319 static size_t get_expression_struct_size(expression_kind_t kind)
321 static const size_t sizes[] = {
322 [EXPR_ERROR] = sizeof(expression_base_t),
323 [EXPR_REFERENCE] = sizeof(reference_expression_t),
324 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
325 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_CHARACTER] = sizeof(string_literal_expression_t),
329 [EXPR_LITERAL_MS_NOOP] = sizeof(literal_expression_t),
330 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
331 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
332 [EXPR_CALL] = sizeof(call_expression_t),
333 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
334 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
335 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
336 [EXPR_SELECT] = sizeof(select_expression_t),
337 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
338 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
339 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
340 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
341 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
342 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
343 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
344 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
345 [EXPR_VA_START] = sizeof(va_start_expression_t),
346 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
347 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
348 [EXPR_STATEMENT] = sizeof(statement_expression_t),
349 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
351 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
352 return sizes[EXPR_UNARY_FIRST];
354 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
355 return sizes[EXPR_BINARY_FIRST];
357 assert((size_t)kind < lengthof(sizes));
358 assert(sizes[kind] != 0);
363 * Allocate a statement node of given kind and initialize all
364 * fields with zero. Sets its source position to the position
365 * of the current token.
367 static statement_t *allocate_statement_zero(statement_kind_t kind)
369 size_t size = get_statement_struct_size(kind);
370 statement_t *res = allocate_ast_zero(size);
372 res->base.kind = kind;
373 res->base.parent = current_parent;
374 res->base.pos = *HERE;
379 * Allocate an expression node of given kind and initialize all
382 * @param kind the kind of the expression to allocate
384 static expression_t *allocate_expression_zero(expression_kind_t kind)
386 size_t size = get_expression_struct_size(kind);
387 expression_t *res = allocate_ast_zero(size);
389 res->base.kind = kind;
390 res->base.type = type_error_type;
391 res->base.pos = *HERE;
396 * Creates a new invalid expression at the source position
397 * of the current token.
399 static expression_t *create_error_expression(void)
401 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
402 expression->base.type = type_error_type;
407 * Creates a new invalid statement.
409 static statement_t *create_error_statement(void)
411 return allocate_statement_zero(STATEMENT_ERROR);
415 * Allocate a new empty statement.
417 static statement_t *create_empty_statement(void)
419 return allocate_statement_zero(STATEMENT_EMPTY);
423 * Returns the size of an initializer node.
425 * @param kind the initializer kind
427 static size_t get_initializer_size(initializer_kind_t kind)
429 static const size_t sizes[] = {
430 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
431 [INITIALIZER_STRING] = sizeof(initializer_value_t),
432 [INITIALIZER_LIST] = sizeof(initializer_list_t),
433 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
435 assert((size_t)kind < lengthof(sizes));
436 assert(sizes[kind] != 0);
441 * Allocate an initializer node of given kind and initialize all
444 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
446 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
453 * Returns the index of the top element of the environment stack.
455 static size_t environment_top(void)
457 return ARR_LEN(environment_stack);
461 * Returns the index of the top element of the global label stack.
463 static size_t label_top(void)
465 return ARR_LEN(label_stack);
469 * Return the next token.
471 static inline void next_token(void)
473 token = lookahead_buffer[lookahead_bufpos];
474 lookahead_buffer[lookahead_bufpos] = pp_token;
475 next_preprocessing_token();
477 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
480 print_token(stderr, &token);
481 fprintf(stderr, "\n");
485 static inline void eat(token_kind_t const kind)
487 assert(token.kind == kind);
493 * Consume the current token, if it is of the expected kind.
495 * @param kind The kind of token to consume.
496 * @return Whether the token was consumed.
498 static inline bool accept(token_kind_t const kind)
500 if (token.kind == kind) {
509 * Return the next token with a given lookahead.
511 static inline const token_t *look_ahead(size_t num)
513 assert(0 < num && num <= MAX_LOOKAHEAD);
514 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
515 return &lookahead_buffer[pos];
519 * Adds a token type to the token type anchor set (a multi-set).
521 static void add_anchor_token(token_kind_t const token_kind)
523 assert(token_kind < T_LAST_TOKEN);
524 ++token_anchor_set[token_kind];
528 * Remove a token type from the token type anchor set (a multi-set).
530 static void rem_anchor_token(token_kind_t const token_kind)
532 assert(token_kind < T_LAST_TOKEN);
533 assert(token_anchor_set[token_kind] != 0);
534 --token_anchor_set[token_kind];
538 * Eat tokens until a matching token type is found.
540 static void eat_until_matching_token(token_kind_t const type)
542 token_kind_t end_token;
544 case '(': end_token = ')'; break;
545 case '{': end_token = '}'; break;
546 case '[': end_token = ']'; break;
547 default: end_token = type; break;
550 unsigned parenthesis_count = 0;
551 unsigned brace_count = 0;
552 unsigned bracket_count = 0;
553 while (token.kind != end_token ||
554 parenthesis_count != 0 ||
556 bracket_count != 0) {
557 switch (token.kind) {
559 case '(': ++parenthesis_count; break;
560 case '{': ++brace_count; break;
561 case '[': ++bracket_count; break;
564 if (parenthesis_count > 0)
574 if (bracket_count > 0)
577 if (token.kind == end_token &&
578 parenthesis_count == 0 &&
592 * Eat input tokens until an anchor is found.
594 static void eat_until_anchor(void)
596 while (token_anchor_set[token.kind] == 0) {
597 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
598 eat_until_matching_token(token.kind);
604 * Eat a whole block from input tokens.
606 static void eat_block(void)
608 eat_until_matching_token('{');
613 * Report a parse error because an expected token was not found.
616 #if defined __GNUC__ && __GNUC__ >= 4
617 __attribute__((sentinel))
619 void parse_error_expected(const char *message, ...)
621 if (message != NULL) {
622 errorf(HERE, "%s", message);
625 va_start(ap, message);
626 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
631 * Report an incompatible type.
633 static void type_error_incompatible(const char *msg,
634 const position_t *pos, type_t *type1, type_t *type2)
636 errorf(pos, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
639 static bool skip_till(token_kind_t const expected, char const *const context)
641 if (UNLIKELY(token.kind != expected)) {
642 parse_error_expected(context, expected, NULL);
643 add_anchor_token(expected);
645 rem_anchor_token(expected);
646 if (token.kind != expected)
653 * Expect the current token is the expected token.
654 * If not, generate an error and skip until the next anchor.
656 static void expect(token_kind_t const expected)
658 if (skip_till(expected, NULL))
662 static symbol_t *expect_identifier(char const *const context,
663 position_t *const pos)
665 if (!skip_till(T_IDENTIFIER, context))
667 symbol_t *const sym = token.base.symbol;
675 * Push a given scope on the scope stack and make it the
678 static scope_t *scope_push(scope_t *new_scope)
680 if (current_scope != NULL) {
681 new_scope->depth = current_scope->depth + 1;
684 scope_t *old_scope = current_scope;
685 current_scope = new_scope;
690 * Pop the current scope from the scope stack.
692 static void scope_pop(scope_t *old_scope)
694 current_scope = old_scope;
698 * Search an entity by its symbol in a given namespace.
700 static entity_t *get_entity(const symbol_t *const symbol,
701 namespace_tag_t namespc)
703 entity_t *entity = symbol->entity;
704 for (; entity != NULL; entity = entity->base.symbol_next) {
705 if ((namespace_tag_t)entity->base.namespc == namespc)
712 /* §6.2.3:1 24) There is only one name space for tags even though three are
714 static entity_t *get_tag(symbol_t const *const symbol,
715 entity_kind_tag_t const kind)
717 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
718 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
720 "'%Y' defined as wrong kind of tag (previous definition %P)",
721 symbol, &entity->base.pos);
728 * pushs an entity on the environment stack and links the corresponding symbol
731 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
733 symbol_t *symbol = entity->base.symbol;
734 entity_namespace_t namespc = entity->base.namespc;
735 assert(namespc != 0);
737 /* replace/add entity into entity list of the symbol */
740 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
745 /* replace an entry? */
746 if (iter->base.namespc == namespc) {
747 entity->base.symbol_next = iter->base.symbol_next;
753 /* remember old declaration */
755 entry.symbol = symbol;
756 entry.old_entity = iter;
757 entry.namespc = namespc;
758 ARR_APP1(stack_entry_t, *stack_ptr, entry);
762 * Push an entity on the environment stack.
764 static void environment_push(entity_t *entity)
766 assert(entity->base.pos.input_name != NULL);
767 assert(entity->base.parent_scope != NULL);
768 stack_push(&environment_stack, entity);
772 * Push a declaration on the global label stack.
774 * @param declaration the declaration
776 static void label_push(entity_t *label)
778 /* we abuse the parameters scope as parent for the labels */
779 label->base.parent_scope = ¤t_function->parameters;
780 stack_push(&label_stack, label);
784 * pops symbols from the environment stack until @p new_top is the top element
786 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
788 stack_entry_t *stack = *stack_ptr;
789 size_t top = ARR_LEN(stack);
792 assert(new_top <= top);
796 for (i = top; i > new_top; --i) {
797 stack_entry_t *entry = &stack[i - 1];
799 entity_t *old_entity = entry->old_entity;
800 symbol_t *symbol = entry->symbol;
801 entity_namespace_t namespc = entry->namespc;
803 /* replace with old_entity/remove */
806 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
808 assert(iter != NULL);
809 /* replace an entry? */
810 if (iter->base.namespc == namespc)
814 /* restore definition from outer scopes (if there was one) */
815 if (old_entity != NULL) {
816 old_entity->base.symbol_next = iter->base.symbol_next;
817 *anchor = old_entity;
819 /* remove entry from list */
820 *anchor = iter->base.symbol_next;
824 ARR_SHRINKLEN(*stack_ptr, new_top);
828 * Pop all entries from the environment stack until the new_top
831 * @param new_top the new stack top
833 static void environment_pop_to(size_t new_top)
835 stack_pop_to(&environment_stack, new_top);
839 * Pop all entries from the global label stack until the new_top
842 * @param new_top the new stack top
844 static void label_pop_to(size_t new_top)
846 stack_pop_to(&label_stack, new_top);
850 * §6.3.1.1:2 Do integer promotion for a given type.
852 * @param type the type to promote
853 * @return the promoted type
855 static type_t *promote_integer(type_t *type)
857 atomic_type_kind_t akind = get_arithmetic_akind(type);
858 if (get_akind_rank(akind) < get_akind_rank(ATOMIC_TYPE_INT))
865 * Check if a given expression represents a null pointer constant.
867 * @param expression the expression to check
869 static bool is_null_pointer_constant(const expression_t *expression)
871 /* skip void* cast */
872 if (expression->kind == EXPR_UNARY_CAST) {
873 type_t *const type = skip_typeref(expression->base.type);
874 if (types_compatible(type, type_void_ptr))
875 expression = expression->unary.value;
878 type_t *const type = skip_typeref(expression->base.type);
879 if (!is_type_integer(type))
881 switch (is_constant_expression(expression)) {
882 case EXPR_CLASS_ERROR: return true;
883 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
884 default: return false;
889 * Create an implicit cast expression.
891 * @param expression the expression to cast
892 * @param dest_type the destination type
894 static expression_t *create_implicit_cast(expression_t *expression,
897 type_t *const source_type = skip_typeref(expression->base.type);
898 if (source_type == skip_typeref(dest_type))
901 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
902 cast->unary.value = expression;
903 cast->base.type = dest_type;
904 cast->base.implicit = true;
909 typedef enum assign_error_t {
911 ASSIGN_ERROR_INCOMPATIBLE,
912 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
913 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
914 ASSIGN_WARNING_POINTER_FROM_INT,
915 ASSIGN_WARNING_INT_FROM_POINTER
918 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)
920 type_t *const orig_type_right = right->base.type;
921 type_t *const type_left = skip_typeref(orig_type_left);
922 type_t *const type_right = skip_typeref(orig_type_right);
927 case ASSIGN_ERROR_INCOMPATIBLE:
928 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
931 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
932 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
933 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
935 /* the left type has all qualifiers from the right type */
936 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
937 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);
941 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
942 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
945 case ASSIGN_WARNING_POINTER_FROM_INT:
946 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
949 case ASSIGN_WARNING_INT_FROM_POINTER:
950 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
954 panic("invalid error value");
958 /** Implements the rules from §6.5.16.1 */
959 static assign_error_t semantic_assign(type_t *orig_type_left,
960 const expression_t *const right)
962 type_t *const orig_type_right = right->base.type;
963 type_t *const type_left = skip_typeref(orig_type_left);
964 type_t *const type_right = skip_typeref(orig_type_right);
966 if (is_type_pointer(type_left)) {
967 if (is_null_pointer_constant(right)) {
968 return ASSIGN_SUCCESS;
969 } else if (is_type_pointer(type_right)) {
970 type_t *points_to_left
971 = skip_typeref(type_left->pointer.points_to);
972 type_t *points_to_right
973 = skip_typeref(type_right->pointer.points_to);
974 assign_error_t res = ASSIGN_SUCCESS;
976 /* the left type has all qualifiers from the right type */
977 unsigned missing_qualifiers
978 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
979 if (missing_qualifiers != 0) {
980 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
983 points_to_left = get_unqualified_type(points_to_left);
984 points_to_right = get_unqualified_type(points_to_right);
986 if (is_type_void(points_to_left))
989 if (is_type_void(points_to_right)) {
990 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
991 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
994 if (!types_compatible(points_to_left, points_to_right)) {
995 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
999 } else if (is_type_integer(type_right)) {
1000 return ASSIGN_WARNING_POINTER_FROM_INT;
1002 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1003 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1004 && is_type_pointer(type_right))) {
1005 return ASSIGN_SUCCESS;
1006 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1007 type_t *const unqual_type_left = get_unqualified_type(type_left);
1008 type_t *const unqual_type_right = get_unqualified_type(type_right);
1009 if (types_compatible(unqual_type_left, unqual_type_right)) {
1010 return ASSIGN_SUCCESS;
1012 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1013 return ASSIGN_WARNING_INT_FROM_POINTER;
1016 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1017 return ASSIGN_SUCCESS;
1019 return ASSIGN_ERROR_INCOMPATIBLE;
1022 static expression_t *parse_constant_expression(void)
1024 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1026 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1027 errorf(&result->base.pos, "expression '%E' is not constant", result);
1033 static expression_t *parse_assignment_expression(void)
1035 return parse_subexpression(PREC_ASSIGNMENT);
1038 static void append_string(string_t const *const s)
1040 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1041 * possible, because other tokens are grown there alongside. */
1042 obstack_grow(&ast_obstack, s->begin, s->size);
1045 static string_t finish_string(string_encoding_t const enc)
1047 obstack_1grow(&ast_obstack, '\0');
1048 size_t const size = obstack_object_size(&ast_obstack) - 1;
1049 char const *const string = obstack_finish(&ast_obstack);
1050 return (string_t){ string, size, enc };
1053 static string_t concat_string_literals(void)
1055 assert(token.kind == T_STRING_LITERAL);
1058 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1059 append_string(&token.literal.string);
1060 eat(T_STRING_LITERAL);
1061 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1062 string_encoding_t enc = token.literal.string.encoding;
1064 string_encoding_t const new_enc = token.literal.string.encoding;
1065 if (new_enc != enc && new_enc != STRING_ENCODING_CHAR) {
1066 if (enc == STRING_ENCODING_CHAR) {
1069 errorf(HERE, "concatenating string literals with encodings %s and %s", get_string_encoding_prefix(enc), get_string_encoding_prefix(new_enc));
1072 append_string(&token.literal.string);
1073 eat(T_STRING_LITERAL);
1074 } while (token.kind == T_STRING_LITERAL);
1075 result = finish_string(enc);
1077 result = token.literal.string;
1078 eat(T_STRING_LITERAL);
1084 static string_t parse_string_literals(char const *const context)
1086 if (!skip_till(T_STRING_LITERAL, context))
1087 return (string_t){ "", 0, STRING_ENCODING_CHAR };
1089 position_t const pos = *HERE;
1090 string_t const res = concat_string_literals();
1092 if (res.encoding != STRING_ENCODING_CHAR) {
1093 errorf(&pos, "expected plain string literal, got %s string literal", get_string_encoding_prefix(res.encoding));
1099 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1101 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1102 attribute->kind = kind;
1103 attribute->pos = *HERE;
1108 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1111 * __attribute__ ( ( attribute-list ) )
1115 * attribute_list , attrib
1120 * any-word ( identifier )
1121 * any-word ( identifier , nonempty-expr-list )
1122 * any-word ( expr-list )
1124 * where the "identifier" must not be declared as a type, and
1125 * "any-word" may be any identifier (including one declared as a
1126 * type), a reserved word storage class specifier, type specifier or
1127 * type qualifier. ??? This still leaves out most reserved keywords
1128 * (following the old parser), shouldn't we include them, and why not
1129 * allow identifiers declared as types to start the arguments?
1131 * Matze: this all looks confusing and little systematic, so we're even less
1132 * strict and parse any list of things which are identifiers or
1133 * (assignment-)expressions.
1135 static attribute_argument_t *parse_attribute_arguments(void)
1137 attribute_argument_t *first = NULL;
1138 attribute_argument_t **anchor = &first;
1139 if (token.kind != ')') do {
1140 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1142 /* is it an identifier */
1143 if (token.kind == T_IDENTIFIER
1144 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1145 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1146 argument->v.symbol = token.base.symbol;
1149 /* must be an expression */
1150 expression_t *expression = parse_assignment_expression();
1152 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1153 argument->v.expression = expression;
1156 /* append argument */
1158 anchor = &argument->next;
1159 } while (accept(','));
1164 static attribute_t *parse_attribute_asm(void)
1166 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1169 attribute->a.arguments = parse_attribute_arguments();
1173 static attribute_t *parse_attribute_gnu_single(void)
1175 /* parse "any-word" */
1176 symbol_t *const symbol = token.base.symbol;
1177 if (symbol == NULL) {
1178 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1182 attribute_kind_t kind;
1183 char const *const name = symbol->string;
1184 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1185 if (kind > ATTRIBUTE_GNU_LAST) {
1186 /* special case for "__const" */
1187 if (token.kind == T_const) {
1188 kind = ATTRIBUTE_GNU_CONST;
1192 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1193 /* TODO: we should still save the attribute in the list... */
1194 kind = ATTRIBUTE_UNKNOWN;
1198 const char *attribute_name = get_attribute_name(kind);
1199 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1203 attribute_t *attribute = allocate_attribute_zero(kind);
1206 /* parse arguments */
1208 attribute->a.arguments = parse_attribute_arguments();
1213 static attribute_t *parse_attribute_gnu(void)
1215 attribute_t *first = NULL;
1216 attribute_t **anchor = &first;
1218 eat(T___attribute__);
1219 add_anchor_token(')');
1220 add_anchor_token(',');
1224 if (token.kind != ')') do {
1225 attribute_t *attribute = parse_attribute_gnu_single();
1227 *anchor = attribute;
1228 anchor = &attribute->next;
1230 } while (accept(','));
1231 rem_anchor_token(',');
1232 rem_anchor_token(')');
1239 /** Parse attributes. */
1240 static attribute_t *parse_attributes(attribute_t *first)
1242 attribute_t **anchor = &first;
1244 while (*anchor != NULL)
1245 anchor = &(*anchor)->next;
1247 attribute_t *attribute;
1248 switch (token.kind) {
1249 case T___attribute__:
1250 attribute = parse_attribute_gnu();
1251 if (attribute == NULL)
1256 attribute = parse_attribute_asm();
1260 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1265 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1269 case T__forceinline:
1270 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1271 eat(T__forceinline);
1275 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1280 /* TODO record modifier */
1281 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1282 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1290 *anchor = attribute;
1291 anchor = &attribute->next;
1295 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1297 static entity_t *determine_lhs_ent(expression_t *const expr,
1300 switch (expr->kind) {
1301 case EXPR_REFERENCE: {
1302 entity_t *const entity = expr->reference.entity;
1303 /* we should only find variables as lvalues... */
1304 if (entity->base.kind != ENTITY_VARIABLE
1305 && entity->base.kind != ENTITY_PARAMETER)
1311 case EXPR_ARRAY_ACCESS: {
1312 expression_t *const ref = expr->array_access.array_ref;
1313 entity_t * ent = NULL;
1314 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1315 ent = determine_lhs_ent(ref, lhs_ent);
1318 mark_vars_read(ref, lhs_ent);
1320 mark_vars_read(expr->array_access.index, lhs_ent);
1325 mark_vars_read(expr->select.compound, lhs_ent);
1326 if (is_type_compound(skip_typeref(expr->base.type)))
1327 return determine_lhs_ent(expr->select.compound, lhs_ent);
1331 case EXPR_UNARY_DEREFERENCE: {
1332 expression_t *const val = expr->unary.value;
1333 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1335 return determine_lhs_ent(val->unary.value, lhs_ent);
1337 mark_vars_read(val, NULL);
1343 mark_vars_read(expr, NULL);
1348 #define ENT_ANY ((entity_t*)-1)
1351 * Mark declarations, which are read. This is used to detect variables, which
1355 * x is not marked as "read", because it is only read to calculate its own new
1359 * x and y are not detected as "not read", because multiple variables are
1362 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1364 switch (expr->kind) {
1365 case EXPR_REFERENCE: {
1366 entity_t *const entity = expr->reference.entity;
1367 if (entity->kind != ENTITY_VARIABLE
1368 && entity->kind != ENTITY_PARAMETER)
1371 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1372 entity->variable.read = true;
1378 // TODO respect pure/const
1379 mark_vars_read(expr->call.function, NULL);
1380 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1381 mark_vars_read(arg->expression, NULL);
1385 case EXPR_CONDITIONAL:
1386 // TODO lhs_decl should depend on whether true/false have an effect
1387 mark_vars_read(expr->conditional.condition, NULL);
1388 if (expr->conditional.true_expression != NULL)
1389 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1390 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1394 if (lhs_ent == ENT_ANY
1395 && !is_type_compound(skip_typeref(expr->base.type)))
1397 mark_vars_read(expr->select.compound, lhs_ent);
1400 case EXPR_ARRAY_ACCESS: {
1401 mark_vars_read(expr->array_access.index, lhs_ent);
1402 expression_t *const ref = expr->array_access.array_ref;
1403 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1404 if (lhs_ent == ENT_ANY)
1407 mark_vars_read(ref, lhs_ent);
1412 mark_vars_read(expr->va_arge.ap, lhs_ent);
1416 mark_vars_read(expr->va_copye.src, lhs_ent);
1419 case EXPR_UNARY_CAST:
1420 /* Special case: Use void cast to mark a variable as "read" */
1421 if (is_type_void(skip_typeref(expr->base.type)))
1426 case EXPR_UNARY_THROW:
1427 if (expr->unary.value == NULL)
1430 case EXPR_UNARY_DEREFERENCE:
1431 case EXPR_UNARY_DELETE:
1432 case EXPR_UNARY_DELETE_ARRAY:
1433 if (lhs_ent == ENT_ANY)
1437 case EXPR_UNARY_NEGATE:
1438 case EXPR_UNARY_PLUS:
1439 case EXPR_UNARY_COMPLEMENT:
1440 case EXPR_UNARY_NOT:
1441 case EXPR_UNARY_TAKE_ADDRESS:
1442 case EXPR_UNARY_POSTFIX_INCREMENT:
1443 case EXPR_UNARY_POSTFIX_DECREMENT:
1444 case EXPR_UNARY_PREFIX_INCREMENT:
1445 case EXPR_UNARY_PREFIX_DECREMENT:
1446 case EXPR_UNARY_ASSUME:
1447 case EXPR_UNARY_IMAG:
1448 case EXPR_UNARY_REAL:
1450 mark_vars_read(expr->unary.value, lhs_ent);
1453 case EXPR_BINARY_ADD:
1454 case EXPR_BINARY_SUB:
1455 case EXPR_BINARY_MUL:
1456 case EXPR_BINARY_DIV:
1457 case EXPR_BINARY_MOD:
1458 case EXPR_BINARY_EQUAL:
1459 case EXPR_BINARY_NOTEQUAL:
1460 case EXPR_BINARY_LESS:
1461 case EXPR_BINARY_LESSEQUAL:
1462 case EXPR_BINARY_GREATER:
1463 case EXPR_BINARY_GREATEREQUAL:
1464 case EXPR_BINARY_BITWISE_AND:
1465 case EXPR_BINARY_BITWISE_OR:
1466 case EXPR_BINARY_BITWISE_XOR:
1467 case EXPR_BINARY_LOGICAL_AND:
1468 case EXPR_BINARY_LOGICAL_OR:
1469 case EXPR_BINARY_SHIFTLEFT:
1470 case EXPR_BINARY_SHIFTRIGHT:
1471 case EXPR_BINARY_COMMA:
1472 case EXPR_BINARY_ISGREATER:
1473 case EXPR_BINARY_ISGREATEREQUAL:
1474 case EXPR_BINARY_ISLESS:
1475 case EXPR_BINARY_ISLESSEQUAL:
1476 case EXPR_BINARY_ISLESSGREATER:
1477 case EXPR_BINARY_ISUNORDERED:
1478 mark_vars_read(expr->binary.left, lhs_ent);
1479 mark_vars_read(expr->binary.right, lhs_ent);
1482 case EXPR_BINARY_ASSIGN:
1483 case EXPR_BINARY_MUL_ASSIGN:
1484 case EXPR_BINARY_DIV_ASSIGN:
1485 case EXPR_BINARY_MOD_ASSIGN:
1486 case EXPR_BINARY_ADD_ASSIGN:
1487 case EXPR_BINARY_SUB_ASSIGN:
1488 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1489 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1490 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1491 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1492 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1493 if (lhs_ent == ENT_ANY)
1495 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1496 mark_vars_read(expr->binary.right, lhs_ent);
1501 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1504 case EXPR_LITERAL_CASES:
1505 case EXPR_LITERAL_CHARACTER:
1507 case EXPR_STRING_LITERAL:
1508 case EXPR_COMPOUND_LITERAL: // TODO init?
1510 case EXPR_CLASSIFY_TYPE:
1513 case EXPR_BUILTIN_CONSTANT_P:
1514 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1516 case EXPR_STATEMENT: // TODO
1517 case EXPR_LABEL_ADDRESS:
1518 case EXPR_ENUM_CONSTANT:
1522 panic("unhandled expression");
1525 static designator_t *parse_designation(void)
1527 designator_t *result = NULL;
1528 designator_t **anchor = &result;
1531 designator_t *designator;
1532 switch (token.kind) {
1534 designator = allocate_ast_zero(sizeof(designator[0]));
1535 designator->pos = *HERE;
1537 add_anchor_token(']');
1538 add_anchor_token(T_DOTDOTDOT);
1539 designator->array_index = parse_constant_expression();
1540 if (accept(T_DOTDOTDOT)) {
1541 designator->range_last = parse_constant_expression();
1542 errorf(&designator->pos, "range initializer not supported");
1544 rem_anchor_token(T_DOTDOTDOT);
1545 rem_anchor_token(']');
1549 designator = allocate_ast_zero(sizeof(designator[0]));
1550 designator->pos = *HERE;
1552 designator->symbol = expect_identifier("while parsing designator", NULL);
1553 if (!designator->symbol)
1561 assert(designator != NULL);
1562 *anchor = designator;
1563 anchor = &designator->next;
1568 * Build an initializer from a given expression.
1570 static initializer_t *initializer_from_expression(type_t *orig_type,
1571 expression_t *expression)
1573 /* TODO check that expression is a constant expression */
1575 type_t *const type = skip_typeref(orig_type);
1577 /* §6.7.8.14/15 char array may be initialized by string literals */
1578 if (expression->kind == EXPR_STRING_LITERAL && is_type_array(type)) {
1579 array_type_t *const array_type = &type->array;
1580 type_t *const element_type = skip_typeref(array_type->element_type);
1581 switch (expression->string_literal.value.encoding) {
1582 case STRING_ENCODING_CHAR:
1583 case STRING_ENCODING_UTF8: {
1584 if (is_type_atomic(element_type, ATOMIC_TYPE_CHAR) ||
1585 is_type_atomic(element_type, ATOMIC_TYPE_SCHAR) ||
1586 is_type_atomic(element_type, ATOMIC_TYPE_UCHAR)) {
1587 goto make_string_init;
1592 case STRING_ENCODING_CHAR16:
1593 case STRING_ENCODING_CHAR32:
1594 case STRING_ENCODING_WIDE: {
1595 assert(is_type_pointer(expression->base.type));
1596 type_t *const init_type = get_unqualified_type(expression->base.type->pointer.points_to);
1597 if (types_compatible(get_unqualified_type(element_type), init_type)) {
1599 initializer_t *const init = allocate_initializer_zero(INITIALIZER_STRING);
1600 init->value.value = expression;
1608 assign_error_t error = semantic_assign(type, expression);
1609 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1611 report_assign_error(error, type, expression, "initializer",
1612 &expression->base.pos);
1614 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1615 result->value.value = create_implicit_cast(expression, type);
1621 * Parses an scalar initializer.
1623 * §6.7.8.11; eat {} without warning
1625 static initializer_t *parse_scalar_initializer(type_t *type,
1626 bool must_be_constant)
1628 /* there might be extra {} hierarchies */
1630 if (token.kind == '{') {
1631 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1635 } while (token.kind == '{');
1638 expression_t *expression = parse_assignment_expression();
1639 mark_vars_read(expression, NULL);
1640 if (must_be_constant && !is_linker_constant(expression)) {
1641 errorf(&expression->base.pos,
1642 "initialisation expression '%E' is not constant",
1646 initializer_t *initializer = initializer_from_expression(type, expression);
1648 if (initializer == NULL) {
1649 errorf(&expression->base.pos,
1650 "expression '%E' (type '%T') doesn't match expected type '%T'",
1651 expression, expression->base.type, type);
1656 bool additional_warning_displayed = false;
1657 while (braces > 0) {
1659 if (token.kind != '}') {
1660 if (!additional_warning_displayed) {
1661 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1662 additional_warning_displayed = true;
1673 * An entry in the type path.
1675 typedef struct type_path_entry_t type_path_entry_t;
1676 struct type_path_entry_t {
1677 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1679 size_t index; /**< For array types: the current index. */
1680 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1685 * A type path expression a position inside compound or array types.
1687 typedef struct type_path_t type_path_t;
1688 struct type_path_t {
1689 type_path_entry_t *path; /**< An flexible array containing the current path. */
1690 type_t *top_type; /**< type of the element the path points */
1691 size_t max_index; /**< largest index in outermost array */
1695 * Prints a type path for debugging.
1697 static __attribute__((unused)) void debug_print_type_path(
1698 const type_path_t *path)
1700 size_t len = ARR_LEN(path->path);
1702 for (size_t i = 0; i < len; ++i) {
1703 const type_path_entry_t *entry = & path->path[i];
1705 type_t *type = skip_typeref(entry->type);
1706 if (is_type_compound(type)) {
1707 /* in gcc mode structs can have no members */
1708 if (entry->v.compound_entry == NULL) {
1712 fprintf(stderr, ".%s",
1713 entry->v.compound_entry->base.symbol->string);
1714 } else if (is_type_array(type)) {
1715 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1717 fprintf(stderr, "-INVALID-");
1720 if (path->top_type != NULL) {
1721 fprintf(stderr, " (");
1722 print_type(path->top_type);
1723 fprintf(stderr, ")");
1728 * Return the top type path entry, i.e. in a path
1729 * (type).a.b returns the b.
1731 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1733 size_t len = ARR_LEN(path->path);
1735 return &path->path[len-1];
1739 * Enlarge the type path by an (empty) element.
1741 static type_path_entry_t *append_to_type_path(type_path_t *path)
1743 size_t len = ARR_LEN(path->path);
1744 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1746 type_path_entry_t *result = & path->path[len];
1747 memset(result, 0, sizeof(result[0]));
1752 * Descending into a sub-type. Enter the scope of the current top_type.
1754 static void descend_into_subtype(type_path_t *path)
1756 type_t *orig_top_type = path->top_type;
1757 type_t *top_type = skip_typeref(orig_top_type);
1759 type_path_entry_t *top = append_to_type_path(path);
1760 top->type = top_type;
1762 if (is_type_compound(top_type)) {
1763 compound_t *const compound = top_type->compound.compound;
1764 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1766 if (entry != NULL) {
1767 top->v.compound_entry = &entry->declaration;
1768 path->top_type = entry->declaration.type;
1770 path->top_type = NULL;
1772 } else if (is_type_array(top_type)) {
1774 path->top_type = top_type->array.element_type;
1776 assert(!is_type_valid(top_type));
1781 * Pop an entry from the given type path, i.e. returning from
1782 * (type).a.b to (type).a
1784 static void ascend_from_subtype(type_path_t *path)
1786 type_path_entry_t *top = get_type_path_top(path);
1788 path->top_type = top->type;
1790 size_t len = ARR_LEN(path->path);
1791 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1795 * Pop entries from the given type path until the given
1796 * path level is reached.
1798 static void ascend_to(type_path_t *path, size_t top_path_level)
1800 size_t len = ARR_LEN(path->path);
1802 while (len > top_path_level) {
1803 ascend_from_subtype(path);
1804 len = ARR_LEN(path->path);
1808 static bool walk_designator(type_path_t *path, const designator_t *designator,
1809 bool used_in_offsetof)
1811 for (; designator != NULL; designator = designator->next) {
1812 type_path_entry_t *top = get_type_path_top(path);
1813 type_t *orig_type = top->type;
1815 type_t *type = skip_typeref(orig_type);
1817 if (designator->symbol != NULL) {
1818 symbol_t *symbol = designator->symbol;
1819 if (!is_type_compound(type)) {
1820 if (is_type_valid(type)) {
1821 errorf(&designator->pos,
1822 "'.%Y' designator used for non-compound type '%T'",
1826 top->type = type_error_type;
1827 top->v.compound_entry = NULL;
1828 orig_type = type_error_type;
1830 compound_t *compound = type->compound.compound;
1831 entity_t *iter = compound->members.entities;
1832 for (; iter != NULL; iter = iter->base.next) {
1833 if (iter->base.symbol == symbol) {
1838 errorf(&designator->pos,
1839 "'%T' has no member named '%Y'", orig_type, symbol);
1842 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1843 if (used_in_offsetof && iter->compound_member.bitfield) {
1844 errorf(&designator->pos,
1845 "offsetof designator '%Y' must not specify bitfield",
1850 top->type = orig_type;
1851 top->v.compound_entry = &iter->declaration;
1852 orig_type = iter->declaration.type;
1855 expression_t *array_index = designator->array_index;
1856 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1859 if (!is_type_array(type)) {
1860 if (is_type_valid(type)) {
1861 errorf(&designator->pos,
1862 "[%E] designator used for non-array type '%T'",
1863 array_index, orig_type);
1868 long index = fold_constant_to_int(array_index);
1869 if (!used_in_offsetof) {
1871 errorf(&designator->pos,
1872 "array index [%E] must be positive", array_index);
1873 } else if (type->array.size_constant) {
1874 long array_size = type->array.size;
1875 if (index >= array_size) {
1876 errorf(&designator->pos,
1877 "designator [%E] (%d) exceeds array size %d",
1878 array_index, index, array_size);
1883 top->type = orig_type;
1884 top->v.index = (size_t) index;
1885 orig_type = type->array.element_type;
1887 path->top_type = orig_type;
1889 if (designator->next != NULL) {
1890 descend_into_subtype(path);
1896 static void advance_current_object(type_path_t *path, size_t top_path_level)
1898 type_path_entry_t *top = get_type_path_top(path);
1900 type_t *type = skip_typeref(top->type);
1901 if (is_type_union(type)) {
1902 /* in unions only the first element is initialized */
1903 top->v.compound_entry = NULL;
1904 } else if (is_type_struct(type)) {
1905 declaration_t *entry = top->v.compound_entry;
1907 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1908 if (next_entity != NULL) {
1909 assert(is_declaration(next_entity));
1910 entry = &next_entity->declaration;
1915 top->v.compound_entry = entry;
1916 if (entry != NULL) {
1917 path->top_type = entry->type;
1920 } else if (is_type_array(type)) {
1921 assert(is_type_array(type));
1925 if (!type->array.size_constant || top->v.index < type->array.size) {
1929 assert(!is_type_valid(type));
1933 /* we're past the last member of the current sub-aggregate, try if we
1934 * can ascend in the type hierarchy and continue with another subobject */
1935 size_t len = ARR_LEN(path->path);
1937 if (len > top_path_level) {
1938 ascend_from_subtype(path);
1939 advance_current_object(path, top_path_level);
1941 path->top_type = NULL;
1946 * skip any {...} blocks until a closing bracket is reached.
1948 static void skip_initializers(void)
1952 while (token.kind != '}') {
1953 if (token.kind == T_EOF)
1955 if (token.kind == '{') {
1963 static initializer_t *create_empty_initializer(void)
1965 static initializer_t empty_initializer
1966 = { .list = { { INITIALIZER_LIST }, 0 } };
1967 return &empty_initializer;
1971 * Parse a part of an initialiser for a struct or union,
1973 static initializer_t *parse_sub_initializer(type_path_t *path,
1974 type_t *outer_type, size_t top_path_level,
1975 parse_initializer_env_t *env)
1977 if (token.kind == '}') {
1978 /* empty initializer */
1979 return create_empty_initializer();
1982 initializer_t *result = NULL;
1984 type_t *orig_type = path->top_type;
1985 type_t *type = NULL;
1987 if (orig_type == NULL) {
1988 /* We are initializing an empty compound. */
1990 type = skip_typeref(orig_type);
1993 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1996 designator_t *designator = NULL;
1997 if (token.kind == '.' || token.kind == '[') {
1998 designator = parse_designation();
1999 goto finish_designator;
2000 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2001 /* GNU-style designator ("identifier: value") */
2002 designator = allocate_ast_zero(sizeof(designator[0]));
2003 designator->pos = *HERE;
2004 designator->symbol = token.base.symbol;
2009 /* reset path to toplevel, evaluate designator from there */
2010 ascend_to(path, top_path_level);
2011 if (!walk_designator(path, designator, false)) {
2012 /* can't continue after designation error */
2016 initializer_t *designator_initializer
2017 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2018 designator_initializer->designator.designator = designator;
2019 ARR_APP1(initializer_t*, initializers, designator_initializer);
2021 orig_type = path->top_type;
2022 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2027 if (token.kind == '{') {
2028 if (type != NULL && is_type_scalar(type)) {
2029 sub = parse_scalar_initializer(type, env->must_be_constant);
2032 if (env->entity != NULL) {
2033 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2035 errorf(HERE, "extra brace group at end of initializer");
2040 descend_into_subtype(path);
2043 add_anchor_token('}');
2044 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2046 rem_anchor_token('}');
2051 goto error_parse_next;
2053 ascend_from_subtype(path);
2056 /* must be an expression */
2057 expression_t *expression = parse_assignment_expression();
2058 mark_vars_read(expression, NULL);
2060 if (env->must_be_constant && !is_linker_constant(expression)) {
2061 errorf(&expression->base.pos,
2062 "Initialisation expression '%E' is not constant",
2067 /* we are already outside, ... */
2068 if (outer_type == NULL)
2069 goto error_parse_next;
2070 type_t *const outer_type_skip = skip_typeref(outer_type);
2071 if (is_type_compound(outer_type_skip) &&
2072 !outer_type_skip->compound.compound->complete) {
2073 goto error_parse_next;
2076 position_t const* const pos = &expression->base.pos;
2077 if (env->entity != NULL) {
2078 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2080 warningf(WARN_OTHER, pos, "excess elements in initializer");
2082 goto error_parse_next;
2085 /* handle { "string" } special case */
2086 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2087 result = initializer_from_expression(outer_type, expression);
2088 if (result != NULL) {
2090 if (token.kind != '}') {
2091 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", outer_type);
2093 /* TODO: eat , ... */
2098 /* descend into subtypes until expression matches type */
2100 orig_type = path->top_type;
2101 type = skip_typeref(orig_type);
2103 sub = initializer_from_expression(orig_type, expression);
2107 if (!is_type_valid(type)) {
2110 if (is_type_scalar(type)) {
2111 errorf(&expression->base.pos,
2112 "expression '%E' doesn't match expected type '%T'",
2113 expression, orig_type);
2117 descend_into_subtype(path);
2121 /* update largest index of top array */
2122 const type_path_entry_t *first = &path->path[0];
2123 type_t *first_type = first->type;
2124 first_type = skip_typeref(first_type);
2125 if (is_type_array(first_type)) {
2126 size_t index = first->v.index;
2127 if (index > path->max_index)
2128 path->max_index = index;
2131 /* append to initializers list */
2132 ARR_APP1(initializer_t*, initializers, sub);
2137 if (token.kind == '}') {
2142 /* advance to the next declaration if we are not at the end */
2143 advance_current_object(path, top_path_level);
2144 orig_type = path->top_type;
2145 if (orig_type != NULL)
2146 type = skip_typeref(orig_type);
2152 size_t len = ARR_LEN(initializers);
2153 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2154 result = allocate_ast_zero(size);
2155 result->kind = INITIALIZER_LIST;
2156 result->list.len = len;
2157 memcpy(&result->list.initializers, initializers,
2158 len * sizeof(initializers[0]));
2162 skip_initializers();
2164 DEL_ARR_F(initializers);
2165 ascend_to(path, top_path_level+1);
2169 static expression_t *make_size_literal(size_t value)
2171 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2172 literal->base.type = type_size_t;
2175 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2176 literal->literal.value = make_string(buf);
2182 * Parses an initializer. Parsers either a compound literal
2183 * (env->declaration == NULL) or an initializer of a declaration.
2185 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2187 type_t *type = skip_typeref(env->type);
2188 size_t max_index = 0;
2189 initializer_t *result;
2191 if (is_type_scalar(type)) {
2192 result = parse_scalar_initializer(type, env->must_be_constant);
2193 } else if (token.kind == '{') {
2197 memset(&path, 0, sizeof(path));
2198 path.top_type = env->type;
2199 path.path = NEW_ARR_F(type_path_entry_t, 0);
2201 descend_into_subtype(&path);
2203 add_anchor_token('}');
2204 result = parse_sub_initializer(&path, env->type, 1, env);
2205 rem_anchor_token('}');
2207 max_index = path.max_index;
2208 DEL_ARR_F(path.path);
2212 /* parse_scalar_initializer() also works in this case: we simply
2213 * have an expression without {} around it */
2214 result = parse_scalar_initializer(type, env->must_be_constant);
2217 /* §6.7.8:22 array initializers for arrays with unknown size determine
2218 * the array type size */
2219 if (is_type_array(type) && type->array.size_expression == NULL
2220 && result != NULL) {
2222 switch (result->kind) {
2223 case INITIALIZER_LIST:
2224 assert(max_index != 0xdeadbeaf);
2225 size = max_index + 1;
2228 case INITIALIZER_STRING: {
2229 size = get_string_len(&get_init_string(result)->value) + 1;
2233 case INITIALIZER_DESIGNATOR:
2234 case INITIALIZER_VALUE:
2235 /* can happen for parse errors */
2240 internal_errorf(HERE, "invalid initializer type");
2243 type_t *new_type = duplicate_type(type);
2245 new_type->array.size_expression = make_size_literal(size);
2246 new_type->array.size_constant = true;
2247 new_type->array.has_implicit_size = true;
2248 new_type->array.size = size;
2249 env->type = new_type;
2255 static void append_entity(scope_t *scope, entity_t *entity)
2257 if (scope->last_entity != NULL) {
2258 scope->last_entity->base.next = entity;
2260 scope->entities = entity;
2262 entity->base.parent_entity = current_entity;
2263 scope->last_entity = entity;
2267 static compound_t *parse_compound_type_specifier(bool is_struct)
2269 position_t const pos = *HERE;
2270 eat(is_struct ? T_struct : T_union);
2272 symbol_t *symbol = NULL;
2273 entity_t *entity = NULL;
2274 attribute_t *attributes = NULL;
2276 if (token.kind == T___attribute__) {
2277 attributes = parse_attributes(NULL);
2280 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2281 if (token.kind == T_IDENTIFIER) {
2282 /* the compound has a name, check if we have seen it already */
2283 symbol = token.base.symbol;
2284 entity = get_tag(symbol, kind);
2287 if (entity != NULL) {
2288 if (entity->base.parent_scope != current_scope &&
2289 (token.kind == '{' || token.kind == ';')) {
2290 /* we're in an inner scope and have a definition. Shadow
2291 * existing definition in outer scope */
2293 } else if (entity->compound.complete && token.kind == '{') {
2294 position_t const *const ppos = &entity->base.pos;
2295 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2296 /* clear members in the hope to avoid further errors */
2297 entity->compound.members.entities = NULL;
2300 } else if (token.kind != '{') {
2301 char const *const msg =
2302 is_struct ? "while parsing struct type specifier" :
2303 "while parsing union type specifier";
2304 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2309 if (entity == NULL) {
2310 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2311 entity->compound.alignment = 1;
2312 entity->base.parent_scope = current_scope;
2313 if (symbol != NULL) {
2314 environment_push(entity);
2316 append_entity(current_scope, entity);
2319 if (token.kind == '{') {
2320 parse_compound_type_entries(&entity->compound);
2322 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2323 if (symbol == NULL) {
2324 assert(anonymous_entity == NULL);
2325 anonymous_entity = entity;
2329 if (attributes != NULL) {
2330 entity->compound.attributes = attributes;
2331 handle_entity_attributes(attributes, entity);
2334 return &entity->compound;
2337 static void parse_enum_entries(type_t *const enum_type)
2341 if (token.kind == '}') {
2342 errorf(HERE, "empty enum not allowed");
2347 add_anchor_token('}');
2348 add_anchor_token(',');
2350 add_anchor_token('=');
2352 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2353 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2354 entity->enum_value.enum_type = enum_type;
2355 rem_anchor_token('=');
2358 expression_t *value = parse_constant_expression();
2360 value = create_implicit_cast(value, enum_type);
2361 entity->enum_value.value = value;
2366 record_entity(entity, false);
2367 } while (accept(',') && token.kind != '}');
2368 rem_anchor_token(',');
2369 rem_anchor_token('}');
2374 static type_t *parse_enum_specifier(void)
2376 position_t const pos = *HERE;
2381 switch (token.kind) {
2383 symbol = token.base.symbol;
2384 entity = get_tag(symbol, ENTITY_ENUM);
2387 if (entity != NULL) {
2388 if (entity->base.parent_scope != current_scope &&
2389 (token.kind == '{' || token.kind == ';')) {
2390 /* we're in an inner scope and have a definition. Shadow
2391 * existing definition in outer scope */
2393 } else if (entity->enume.complete && token.kind == '{') {
2394 position_t const *const ppos = &entity->base.pos;
2395 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2406 parse_error_expected("while parsing enum type specifier",
2407 T_IDENTIFIER, '{', NULL);
2411 if (entity == NULL) {
2412 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2413 entity->base.parent_scope = current_scope;
2416 type_t *const type = allocate_type_zero(TYPE_ENUM);
2417 type->enumt.enume = &entity->enume;
2418 type->enumt.base.akind = ATOMIC_TYPE_INT;
2420 if (token.kind == '{') {
2421 if (symbol != NULL) {
2422 environment_push(entity);
2424 append_entity(current_scope, entity);
2425 entity->enume.complete = true;
2427 parse_enum_entries(type);
2428 parse_attributes(NULL);
2430 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2431 if (symbol == NULL) {
2432 assert(anonymous_entity == NULL);
2433 anonymous_entity = entity;
2435 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2436 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2443 * if a symbol is a typedef to another type, return true
2445 static bool is_typedef_symbol(symbol_t *symbol)
2447 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2448 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2451 static type_t *parse_typeof(void)
2457 add_anchor_token(')');
2460 expression_t *expression = NULL;
2462 switch (token.kind) {
2464 if (is_typedef_symbol(token.base.symbol)) {
2466 type = parse_typename();
2469 expression = parse_expression();
2470 type = revert_automatic_type_conversion(expression);
2475 rem_anchor_token(')');
2478 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2479 typeof_type->typeoft.expression = expression;
2480 typeof_type->typeoft.typeof_type = type;
2485 typedef enum specifiers_t {
2487 SPECIFIER_SIGNED = 1 << 0,
2488 SPECIFIER_UNSIGNED = 1 << 1,
2489 SPECIFIER_LONG = 1 << 2,
2490 SPECIFIER_INT = 1 << 3,
2491 SPECIFIER_DOUBLE = 1 << 4,
2492 SPECIFIER_CHAR = 1 << 5,
2493 SPECIFIER_WCHAR_T = 1 << 6,
2494 SPECIFIER_SHORT = 1 << 7,
2495 SPECIFIER_LONG_LONG = 1 << 8,
2496 SPECIFIER_FLOAT = 1 << 9,
2497 SPECIFIER_BOOL = 1 << 10,
2498 SPECIFIER_VOID = 1 << 11,
2499 SPECIFIER_INT8 = 1 << 12,
2500 SPECIFIER_INT16 = 1 << 13,
2501 SPECIFIER_INT32 = 1 << 14,
2502 SPECIFIER_INT64 = 1 << 15,
2503 SPECIFIER_INT128 = 1 << 16,
2504 SPECIFIER_COMPLEX = 1 << 17,
2505 SPECIFIER_IMAGINARY = 1 << 18,
2508 static type_t *get_typedef_type(symbol_t *symbol)
2510 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2511 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2514 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2515 type->typedeft.typedefe = &entity->typedefe;
2520 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2522 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2524 add_anchor_token(')');
2525 add_anchor_token(',');
2529 add_anchor_token('=');
2531 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2532 rem_anchor_token('=');
2534 symbol_t **prop = NULL;
2536 if (streq(prop_sym->string, "put")) {
2537 prop = &property->put_symbol;
2538 } else if (streq(prop_sym->string, "get")) {
2539 prop = &property->get_symbol;
2541 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2545 add_anchor_token(T_IDENTIFIER);
2547 rem_anchor_token(T_IDENTIFIER);
2549 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2551 *prop = sym ? sym : sym_anonymous;
2552 } while (accept(','));
2553 rem_anchor_token(',');
2554 rem_anchor_token(')');
2556 attribute->a.property = property;
2562 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2564 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2565 if (accept(T_restrict)) {
2566 kind = ATTRIBUTE_MS_RESTRICT;
2567 } else if (token.kind == T_IDENTIFIER) {
2568 char const *const name = token.base.symbol->string;
2569 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2571 const char *attribute_name = get_attribute_name(k);
2572 if (attribute_name != NULL && streq(attribute_name, name)) {
2578 if (kind == ATTRIBUTE_UNKNOWN) {
2579 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2582 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2586 attribute_t *attribute = allocate_attribute_zero(kind);
2589 if (kind == ATTRIBUTE_MS_PROPERTY) {
2590 return parse_attribute_ms_property(attribute);
2593 /* parse arguments */
2595 attribute->a.arguments = parse_attribute_arguments();
2600 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2604 add_anchor_token(')');
2606 if (token.kind != ')') {
2607 attribute_t **anchor = &first;
2609 while (*anchor != NULL)
2610 anchor = &(*anchor)->next;
2612 attribute_t *attribute
2613 = parse_microsoft_extended_decl_modifier_single();
2614 if (attribute == NULL)
2617 *anchor = attribute;
2618 anchor = &attribute->next;
2619 } while (accept(','));
2621 rem_anchor_token(')');
2626 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2628 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2629 if (is_declaration(entity)) {
2630 entity->declaration.type = type_error_type;
2631 entity->declaration.implicit = true;
2632 } else if (kind == ENTITY_TYPEDEF) {
2633 entity->typedefe.type = type_error_type;
2634 entity->typedefe.builtin = true;
2636 if (kind != ENTITY_COMPOUND_MEMBER)
2637 record_entity(entity, false);
2641 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2643 type_t *type = NULL;
2644 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2645 unsigned type_specifiers = 0;
2646 bool newtype = false;
2647 bool saw_error = false;
2649 memset(specifiers, 0, sizeof(*specifiers));
2650 specifiers->pos = *HERE;
2653 specifiers->attributes = parse_attributes(specifiers->attributes);
2655 switch (token.kind) {
2657 #define MATCH_STORAGE_CLASS(token, class) \
2659 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2660 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2662 specifiers->storage_class = class; \
2663 if (specifiers->thread_local) \
2664 goto check_thread_storage_class; \
2668 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2669 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2670 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2671 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2672 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2675 specifiers->attributes
2676 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2679 case T__Thread_local:
2680 if (specifiers->thread_local) {
2681 errorf(HERE, "duplicate %K", &token);
2683 specifiers->thread_local = true;
2684 check_thread_storage_class:
2685 switch (specifiers->storage_class) {
2686 case STORAGE_CLASS_EXTERN:
2687 case STORAGE_CLASS_NONE:
2688 case STORAGE_CLASS_STATIC:
2692 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2693 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2694 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2695 wrong_thread_storage_class:
2696 errorf(HERE, "%K used with '%s'", &token, wrong);
2703 /* type qualifiers */
2704 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2706 qualifiers |= qualifier; \
2710 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2711 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2712 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2713 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2714 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2715 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2716 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2717 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2719 /* type specifiers */
2720 #define MATCH_SPECIFIER(token, specifier, name) \
2722 if (type_specifiers & specifier) { \
2723 errorf(HERE, "multiple " name " type specifiers given"); \
2725 type_specifiers |= specifier; \
2730 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2731 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2732 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2733 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2734 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2735 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2736 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2737 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2738 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2739 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2740 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2741 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2742 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2743 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2744 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2745 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2746 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2747 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2751 specifiers->is_inline = true;
2755 case T__forceinline:
2756 eat(T__forceinline);
2757 specifiers->modifiers |= DM_FORCEINLINE;
2762 if (type_specifiers & SPECIFIER_LONG_LONG) {
2763 errorf(HERE, "too many long type specifiers given");
2764 } else if (type_specifiers & SPECIFIER_LONG) {
2765 type_specifiers |= SPECIFIER_LONG_LONG;
2767 type_specifiers |= SPECIFIER_LONG;
2772 #define CHECK_DOUBLE_TYPE() \
2773 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2776 CHECK_DOUBLE_TYPE();
2777 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2779 type->compound.compound = parse_compound_type_specifier(true);
2782 CHECK_DOUBLE_TYPE();
2783 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2784 type->compound.compound = parse_compound_type_specifier(false);
2787 CHECK_DOUBLE_TYPE();
2788 type = parse_enum_specifier();
2791 CHECK_DOUBLE_TYPE();
2792 type = parse_typeof();
2794 case T___builtin_va_list:
2795 CHECK_DOUBLE_TYPE();
2796 type = duplicate_type(type_valist);
2797 eat(T___builtin_va_list);
2800 case T_IDENTIFIER: {
2801 /* only parse identifier if we haven't found a type yet */
2802 if (type != NULL || type_specifiers != 0) {
2803 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2804 * declaration, so it doesn't generate errors about expecting '(' or
2806 switch (look_ahead(1)->kind) {
2813 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2817 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2822 goto finish_specifiers;
2826 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2827 if (typedef_type == NULL) {
2828 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2829 * declaration, so it doesn't generate 'implicit int' followed by more
2830 * errors later on. */
2831 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2837 errorf(HERE, "%K does not name a type", &token);
2839 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2841 type = allocate_type_zero(TYPE_TYPEDEF);
2842 type->typedeft.typedefe = &entity->typedefe;
2850 goto finish_specifiers;
2855 type = typedef_type;
2859 /* function specifier */
2861 goto finish_specifiers;
2866 specifiers->attributes = parse_attributes(specifiers->attributes);
2868 if (type == NULL || (saw_error && type_specifiers != 0)) {
2869 position_t const* const pos = &specifiers->pos;
2870 atomic_type_kind_t atomic_type;
2872 /* match valid basic types */
2873 switch (type_specifiers & ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2874 case SPECIFIER_VOID:
2875 if (type_specifiers & (SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2876 if (type_specifiers & SPECIFIER_COMPLEX)
2877 errorf(pos, "_Complex specifier is invalid for void");
2878 if (type_specifiers & SPECIFIER_IMAGINARY)
2879 errorf(pos, "_Imaginary specifier is invalid for void");
2880 type_specifiers &= ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY);
2882 atomic_type = ATOMIC_TYPE_VOID;
2884 case SPECIFIER_WCHAR_T:
2885 atomic_type = ATOMIC_TYPE_WCHAR_T;
2887 case SPECIFIER_CHAR:
2888 atomic_type = ATOMIC_TYPE_CHAR;
2890 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2891 atomic_type = ATOMIC_TYPE_SCHAR;
2893 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2894 atomic_type = ATOMIC_TYPE_UCHAR;
2896 case SPECIFIER_SHORT:
2897 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2898 case SPECIFIER_SHORT | SPECIFIER_INT:
2899 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2900 atomic_type = ATOMIC_TYPE_SHORT;
2902 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2903 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2904 atomic_type = ATOMIC_TYPE_USHORT;
2907 case SPECIFIER_SIGNED:
2908 case SPECIFIER_SIGNED | SPECIFIER_INT:
2909 atomic_type = ATOMIC_TYPE_INT;
2911 case SPECIFIER_UNSIGNED:
2912 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2913 atomic_type = ATOMIC_TYPE_UINT;
2915 case SPECIFIER_LONG:
2916 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2917 case SPECIFIER_LONG | SPECIFIER_INT:
2918 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2919 atomic_type = ATOMIC_TYPE_LONG;
2921 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2922 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2923 atomic_type = ATOMIC_TYPE_ULONG;
2926 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2927 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2928 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2929 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2931 atomic_type = ATOMIC_TYPE_LONGLONG;
2932 goto warn_about_long_long;
2934 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2935 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2937 atomic_type = ATOMIC_TYPE_ULONGLONG;
2938 warn_about_long_long:
2939 warningf(WARN_LONG_LONG, &specifiers->pos, "ISO C90 does not support 'long long'");
2942 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2943 atomic_type = unsigned_int8_type_kind;
2946 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2947 atomic_type = unsigned_int16_type_kind;
2950 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2951 atomic_type = unsigned_int32_type_kind;
2954 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2955 atomic_type = unsigned_int64_type_kind;
2958 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2959 atomic_type = unsigned_int128_type_kind;
2962 case SPECIFIER_INT8:
2963 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2964 atomic_type = int8_type_kind;
2967 case SPECIFIER_INT16:
2968 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2969 atomic_type = int16_type_kind;
2972 case SPECIFIER_INT32:
2973 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2974 atomic_type = int32_type_kind;
2977 case SPECIFIER_INT64:
2978 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2979 atomic_type = int64_type_kind;
2982 case SPECIFIER_INT128:
2983 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2984 atomic_type = int128_type_kind;
2987 case SPECIFIER_FLOAT:
2988 atomic_type = ATOMIC_TYPE_FLOAT;
2990 case SPECIFIER_DOUBLE:
2991 atomic_type = ATOMIC_TYPE_DOUBLE;
2993 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2994 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2996 case SPECIFIER_BOOL:
2997 if (type_specifiers & (SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY)) {
2998 if (type_specifiers & SPECIFIER_COMPLEX)
2999 errorf(pos, "_Complex specifier is invalid for _Bool");
3000 if (type_specifiers & SPECIFIER_IMAGINARY)
3001 errorf(pos, "_Imaginary specifier is invalid for _Bool");
3002 type_specifiers &= ~(SPECIFIER_COMPLEX|SPECIFIER_IMAGINARY);
3004 atomic_type = ATOMIC_TYPE_BOOL;
3007 /* invalid specifier combination, give an error message */
3008 if (type_specifiers == 0) {
3010 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3011 if (!(c_mode & _CXX) && !strict_mode) {
3012 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3013 atomic_type = ATOMIC_TYPE_INT;
3016 errorf(pos, "no type specifiers given in declaration");
3019 } else if (type_specifiers == SPECIFIER_COMPLEX) {
3020 warningf(WARN_OTHER, pos, "_Complex requires a type specifier; assuming '_Complex double'");
3021 atomic_type = ATOMIC_TYPE_DOUBLE;
3023 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3024 (type_specifiers & SPECIFIER_UNSIGNED)) {
3025 errorf(pos, "signed and unsigned specifiers given");
3026 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3027 errorf(pos, "only integer types can be signed or unsigned");
3029 errorf(pos, "multiple datatypes in declaration");
3031 specifiers->type = type_error_type;
3036 if (type_specifiers & SPECIFIER_COMPLEX) {
3037 type = allocate_type_zero(TYPE_COMPLEX);
3038 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3039 type = allocate_type_zero(TYPE_IMAGINARY);
3041 type = allocate_type_zero(TYPE_ATOMIC);
3043 type->atomic.akind = atomic_type;
3045 } else if (type_specifiers != 0) {
3046 errorf(&specifiers->pos, "multiple datatypes in declaration");
3049 /* FIXME: check type qualifiers here */
3050 type->base.qualifiers = qualifiers;
3053 type = identify_new_type(type);
3055 type = typehash_insert(type);
3058 if (specifiers->attributes != NULL)
3059 type = handle_type_attributes(specifiers->attributes, type);
3060 specifiers->type = type;
3063 static type_qualifiers_t parse_type_qualifiers(void)
3065 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3068 switch (token.kind) {
3069 /* type qualifiers */
3070 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3071 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3072 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3073 /* microsoft extended type modifiers */
3074 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3075 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3076 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3077 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3078 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3087 * Parses an K&R identifier list
3089 static void parse_identifier_list(scope_t *scope)
3091 assert(token.kind == T_IDENTIFIER);
3093 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3094 /* a K&R parameter has no type, yet */
3098 append_entity(scope, entity);
3099 } while (accept(',') && token.kind == T_IDENTIFIER);
3102 static entity_t *parse_parameter(void)
3104 declaration_specifiers_t specifiers;
3105 parse_declaration_specifiers(&specifiers);
3107 entity_t *entity = parse_declarator(&specifiers,
3108 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3109 anonymous_entity = NULL;
3113 static void semantic_parameter_incomplete(const entity_t *entity)
3115 assert(entity->kind == ENTITY_PARAMETER);
3117 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3118 * list in a function declarator that is part of a
3119 * definition of that function shall not have
3120 * incomplete type. */
3121 type_t *type = skip_typeref(entity->declaration.type);
3122 if (is_type_incomplete(type)) {
3123 errorf(&entity->base.pos, "'%N' has incomplete type", entity);
3127 static bool has_parameters(void)
3129 /* func(void) is not a parameter */
3130 if (look_ahead(1)->kind != ')')
3132 if (token.kind == T_IDENTIFIER) {
3133 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3136 if (entity->kind != ENTITY_TYPEDEF)
3138 type_t const *const type = skip_typeref(entity->typedefe.type);
3139 if (!is_type_void(type))
3141 if (c_mode & _CXX) {
3142 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3143 * is not allowed. */
3144 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3145 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3146 /* §6.7.5.3:10 Qualification is not allowed here. */
3147 errorf(HERE, "'void' as parameter must not have type qualifiers");
3149 } else if (token.kind != T_void) {
3157 * Parses function type parameters (and optionally creates variable_t entities
3158 * for them in a scope)
3160 static void parse_parameters(function_type_t *type, scope_t *scope)
3162 add_anchor_token(')');
3165 if (token.kind == T_IDENTIFIER &&
3166 !is_typedef_symbol(token.base.symbol) &&
3167 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3168 type->kr_style_parameters = true;
3169 parse_identifier_list(scope);
3170 } else if (token.kind == ')') {
3171 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3172 if (!(c_mode & _CXX))
3173 type->unspecified_parameters = true;
3174 } else if (has_parameters()) {
3175 function_parameter_t **anchor = &type->parameters;
3176 add_anchor_token(',');
3178 switch (token.kind) {
3181 type->variadic = true;
3182 goto parameters_finished;
3187 entity_t *entity = parse_parameter();
3188 if (entity->kind == ENTITY_TYPEDEF) {
3189 errorf(&entity->base.pos,
3190 "typedef not allowed as function parameter");
3193 assert(is_declaration(entity));
3195 semantic_parameter_incomplete(entity);
3197 function_parameter_t *const parameter =
3198 allocate_parameter(entity->declaration.type);
3200 if (scope != NULL) {
3201 append_entity(scope, entity);
3204 *anchor = parameter;
3205 anchor = ¶meter->next;
3210 goto parameters_finished;
3212 } while (accept(','));
3213 parameters_finished:
3214 rem_anchor_token(',');
3217 rem_anchor_token(')');
3221 typedef enum construct_type_kind_t {
3222 CONSTRUCT_POINTER = 1,
3223 CONSTRUCT_REFERENCE,
3226 } construct_type_kind_t;
3228 typedef union construct_type_t construct_type_t;
3230 typedef struct construct_type_base_t {
3231 construct_type_kind_t kind;
3233 construct_type_t *next;
3234 } construct_type_base_t;
3236 typedef struct parsed_pointer_t {
3237 construct_type_base_t base;
3238 type_qualifiers_t type_qualifiers;
3239 variable_t *base_variable; /**< MS __based extension. */
3242 typedef struct parsed_reference_t {
3243 construct_type_base_t base;
3244 } parsed_reference_t;
3246 typedef struct construct_function_type_t {
3247 construct_type_base_t base;
3248 type_t *function_type;
3249 } construct_function_type_t;
3251 typedef struct parsed_array_t {
3252 construct_type_base_t base;
3253 type_qualifiers_t type_qualifiers;
3259 union construct_type_t {
3260 construct_type_kind_t kind;
3261 construct_type_base_t base;
3262 parsed_pointer_t pointer;
3263 parsed_reference_t reference;
3264 construct_function_type_t function;
3265 parsed_array_t array;
3268 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3270 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3271 memset(cons, 0, size);
3273 cons->base.pos = *HERE;
3278 static construct_type_t *parse_pointer_declarator(void)
3280 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3282 cons->pointer.type_qualifiers = parse_type_qualifiers();
3283 //cons->pointer.base_variable = base_variable;
3288 /* ISO/IEC 14882:1998(E) §8.3.2 */
3289 static construct_type_t *parse_reference_declarator(void)
3291 if (!(c_mode & _CXX))
3292 errorf(HERE, "references are only available for C++");
3294 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3301 static construct_type_t *parse_array_declarator(void)
3303 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3304 parsed_array_t *const array = &cons->array;
3307 add_anchor_token(']');
3309 bool is_static = accept(T_static);
3311 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3314 is_static = accept(T_static);
3316 array->type_qualifiers = type_qualifiers;
3317 array->is_static = is_static;
3319 expression_t *size = NULL;
3320 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3321 array->is_variable = true;
3323 } else if (token.kind != ']') {
3324 size = parse_assignment_expression();
3326 /* §6.7.5.2:1 Array size must have integer type */
3327 type_t *const orig_type = size->base.type;
3328 type_t *const type = skip_typeref(orig_type);
3329 if (!is_type_integer(type) && is_type_valid(type)) {
3330 errorf(&size->base.pos,
3331 "array size '%E' must have integer type but has type '%T'",
3336 mark_vars_read(size, NULL);
3339 if (is_static && size == NULL)
3340 errorf(&array->base.pos, "static array parameters require a size");
3342 rem_anchor_token(']');
3348 static construct_type_t *parse_function_declarator(scope_t *scope)
3350 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3352 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3353 function_type_t *ftype = &type->function;
3355 ftype->linkage = current_linkage;
3356 ftype->calling_convention = CC_DEFAULT;
3358 parse_parameters(ftype, scope);
3360 cons->function.function_type = type;
3365 typedef struct parse_declarator_env_t {
3366 bool may_be_abstract : 1;
3367 bool must_be_abstract : 1;
3368 decl_modifiers_t modifiers;
3372 attribute_t *attributes;
3373 } parse_declarator_env_t;
3376 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3378 /* construct a single linked list of construct_type_t's which describe
3379 * how to construct the final declarator type */
3380 construct_type_t *first = NULL;
3381 construct_type_t **anchor = &first;
3383 env->attributes = parse_attributes(env->attributes);
3386 construct_type_t *type;
3387 //variable_t *based = NULL; /* MS __based extension */
3388 switch (token.kind) {
3390 type = parse_reference_declarator();
3394 panic("based not supported anymore");
3399 type = parse_pointer_declarator();
3403 goto ptr_operator_end;
3407 anchor = &type->base.next;
3409 /* TODO: find out if this is correct */
3410 env->attributes = parse_attributes(env->attributes);
3414 construct_type_t *inner_types = NULL;
3416 switch (token.kind) {
3418 if (env->must_be_abstract) {
3419 errorf(HERE, "no identifier expected in typename");
3421 env->symbol = token.base.symbol;
3428 /* Parenthesized declarator or function declarator? */
3429 token_t const *const la1 = look_ahead(1);
3430 switch (la1->kind) {
3432 if (is_typedef_symbol(la1->base.symbol)) {
3434 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3435 * interpreted as ``function with no parameter specification'', rather
3436 * than redundant parentheses around the omitted identifier. */
3438 /* Function declarator. */
3439 if (!env->may_be_abstract) {
3440 errorf(HERE, "function declarator must have a name");
3447 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3448 /* Paranthesized declarator. */
3450 add_anchor_token(')');
3451 inner_types = parse_inner_declarator(env);
3452 if (inner_types != NULL) {
3453 /* All later declarators only modify the return type */
3454 env->must_be_abstract = true;
3456 rem_anchor_token(')');
3465 if (env->may_be_abstract)
3467 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3472 construct_type_t **const p = anchor;
3475 construct_type_t *type;
3476 switch (token.kind) {
3478 scope_t *scope = NULL;
3479 if (!env->must_be_abstract) {
3480 scope = &env->parameters;
3483 type = parse_function_declarator(scope);
3487 type = parse_array_declarator();
3490 goto declarator_finished;
3493 /* insert in the middle of the list (at p) */
3494 type->base.next = *p;
3497 anchor = &type->base.next;
3500 declarator_finished:
3501 /* append inner_types at the end of the list, we don't to set anchor anymore
3502 * as it's not needed anymore */
3503 *anchor = inner_types;
3508 static type_t *construct_declarator_type(construct_type_t *construct_list,
3511 construct_type_t *iter = construct_list;
3512 for (; iter != NULL; iter = iter->base.next) {
3513 position_t const* const pos = &iter->base.pos;
3514 switch (iter->kind) {
3515 case CONSTRUCT_FUNCTION: {
3516 construct_function_type_t *function = &iter->function;
3517 type_t *function_type = function->function_type;
3519 function_type->function.return_type = type;
3521 type_t *skipped_return_type = skip_typeref(type);
3523 if (is_type_function(skipped_return_type)) {
3524 errorf(pos, "function returning function is not allowed");
3525 } else if (is_type_array(skipped_return_type)) {
3526 errorf(pos, "function returning array is not allowed");
3528 if (skipped_return_type->base.qualifiers != 0) {
3529 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3533 /* The function type was constructed earlier. Freeing it here will
3534 * destroy other types. */
3535 type = typehash_insert(function_type);
3539 case CONSTRUCT_POINTER: {
3540 if (is_type_reference(skip_typeref(type)))
3541 errorf(pos, "cannot declare a pointer to reference");
3543 parsed_pointer_t *pointer = &iter->pointer;
3544 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3548 case CONSTRUCT_REFERENCE:
3549 if (is_type_reference(skip_typeref(type)))
3550 errorf(pos, "cannot declare a reference to reference");
3552 type = make_reference_type(type);
3555 case CONSTRUCT_ARRAY: {
3556 if (is_type_reference(skip_typeref(type)))
3557 errorf(pos, "cannot declare an array of references");
3559 parsed_array_t *array = &iter->array;
3560 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3562 expression_t *size_expression = array->size;
3563 if (size_expression != NULL) {
3565 = create_implicit_cast(size_expression, type_size_t);
3568 array_type->base.qualifiers = array->type_qualifiers;
3569 array_type->array.element_type = type;
3570 array_type->array.is_static = array->is_static;
3571 array_type->array.is_variable = array->is_variable;
3572 array_type->array.size_expression = size_expression;
3574 if (size_expression != NULL) {
3575 switch (is_constant_expression(size_expression)) {
3576 case EXPR_CLASS_CONSTANT: {
3577 long const size = fold_constant_to_int(size_expression);
3578 array_type->array.size = size;
3579 array_type->array.size_constant = true;
3580 /* §6.7.5.2:1 If the expression is a constant expression,
3581 * it shall have a value greater than zero. */
3583 errorf(&size_expression->base.pos,
3584 "size of array must be greater than zero");
3585 } else if (size == 0 && !GNU_MODE) {
3586 errorf(&size_expression->base.pos,
3587 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3592 case EXPR_CLASS_VARIABLE:
3593 array_type->array.is_vla = true;
3596 case EXPR_CLASS_ERROR:
3601 type_t *skipped_type = skip_typeref(type);
3603 if (is_type_incomplete(skipped_type)) {
3604 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3605 } else if (is_type_function(skipped_type)) {
3606 errorf(pos, "array of functions is not allowed");
3608 type = identify_new_type(array_type);
3612 internal_errorf(pos, "invalid type construction found");
3618 static type_t *automatic_type_conversion(type_t *orig_type);
3620 static type_t *semantic_parameter(const position_t *pos, type_t *type,
3621 const declaration_specifiers_t *specifiers,
3622 entity_t const *const param)
3624 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3625 * shall be adjusted to ``qualified pointer to type'',
3627 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3628 * type'' shall be adjusted to ``pointer to function
3629 * returning type'', as in 6.3.2.1. */
3630 type = automatic_type_conversion(type);
3632 if (specifiers->is_inline && is_type_valid(type)) {
3633 errorf(pos, "'%N' declared 'inline'", param);
3636 /* §6.9.1:6 The declarations in the declaration list shall contain
3637 * no storage-class specifier other than register and no
3638 * initializations. */
3639 if (specifiers->thread_local || (
3640 specifiers->storage_class != STORAGE_CLASS_NONE &&
3641 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3643 errorf(pos, "invalid storage class for '%N'", param);
3646 /* delay test for incomplete type, because we might have (void)
3647 * which is legal but incomplete... */
3652 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3653 declarator_flags_t flags)
3655 parse_declarator_env_t env;
3656 memset(&env, 0, sizeof(env));
3657 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3659 construct_type_t *construct_type = parse_inner_declarator(&env);
3661 construct_declarator_type(construct_type, specifiers->type);
3662 type_t *type = skip_typeref(orig_type);
3664 if (construct_type != NULL) {
3665 obstack_free(&temp_obst, construct_type);
3668 attribute_t *attributes = parse_attributes(env.attributes);
3669 /* append (shared) specifier attribute behind attributes of this
3671 attribute_t **anchor = &attributes;
3672 while (*anchor != NULL)
3673 anchor = &(*anchor)->next;
3674 *anchor = specifiers->attributes;
3677 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3678 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.pos);
3679 entity->typedefe.type = orig_type;
3681 if (anonymous_entity != NULL) {
3682 if (is_type_compound(type)) {
3683 assert(anonymous_entity->compound.alias == NULL);
3684 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3685 anonymous_entity->kind == ENTITY_UNION);
3686 anonymous_entity->compound.alias = entity;
3687 anonymous_entity = NULL;
3688 } else if (is_type_enum(type)) {
3689 assert(anonymous_entity->enume.alias == NULL);
3690 assert(anonymous_entity->kind == ENTITY_ENUM);
3691 anonymous_entity->enume.alias = entity;
3692 anonymous_entity = NULL;
3696 /* create a declaration type entity */
3697 position_t const *const pos = env.symbol ? &env.pos : &specifiers->pos;
3698 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3699 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3701 if (env.symbol != NULL) {
3702 if (specifiers->is_inline && is_type_valid(type)) {
3703 errorf(&env.pos, "'%N' declared 'inline'", entity);
3706 if (specifiers->thread_local ||
3707 specifiers->storage_class != STORAGE_CLASS_NONE) {
3708 errorf(&env.pos, "'%N' must have no storage class", entity);
3711 } else if (flags & DECL_IS_PARAMETER) {
3712 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3713 orig_type = semantic_parameter(&env.pos, orig_type, specifiers, entity);
3714 } else if (is_type_function(type)) {
3715 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3716 entity->function.is_inline = specifiers->is_inline;
3717 entity->function.elf_visibility = default_visibility;
3718 entity->function.parameters = env.parameters;
3720 if (env.symbol != NULL) {
3721 /* this needs fixes for C++ */
3722 bool in_function_scope = current_function != NULL;
3724 if (specifiers->thread_local || (
3725 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3726 specifiers->storage_class != STORAGE_CLASS_NONE &&
3727 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3729 errorf(&env.pos, "invalid storage class for '%N'", entity);
3733 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3734 entity->variable.elf_visibility = default_visibility;
3735 entity->variable.thread_local = specifiers->thread_local;
3737 if (env.symbol != NULL) {
3738 if (specifiers->is_inline && is_type_valid(type)) {
3739 errorf(&env.pos, "'%N' declared 'inline'", entity);
3742 bool invalid_storage_class = false;
3743 if (current_scope == file_scope) {
3744 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3745 specifiers->storage_class != STORAGE_CLASS_NONE &&
3746 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3747 invalid_storage_class = true;
3750 if (specifiers->thread_local &&
3751 specifiers->storage_class == STORAGE_CLASS_NONE) {
3752 invalid_storage_class = true;
3755 if (invalid_storage_class) {
3756 errorf(&env.pos, "invalid storage class for '%N'", entity);
3761 entity->declaration.type = orig_type;
3762 entity->declaration.alignment = get_type_alignment(orig_type);
3763 entity->declaration.modifiers = env.modifiers;
3764 entity->declaration.attributes = attributes;
3766 storage_class_t storage_class = specifiers->storage_class;
3767 entity->declaration.declared_storage_class = storage_class;
3769 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3770 storage_class = STORAGE_CLASS_AUTO;
3771 entity->declaration.storage_class = storage_class;
3774 if (attributes != NULL) {
3775 handle_entity_attributes(attributes, entity);
3778 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3779 adapt_special_functions(&entity->function);
3785 static type_t *parse_abstract_declarator(type_t *base_type)
3787 parse_declarator_env_t env;
3788 memset(&env, 0, sizeof(env));
3789 env.may_be_abstract = true;
3790 env.must_be_abstract = true;
3792 construct_type_t *construct_type = parse_inner_declarator(&env);
3794 type_t *result = construct_declarator_type(construct_type, base_type);
3795 if (construct_type != NULL) {
3796 obstack_free(&temp_obst, construct_type);
3798 result = handle_type_attributes(env.attributes, result);
3804 * Check if the declaration of main is suspicious. main should be a
3805 * function with external linkage, returning int, taking either zero
3806 * arguments, two, or three arguments of appropriate types, ie.
3808 * int main([ int argc, char **argv [, char **env ] ]).
3810 * @param decl the declaration to check
3811 * @param type the function type of the declaration
3813 static void check_main(const entity_t *entity)
3815 const position_t *pos = &entity->base.pos;
3816 if (entity->kind != ENTITY_FUNCTION) {
3817 warningf(WARN_MAIN, pos, "'main' is not a function");
3821 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3822 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3825 type_t *type = skip_typeref(entity->declaration.type);
3826 assert(is_type_function(type));
3828 function_type_t const *const func_type = &type->function;
3829 type_t *const ret_type = func_type->return_type;
3830 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3831 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3833 const function_parameter_t *parm = func_type->parameters;
3835 type_t *const first_type = skip_typeref(parm->type);
3836 type_t *const first_type_unqual = get_unqualified_type(first_type);
3837 if (!types_compatible(first_type_unqual, type_int)) {
3838 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3842 type_t *const second_type = skip_typeref(parm->type);
3843 type_t *const second_type_unqual
3844 = get_unqualified_type(second_type);
3845 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3846 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3850 type_t *const third_type = skip_typeref(parm->type);
3851 type_t *const third_type_unqual
3852 = get_unqualified_type(third_type);
3853 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3854 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3858 goto warn_arg_count;
3862 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3867 static void error_redefined_as_different_kind(const position_t *pos,
3868 const entity_t *old, entity_kind_t new_kind)
3870 char const *const what = get_entity_kind_name(new_kind);
3871 position_t const *const ppos = &old->base.pos;
3872 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3875 static bool is_entity_valid(entity_t *const ent)
3877 if (is_declaration(ent)) {
3878 return is_type_valid(skip_typeref(ent->declaration.type));
3879 } else if (ent->kind == ENTITY_TYPEDEF) {
3880 return is_type_valid(skip_typeref(ent->typedefe.type));
3885 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3887 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3888 if (attributes_equal(tattr, attr))
3895 * Tests whether new_list contains any attributes not included in old_list
3897 static bool has_new_attributes(const attribute_t *old_list,
3898 const attribute_t *new_list)
3900 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3901 if (!contains_attribute(old_list, attr))
3908 * Merge in attributes from an attribute list (probably from a previous
3909 * declaration with the same name). Warning: destroys the old structure
3910 * of the attribute list - don't reuse attributes after this call.
3912 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3915 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3917 if (contains_attribute(decl->attributes, attr))
3920 /* move attribute to new declarations attributes list */
3921 attr->next = decl->attributes;
3922 decl->attributes = attr;
3926 static bool is_main(entity_t*);
3929 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3930 * for various problems that occur for multiple definitions
3932 entity_t *record_entity(entity_t *entity, const bool is_definition)
3934 const symbol_t *const symbol = entity->base.symbol;
3935 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3936 const position_t *pos = &entity->base.pos;
3938 /* can happen in error cases */
3942 assert(!entity->base.parent_scope);
3943 assert(current_scope);
3944 entity->base.parent_scope = current_scope;
3946 entity_t *const previous_entity = get_entity(symbol, namespc);
3947 /* pushing the same entity twice will break the stack structure */
3948 assert(previous_entity != entity);
3950 if (entity->kind == ENTITY_FUNCTION) {
3951 type_t *const orig_type = entity->declaration.type;
3952 type_t *const type = skip_typeref(orig_type);
3954 assert(is_type_function(type));
3955 if (type->function.unspecified_parameters &&
3956 previous_entity == NULL &&
3957 !entity->declaration.implicit) {
3958 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3961 if (is_main(entity)) {
3966 if (is_declaration(entity) &&
3967 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3968 current_scope != file_scope &&
3969 !entity->declaration.implicit) {
3970 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3973 if (previous_entity != NULL) {
3974 position_t const *const ppos = &previous_entity->base.pos;
3976 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3977 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3978 assert(previous_entity->kind == ENTITY_PARAMETER);
3979 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3983 if (previous_entity->base.parent_scope == current_scope) {
3984 if (previous_entity->kind != entity->kind) {
3985 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3986 error_redefined_as_different_kind(pos, previous_entity,
3991 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3992 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3995 if (previous_entity->kind == ENTITY_TYPEDEF) {
3996 type_t *const type = skip_typeref(entity->typedefe.type);
3997 type_t *const prev_type
3998 = skip_typeref(previous_entity->typedefe.type);
3999 if (c_mode & _CXX) {
4000 /* C++ allows double typedef if they are identical
4001 * (after skipping typedefs) */
4002 if (type == prev_type)
4005 /* GCC extension: redef in system headers is allowed */
4006 if ((pos->is_system_header || ppos->is_system_header) &&
4007 types_compatible(type, prev_type))
4010 errorf(pos, "redefinition of '%N' (declared %P)",
4015 /* at this point we should have only VARIABLES or FUNCTIONS */
4016 assert(is_declaration(previous_entity) && is_declaration(entity));
4018 declaration_t *const prev_decl = &previous_entity->declaration;
4019 declaration_t *const decl = &entity->declaration;
4021 /* can happen for K&R style declarations */
4022 if (prev_decl->type == NULL &&
4023 previous_entity->kind == ENTITY_PARAMETER &&
4024 entity->kind == ENTITY_PARAMETER) {
4025 prev_decl->type = decl->type;
4026 prev_decl->storage_class = decl->storage_class;
4027 prev_decl->declared_storage_class = decl->declared_storage_class;
4028 prev_decl->modifiers = decl->modifiers;
4029 return previous_entity;
4032 type_t *const type = skip_typeref(decl->type);
4033 type_t *const prev_type = skip_typeref(prev_decl->type);
4035 if (!types_compatible(type, prev_type)) {
4036 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4038 unsigned old_storage_class = prev_decl->storage_class;
4040 if (is_definition &&
4042 !(prev_decl->modifiers & DM_USED) &&
4043 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4044 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4047 storage_class_t new_storage_class = decl->storage_class;
4049 /* pretend no storage class means extern for function
4050 * declarations (except if the previous declaration is neither
4051 * none nor extern) */
4052 if (entity->kind == ENTITY_FUNCTION) {
4053 /* the previous declaration could have unspecified parameters or
4054 * be a typedef, so use the new type */
4055 if (prev_type->function.unspecified_parameters || is_definition)
4056 prev_decl->type = type;
4058 switch (old_storage_class) {
4059 case STORAGE_CLASS_NONE:
4060 old_storage_class = STORAGE_CLASS_EXTERN;
4063 case STORAGE_CLASS_EXTERN:
4064 if (is_definition) {
4065 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4066 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4068 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4069 new_storage_class = STORAGE_CLASS_EXTERN;
4076 } else if (is_type_incomplete(prev_type)) {
4077 prev_decl->type = type;
4080 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4081 new_storage_class == STORAGE_CLASS_EXTERN) {
4083 warn_redundant_declaration: ;
4085 = has_new_attributes(prev_decl->attributes,
4087 if (has_new_attrs) {
4088 merge_in_attributes(decl, prev_decl->attributes);
4089 } else if (!is_definition &&
4090 is_type_valid(prev_type) &&
4091 !pos->is_system_header) {
4092 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4094 } else if (current_function == NULL) {
4095 if (old_storage_class != STORAGE_CLASS_STATIC &&
4096 new_storage_class == STORAGE_CLASS_STATIC) {
4097 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4098 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4099 prev_decl->storage_class = STORAGE_CLASS_NONE;
4100 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4102 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4104 goto error_redeclaration;
4105 goto warn_redundant_declaration;
4107 } else if (is_type_valid(prev_type)) {
4108 if (old_storage_class == new_storage_class) {
4109 error_redeclaration:
4110 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4112 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4117 prev_decl->modifiers |= decl->modifiers;
4118 if (entity->kind == ENTITY_FUNCTION) {
4119 previous_entity->function.is_inline |= entity->function.is_inline;
4121 return previous_entity;
4125 if (is_warn_on(why = WARN_SHADOW) ||
4126 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4127 char const *const what = get_entity_kind_name(previous_entity->kind);
4128 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4132 if (entity->kind == ENTITY_FUNCTION) {
4133 if (is_definition &&
4134 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4136 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4137 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4139 goto warn_missing_declaration;
4142 } else if (entity->kind == ENTITY_VARIABLE) {
4143 if (current_scope == file_scope &&
4144 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4145 !entity->declaration.implicit) {
4146 warn_missing_declaration:
4147 if (is_type_valid(skip_typeref(entity->declaration.type)))
4148 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4153 environment_push(entity);
4154 append_entity(current_scope, entity);
4159 static void parser_error_multiple_definition(entity_t *entity,
4160 const position_t *pos)
4162 errorf(pos, "redefinition of '%N' (declared %P)", entity, &entity->base.pos);
4165 static bool is_declaration_specifier(const token_t *token)
4167 switch (token->kind) {
4171 return is_typedef_symbol(token->base.symbol);
4178 static void parse_init_declarator_rest(entity_t *entity)
4180 type_t *orig_type = type_error_type;
4182 if (entity->base.kind == ENTITY_TYPEDEF) {
4183 position_t const *const pos = &entity->base.pos;
4184 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4186 assert(is_declaration(entity));
4187 orig_type = entity->declaration.type;
4190 type_t *type = skip_typeref(orig_type);
4192 if (entity->kind == ENTITY_VARIABLE
4193 && entity->variable.initializer != NULL) {
4194 parser_error_multiple_definition(entity, HERE);
4198 declaration_t *const declaration = &entity->declaration;
4199 bool must_be_constant = false;
4200 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4201 entity->base.parent_scope == file_scope) {
4202 must_be_constant = true;
4205 if (is_type_function(type)) {
4206 position_t const *const pos = &entity->base.pos;
4207 errorf(pos, "'%N' is initialized like a variable", entity);
4208 orig_type = type_error_type;
4211 parse_initializer_env_t env;
4212 env.type = orig_type;
4213 env.must_be_constant = must_be_constant;
4214 env.entity = entity;
4216 initializer_t *initializer = parse_initializer(&env);
4218 if (entity->kind == ENTITY_VARIABLE) {
4219 /* §6.7.5:22 array initializers for arrays with unknown size
4220 * determine the array type size */
4221 declaration->type = env.type;
4222 entity->variable.initializer = initializer;
4226 /* parse rest of a declaration without any declarator */
4227 static void parse_anonymous_declaration_rest(
4228 const declaration_specifiers_t *specifiers)
4231 anonymous_entity = NULL;
4233 position_t const *const pos = &specifiers->pos;
4234 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4235 specifiers->thread_local) {
4236 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4239 type_t *type = specifiers->type;
4240 switch (type->kind) {
4241 case TYPE_COMPOUND_STRUCT:
4242 case TYPE_COMPOUND_UNION: {
4243 if (type->compound.compound->base.symbol == NULL) {
4244 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4253 warningf(WARN_OTHER, pos, "empty declaration");
4258 static void check_variable_type_complete(entity_t *ent)
4260 if (ent->kind != ENTITY_VARIABLE)
4263 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4264 * type for the object shall be complete [...] */
4265 declaration_t *decl = &ent->declaration;
4266 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4267 decl->storage_class == STORAGE_CLASS_STATIC)
4270 type_t *const type = skip_typeref(decl->type);
4271 if (!is_type_incomplete(type))
4274 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4275 * are given length one. */
4276 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4277 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4281 errorf(&ent->base.pos, "variable '%#N' has incomplete type", ent);
4285 static void parse_declaration_rest(entity_t *ndeclaration,
4286 const declaration_specifiers_t *specifiers,
4287 parsed_declaration_func finished_declaration,
4288 declarator_flags_t flags)
4290 add_anchor_token(';');
4291 add_anchor_token(',');
4293 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4295 if (token.kind == '=') {
4296 parse_init_declarator_rest(entity);
4297 } else if (entity->kind == ENTITY_VARIABLE) {
4298 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4299 * [...] where the extern specifier is explicitly used. */
4300 declaration_t *decl = &entity->declaration;
4301 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4302 is_type_reference(skip_typeref(decl->type))) {
4303 position_t const *const pos = &entity->base.pos;
4304 errorf(pos, "reference '%#N' must be initialized", entity);
4308 check_variable_type_complete(entity);
4313 add_anchor_token('=');
4314 ndeclaration = parse_declarator(specifiers, flags);
4315 rem_anchor_token('=');
4317 rem_anchor_token(',');
4318 rem_anchor_token(';');
4321 anonymous_entity = NULL;
4324 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4326 symbol_t *symbol = entity->base.symbol;
4330 assert(entity->base.namespc == NAMESPACE_NORMAL);
4331 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4332 if (previous_entity == NULL
4333 || previous_entity->base.parent_scope != current_scope) {
4334 errorf(&entity->base.pos, "expected declaration of a function parameter, found '%Y'",
4339 if (is_definition) {
4340 errorf(HERE, "'%N' is initialised", entity);
4343 return record_entity(entity, false);
4346 static void parse_declaration(parsed_declaration_func finished_declaration,
4347 declarator_flags_t flags)
4349 add_anchor_token(';');
4350 declaration_specifiers_t specifiers;
4351 parse_declaration_specifiers(&specifiers);
4352 rem_anchor_token(';');
4354 if (token.kind == ';') {
4355 parse_anonymous_declaration_rest(&specifiers);
4357 entity_t *entity = parse_declarator(&specifiers, flags);
4358 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4363 static type_t *get_default_promoted_type(type_t *orig_type)
4365 type_t *result = orig_type;
4367 type_t *type = skip_typeref(orig_type);
4368 if (is_type_integer(type)) {
4369 result = promote_integer(type);
4370 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4371 result = type_double;
4377 static void parse_kr_declaration_list(entity_t *entity)
4379 if (entity->kind != ENTITY_FUNCTION)
4382 type_t *type = skip_typeref(entity->declaration.type);
4383 assert(is_type_function(type));
4384 if (!type->function.kr_style_parameters)
4387 add_anchor_token('{');
4389 PUSH_SCOPE(&entity->function.parameters);
4391 entity_t *parameter = entity->function.parameters.entities;
4392 for ( ; parameter != NULL; parameter = parameter->base.next) {
4393 assert(parameter->base.parent_scope == NULL);
4394 parameter->base.parent_scope = current_scope;
4395 environment_push(parameter);
4398 /* parse declaration list */
4400 switch (token.kind) {
4402 /* This covers symbols, which are no type, too, and results in
4403 * better error messages. The typical cases are misspelled type
4404 * names and missing includes. */
4406 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4416 /* update function type */
4417 type_t *new_type = duplicate_type(type);
4419 function_parameter_t *parameters = NULL;
4420 function_parameter_t **anchor = ¶meters;
4422 /* did we have an earlier prototype? */
4423 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4424 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4427 function_parameter_t *proto_parameter = NULL;
4428 if (proto_type != NULL) {
4429 type_t *proto_type_type = proto_type->declaration.type;
4430 proto_parameter = proto_type_type->function.parameters;
4431 /* If a K&R function definition has a variadic prototype earlier, then
4432 * make the function definition variadic, too. This should conform to
4433 * §6.7.5.3:15 and §6.9.1:8. */
4434 new_type->function.variadic = proto_type_type->function.variadic;
4436 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4438 new_type->function.unspecified_parameters = true;
4441 bool need_incompatible_warning = false;
4442 parameter = entity->function.parameters.entities;
4443 for (; parameter != NULL; parameter = parameter->base.next,
4445 proto_parameter == NULL ? NULL : proto_parameter->next) {
4446 if (parameter->kind != ENTITY_PARAMETER)
4449 type_t *parameter_type = parameter->declaration.type;
4450 if (parameter_type == NULL) {
4451 position_t const* const pos = ¶meter->base.pos;
4453 errorf(pos, "no type specified for function '%N'", parameter);
4454 parameter_type = type_error_type;
4456 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4457 parameter_type = type_int;
4459 parameter->declaration.type = parameter_type;
4462 semantic_parameter_incomplete(parameter);
4464 /* we need the default promoted types for the function type */
4465 type_t *not_promoted = parameter_type;
4466 parameter_type = get_default_promoted_type(parameter_type);
4468 /* gcc special: if the type of the prototype matches the unpromoted
4469 * type don't promote */
4470 if (!strict_mode && proto_parameter != NULL) {
4471 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4472 type_t *promo_skip = skip_typeref(parameter_type);
4473 type_t *param_skip = skip_typeref(not_promoted);
4474 if (!types_compatible(proto_p_type, promo_skip)
4475 && types_compatible(proto_p_type, param_skip)) {
4477 need_incompatible_warning = true;
4478 parameter_type = not_promoted;
4481 function_parameter_t *const function_parameter
4482 = allocate_parameter(parameter_type);
4484 *anchor = function_parameter;
4485 anchor = &function_parameter->next;
4488 new_type->function.parameters = parameters;
4489 new_type = identify_new_type(new_type);
4491 if (need_incompatible_warning) {
4492 symbol_t const *const sym = entity->base.symbol;
4493 position_t const *const pos = &entity->base.pos;
4494 position_t const *const ppos = &proto_type->base.pos;
4495 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4497 entity->declaration.type = new_type;
4499 rem_anchor_token('{');
4502 static bool first_err = true;
4505 * When called with first_err set, prints the name of the current function,
4508 static void print_in_function(void)
4512 char const *const file = current_function->base.base.pos.input_name;
4513 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4518 * Check if all labels are defined in the current function.
4519 * Check if all labels are used in the current function.
4521 static void check_labels(void)
4523 for (const goto_statement_t *goto_statement = goto_first;
4524 goto_statement != NULL;
4525 goto_statement = goto_statement->next) {
4526 label_t *label = goto_statement->label;
4527 if (label->base.pos.input_name == NULL) {
4528 print_in_function();
4529 position_t const *const pos = &goto_statement->base.pos;
4530 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4534 if (is_warn_on(WARN_UNUSED_LABEL)) {
4535 for (const label_statement_t *label_statement = label_first;
4536 label_statement != NULL;
4537 label_statement = label_statement->next) {
4538 label_t *label = label_statement->label;
4540 if (! label->used) {
4541 print_in_function();
4542 position_t const *const pos = &label_statement->base.pos;
4543 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4549 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4551 entity_t const *const end = last != NULL ? last->base.next : NULL;
4552 for (; entity != end; entity = entity->base.next) {
4553 if (!is_declaration(entity))
4556 declaration_t *declaration = &entity->declaration;
4557 if (declaration->implicit)
4560 if (!declaration->used) {
4561 print_in_function();
4562 warningf(why, &entity->base.pos, "'%N' is unused", entity);
4563 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4564 print_in_function();
4565 warningf(why, &entity->base.pos, "'%N' is never read", entity);
4570 static void check_unused_variables(statement_t *const stmt, void *const env)
4574 switch (stmt->kind) {
4575 case STATEMENT_DECLARATION: {
4576 declaration_statement_t const *const decls = &stmt->declaration;
4577 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4582 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4591 * Check declarations of current_function for unused entities.
4593 static void check_declarations(void)
4595 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4596 const scope_t *scope = ¤t_function->parameters;
4597 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4599 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4600 walk_statements(current_function->body, check_unused_variables, NULL);
4604 static int determine_truth(expression_t const* const cond)
4607 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4608 fold_constant_to_bool(cond) ? 1 :
4612 static void check_reachable(statement_t *);
4613 static bool reaches_end;
4615 static bool expression_returns(expression_t const *const expr)
4617 switch (expr->kind) {
4619 expression_t const *const func = expr->call.function;
4620 type_t const *const type = skip_typeref(func->base.type);
4621 if (type->kind == TYPE_POINTER) {
4622 type_t const *const points_to
4623 = skip_typeref(type->pointer.points_to);
4624 if (points_to->kind == TYPE_FUNCTION
4625 && points_to->function.modifiers & DM_NORETURN)
4629 if (!expression_returns(func))
4632 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4633 if (!expression_returns(arg->expression))
4640 case EXPR_REFERENCE:
4641 case EXPR_ENUM_CONSTANT:
4642 case EXPR_LITERAL_CASES:
4643 case EXPR_LITERAL_CHARACTER:
4644 case EXPR_STRING_LITERAL:
4645 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4646 case EXPR_LABEL_ADDRESS:
4647 case EXPR_CLASSIFY_TYPE:
4648 case EXPR_SIZEOF: // TODO handle obscure VLA case
4651 case EXPR_BUILTIN_CONSTANT_P:
4652 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4657 case EXPR_STATEMENT: {
4658 bool old_reaches_end = reaches_end;
4659 reaches_end = false;
4660 check_reachable(expr->statement.statement);
4661 bool returns = reaches_end;
4662 reaches_end = old_reaches_end;
4666 case EXPR_CONDITIONAL:
4667 // TODO handle constant expression
4669 if (!expression_returns(expr->conditional.condition))
4672 if (expr->conditional.true_expression != NULL
4673 && expression_returns(expr->conditional.true_expression))
4676 return expression_returns(expr->conditional.false_expression);
4679 return expression_returns(expr->select.compound);
4681 case EXPR_ARRAY_ACCESS:
4683 expression_returns(expr->array_access.array_ref) &&
4684 expression_returns(expr->array_access.index);
4687 return expression_returns(expr->va_starte.ap);
4690 return expression_returns(expr->va_arge.ap);
4693 return expression_returns(expr->va_copye.src);
4695 case EXPR_UNARY_CASES_MANDATORY:
4696 return expression_returns(expr->unary.value);
4698 case EXPR_UNARY_THROW:
4701 case EXPR_BINARY_CASES:
4702 // TODO handle constant lhs of && and ||
4704 expression_returns(expr->binary.left) &&
4705 expression_returns(expr->binary.right);
4708 panic("unhandled expression");
4711 static bool initializer_returns(initializer_t const *const init)
4713 switch (init->kind) {
4714 case INITIALIZER_VALUE:
4715 return expression_returns(init->value.value);
4717 case INITIALIZER_LIST: {
4718 initializer_t * const* i = init->list.initializers;
4719 initializer_t * const* const end = i + init->list.len;
4720 bool returns = true;
4721 for (; i != end; ++i) {
4722 if (!initializer_returns(*i))
4728 case INITIALIZER_STRING:
4729 case INITIALIZER_DESIGNATOR: // designators have no payload
4732 panic("unhandled initializer");
4735 static bool noreturn_candidate;
4737 static void check_reachable(statement_t *const stmt)
4739 if (stmt->base.reachable)
4741 if (stmt->kind != STATEMENT_DO_WHILE)
4742 stmt->base.reachable = true;
4744 statement_t *last = stmt;
4746 switch (stmt->kind) {
4747 case STATEMENT_ERROR:
4748 case STATEMENT_EMPTY:
4750 next = stmt->base.next;
4753 case STATEMENT_DECLARATION: {
4754 declaration_statement_t const *const decl = &stmt->declaration;
4755 entity_t const * ent = decl->declarations_begin;
4756 entity_t const *const last_decl = decl->declarations_end;
4758 for (;; ent = ent->base.next) {
4759 if (ent->kind == ENTITY_VARIABLE &&
4760 ent->variable.initializer != NULL &&
4761 !initializer_returns(ent->variable.initializer)) {
4764 if (ent == last_decl)
4768 next = stmt->base.next;
4772 case STATEMENT_COMPOUND:
4773 next = stmt->compound.statements;
4775 next = stmt->base.next;
4778 case STATEMENT_RETURN: {
4779 expression_t const *const val = stmt->returns.value;
4780 if (val == NULL || expression_returns(val))
4781 noreturn_candidate = false;
4785 case STATEMENT_IF: {
4786 if_statement_t const *const ifs = &stmt->ifs;
4787 expression_t const *const cond = ifs->condition;
4789 if (!expression_returns(cond))
4792 int const val = determine_truth(cond);
4795 check_reachable(ifs->true_statement);
4800 if (ifs->false_statement != NULL) {
4801 check_reachable(ifs->false_statement);
4805 next = stmt->base.next;
4809 case STATEMENT_SWITCH: {
4810 switch_statement_t const *const switchs = &stmt->switchs;
4811 expression_t const *const expr = switchs->expression;
4813 if (!expression_returns(expr))
4816 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4817 ir_tarval *const val = fold_constant_to_tarval(expr);
4818 case_label_statement_t * defaults = NULL;
4819 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4820 if (i->expression == NULL) {
4825 if (i->first_case == val || i->last_case == val ||
4826 ((tarval_cmp(i->first_case, val) & ir_relation_less_equal)
4827 && (tarval_cmp(val, i->last_case) & ir_relation_less_equal))) {
4828 check_reachable((statement_t*)i);
4833 if (defaults != NULL) {
4834 check_reachable((statement_t*)defaults);
4838 bool has_default = false;
4839 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4840 if (i->expression == NULL)
4843 check_reachable((statement_t*)i);
4850 next = stmt->base.next;
4854 case STATEMENT_EXPRESSION: {
4855 /* Check for noreturn function call */
4856 expression_t const *const expr = stmt->expression.expression;
4857 if (!expression_returns(expr))
4860 next = stmt->base.next;
4864 case STATEMENT_CONTINUE:
4865 for (statement_t *parent = stmt;;) {
4866 parent = parent->base.parent;
4867 if (parent == NULL) /* continue not within loop */
4871 switch (parent->kind) {
4872 case STATEMENT_DO_WHILE: goto continue_do_while;
4873 case STATEMENT_FOR: goto continue_for;
4879 case STATEMENT_BREAK:
4880 for (statement_t *parent = stmt;;) {
4881 parent = parent->base.parent;
4882 if (parent == NULL) /* break not within loop/switch */
4885 switch (parent->kind) {
4886 case STATEMENT_SWITCH:
4887 case STATEMENT_DO_WHILE:
4890 next = parent->base.next;
4891 goto found_break_parent;
4899 case STATEMENT_COMPUTED_GOTO: {
4900 if (!expression_returns(stmt->computed_goto.expression))
4903 statement_t *parent = stmt->base.parent;
4904 if (parent == NULL) /* top level goto */
4910 case STATEMENT_GOTO:
4911 next = stmt->gotos.label->statement;
4912 if (next == NULL) /* missing label */
4916 case STATEMENT_LABEL:
4917 next = stmt->label.statement;
4920 case STATEMENT_CASE_LABEL:
4921 next = stmt->case_label.statement;
4924 case STATEMENT_DO_WHILE:
4925 next = stmt->do_while.body;
4928 case STATEMENT_FOR: {
4929 for_statement_t *const fors = &stmt->fors;
4931 if (fors->condition_reachable)
4933 fors->condition_reachable = true;
4935 expression_t const *const cond = fors->condition;
4940 } else if (expression_returns(cond)) {
4941 val = determine_truth(cond);
4947 check_reachable(fors->body);
4952 next = stmt->base.next;
4956 case STATEMENT_MS_TRY: {
4957 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4958 check_reachable(ms_try->try_statement);
4959 next = ms_try->final_statement;
4963 case STATEMENT_LEAVE: {
4964 statement_t *parent = stmt;
4966 parent = parent->base.parent;
4967 if (parent == NULL) /* __leave not within __try */
4970 if (parent->kind == STATEMENT_MS_TRY) {
4972 next = parent->ms_try.final_statement;
4980 panic("invalid statement kind");
4983 while (next == NULL) {
4984 next = last->base.parent;
4986 noreturn_candidate = false;
4988 type_t *const type = skip_typeref(current_function->base.type);
4989 assert(is_type_function(type));
4990 type_t *const ret = skip_typeref(type->function.return_type);
4991 if (!is_type_void(ret) &&
4992 is_type_valid(ret) &&
4993 !is_main(current_entity)) {
4994 position_t const *const pos = &stmt->base.pos;
4995 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5000 switch (next->kind) {
5001 case STATEMENT_ERROR:
5002 case STATEMENT_EMPTY:
5003 case STATEMENT_DECLARATION:
5004 case STATEMENT_EXPRESSION:
5006 case STATEMENT_RETURN:
5007 case STATEMENT_CONTINUE:
5008 case STATEMENT_BREAK:
5009 case STATEMENT_COMPUTED_GOTO:
5010 case STATEMENT_GOTO:
5011 case STATEMENT_LEAVE:
5012 panic("invalid control flow in function");
5014 case STATEMENT_COMPOUND:
5015 if (next->compound.stmt_expr) {
5021 case STATEMENT_SWITCH:
5022 case STATEMENT_LABEL:
5023 case STATEMENT_CASE_LABEL:
5025 next = next->base.next;
5028 case STATEMENT_DO_WHILE: {
5030 if (next->base.reachable)
5032 next->base.reachable = true;
5034 do_while_statement_t const *const dw = &next->do_while;
5035 expression_t const *const cond = dw->condition;
5037 if (!expression_returns(cond))
5040 int const val = determine_truth(cond);
5043 check_reachable(dw->body);
5049 next = next->base.next;
5053 case STATEMENT_FOR: {
5055 for_statement_t *const fors = &next->fors;
5057 fors->step_reachable = true;
5059 if (fors->condition_reachable)
5061 fors->condition_reachable = true;
5063 expression_t const *const cond = fors->condition;
5068 } else if (expression_returns(cond)) {
5069 val = determine_truth(cond);
5075 check_reachable(fors->body);
5081 next = next->base.next;
5085 case STATEMENT_MS_TRY:
5087 next = next->ms_try.final_statement;
5092 check_reachable(next);
5095 static void check_unreachable(statement_t* const stmt, void *const env)
5099 switch (stmt->kind) {
5100 case STATEMENT_DO_WHILE:
5101 if (!stmt->base.reachable) {
5102 expression_t const *const cond = stmt->do_while.condition;
5103 if (determine_truth(cond) >= 0) {
5104 position_t const *const pos = &cond->base.pos;
5105 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5110 case STATEMENT_FOR: {
5111 for_statement_t const* const fors = &stmt->fors;
5113 // if init and step are unreachable, cond is unreachable, too
5114 if (!stmt->base.reachable && !fors->step_reachable) {
5115 goto warn_unreachable;
5117 if (!stmt->base.reachable && fors->initialisation != NULL) {
5118 position_t const *const pos = &fors->initialisation->base.pos;
5119 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5122 if (!fors->condition_reachable && fors->condition != NULL) {
5123 position_t const *const pos = &fors->condition->base.pos;
5124 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5127 if (!fors->step_reachable && fors->step != NULL) {
5128 position_t const *const pos = &fors->step->base.pos;
5129 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5135 case STATEMENT_COMPOUND:
5136 if (stmt->compound.statements != NULL)
5138 goto warn_unreachable;
5140 case STATEMENT_DECLARATION: {
5141 /* Only warn if there is at least one declarator with an initializer.
5142 * This typically occurs in switch statements. */
5143 declaration_statement_t const *const decl = &stmt->declaration;
5144 entity_t const * ent = decl->declarations_begin;
5145 entity_t const *const last = decl->declarations_end;
5147 for (;; ent = ent->base.next) {
5148 if (ent->kind == ENTITY_VARIABLE &&
5149 ent->variable.initializer != NULL) {
5150 goto warn_unreachable;
5160 if (!stmt->base.reachable) {
5161 position_t const *const pos = &stmt->base.pos;
5162 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5168 static bool is_main(entity_t *entity)
5170 static symbol_t *sym_main = NULL;
5171 if (sym_main == NULL) {
5172 sym_main = symbol_table_insert("main");
5175 if (entity->base.symbol != sym_main)
5177 /* must be in outermost scope */
5178 if (entity->base.parent_scope != file_scope)
5184 static void prepare_main_collect2(entity_t*);
5186 static void parse_external_declaration(void)
5188 /* function-definitions and declarations both start with declaration
5190 add_anchor_token(';');
5191 declaration_specifiers_t specifiers;
5192 parse_declaration_specifiers(&specifiers);
5193 rem_anchor_token(';');
5195 /* must be a declaration */
5196 if (token.kind == ';') {
5197 parse_anonymous_declaration_rest(&specifiers);
5201 add_anchor_token(',');
5202 add_anchor_token('=');
5203 add_anchor_token(';');
5204 add_anchor_token('{');
5206 /* declarator is common to both function-definitions and declarations */
5207 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5209 rem_anchor_token('{');
5210 rem_anchor_token(';');
5211 rem_anchor_token('=');
5212 rem_anchor_token(',');
5214 /* must be a declaration */
5215 switch (token.kind) {
5219 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5224 /* must be a function definition */
5225 parse_kr_declaration_list(ndeclaration);
5227 if (token.kind != '{') {
5228 parse_error_expected("while parsing function definition", '{', NULL);
5229 eat_until_matching_token(';');
5233 assert(is_declaration(ndeclaration));
5234 type_t *const orig_type = ndeclaration->declaration.type;
5235 type_t * type = skip_typeref(orig_type);
5237 if (!is_type_function(type)) {
5238 if (is_type_valid(type)) {
5239 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5245 position_t const *const pos = &ndeclaration->base.pos;
5246 if (is_typeref(orig_type)) {
5248 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5251 if (is_type_compound(skip_typeref(type->function.return_type))) {
5252 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5254 if (type->function.unspecified_parameters) {
5255 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5257 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5260 /* §6.7.5.3:14 a function definition with () means no
5261 * parameters (and not unspecified parameters) */
5262 if (type->function.unspecified_parameters &&
5263 type->function.parameters == NULL) {
5264 type_t *copy = duplicate_type(type);
5265 copy->function.unspecified_parameters = false;
5266 type = identify_new_type(copy);
5268 ndeclaration->declaration.type = type;
5271 entity_t *const entity = record_entity(ndeclaration, true);
5272 assert(entity->kind == ENTITY_FUNCTION);
5273 assert(ndeclaration->kind == ENTITY_FUNCTION);
5275 function_t *const function = &entity->function;
5276 if (ndeclaration != entity) {
5277 function->parameters = ndeclaration->function.parameters;
5280 PUSH_SCOPE(&function->parameters);
5282 entity_t *parameter = function->parameters.entities;
5283 for (; parameter != NULL; parameter = parameter->base.next) {
5284 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5285 parameter->base.parent_scope = current_scope;
5287 assert(parameter->base.parent_scope == NULL
5288 || parameter->base.parent_scope == current_scope);
5289 parameter->base.parent_scope = current_scope;
5290 if (parameter->base.symbol == NULL) {
5291 errorf(¶meter->base.pos, "parameter name omitted");
5294 environment_push(parameter);
5297 if (function->body != NULL) {
5298 parser_error_multiple_definition(entity, HERE);
5301 /* parse function body */
5302 int label_stack_top = label_top();
5303 function_t *old_current_function = current_function;
5304 current_function = function;
5305 PUSH_CURRENT_ENTITY(entity);
5309 goto_anchor = &goto_first;
5311 label_anchor = &label_first;
5313 statement_t *const body = parse_compound_statement(false);
5314 function->body = body;
5317 check_declarations();
5318 if (is_warn_on(WARN_RETURN_TYPE) ||
5319 is_warn_on(WARN_UNREACHABLE_CODE) ||
5320 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5321 noreturn_candidate = true;
5322 check_reachable(body);
5323 if (is_warn_on(WARN_UNREACHABLE_CODE))
5324 walk_statements(body, check_unreachable, NULL);
5325 if (noreturn_candidate &&
5326 !(function->base.modifiers & DM_NORETURN)) {
5327 position_t const *const pos = &body->base.pos;
5328 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5332 if (is_main(entity)) {
5333 /* Force main to C linkage. */
5334 type_t *const type = entity->declaration.type;
5335 assert(is_type_function(type));
5336 if (type->function.linkage != LINKAGE_C) {
5337 type_t *new_type = duplicate_type(type);
5338 new_type->function.linkage = LINKAGE_C;
5339 entity->declaration.type = identify_new_type(new_type);
5342 if (enable_main_collect2_hack)
5343 prepare_main_collect2(entity);
5346 POP_CURRENT_ENTITY();
5348 assert(current_function == function);
5349 current_function = old_current_function;
5350 label_pop_to(label_stack_top);
5356 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5358 entity_t *iter = compound->members.entities;
5359 for (; iter != NULL; iter = iter->base.next) {
5360 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5363 if (iter->base.symbol == symbol) {
5365 } else if (iter->base.symbol == NULL) {
5366 /* search in anonymous structs and unions */
5367 type_t *type = skip_typeref(iter->declaration.type);
5368 if (is_type_compound(type)) {
5369 if (find_compound_entry(type->compound.compound, symbol)
5380 static void check_deprecated(const position_t *pos, const entity_t *entity)
5382 if (!is_declaration(entity))
5384 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5387 position_t const *const epos = &entity->base.pos;
5388 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5390 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5392 warningf(WARN_DEPRECATED_DECLARATIONS, pos, "'%N' is deprecated (declared %P)", entity, epos);
5397 static expression_t *create_select(const position_t *pos, expression_t *addr,
5398 type_qualifiers_t qualifiers,
5401 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5403 check_deprecated(pos, entry);
5405 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5406 select->select.compound = addr;
5407 select->select.compound_entry = entry;
5409 type_t *entry_type = entry->declaration.type;
5410 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5412 /* bitfields need special treatment */
5413 if (entry->compound_member.bitfield) {
5414 unsigned bit_size = entry->compound_member.bit_size;
5415 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5416 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5417 res_type = type_int;
5421 /* we always do the auto-type conversions; the & and sizeof parser contains
5422 * code to revert this! */
5423 select->base.type = automatic_type_conversion(res_type);
5430 * Find entry with symbol in compound. Search anonymous structs and unions and
5431 * creates implicit select expressions for them.
5432 * Returns the adress for the innermost compound.
5434 static expression_t *find_create_select(const position_t *pos,
5436 type_qualifiers_t qualifiers,
5437 compound_t *compound, symbol_t *symbol)
5439 entity_t *iter = compound->members.entities;
5440 for (; iter != NULL; iter = iter->base.next) {
5441 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5444 symbol_t *iter_symbol = iter->base.symbol;
5445 if (iter_symbol == NULL) {
5446 type_t *type = iter->declaration.type;
5447 if (!is_type_compound(type))
5450 compound_t *sub_compound = type->compound.compound;
5452 if (find_compound_entry(sub_compound, symbol) == NULL)
5455 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5456 sub_addr->base.pos = *pos;
5457 sub_addr->base.implicit = true;
5458 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5462 if (iter_symbol == symbol) {
5463 return create_select(pos, addr, qualifiers, iter);
5470 static void parse_bitfield_member(entity_t *entity)
5474 expression_t *size = parse_constant_expression();
5477 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5478 type_t *type = entity->declaration.type;
5479 if (!is_type_integer(skip_typeref(type))) {
5480 errorf(HERE, "bitfield base type '%T' is not an integer type",
5484 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5485 /* error already reported by parse_constant_expression */
5486 size_long = get_type_size(type) * 8;
5488 size_long = fold_constant_to_int(size);
5490 const symbol_t *symbol = entity->base.symbol;
5491 const symbol_t *user_symbol
5492 = symbol == NULL ? sym_anonymous : symbol;
5493 unsigned bit_size = get_type_size(type) * 8;
5494 if (size_long < 0) {
5495 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5496 } else if (size_long == 0 && symbol != NULL) {
5497 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5498 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5499 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5502 /* hope that people don't invent crazy types with more bits
5503 * than our struct can hold */
5505 (1 << sizeof(entity->compound_member.bit_size)*8));
5509 entity->compound_member.bitfield = true;
5510 entity->compound_member.bit_size = (unsigned char)size_long;
5513 static void parse_compound_declarators(compound_t *compound,
5514 const declaration_specifiers_t *specifiers)
5516 add_anchor_token(';');
5517 add_anchor_token(',');
5521 if (token.kind == ':') {
5522 /* anonymous bitfield */
5523 type_t *type = specifiers->type;
5524 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5525 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5526 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5527 entity->declaration.type = type;
5529 parse_bitfield_member(entity);
5531 attribute_t *attributes = parse_attributes(NULL);
5532 attribute_t **anchor = &attributes;
5533 while (*anchor != NULL)
5534 anchor = &(*anchor)->next;
5535 *anchor = specifiers->attributes;
5536 if (attributes != NULL) {
5537 handle_entity_attributes(attributes, entity);
5539 entity->declaration.attributes = attributes;
5541 append_entity(&compound->members, entity);
5543 entity = parse_declarator(specifiers,
5544 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5545 position_t const *const pos = &entity->base.pos;
5546 if (entity->kind == ENTITY_TYPEDEF) {
5547 errorf(pos, "typedef not allowed as compound member");
5549 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5551 /* make sure we don't define a symbol multiple times */
5552 symbol_t *symbol = entity->base.symbol;
5553 if (symbol != NULL) {
5554 entity_t *prev = find_compound_entry(compound, symbol);
5556 position_t const *const ppos = &prev->base.pos;
5557 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5561 if (token.kind == ':') {
5562 parse_bitfield_member(entity);
5564 attribute_t *attributes = parse_attributes(NULL);
5565 handle_entity_attributes(attributes, entity);
5567 type_t *orig_type = entity->declaration.type;
5568 type_t *type = skip_typeref(orig_type);
5569 if (is_type_function(type)) {
5570 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5571 } else if (is_type_incomplete(type)) {
5572 /* §6.7.2.1:16 flexible array member */
5573 if (!is_type_array(type) ||
5574 token.kind != ';' ||
5575 look_ahead(1)->kind != '}') {
5576 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5577 } else if (compound->members.entities == NULL) {
5578 errorf(pos, "flexible array member in otherwise empty struct");
5583 append_entity(&compound->members, entity);
5586 } while (accept(','));
5587 rem_anchor_token(',');
5588 rem_anchor_token(';');
5591 anonymous_entity = NULL;
5594 static void parse_compound_type_entries(compound_t *compound)
5597 add_anchor_token('}');
5600 switch (token.kind) {
5602 case T___extension__:
5603 case T_IDENTIFIER: {
5605 declaration_specifiers_t specifiers;
5606 parse_declaration_specifiers(&specifiers);
5607 parse_compound_declarators(compound, &specifiers);
5613 rem_anchor_token('}');
5616 compound->complete = true;
5622 static type_t *parse_typename(void)
5624 declaration_specifiers_t specifiers;
5625 parse_declaration_specifiers(&specifiers);
5626 if (specifiers.storage_class != STORAGE_CLASS_NONE
5627 || specifiers.thread_local) {
5628 /* TODO: improve error message, user does probably not know what a
5629 * storage class is...
5631 errorf(&specifiers.pos, "typename must not have a storage class");
5634 type_t *result = parse_abstract_declarator(specifiers.type);
5642 typedef expression_t* (*parse_expression_function)(void);
5643 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5645 typedef struct expression_parser_function_t expression_parser_function_t;
5646 struct expression_parser_function_t {
5647 parse_expression_function parser;
5648 precedence_t infix_precedence;
5649 parse_expression_infix_function infix_parser;
5652 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5654 static type_t *get_string_type(string_encoding_t const enc)
5656 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5658 case STRING_ENCODING_CHAR:
5659 case STRING_ENCODING_UTF8: return warn ? type_const_char_ptr : type_char_ptr;
5660 case STRING_ENCODING_CHAR16: return warn ? type_char16_t_const_ptr : type_char16_t_ptr;
5661 case STRING_ENCODING_CHAR32: return warn ? type_char32_t_const_ptr : type_char32_t_ptr;
5662 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5664 panic("invalid string encoding");
5668 * Parse a string constant.
5670 static expression_t *parse_string_literal(void)
5672 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5673 expr->string_literal.value = concat_string_literals();
5674 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5679 * Parse a boolean constant.
5681 static expression_t *parse_boolean_literal(bool value)
5683 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5684 literal->base.type = type_bool;
5685 literal->literal.value.begin = value ? "true" : "false";
5686 literal->literal.value.size = value ? 4 : 5;
5688 eat(value ? T_true : T_false);
5692 static void warn_traditional_suffix(char const *const suffix)
5694 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%s' suffix", suffix);
5697 static void check_integer_suffix(expression_t *const expr, char const *const suffix)
5699 unsigned spec = SPECIFIER_NONE;
5700 char const *c = suffix;
5701 while (*c != '\0') {
5706 add = SPECIFIER_LONG;
5708 add |= SPECIFIER_LONG_LONG;
5714 add = SPECIFIER_UNSIGNED;
5722 add = SPECIFIER_COMPLEX;
5736 switch (spec & ~SPECIFIER_COMPLEX) {
5737 case SPECIFIER_NONE: type = type_int; break;
5738 case SPECIFIER_LONG: type = type_long; break;
5739 case SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_long_long; break;
5740 case SPECIFIER_UNSIGNED: type = type_unsigned_int; break;
5741 case SPECIFIER_UNSIGNED | SPECIFIER_LONG: type = type_unsigned_long; break;
5742 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG: type = type_unsigned_long_long; break;
5743 default: panic("inconsistent suffix");
5745 if (spec != SPECIFIER_NONE && spec != SPECIFIER_LONG) {
5746 warn_traditional_suffix(suffix);
5748 if (spec & SPECIFIER_COMPLEX) {
5749 assert(type->kind == TYPE_ATOMIC);
5750 type = make_complex_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
5752 expr->base.type = type;
5753 /* Integer type depends on the size of the number and the size
5754 * representable by the types. The backend/codegeneration has to
5755 * determine that. */
5756 determine_literal_type(&expr->literal);
5759 errorf(HERE, "invalid suffix '%s' on integer constant", suffix);
5763 static void check_floatingpoint_suffix(expression_t *const expr, char const *const suffix)
5766 char const *c = suffix;
5767 bool is_complex = false;
5771 case 'f': type = type_float; ++c; break;
5773 case 'l': type = type_long_double; ++c; break;
5783 default: type = type_double; break;
5788 assert(type->kind == TYPE_ATOMIC);
5789 type = make_complex_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
5792 expr->base.type = type;
5793 if (suffix[0] != '\0') {
5794 warn_traditional_suffix(suffix);
5797 errorf(HERE, "invalid suffix '%s' on floatingpoint constant", suffix);
5801 static expression_t *parse_number_literal(void)
5803 string_t const *const str = &token.literal.string;
5804 char const * i = str->begin;
5805 unsigned digits = 0;
5806 bool is_float = false;
5808 /* Parse base prefix. */
5812 case 'B': case 'b': base = 2; ++i; break;
5813 case 'X': case 'x': base = 16; ++i; break;
5814 default: base = 8; digits |= 1U << 0; break;
5820 /* Parse mantissa. */
5826 errorf(HERE, "multiple decimal points in %K", &token);
5835 case '0': digit = 0; break;
5836 case '1': digit = 1; break;
5837 case '2': digit = 2; break;
5838 case '3': digit = 3; break;
5839 case '4': digit = 4; break;
5840 case '5': digit = 5; break;
5841 case '6': digit = 6; break;
5842 case '7': digit = 7; break;
5843 case '8': digit = 8; break;
5844 case '9': digit = 9; break;
5845 case 'A': case 'a': digit = 10; break;
5846 case 'B': case 'b': digit = 11; break;
5847 case 'C': case 'c': digit = 12; break;
5848 case 'D': case 'd': digit = 13; break;
5849 case 'E': case 'e': digit = 14; break;
5850 case 'F': case 'f': digit = 15; break;
5852 default: goto done_mantissa;
5855 if (digit >= 10 && base != 16)
5858 digits |= 1U << digit;
5862 /* Parse exponent. */
5866 errorf(HERE, "binary floating %K not allowed", &token);
5871 if (*i == 'E' || *i == 'e') {
5873 goto parse_exponent;
5878 if (*i == 'P' || *i == 'p') {
5883 if (*i == '-' || *i == '+')
5889 } while (isdigit(*i));
5891 errorf(HERE, "exponent of %K has no digits", &token);
5893 } else if (is_float) {
5894 errorf(HERE, "hexadecimal floating %K requires an exponent", &token);
5900 panic("invalid base");
5904 expression_t *const expr = allocate_expression_zero(is_float ? EXPR_LITERAL_FLOATINGPOINT : EXPR_LITERAL_INTEGER);
5905 expr->literal.value = *str;
5909 errorf(HERE, "%K has no digits", &token);
5910 } else if (digits & ~((1U << base) - 1)) {
5911 errorf(HERE, "invalid digit in %K", &token);
5913 expr->literal.suffix = i;
5915 check_floatingpoint_suffix(expr, i);
5917 check_integer_suffix(expr, i);
5927 * Parse a character constant.
5929 static expression_t *parse_character_constant(void)
5931 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5932 literal->string_literal.value = token.literal.string;
5934 size_t const size = get_string_len(&token.literal.string);
5935 switch (token.literal.string.encoding) {
5936 case STRING_ENCODING_CHAR:
5937 case STRING_ENCODING_UTF8:
5938 literal->base.type = c_mode & _CXX ? type_char : type_int;
5940 if (!GNU_MODE && !(c_mode & _C99)) {
5941 errorf(HERE, "more than 1 character in character constant");
5943 literal->base.type = type_int;
5944 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5949 case STRING_ENCODING_CHAR16: literal->base.type = type_char16_t; goto warn_multi;
5950 case STRING_ENCODING_CHAR32: literal->base.type = type_char32_t; goto warn_multi;
5951 case STRING_ENCODING_WIDE: literal->base.type = type_wchar_t; goto warn_multi;
5954 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5959 eat(T_CHARACTER_CONSTANT);
5963 static entity_t *create_implicit_function(symbol_t *symbol, position_t const *const pos)
5965 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5966 ntype->function.return_type = type_int;
5967 ntype->function.unspecified_parameters = true;
5968 ntype->function.linkage = LINKAGE_C;
5969 type_t *type = identify_new_type(ntype);
5971 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5972 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5973 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5974 entity->declaration.type = type;
5975 entity->declaration.implicit = true;
5977 if (current_scope != NULL)
5978 record_entity(entity, false);
5984 * Performs automatic type cast as described in §6.3.2.1.
5986 * @param orig_type the original type
5988 static type_t *automatic_type_conversion(type_t *orig_type)
5990 type_t *type = skip_typeref(orig_type);
5991 if (is_type_array(type)) {
5992 array_type_t *array_type = &type->array;
5993 type_t *element_type = array_type->element_type;
5994 unsigned qualifiers = array_type->base.qualifiers;
5996 return make_pointer_type(element_type, qualifiers);
5999 if (is_type_function(type)) {
6000 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6007 * reverts the automatic casts of array to pointer types and function
6008 * to function-pointer types as defined §6.3.2.1
6010 type_t *revert_automatic_type_conversion(const expression_t *expression)
6012 switch (expression->kind) {
6013 case EXPR_REFERENCE: {
6014 entity_t *entity = expression->reference.entity;
6015 if (is_declaration(entity)) {
6016 return entity->declaration.type;
6017 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6018 return entity->enum_value.enum_type;
6020 panic("no declaration or enum in reference");
6025 entity_t *entity = expression->select.compound_entry;
6026 assert(is_declaration(entity));
6027 type_t *type = entity->declaration.type;
6028 return get_qualified_type(type, expression->base.type->base.qualifiers);
6031 case EXPR_UNARY_DEREFERENCE: {
6032 const expression_t *const value = expression->unary.value;
6033 type_t *const type = skip_typeref(value->base.type);
6034 if (!is_type_pointer(type))
6035 return type_error_type;
6036 return type->pointer.points_to;
6039 case EXPR_ARRAY_ACCESS: {
6040 const expression_t *array_ref = expression->array_access.array_ref;
6041 type_t *type_left = skip_typeref(array_ref->base.type);
6042 if (!is_type_pointer(type_left))
6043 return type_error_type;
6044 return type_left->pointer.points_to;
6047 case EXPR_STRING_LITERAL: {
6048 size_t const size = get_string_len(&expression->string_literal.value) + 1;
6049 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
6050 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
6053 case EXPR_COMPOUND_LITERAL:
6054 return expression->compound_literal.type;
6059 return expression->base.type;
6063 * Find an entity matching a symbol in a scope.
6064 * Uses current scope if scope is NULL
6066 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6067 namespace_tag_t namespc)
6069 if (scope == NULL) {
6070 return get_entity(symbol, namespc);
6073 /* we should optimize here, if scope grows above a certain size we should
6074 construct a hashmap here... */
6075 entity_t *entity = scope->entities;
6076 for ( ; entity != NULL; entity = entity->base.next) {
6077 if (entity->base.symbol == symbol
6078 && (namespace_tag_t)entity->base.namespc == namespc)
6085 static entity_t *parse_qualified_identifier(void)
6087 /* namespace containing the symbol */
6090 const scope_t *lookup_scope = NULL;
6092 if (accept(T_COLONCOLON))
6093 lookup_scope = &unit->scope;
6097 symbol = expect_identifier("while parsing identifier", &pos);
6099 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6102 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6104 if (!accept(T_COLONCOLON))
6107 switch (entity->kind) {
6108 case ENTITY_NAMESPACE:
6109 lookup_scope = &entity->namespacee.members;
6114 lookup_scope = &entity->compound.members;
6117 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6118 symbol, get_entity_kind_name(entity->kind));
6120 /* skip further qualifications */
6121 while (accept(T_IDENTIFIER) && accept(T_COLONCOLON)) {}
6123 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6127 if (entity == NULL) {
6128 if (!strict_mode && token.kind == '(') {
6129 /* an implicitly declared function */
6130 entity = create_implicit_function(symbol, &pos);
6131 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6133 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6134 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6141 static expression_t *parse_reference(void)
6143 position_t const pos = *HERE;
6144 entity_t *const entity = parse_qualified_identifier();
6147 if (is_declaration(entity)) {
6148 orig_type = entity->declaration.type;
6149 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6150 orig_type = entity->enum_value.enum_type;
6152 panic("expected declaration or enum value in reference");
6155 /* we always do the auto-type conversions; the & and sizeof parser contains
6156 * code to revert this! */
6157 type_t *type = automatic_type_conversion(orig_type);
6159 expression_kind_t kind = EXPR_REFERENCE;
6160 if (entity->kind == ENTITY_ENUM_VALUE)
6161 kind = EXPR_ENUM_CONSTANT;
6163 expression_t *expression = allocate_expression_zero(kind);
6164 expression->base.pos = pos;
6165 expression->base.type = type;
6166 expression->reference.entity = entity;
6168 /* this declaration is used */
6169 if (is_declaration(entity)) {
6170 entity->declaration.used = true;
6173 if (entity->base.parent_scope != file_scope
6174 && (current_function != NULL
6175 && entity->base.parent_scope->depth < current_function->parameters.depth)
6176 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6177 /* access of a variable from an outer function */
6178 entity->variable.address_taken = true;
6179 current_function->need_closure = true;
6182 check_deprecated(&pos, entity);
6187 static bool semantic_cast(expression_t *cast)
6189 expression_t *expression = cast->unary.value;
6190 type_t *orig_dest_type = cast->base.type;
6191 type_t *orig_type_right = expression->base.type;
6192 type_t const *dst_type = skip_typeref(orig_dest_type);
6193 type_t const *src_type = skip_typeref(orig_type_right);
6194 position_t const *pos = &cast->base.pos;
6196 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation
6197 * than for utility. */
6198 if (is_type_void(dst_type))
6201 /* only integer and pointer can be casted to pointer */
6202 if (is_type_pointer(dst_type) &&
6203 !is_type_pointer(src_type) &&
6204 !is_type_integer(src_type) &&
6205 is_type_valid(src_type)) {
6206 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6210 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6211 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6215 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6216 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6220 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6221 type_t *src = skip_typeref(src_type->pointer.points_to);
6222 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6223 unsigned missing_qualifiers =
6224 src->base.qualifiers & ~dst->base.qualifiers;
6225 if (missing_qualifiers != 0) {
6226 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6232 static void semantic_complex_extract(unary_expression_t *extract)
6234 type_t *orig_value_type = extract->value->base.type;
6235 type_t *value_type = skip_typeref(orig_value_type);
6236 if (!is_type_valid(value_type)) {
6237 extract->base.type = type_error_type;
6241 type_t *type = value_type;
6242 if (!is_type_complex(type)) {
6243 if (!is_type_arithmetic(type)) {
6244 errorf(&extract->base.pos,
6245 "%s requires an argument with complex or arithmetic type, got '%T'",
6246 extract->base.kind == EXPR_UNARY_IMAG ? "__imag__" : "__real__",
6248 extract->base.type = type_error_type;
6251 atomic_type_kind_t const akind = get_arithmetic_akind(type);
6252 type = make_complex_type(akind, TYPE_QUALIFIER_NONE);
6253 extract->value = create_implicit_cast(extract->value, type);
6255 assert(type->kind == TYPE_COMPLEX);
6256 type = make_atomic_type(type->atomic.akind, TYPE_QUALIFIER_NONE);
6257 extract->base.type = type;
6260 static expression_t *parse_compound_literal(position_t const *const pos,
6263 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6264 expression->base.pos = *pos;
6265 bool global_scope = current_scope == file_scope;
6267 parse_initializer_env_t env;
6270 env.must_be_constant = global_scope;
6271 initializer_t *initializer = parse_initializer(&env);
6274 expression->base.type = automatic_type_conversion(type);
6275 expression->compound_literal.initializer = initializer;
6276 expression->compound_literal.type = type;
6277 expression->compound_literal.global_scope = global_scope;
6283 * Parse a cast expression.
6285 static expression_t *parse_cast(void)
6287 position_t const pos = *HERE;
6290 add_anchor_token(')');
6292 type_t *type = parse_typename();
6294 rem_anchor_token(')');
6297 if (token.kind == '{') {
6298 return parse_compound_literal(&pos, type);
6301 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6302 cast->base.pos = pos;
6304 expression_t *value = parse_subexpression(PREC_CAST);
6305 cast->base.type = type;
6306 cast->unary.value = value;
6308 if (!semantic_cast(cast)) {
6309 cast->base.type = type_error_type;
6315 static expression_t *parse_complex_extract_expression(expression_kind_t const kind)
6317 expression_t *extract = allocate_expression_zero(kind);
6320 extract->unary.value = parse_subexpression(PREC_CAST);
6321 semantic_complex_extract(&extract->unary);
6326 * Parse a statement expression.
6328 static expression_t *parse_statement_expression(void)
6330 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6333 add_anchor_token(')');
6335 statement_t *statement = parse_compound_statement(true);
6336 statement->compound.stmt_expr = true;
6337 expression->statement.statement = statement;
6339 /* find last statement and use its type */
6340 type_t *type = type_void;
6341 const statement_t *stmt = statement->compound.statements;
6343 while (stmt->base.next != NULL)
6344 stmt = stmt->base.next;
6346 if (stmt->kind == STATEMENT_EXPRESSION) {
6347 type = stmt->expression.expression->base.type;
6350 position_t const *const pos = &expression->base.pos;
6351 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6353 expression->base.type = type;
6355 rem_anchor_token(')');
6361 * Parse a parenthesized expression.
6363 static expression_t *parse_parenthesized_expression(void)
6365 token_t const* const la1 = look_ahead(1);
6366 switch (la1->kind) {
6368 /* gcc extension: a statement expression */
6369 return parse_statement_expression();
6372 if (is_typedef_symbol(la1->base.symbol)) {
6374 return parse_cast();
6379 add_anchor_token(')');
6380 expression_t *result = parse_expression();
6381 result->base.parenthesized = true;
6382 rem_anchor_token(')');
6388 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6390 if (current_function == NULL) {
6391 errorf(HERE, "%K used outside of a function", &token);
6394 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6395 expression->base.type = type_char_ptr;
6396 expression->funcname.kind = kind;
6403 static designator_t *parse_designator(void)
6405 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6406 result->symbol = expect_identifier("while parsing member designator", &result->pos);
6407 if (!result->symbol)
6410 designator_t *last_designator = result;
6413 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6414 designator->symbol = expect_identifier("while parsing member designator", &designator->pos);
6415 if (!designator->symbol)
6418 last_designator->next = designator;
6419 last_designator = designator;
6423 add_anchor_token(']');
6424 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6425 designator->pos = *HERE;
6426 designator->array_index = parse_expression();
6427 rem_anchor_token(']');
6430 last_designator->next = designator;
6431 last_designator = designator;
6441 * Parse the __builtin_offsetof() expression.
6443 static expression_t *parse_offsetof(void)
6445 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6446 expression->base.type = type_size_t;
6448 eat(T___builtin_offsetof);
6450 add_anchor_token(')');
6451 add_anchor_token(',');
6453 type_t *type = parse_typename();
6454 rem_anchor_token(',');
6456 designator_t *designator = parse_designator();
6457 rem_anchor_token(')');
6460 expression->offsetofe.type = type;
6461 expression->offsetofe.designator = designator;
6464 memset(&path, 0, sizeof(path));
6465 path.top_type = type;
6466 path.path = NEW_ARR_F(type_path_entry_t, 0);
6468 descend_into_subtype(&path);
6470 if (!walk_designator(&path, designator, true)) {
6471 return create_error_expression();
6474 DEL_ARR_F(path.path);
6479 static bool is_last_parameter(expression_t *const param)
6481 if (param->kind == EXPR_REFERENCE) {
6482 entity_t *const entity = param->reference.entity;
6483 if (entity->kind == ENTITY_PARAMETER &&
6484 !entity->base.next &&
6485 entity->base.parent_scope == ¤t_function->parameters) {
6490 if (!is_type_valid(skip_typeref(param->base.type)))
6497 * Parses a __builtin_va_start() expression.
6499 static expression_t *parse_va_start(void)
6501 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6503 eat(T___builtin_va_start);
6505 add_anchor_token(')');
6506 add_anchor_token(',');
6508 expression->va_starte.ap = parse_assignment_expression();
6509 rem_anchor_token(',');
6511 expression_t *const param = parse_assignment_expression();
6512 expression->va_starte.parameter = param;
6513 rem_anchor_token(')');
6516 if (!current_function) {
6517 errorf(&expression->base.pos, "'va_start' used outside of function");
6518 } else if (!current_function->base.type->function.variadic) {
6519 errorf(&expression->base.pos, "'va_start' used in non-variadic function");
6520 } else if (!is_last_parameter(param)) {
6521 errorf(¶m->base.pos, "second argument of 'va_start' must be last parameter of the current function");
6528 * Parses a __builtin_va_arg() expression.
6530 static expression_t *parse_va_arg(void)
6532 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6534 eat(T___builtin_va_arg);
6536 add_anchor_token(')');
6537 add_anchor_token(',');
6540 ap.expression = parse_assignment_expression();
6541 expression->va_arge.ap = ap.expression;
6542 check_call_argument(type_valist, &ap, 1);
6544 rem_anchor_token(',');
6546 expression->base.type = parse_typename();
6547 rem_anchor_token(')');
6554 * Parses a __builtin_va_copy() expression.
6556 static expression_t *parse_va_copy(void)
6558 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6560 eat(T___builtin_va_copy);
6562 add_anchor_token(')');
6563 add_anchor_token(',');
6565 expression_t *dst = parse_assignment_expression();
6566 assign_error_t error = semantic_assign(type_valist, dst);
6567 report_assign_error(error, type_valist, dst, "call argument 1",
6569 expression->va_copye.dst = dst;
6571 rem_anchor_token(',');
6574 call_argument_t src;
6575 src.expression = parse_assignment_expression();
6576 check_call_argument(type_valist, &src, 2);
6577 expression->va_copye.src = src.expression;
6578 rem_anchor_token(')');
6585 * Parses a __builtin_constant_p() expression.
6587 static expression_t *parse_builtin_constant(void)
6589 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6591 eat(T___builtin_constant_p);
6593 add_anchor_token(')');
6595 expression->builtin_constant.value = parse_expression();
6596 rem_anchor_token(')');
6598 expression->base.type = type_int;
6604 * Parses a __builtin_types_compatible_p() expression.
6606 static expression_t *parse_builtin_types_compatible(void)
6608 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6610 eat(T___builtin_types_compatible_p);
6612 add_anchor_token(')');
6613 add_anchor_token(',');
6615 expression->builtin_types_compatible.left = parse_typename();
6616 rem_anchor_token(',');
6618 expression->builtin_types_compatible.right = parse_typename();
6619 rem_anchor_token(')');
6621 expression->base.type = type_int;
6627 * Parses a __builtin_is_*() compare expression.
6629 static expression_t *parse_compare_builtin(void)
6631 expression_kind_t kind;
6632 switch (token.kind) {
6633 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6634 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6635 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6636 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6637 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6638 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6639 default: internal_errorf(HERE, "invalid compare builtin found");
6641 expression_t *const expression = allocate_expression_zero(kind);
6644 add_anchor_token(')');
6645 add_anchor_token(',');
6647 expression->binary.left = parse_assignment_expression();
6648 rem_anchor_token(',');
6650 expression->binary.right = parse_assignment_expression();
6651 rem_anchor_token(')');
6654 type_t *const orig_type_left = expression->binary.left->base.type;
6655 type_t *const orig_type_right = expression->binary.right->base.type;
6657 type_t *const type_left = skip_typeref(orig_type_left);
6658 type_t *const type_right = skip_typeref(orig_type_right);
6659 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6660 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6661 type_error_incompatible("invalid operands in comparison",
6662 &expression->base.pos, orig_type_left, orig_type_right);
6665 semantic_comparison(&expression->binary, true);
6672 * Parses a MS assume() expression.
6674 static expression_t *parse_assume(void)
6676 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6680 add_anchor_token(')');
6682 expression->unary.value = parse_expression();
6683 rem_anchor_token(')');
6686 expression->base.type = type_void;
6691 * Return the label for the current symbol or create a new one.
6693 static label_t *get_label(char const *const context)
6695 assert(current_function != NULL);
6697 symbol_t *const sym = expect_identifier(context, NULL);
6701 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6702 /* If we find a local label, we already created the declaration. */
6703 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6704 if (label->base.parent_scope != current_scope) {
6705 assert(label->base.parent_scope->depth < current_scope->depth);
6706 current_function->goto_to_outer = true;
6708 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6709 /* There is no matching label in the same function, so create a new one. */
6710 position_t const nowhere = { NULL, 0, 0, false };
6711 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6715 return &label->label;
6719 * Parses a GNU && label address expression.
6721 static expression_t *parse_label_address(void)
6723 position_t const pos = *HERE;
6726 label_t *const label = get_label("while parsing label address");
6728 return create_error_expression();
6731 label->address_taken = true;
6733 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6734 expression->base.pos = pos;
6736 /* label address is treated as a void pointer */
6737 expression->base.type = type_void_ptr;
6738 expression->label_address.label = label;
6743 * Parse a microsoft __noop expression.
6745 static expression_t *parse_noop_expression(void)
6747 /* the result is a (int)0 */
6748 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6749 literal->base.type = type_int;
6750 literal->literal.value.begin = "__noop";
6751 literal->literal.value.size = 6;
6755 if (token.kind == '(') {
6756 /* parse arguments */
6758 add_anchor_token(')');
6759 add_anchor_token(',');
6761 if (token.kind != ')') do {
6762 (void)parse_assignment_expression();
6763 } while (accept(','));
6765 rem_anchor_token(',');
6766 rem_anchor_token(')');
6774 * Parses a primary expression.
6776 static expression_t *parse_primary_expression(void)
6778 switch (token.kind) {
6779 case T_false: return parse_boolean_literal(false);
6780 case T_true: return parse_boolean_literal(true);
6781 case T_NUMBER: return parse_number_literal();
6782 case T_CHARACTER_CONSTANT: return parse_character_constant();
6783 case T_STRING_LITERAL: return parse_string_literal();
6784 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6785 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6786 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6787 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6788 case T___builtin_offsetof: return parse_offsetof();
6789 case T___builtin_va_start: return parse_va_start();
6790 case T___builtin_va_arg: return parse_va_arg();
6791 case T___builtin_va_copy: return parse_va_copy();
6792 case T___builtin_isgreater:
6793 case T___builtin_isgreaterequal:
6794 case T___builtin_isless:
6795 case T___builtin_islessequal:
6796 case T___builtin_islessgreater:
6797 case T___builtin_isunordered: return parse_compare_builtin();
6798 case T___builtin_constant_p: return parse_builtin_constant();
6799 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6800 case T__assume: return parse_assume();
6803 return parse_label_address();
6806 case '(': return parse_parenthesized_expression();
6807 case T___noop: return parse_noop_expression();
6808 case T___imag__: return parse_complex_extract_expression(EXPR_UNARY_IMAG);
6809 case T___real__: return parse_complex_extract_expression(EXPR_UNARY_REAL);
6811 /* Gracefully handle type names while parsing expressions. */
6813 return parse_reference();
6815 if (!is_typedef_symbol(token.base.symbol)) {
6816 return parse_reference();
6820 position_t const pos = *HERE;
6821 declaration_specifiers_t specifiers;
6822 parse_declaration_specifiers(&specifiers);
6823 type_t const *const type = parse_abstract_declarator(specifiers.type);
6824 errorf(&pos, "encountered type '%T' while parsing expression", type);
6825 return create_error_expression();
6829 errorf(HERE, "unexpected token %K, expected an expression", &token);
6831 return create_error_expression();
6834 static expression_t *parse_array_expression(expression_t *left)
6836 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6837 array_access_expression_t *const arr = &expr->array_access;
6840 add_anchor_token(']');
6842 expression_t *const inside = parse_expression();
6844 type_t *const orig_type_left = left->base.type;
6845 type_t *const orig_type_inside = inside->base.type;
6847 type_t *const type_left = skip_typeref(orig_type_left);
6848 type_t *const type_inside = skip_typeref(orig_type_inside);
6854 if (is_type_pointer(type_left)) {
6857 idx_type = type_inside;
6858 res_type = type_left->pointer.points_to;
6860 } else if (is_type_pointer(type_inside)) {
6861 arr->flipped = true;
6864 idx_type = type_left;
6865 res_type = type_inside->pointer.points_to;
6867 res_type = automatic_type_conversion(res_type);
6868 if (!is_type_integer(idx_type)) {
6869 if (is_type_valid(idx_type))
6870 errorf(&idx->base.pos, "array subscript must have integer type");
6871 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6872 position_t const *const pos = &idx->base.pos;
6873 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6876 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6877 errorf(&expr->base.pos, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6879 res_type = type_error_type;
6884 arr->array_ref = ref;
6886 arr->base.type = res_type;
6888 rem_anchor_token(']');
6893 static bool is_bitfield(const expression_t *expression)
6895 return expression->kind == EXPR_SELECT
6896 && expression->select.compound_entry->compound_member.bitfield;
6899 static expression_t *parse_typeprop(expression_kind_t const kind)
6901 expression_t *tp_expression = allocate_expression_zero(kind);
6902 tp_expression->base.type = type_size_t;
6904 eat(kind == EXPR_SIZEOF ? T_sizeof : T__Alignof);
6907 expression_t *expression;
6908 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6909 position_t const pos = *HERE;
6911 add_anchor_token(')');
6912 orig_type = parse_typename();
6913 rem_anchor_token(')');
6916 if (token.kind == '{') {
6917 /* It was not sizeof(type) after all. It is sizeof of an expression
6918 * starting with a compound literal */
6919 expression = parse_compound_literal(&pos, orig_type);
6920 goto typeprop_expression;
6923 expression = parse_subexpression(PREC_UNARY);
6925 typeprop_expression:
6926 if (is_bitfield(expression)) {
6927 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6928 errorf(&tp_expression->base.pos,
6929 "operand of %s expression must not be a bitfield", what);
6932 tp_expression->typeprop.tp_expression = expression;
6934 orig_type = revert_automatic_type_conversion(expression);
6935 expression->base.type = orig_type;
6938 tp_expression->typeprop.type = orig_type;
6939 type_t const* const type = skip_typeref(orig_type);
6940 char const* wrong_type = NULL;
6941 if (is_type_incomplete(type)) {
6942 if (!is_type_void(type) || !GNU_MODE)
6943 wrong_type = "incomplete";
6944 } else if (type->kind == TYPE_FUNCTION) {
6946 /* function types are allowed (and return 1) */
6947 position_t const *const pos = &tp_expression->base.pos;
6948 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6949 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6951 wrong_type = "function";
6955 if (wrong_type != NULL) {
6956 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6957 errorf(&tp_expression->base.pos,
6958 "operand of %s expression must not be of %s type '%T'",
6959 what, wrong_type, orig_type);
6962 return tp_expression;
6965 static expression_t *parse_sizeof(void)
6967 return parse_typeprop(EXPR_SIZEOF);
6970 static expression_t *parse_alignof(void)
6972 return parse_typeprop(EXPR_ALIGNOF);
6975 static expression_t *parse_select_expression(expression_t *addr)
6977 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6978 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6979 position_t const pos = *HERE;
6982 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6984 return create_error_expression();
6986 type_t *const orig_type = addr->base.type;
6987 type_t *const type = skip_typeref(orig_type);
6990 bool saw_error = false;
6991 if (is_type_pointer(type)) {
6992 if (!select_left_arrow) {
6994 "request for member '%Y' in something not a struct or union, but '%T'",
6998 type_left = skip_typeref(type->pointer.points_to);
7000 if (select_left_arrow && is_type_valid(type)) {
7001 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7007 if (!is_type_compound(type_left)) {
7008 if (is_type_valid(type_left) && !saw_error) {
7010 "request for member '%Y' in something not a struct or union, but '%T'",
7013 return create_error_expression();
7016 compound_t *compound = type_left->compound.compound;
7017 if (!compound->complete) {
7018 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7020 return create_error_expression();
7023 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7024 expression_t *result =
7025 find_create_select(&pos, addr, qualifiers, compound, symbol);
7027 if (result == NULL) {
7028 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7029 return create_error_expression();
7035 static void check_call_argument(type_t *expected_type,
7036 call_argument_t *argument, unsigned pos)
7038 type_t *expected_type_skip = skip_typeref(expected_type);
7039 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7040 expression_t *arg_expr = argument->expression;
7041 type_t *arg_type = skip_typeref(arg_expr->base.type);
7043 /* handle transparent union gnu extension */
7044 if (is_type_union(expected_type_skip)
7045 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7046 compound_t *union_decl = expected_type_skip->compound.compound;
7047 type_t *best_type = NULL;
7048 entity_t *entry = union_decl->members.entities;
7049 for ( ; entry != NULL; entry = entry->base.next) {
7050 assert(is_declaration(entry));
7051 type_t *decl_type = entry->declaration.type;
7052 error = semantic_assign(decl_type, arg_expr);
7053 if (error == ASSIGN_ERROR_INCOMPATIBLE
7054 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7057 if (error == ASSIGN_SUCCESS) {
7058 best_type = decl_type;
7059 } else if (best_type == NULL) {
7060 best_type = decl_type;
7064 if (best_type != NULL) {
7065 expected_type = best_type;
7069 error = semantic_assign(expected_type, arg_expr);
7070 argument->expression = create_implicit_cast(arg_expr, expected_type);
7072 if (error != ASSIGN_SUCCESS) {
7073 /* report exact scope in error messages (like "in argument 3") */
7075 snprintf(buf, sizeof(buf), "call argument %u", pos);
7076 report_assign_error(error, expected_type, arg_expr, buf,
7077 &arg_expr->base.pos);
7079 type_t *const promoted_type = get_default_promoted_type(arg_type);
7080 if (!types_compatible(expected_type_skip, promoted_type) &&
7081 !types_compatible(expected_type_skip, type_void_ptr) &&
7082 !types_compatible(type_void_ptr, promoted_type)) {
7083 /* Deliberately show the skipped types in this warning */
7084 position_t const *const apos = &arg_expr->base.pos;
7085 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7091 * Handle the semantic restrictions of builtin calls
7093 static void handle_builtin_argument_restrictions(call_expression_t *call)
7095 entity_t *entity = call->function->reference.entity;
7096 switch (entity->function.btk) {
7098 switch (entity->function.b.firm_builtin_kind) {
7099 case ir_bk_return_address:
7100 case ir_bk_frame_address: {
7101 /* argument must be constant */
7102 call_argument_t *argument = call->arguments;
7104 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7105 errorf(&call->base.pos,
7106 "argument of '%Y' must be a constant expression",
7107 call->function->reference.entity->base.symbol);
7111 case ir_bk_prefetch:
7112 /* second and third argument must be constant if existent */
7113 if (call->arguments == NULL)
7115 call_argument_t *rw = call->arguments->next;
7116 call_argument_t *locality = NULL;
7119 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7120 errorf(&call->base.pos,
7121 "second argument of '%Y' must be a constant expression",
7122 call->function->reference.entity->base.symbol);
7124 locality = rw->next;
7126 if (locality != NULL) {
7127 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7128 errorf(&call->base.pos,
7129 "third argument of '%Y' must be a constant expression",
7130 call->function->reference.entity->base.symbol);
7138 case BUILTIN_OBJECT_SIZE:
7139 if (call->arguments == NULL)
7142 call_argument_t *arg = call->arguments->next;
7143 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7144 errorf(&call->base.pos,
7145 "second argument of '%Y' must be a constant expression",
7146 call->function->reference.entity->base.symbol);
7155 * Parse a call expression, i.e. expression '( ... )'.
7157 * @param expression the function address
7159 static expression_t *parse_call_expression(expression_t *expression)
7161 expression_t *result = allocate_expression_zero(EXPR_CALL);
7162 call_expression_t *call = &result->call;
7163 call->function = expression;
7165 type_t *const orig_type = expression->base.type;
7166 type_t *const type = skip_typeref(orig_type);
7168 function_type_t *function_type = NULL;
7169 if (is_type_pointer(type)) {
7170 type_t *const to_type = skip_typeref(type->pointer.points_to);
7172 if (is_type_function(to_type)) {
7173 function_type = &to_type->function;
7174 call->base.type = function_type->return_type;
7178 if (function_type == NULL && is_type_valid(type)) {
7180 "called object '%E' (type '%T') is not a pointer to a function",
7181 expression, orig_type);
7184 /* parse arguments */
7186 add_anchor_token(')');
7187 add_anchor_token(',');
7189 if (token.kind != ')') {
7190 call_argument_t **anchor = &call->arguments;
7192 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7193 argument->expression = parse_assignment_expression();
7196 anchor = &argument->next;
7197 } while (accept(','));
7199 rem_anchor_token(',');
7200 rem_anchor_token(')');
7203 if (function_type == NULL)
7206 /* check type and count of call arguments */
7207 function_parameter_t *parameter = function_type->parameters;
7208 call_argument_t *argument = call->arguments;
7209 if (!function_type->unspecified_parameters) {
7210 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7211 parameter = parameter->next, argument = argument->next) {
7212 check_call_argument(parameter->type, argument, ++pos);
7215 if (parameter != NULL) {
7216 errorf(&expression->base.pos, "too few arguments to function '%E'",
7218 } else if (argument != NULL && !function_type->variadic) {
7219 errorf(&argument->expression->base.pos,
7220 "too many arguments to function '%E'", expression);
7224 /* do default promotion for other arguments */
7225 for (; argument != NULL; argument = argument->next) {
7226 type_t *argument_type = argument->expression->base.type;
7227 if (!is_type_object(skip_typeref(argument_type))) {
7228 errorf(&argument->expression->base.pos,
7229 "call argument '%E' must not be void", argument->expression);
7232 argument_type = get_default_promoted_type(argument_type);
7234 argument->expression
7235 = create_implicit_cast(argument->expression, argument_type);
7240 if (is_type_compound(skip_typeref(function_type->return_type))) {
7241 position_t const *const pos = &expression->base.pos;
7242 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7245 if (expression->kind == EXPR_REFERENCE) {
7246 reference_expression_t *reference = &expression->reference;
7247 if (reference->entity->kind == ENTITY_FUNCTION &&
7248 reference->entity->function.btk != BUILTIN_NONE)
7249 handle_builtin_argument_restrictions(call);
7255 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7257 static bool same_compound_type(const type_t *type1, const type_t *type2)
7260 is_type_compound(type1) &&
7261 type1->kind == type2->kind &&
7262 type1->compound.compound == type2->compound.compound;
7265 static expression_t const *get_reference_address(expression_t const *expr)
7267 bool regular_take_address = true;
7269 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7270 expr = expr->unary.value;
7272 regular_take_address = false;
7275 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7278 expr = expr->unary.value;
7281 if (expr->kind != EXPR_REFERENCE)
7284 /* special case for functions which are automatically converted to a
7285 * pointer to function without an extra TAKE_ADDRESS operation */
7286 if (!regular_take_address &&
7287 expr->reference.entity->kind != ENTITY_FUNCTION) {
7294 static void warn_reference_address_as_bool(expression_t const* expr)
7296 expr = get_reference_address(expr);
7298 position_t const *const pos = &expr->base.pos;
7299 entity_t const *const ent = expr->reference.entity;
7300 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7304 static void warn_assignment_in_condition(const expression_t *const expr)
7306 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7308 if (expr->base.parenthesized)
7310 position_t const *const pos = &expr->base.pos;
7311 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7314 static void semantic_condition(expression_t const *const expr,
7315 char const *const context)
7317 type_t *const type = skip_typeref(expr->base.type);
7318 if (is_type_scalar(type)) {
7319 warn_reference_address_as_bool(expr);
7320 warn_assignment_in_condition(expr);
7321 } else if (is_type_valid(type)) {
7322 errorf(&expr->base.pos, "%s must have scalar type", context);
7327 * Parse a conditional expression, i.e. 'expression ? ... : ...'.
7329 * @param expression the conditional expression
7331 static expression_t *parse_conditional_expression(expression_t *expression)
7333 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7335 conditional_expression_t *conditional = &result->conditional;
7336 conditional->condition = expression;
7339 add_anchor_token(':');
7341 /* §6.5.15:2 The first operand shall have scalar type. */
7342 semantic_condition(expression, "condition of conditional operator");
7344 expression_t *true_expression = expression;
7345 bool gnu_cond = false;
7346 if (GNU_MODE && token.kind == ':') {
7349 true_expression = parse_expression();
7351 rem_anchor_token(':');
7353 expression_t *false_expression =
7354 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7356 type_t *const orig_true_type = true_expression->base.type;
7357 type_t *const orig_false_type = false_expression->base.type;
7358 type_t *const true_type = skip_typeref(orig_true_type);
7359 type_t *const false_type = skip_typeref(orig_false_type);
7362 position_t const *const pos = &conditional->base.pos;
7363 type_t *result_type;
7364 if (is_type_void(true_type) || is_type_void(false_type)) {
7365 /* ISO/IEC 14882:1998(E) §5.16:2 */
7366 if (true_expression->kind == EXPR_UNARY_THROW) {
7367 result_type = false_type;
7368 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7369 result_type = true_type;
7371 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7372 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7374 result_type = type_void;
7376 } else if (is_type_arithmetic(true_type)
7377 && is_type_arithmetic(false_type)) {
7378 result_type = semantic_arithmetic(true_type, false_type);
7379 } else if (same_compound_type(true_type, false_type)) {
7380 /* just take 1 of the 2 types */
7381 result_type = true_type;
7382 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7383 type_t *pointer_type;
7385 expression_t *other_expression;
7386 if (is_type_pointer(true_type) &&
7387 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7388 pointer_type = true_type;
7389 other_type = false_type;
7390 other_expression = false_expression;
7392 pointer_type = false_type;
7393 other_type = true_type;
7394 other_expression = true_expression;
7397 if (is_null_pointer_constant(other_expression)) {
7398 result_type = pointer_type;
7399 } else if (is_type_pointer(other_type)) {
7400 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7401 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7404 if (is_type_void(to1) || is_type_void(to2)) {
7406 } else if (types_compatible(get_unqualified_type(to1),
7407 get_unqualified_type(to2))) {
7410 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7414 type_t *const type =
7415 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7416 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7417 } else if (is_type_integer(other_type)) {
7418 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7419 result_type = pointer_type;
7421 goto types_incompatible;
7425 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7426 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7428 result_type = type_error_type;
7431 conditional->true_expression
7432 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7433 conditional->false_expression
7434 = create_implicit_cast(false_expression, result_type);
7435 conditional->base.type = result_type;
7440 * Parse an extension expression.
7442 static expression_t *parse_extension(void)
7445 expression_t *expression = parse_subexpression(PREC_UNARY);
7451 * Parse a __builtin_classify_type() expression.
7453 static expression_t *parse_builtin_classify_type(void)
7455 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7456 result->base.type = type_int;
7458 eat(T___builtin_classify_type);
7460 add_anchor_token(')');
7462 expression_t *expression = parse_expression();
7463 rem_anchor_token(')');
7465 result->classify_type.type_expression = expression;
7471 * Parse a delete expression
7472 * ISO/IEC 14882:1998(E) §5.3.5
7474 static expression_t *parse_delete(void)
7476 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7477 result->base.type = type_void;
7482 result->kind = EXPR_UNARY_DELETE_ARRAY;
7486 expression_t *const value = parse_subexpression(PREC_CAST);
7487 result->unary.value = value;
7489 type_t *const type = skip_typeref(value->base.type);
7490 if (!is_type_pointer(type)) {
7491 if (is_type_valid(type)) {
7492 errorf(&value->base.pos,
7493 "operand of delete must have pointer type");
7495 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7496 position_t const *const pos = &value->base.pos;
7497 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7504 * Parse a throw expression
7505 * ISO/IEC 14882:1998(E) §15:1
7507 static expression_t *parse_throw(void)
7509 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7510 result->base.type = type_void;
7514 expression_t *value = NULL;
7515 switch (token.kind) {
7517 value = parse_assignment_expression();
7518 /* ISO/IEC 14882:1998(E) §15.1:3 */
7519 type_t *const orig_type = value->base.type;
7520 type_t *const type = skip_typeref(orig_type);
7521 if (is_type_incomplete(type)) {
7522 errorf(&value->base.pos,
7523 "cannot throw object of incomplete type '%T'", orig_type);
7524 } else if (is_type_pointer(type)) {
7525 type_t *const points_to = skip_typeref(type->pointer.points_to);
7526 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7527 errorf(&value->base.pos,
7528 "cannot throw pointer to incomplete type '%T'", orig_type);
7536 result->unary.value = value;
7541 static bool check_pointer_arithmetic(const position_t *pos,
7542 type_t *pointer_type,
7543 type_t *orig_pointer_type)
7545 type_t *points_to = pointer_type->pointer.points_to;
7546 points_to = skip_typeref(points_to);
7548 if (is_type_incomplete(points_to)) {
7549 if (!GNU_MODE || !is_type_void(points_to)) {
7551 "arithmetic with pointer to incomplete type '%T' not allowed",
7555 warningf(WARN_POINTER_ARITH, pos, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7557 } else if (is_type_function(points_to)) {
7560 "arithmetic with pointer to function type '%T' not allowed",
7564 warningf(WARN_POINTER_ARITH, pos,
7565 "pointer to a function '%T' used in arithmetic",
7572 static bool is_lvalue(const expression_t *expression)
7574 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7575 switch (expression->kind) {
7576 case EXPR_ARRAY_ACCESS:
7577 case EXPR_COMPOUND_LITERAL:
7578 case EXPR_REFERENCE:
7580 case EXPR_UNARY_DEREFERENCE:
7584 type_t *type = skip_typeref(expression->base.type);
7586 /* ISO/IEC 14882:1998(E) §3.10:3 */
7587 is_type_reference(type) ||
7588 /* Claim it is an lvalue, if the type is invalid. There was a parse
7589 * error before, which maybe prevented properly recognizing it as
7591 !is_type_valid(type);
7596 static void semantic_incdec(unary_expression_t *expression)
7598 type_t *orig_type = expression->value->base.type;
7599 type_t *type = skip_typeref(orig_type);
7600 if (is_type_pointer(type)) {
7601 if (!check_pointer_arithmetic(&expression->base.pos, type, orig_type)) {
7604 } else if (!is_type_real(type) &&
7605 (!GNU_MODE || !is_type_complex(type)) && is_type_valid(type)) {
7606 /* TODO: improve error message */
7607 errorf(&expression->base.pos,
7608 "operation needs an arithmetic or pointer type");
7609 orig_type = type = type_error_type;
7611 if (!is_lvalue(expression->value)) {
7612 /* TODO: improve error message */
7613 errorf(&expression->base.pos, "lvalue required as operand");
7615 expression->base.type = orig_type;
7618 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7620 atomic_type_kind_t akind = get_arithmetic_akind(type);
7622 if (get_akind_rank(akind) < get_akind_rank(ATOMIC_TYPE_INT)) {
7623 if (type->kind == TYPE_COMPLEX)
7624 res_type = make_complex_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
7626 res_type = type_int;
7630 expr->base.type = res_type;
7631 expr->value = create_implicit_cast(expr->value, res_type);
7634 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7636 type_t *const orig_type = expression->value->base.type;
7637 type_t *const type = skip_typeref(orig_type);
7638 if (!is_type_arithmetic(type)) {
7639 if (is_type_valid(type)) {
7640 position_t const *const pos = &expression->base.pos;
7641 errorf(pos, "operand of unary expression must have arithmetic type, but is '%T'", orig_type);
7644 } else if (is_type_integer(type)) {
7645 promote_unary_int_expr(expression, type);
7647 expression->base.type = orig_type;
7651 static void semantic_unexpr_plus(unary_expression_t *expression)
7653 semantic_unexpr_arithmetic(expression);
7654 position_t const *const pos = &expression->base.pos;
7655 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7658 static void semantic_not(unary_expression_t *expression)
7660 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7661 semantic_condition(expression->value, "operand of !");
7662 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7665 static void semantic_complement(unary_expression_t *expression)
7667 type_t *const orig_type = expression->value->base.type;
7668 type_t *const type = skip_typeref(orig_type);
7669 if (!is_type_integer(type) && (!GNU_MODE || !is_type_complex(type))) {
7670 if (is_type_valid(type)) {
7671 errorf(&expression->base.pos, "operand of ~ must be of integer type");
7676 if (is_type_integer(type)) {
7677 promote_unary_int_expr(expression, type);
7679 expression->base.type = orig_type;
7683 static void semantic_dereference(unary_expression_t *expression)
7685 type_t *const orig_type = expression->value->base.type;
7686 type_t *const type = skip_typeref(orig_type);
7687 if (!is_type_pointer(type)) {
7688 if (is_type_valid(type)) {
7689 errorf(&expression->base.pos,
7690 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7695 type_t *result_type = type->pointer.points_to;
7696 result_type = automatic_type_conversion(result_type);
7697 expression->base.type = result_type;
7701 * Record that an address is taken (expression represents an lvalue).
7703 * @param expression the expression
7704 * @param may_be_register if true, the expression might be an register
7706 static void set_address_taken(expression_t *expression, bool may_be_register)
7708 if (expression->kind != EXPR_REFERENCE)
7711 entity_t *const entity = expression->reference.entity;
7713 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7716 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7717 && !may_be_register) {
7718 position_t const *const pos = &expression->base.pos;
7719 errorf(pos, "address of register '%N' requested", entity);
7722 entity->variable.address_taken = true;
7726 * Check the semantic of the address taken expression.
7728 static void semantic_take_addr(unary_expression_t *expression)
7730 expression_t *value = expression->value;
7731 value->base.type = revert_automatic_type_conversion(value);
7733 type_t *orig_type = value->base.type;
7734 type_t *type = skip_typeref(orig_type);
7735 if (!is_type_valid(type))
7739 if (!is_lvalue(value)) {
7740 errorf(&expression->base.pos, "'&' requires an lvalue");
7742 if (is_bitfield(value)) {
7743 errorf(&expression->base.pos, "'&' not allowed on bitfield");
7746 set_address_taken(value, false);
7748 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7751 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7752 static expression_t *parse_##unexpression_type(void) \
7754 expression_t *unary_expression \
7755 = allocate_expression_zero(unexpression_type); \
7757 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7759 sfunc(&unary_expression->unary); \
7761 return unary_expression; \
7764 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7765 semantic_unexpr_arithmetic)
7766 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7767 semantic_unexpr_plus)
7768 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7770 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7771 semantic_dereference)
7772 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7774 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_COMPLEMENT,
7775 semantic_complement)
7776 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7778 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7781 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7783 static expression_t *parse_##unexpression_type(expression_t *left) \
7785 expression_t *unary_expression \
7786 = allocate_expression_zero(unexpression_type); \
7788 unary_expression->unary.value = left; \
7790 sfunc(&unary_expression->unary); \
7792 return unary_expression; \
7795 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7796 EXPR_UNARY_POSTFIX_INCREMENT,
7798 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7799 EXPR_UNARY_POSTFIX_DECREMENT,
7802 static atomic_type_kind_t semantic_arithmetic_(atomic_type_kind_t kind_left,
7803 atomic_type_kind_t kind_right)
7805 /* §6.3.1.8 Usual arithmetic conversions */
7806 if (kind_left == ATOMIC_TYPE_LONG_DOUBLE
7807 || kind_right == ATOMIC_TYPE_LONG_DOUBLE) {
7808 return ATOMIC_TYPE_LONG_DOUBLE;
7809 } else if (kind_left == ATOMIC_TYPE_DOUBLE
7810 || kind_right == ATOMIC_TYPE_DOUBLE) {
7811 return ATOMIC_TYPE_DOUBLE;
7812 } else if (kind_left == ATOMIC_TYPE_FLOAT
7813 || kind_right == ATOMIC_TYPE_FLOAT) {
7814 return ATOMIC_TYPE_FLOAT;
7817 unsigned rank_left = get_akind_rank(kind_left);
7818 unsigned rank_right = get_akind_rank(kind_right);
7819 unsigned const rank_int = get_akind_rank(ATOMIC_TYPE_INT);
7820 if (rank_left < rank_int) {
7821 kind_left = ATOMIC_TYPE_INT;
7822 rank_left = rank_int;
7824 if (rank_right < rank_int) {
7825 kind_right = ATOMIC_TYPE_INT;
7826 rank_right = rank_int;
7828 if (kind_left == kind_right)
7831 bool const signed_left = is_akind_signed(kind_left);
7832 bool const signed_right = is_akind_signed(kind_right);
7833 if (signed_left == signed_right)
7834 return rank_left >= rank_right ? kind_left : kind_right;
7838 atomic_type_kind_t s_kind;
7839 atomic_type_kind_t u_kind;
7843 u_kind = kind_right;
7844 u_rank = rank_right;
7846 s_kind = kind_right;
7847 s_rank = rank_right;
7851 if (u_rank >= s_rank)
7853 if (get_atomic_type_size(s_kind) > get_atomic_type_size(u_kind))
7857 case ATOMIC_TYPE_INT: return ATOMIC_TYPE_UINT;
7858 case ATOMIC_TYPE_LONG: return ATOMIC_TYPE_ULONG;
7859 case ATOMIC_TYPE_LONGLONG: return ATOMIC_TYPE_ULONGLONG;
7860 default: panic("invalid atomic type");
7864 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7866 atomic_type_kind_t kind_left = get_arithmetic_akind(type_left);
7867 atomic_type_kind_t kind_right = get_arithmetic_akind(type_right);
7868 atomic_type_kind_t kind_res = semantic_arithmetic_(kind_left, kind_right);
7870 if (type_left->kind == TYPE_COMPLEX || type_right->kind == TYPE_COMPLEX) {
7871 return make_complex_type(kind_res, TYPE_QUALIFIER_NONE);
7873 return make_atomic_type(kind_res, TYPE_QUALIFIER_NONE);
7877 * Check the semantic restrictions for a binary expression.
7879 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7881 expression_t *const left = expression->left;
7882 expression_t *const right = expression->right;
7883 type_t *const orig_type_left = left->base.type;
7884 type_t *const orig_type_right = right->base.type;
7885 type_t *const type_left = skip_typeref(orig_type_left);
7886 type_t *const type_right = skip_typeref(orig_type_right);
7888 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7889 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7890 position_t const *const pos = &expression->base.pos;
7891 errorf(pos, "operands of binary expression must have arithmetic types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7896 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7897 expression->left = create_implicit_cast(left, arithmetic_type);
7898 expression->right = create_implicit_cast(right, arithmetic_type);
7899 expression->base.type = arithmetic_type;
7902 static void semantic_binexpr_integer(binary_expression_t *const expression)
7904 expression_t *const left = expression->left;
7905 expression_t *const right = expression->right;
7906 type_t *const orig_type_left = left->base.type;
7907 type_t *const orig_type_right = right->base.type;
7908 type_t *const type_left = skip_typeref(orig_type_left);
7909 type_t *const type_right = skip_typeref(orig_type_right);
7911 if (!is_type_integer(type_left) || !is_type_integer(type_right)
7912 || is_type_complex(type_left) || is_type_complex(type_right)) {
7913 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7914 position_t const *const pos = &expression->base.pos;
7915 errorf(pos, "operands of binary expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7920 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7921 expression->left = create_implicit_cast(left, result_type);
7922 expression->right = create_implicit_cast(right, result_type);
7923 expression->base.type = result_type;
7926 static void warn_div_by_zero(binary_expression_t const *const expression)
7928 if (!is_type_integer(expression->base.type))
7931 expression_t const *const right = expression->right;
7932 /* The type of the right operand can be different for /= */
7933 if (is_type_integer(skip_typeref(right->base.type)) &&
7934 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7935 !fold_constant_to_bool(right)) {
7936 position_t const *const pos = &expression->base.pos;
7937 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7942 * Check the semantic restrictions for a div expression.
7944 static void semantic_div(binary_expression_t *expression)
7946 semantic_binexpr_arithmetic(expression);
7947 warn_div_by_zero(expression);
7951 * Check the semantic restrictions for a mod expression.
7953 static void semantic_mod(binary_expression_t *expression)
7955 semantic_binexpr_integer(expression);
7956 warn_div_by_zero(expression);
7959 static void warn_addsub_in_shift(const expression_t *const expr)
7961 if (expr->base.parenthesized)
7965 switch (expr->kind) {
7966 case EXPR_BINARY_ADD: op = '+'; break;
7967 case EXPR_BINARY_SUB: op = '-'; break;
7971 position_t const *const pos = &expr->base.pos;
7972 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7975 static bool semantic_shift(binary_expression_t *expression)
7977 expression_t *const left = expression->left;
7978 expression_t *const right = expression->right;
7979 type_t *const orig_type_left = left->base.type;
7980 type_t *const orig_type_right = right->base.type;
7981 type_t * type_left = skip_typeref(orig_type_left);
7982 type_t * type_right = skip_typeref(orig_type_right);
7984 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7985 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7986 position_t const *const pos = &expression->base.pos;
7987 errorf(pos, "operands of shift expression must have integer types, but are '%T' and '%T'", orig_type_left, orig_type_right);
7992 type_left = promote_integer(type_left);
7994 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7995 position_t const *const pos = &right->base.pos;
7996 long const count = fold_constant_to_int(right);
7998 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7999 } else if ((unsigned long)count >=
8000 get_atomic_type_size(type_left->atomic.akind) * 8) {
8001 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8005 type_right = promote_integer(type_right);
8006 expression->right = create_implicit_cast(right, type_right);
8011 static void semantic_shift_op(binary_expression_t *expression)
8013 expression_t *const left = expression->left;
8014 expression_t *const right = expression->right;
8016 if (!semantic_shift(expression))
8019 warn_addsub_in_shift(left);
8020 warn_addsub_in_shift(right);
8022 type_t *const orig_type_left = left->base.type;
8023 type_t * type_left = skip_typeref(orig_type_left);
8025 type_left = promote_integer(type_left);
8026 expression->left = create_implicit_cast(left, type_left);
8027 expression->base.type = type_left;
8030 static void semantic_add(binary_expression_t *expression)
8032 expression_t *const left = expression->left;
8033 expression_t *const right = expression->right;
8034 type_t *const orig_type_left = left->base.type;
8035 type_t *const orig_type_right = right->base.type;
8036 type_t *const type_left = skip_typeref(orig_type_left);
8037 type_t *const type_right = skip_typeref(orig_type_right);
8040 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8041 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8042 expression->left = create_implicit_cast(left, arithmetic_type);
8043 expression->right = create_implicit_cast(right, arithmetic_type);
8044 expression->base.type = arithmetic_type;
8045 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8046 check_pointer_arithmetic(&expression->base.pos, type_left,
8048 expression->base.type = type_left;
8049 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8050 check_pointer_arithmetic(&expression->base.pos, type_right,
8052 expression->base.type = type_right;
8053 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8054 errorf(&expression->base.pos,
8055 "invalid operands to binary + ('%T', '%T')",
8056 orig_type_left, orig_type_right);
8060 static void semantic_sub(binary_expression_t *expression)
8062 expression_t *const left = expression->left;
8063 expression_t *const right = expression->right;
8064 type_t *const orig_type_left = left->base.type;
8065 type_t *const orig_type_right = right->base.type;
8066 type_t *const type_left = skip_typeref(orig_type_left);
8067 type_t *const type_right = skip_typeref(orig_type_right);
8068 position_t const *const pos = &expression->base.pos;
8071 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8072 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8073 expression->left = create_implicit_cast(left, arithmetic_type);
8074 expression->right = create_implicit_cast(right, arithmetic_type);
8075 expression->base.type = arithmetic_type;
8076 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8077 check_pointer_arithmetic(&expression->base.pos, type_left,
8079 expression->base.type = type_left;
8080 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8081 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8082 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8083 if (!types_compatible(unqual_left, unqual_right)) {
8085 "subtracting pointers to incompatible types '%T' and '%T'",
8086 orig_type_left, orig_type_right);
8087 } else if (!is_type_object(unqual_left)) {
8088 if (!is_type_void(unqual_left)) {
8089 errorf(pos, "subtracting pointers to non-object types '%T'",
8092 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8095 expression->base.type = type_ptrdiff_t;
8096 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8097 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8098 orig_type_left, orig_type_right);
8102 static void warn_string_literal_address(expression_t const* expr)
8104 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8105 expr = expr->unary.value;
8106 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8108 expr = expr->unary.value;
8111 if (expr->kind == EXPR_STRING_LITERAL) {
8112 position_t const *const pos = &expr->base.pos;
8113 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8117 static bool maybe_negative(expression_t const *const expr)
8119 switch (is_constant_expression(expr)) {
8120 case EXPR_CLASS_ERROR: return false;
8121 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8122 default: return true;
8126 static void warn_comparison(position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8128 warn_string_literal_address(expr);
8130 expression_t const* const ref = get_reference_address(expr);
8131 if (ref != NULL && is_null_pointer_constant(other)) {
8132 entity_t const *const ent = ref->reference.entity;
8133 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8136 if (!expr->base.parenthesized) {
8137 switch (expr->base.kind) {
8138 case EXPR_BINARY_LESS:
8139 case EXPR_BINARY_GREATER:
8140 case EXPR_BINARY_LESSEQUAL:
8141 case EXPR_BINARY_GREATEREQUAL:
8142 case EXPR_BINARY_NOTEQUAL:
8143 case EXPR_BINARY_EQUAL:
8144 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8153 * Check the semantics of comparison expressions.
8155 static void semantic_comparison(binary_expression_t *expression,
8158 position_t const *const pos = &expression->base.pos;
8159 expression_t *const left = expression->left;
8160 expression_t *const right = expression->right;
8162 warn_comparison(pos, left, right);
8163 warn_comparison(pos, right, left);
8165 type_t *orig_type_left = left->base.type;
8166 type_t *orig_type_right = right->base.type;
8167 type_t *type_left = skip_typeref(orig_type_left);
8168 type_t *type_right = skip_typeref(orig_type_right);
8170 /* TODO non-arithmetic types */
8171 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8172 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8174 /* test for signed vs unsigned compares */
8175 if (is_type_integer(arithmetic_type)) {
8176 bool const signed_left = is_type_signed(type_left);
8177 bool const signed_right = is_type_signed(type_right);
8178 if (signed_left != signed_right) {
8179 /* FIXME long long needs better const folding magic */
8180 /* TODO check whether constant value can be represented by other type */
8181 if ((signed_left && maybe_negative(left)) ||
8182 (signed_right && maybe_negative(right))) {
8183 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8188 expression->left = create_implicit_cast(left, arithmetic_type);
8189 expression->right = create_implicit_cast(right, arithmetic_type);
8190 expression->base.type = arithmetic_type;
8191 if (!is_relational && is_type_float(arithmetic_type)) {
8192 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8194 /* for relational ops we need real types, not just arithmetic */
8196 && (!is_type_real(type_left) || !is_type_real(type_right))) {
8197 type_error_incompatible("invalid operands for relational operator", pos, type_left, type_right);
8199 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8200 /* TODO check compatibility */
8201 } else if (is_type_pointer(type_left)) {
8202 expression->right = create_implicit_cast(right, type_left);
8203 } else if (is_type_pointer(type_right)) {
8204 expression->left = create_implicit_cast(left, type_right);
8205 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8206 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8208 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8211 static void semantic_relational(binary_expression_t *expression)
8213 semantic_comparison(expression, true);
8216 static void semantic_equality(binary_expression_t *expression)
8218 semantic_comparison(expression, false);
8222 * Checks if a compound type has constant fields.
8224 static bool has_const_fields(const compound_type_t *type)
8226 compound_t *compound = type->compound;
8227 entity_t *entry = compound->members.entities;
8229 for (; entry != NULL; entry = entry->base.next) {
8230 if (!is_declaration(entry))
8233 const type_t *decl_type = skip_typeref(entry->declaration.type);
8234 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8241 static bool is_valid_assignment_lhs(expression_t const* const left)
8243 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8244 type_t *const type_left = skip_typeref(orig_type_left);
8246 if (!is_lvalue(left)) {
8247 errorf(&left->base.pos,
8248 "left hand side '%E' of assignment is not an lvalue", left);
8252 if (left->kind == EXPR_REFERENCE
8253 && left->reference.entity->kind == ENTITY_FUNCTION) {
8254 errorf(&left->base.pos, "cannot assign to function '%E'", left);
8258 if (is_type_array(type_left)) {
8259 errorf(&left->base.pos, "cannot assign to array '%E'", left);
8262 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8263 errorf(&left->base.pos,
8264 "assignment to read-only location '%E' (type '%T')", left,
8268 if (is_type_incomplete(type_left)) {
8269 errorf(&left->base.pos, "left-hand side '%E' of assignment has incomplete type '%T'",
8270 left, orig_type_left);
8273 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8274 errorf(&left->base.pos, "cannot assign to '%E' because compound type '%T' has read-only fields",
8275 left, orig_type_left);
8282 static void semantic_arithmetic_assign(binary_expression_t *expression)
8284 expression_t *left = expression->left;
8285 expression_t *right = expression->right;
8286 type_t *orig_type_left = left->base.type;
8287 type_t *orig_type_right = right->base.type;
8289 if (!is_valid_assignment_lhs(left))
8292 type_t *type_left = skip_typeref(orig_type_left);
8293 type_t *type_right = skip_typeref(orig_type_right);
8295 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8296 /* TODO: improve error message */
8297 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8298 errorf(&expression->base.pos, "operation needs arithmetic types");
8303 /* combined instructions are tricky. We can't create an implicit cast on
8304 * the left side, because we need the uncasted form for the store.
8305 * The ast2firm pass has to know that left_type must be right_type
8306 * for the arithmetic operation and create a cast by itself */
8307 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8308 expression->right = create_implicit_cast(right, arithmetic_type);
8309 expression->base.type = type_left;
8312 static void semantic_divmod_assign(binary_expression_t *expression)
8314 semantic_arithmetic_assign(expression);
8315 warn_div_by_zero(expression);
8318 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8320 expression_t *const left = expression->left;
8321 expression_t *const right = expression->right;
8322 type_t *const orig_type_left = left->base.type;
8323 type_t *const orig_type_right = right->base.type;
8324 type_t *const type_left = skip_typeref(orig_type_left);
8325 type_t *const type_right = skip_typeref(orig_type_right);
8327 if (!is_valid_assignment_lhs(left))
8330 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8331 /* combined instructions are tricky. We can't create an implicit cast on
8332 * the left side, because we need the uncasted form for the store.
8333 * The ast2firm pass has to know that left_type must be right_type
8334 * for the arithmetic operation and create a cast by itself */
8335 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8336 expression->right = create_implicit_cast(right, arithmetic_type);
8337 expression->base.type = type_left;
8338 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8339 check_pointer_arithmetic(&expression->base.pos, type_left,
8341 expression->base.type = type_left;
8342 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8343 errorf(&expression->base.pos,
8344 "incompatible types '%T' and '%T' in assignment",
8345 orig_type_left, orig_type_right);
8349 static void semantic_integer_assign(binary_expression_t *expression)
8351 expression_t *left = expression->left;
8352 expression_t *right = expression->right;
8353 type_t *orig_type_left = left->base.type;
8354 type_t *orig_type_right = right->base.type;
8356 if (!is_valid_assignment_lhs(left))
8359 type_t *type_left = skip_typeref(orig_type_left);
8360 type_t *type_right = skip_typeref(orig_type_right);
8362 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8363 /* TODO: improve error message */
8364 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8365 errorf(&expression->base.pos, "operation needs integer types");
8370 /* combined instructions are tricky. We can't create an implicit cast on
8371 * the left side, because we need the uncasted form for the store.
8372 * The ast2firm pass has to know that left_type must be right_type
8373 * for the arithmetic operation and create a cast by itself */
8374 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8375 expression->right = create_implicit_cast(right, arithmetic_type);
8376 expression->base.type = type_left;
8379 static void semantic_shift_assign(binary_expression_t *expression)
8381 expression_t *left = expression->left;
8383 if (!is_valid_assignment_lhs(left))
8386 if (!semantic_shift(expression))
8389 expression->base.type = skip_typeref(left->base.type);
8392 static void warn_logical_and_within_or(const expression_t *const expr)
8394 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8396 if (expr->base.parenthesized)
8398 position_t const *const pos = &expr->base.pos;
8399 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8403 * Check the semantic restrictions of a logical expression.
8405 static void semantic_logical_op(binary_expression_t *expression)
8407 /* §6.5.13:2 Each of the operands shall have scalar type.
8408 * §6.5.14:2 Each of the operands shall have scalar type. */
8409 semantic_condition(expression->left, "left operand of logical operator");
8410 semantic_condition(expression->right, "right operand of logical operator");
8411 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8412 warn_logical_and_within_or(expression->left);
8413 warn_logical_and_within_or(expression->right);
8415 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8419 * Check the semantic restrictions of a binary assign expression.
8421 static void semantic_binexpr_assign(binary_expression_t *expression)
8423 expression_t *left = expression->left;
8424 type_t *orig_type_left = left->base.type;
8426 if (!is_valid_assignment_lhs(left))
8429 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8430 report_assign_error(error, orig_type_left, expression->right,
8431 "assignment", &left->base.pos);
8432 expression->right = create_implicit_cast(expression->right, orig_type_left);
8433 expression->base.type = orig_type_left;
8437 * Determine if the outermost operation (or parts thereof) of the given
8438 * expression has no effect in order to generate a warning about this fact.
8439 * Therefore in some cases this only examines some of the operands of the
8440 * expression (see comments in the function and examples below).
8442 * f() + 23; // warning, because + has no effect
8443 * x || f(); // no warning, because x controls execution of f()
8444 * x ? y : f(); // warning, because y has no effect
8445 * (void)x; // no warning to be able to suppress the warning
8446 * This function can NOT be used for an "expression has definitely no effect"-
8448 static bool expression_has_effect(const expression_t *const expr)
8450 switch (expr->kind) {
8451 case EXPR_ERROR: return true; /* do NOT warn */
8452 case EXPR_REFERENCE: return false;
8453 case EXPR_ENUM_CONSTANT: return false;
8454 case EXPR_LABEL_ADDRESS: return false;
8456 /* suppress the warning for microsoft __noop operations */
8457 case EXPR_LITERAL_MS_NOOP: return true;
8458 case EXPR_LITERAL_BOOLEAN:
8459 case EXPR_LITERAL_CHARACTER:
8460 case EXPR_LITERAL_INTEGER:
8461 case EXPR_LITERAL_FLOATINGPOINT:
8462 case EXPR_STRING_LITERAL: return false;
8465 const call_expression_t *const call = &expr->call;
8466 if (call->function->kind != EXPR_REFERENCE)
8469 switch (call->function->reference.entity->function.btk) {
8470 /* FIXME: which builtins have no effect? */
8471 default: return true;
8475 /* Generate the warning if either the left or right hand side of a
8476 * conditional expression has no effect */
8477 case EXPR_CONDITIONAL: {
8478 conditional_expression_t const *const cond = &expr->conditional;
8479 expression_t const *const t = cond->true_expression;
8481 (t == NULL || expression_has_effect(t)) &&
8482 expression_has_effect(cond->false_expression);
8485 case EXPR_SELECT: return false;
8486 case EXPR_ARRAY_ACCESS: return false;
8487 case EXPR_SIZEOF: return false;
8488 case EXPR_CLASSIFY_TYPE: return false;
8489 case EXPR_ALIGNOF: return false;
8491 case EXPR_FUNCNAME: return false;
8492 case EXPR_BUILTIN_CONSTANT_P: return false;
8493 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8494 case EXPR_OFFSETOF: return false;
8495 case EXPR_VA_START: return true;
8496 case EXPR_VA_ARG: return true;
8497 case EXPR_VA_COPY: return true;
8498 case EXPR_STATEMENT: return true; // TODO
8499 case EXPR_COMPOUND_LITERAL: return false;
8501 case EXPR_UNARY_NEGATE: return false;
8502 case EXPR_UNARY_PLUS: return false;
8503 case EXPR_UNARY_COMPLEMENT: return false;
8504 case EXPR_UNARY_NOT: return false;
8505 case EXPR_UNARY_DEREFERENCE: return false;
8506 case EXPR_UNARY_TAKE_ADDRESS: return false;
8507 case EXPR_UNARY_REAL: return false;
8508 case EXPR_UNARY_IMAG: return false;
8509 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8510 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8511 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8512 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8514 /* Treat void casts as if they have an effect in order to being able to
8515 * suppress the warning */
8516 case EXPR_UNARY_CAST: {
8517 type_t *const type = skip_typeref(expr->base.type);
8518 return is_type_void(type);
8521 case EXPR_UNARY_ASSUME: return true;
8522 case EXPR_UNARY_DELETE: return true;
8523 case EXPR_UNARY_DELETE_ARRAY: return true;
8524 case EXPR_UNARY_THROW: return true;
8526 case EXPR_BINARY_ADD: return false;
8527 case EXPR_BINARY_SUB: return false;
8528 case EXPR_BINARY_MUL: return false;
8529 case EXPR_BINARY_DIV: return false;
8530 case EXPR_BINARY_MOD: return false;
8531 case EXPR_BINARY_EQUAL: return false;
8532 case EXPR_BINARY_NOTEQUAL: return false;
8533 case EXPR_BINARY_LESS: return false;
8534 case EXPR_BINARY_LESSEQUAL: return false;
8535 case EXPR_BINARY_GREATER: return false;
8536 case EXPR_BINARY_GREATEREQUAL: return false;
8537 case EXPR_BINARY_BITWISE_AND: return false;
8538 case EXPR_BINARY_BITWISE_OR: return false;
8539 case EXPR_BINARY_BITWISE_XOR: return false;
8540 case EXPR_BINARY_SHIFTLEFT: return false;
8541 case EXPR_BINARY_SHIFTRIGHT: return false;
8542 case EXPR_BINARY_ASSIGN: return true;
8543 case EXPR_BINARY_MUL_ASSIGN: return true;
8544 case EXPR_BINARY_DIV_ASSIGN: return true;
8545 case EXPR_BINARY_MOD_ASSIGN: return true;
8546 case EXPR_BINARY_ADD_ASSIGN: return true;
8547 case EXPR_BINARY_SUB_ASSIGN: return true;
8548 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8549 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8550 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8551 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8552 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8554 /* Only examine the right hand side of && and ||, because the left hand
8555 * side already has the effect of controlling the execution of the right
8557 case EXPR_BINARY_LOGICAL_AND:
8558 case EXPR_BINARY_LOGICAL_OR:
8559 /* Only examine the right hand side of a comma expression, because the left
8560 * hand side has a separate warning */
8561 case EXPR_BINARY_COMMA:
8562 return expression_has_effect(expr->binary.right);
8564 case EXPR_BINARY_ISGREATER: return false;
8565 case EXPR_BINARY_ISGREATEREQUAL: return false;
8566 case EXPR_BINARY_ISLESS: return false;
8567 case EXPR_BINARY_ISLESSEQUAL: return false;
8568 case EXPR_BINARY_ISLESSGREATER: return false;
8569 case EXPR_BINARY_ISUNORDERED: return false;
8572 internal_errorf(HERE, "unexpected expression");
8575 static void semantic_comma(binary_expression_t *expression)
8577 const expression_t *const left = expression->left;
8578 if (!expression_has_effect(left)) {
8579 position_t const *const pos = &left->base.pos;
8580 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8582 expression->base.type = expression->right->base.type;
8586 * @param prec_r precedence of the right operand
8588 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8589 static expression_t *parse_##binexpression_type(expression_t *left) \
8591 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8592 binexpr->binary.left = left; \
8595 expression_t *right = parse_subexpression(prec_r); \
8597 binexpr->binary.right = right; \
8598 sfunc(&binexpr->binary); \
8603 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8604 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_div)
8605 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_mod)
8606 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8607 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8608 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8609 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8610 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_relational)
8611 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_relational)
8612 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_relational)
8613 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_relational)
8614 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_equality)
8615 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_equality)
8616 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8617 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8618 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8619 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8620 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8621 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8622 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8623 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8624 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8625 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8626 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8627 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8628 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8629 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8630 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8631 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8632 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8635 static expression_t *parse_subexpression(precedence_t precedence)
8637 expression_parser_function_t *parser
8638 = &expression_parsers[token.kind];
8641 if (parser->parser != NULL) {
8642 left = parser->parser();
8644 left = parse_primary_expression();
8646 assert(left != NULL);
8649 parser = &expression_parsers[token.kind];
8650 if (parser->infix_parser == NULL)
8652 if (parser->infix_precedence < precedence)
8655 left = parser->infix_parser(left);
8657 assert(left != NULL);
8664 * Parse an expression.
8666 static expression_t *parse_expression(void)
8668 return parse_subexpression(PREC_EXPRESSION);
8672 * Register a parser for a prefix-like operator.
8674 * @param parser the parser function
8675 * @param token_kind the token type of the prefix token
8677 static void register_expression_parser(parse_expression_function parser,
8680 expression_parser_function_t *entry = &expression_parsers[token_kind];
8682 assert(!entry->parser);
8683 entry->parser = parser;
8687 * Register a parser for an infix operator with given precedence.
8689 * @param parser the parser function
8690 * @param token_kind the token type of the infix operator
8691 * @param precedence the precedence of the operator
8693 static void register_infix_parser(parse_expression_infix_function parser,
8694 int token_kind, precedence_t precedence)
8696 expression_parser_function_t *entry = &expression_parsers[token_kind];
8698 assert(!entry->infix_parser);
8699 entry->infix_parser = parser;
8700 entry->infix_precedence = precedence;
8704 * Initialize the expression parsers.
8706 static void init_expression_parsers(void)
8708 memset(&expression_parsers, 0, sizeof(expression_parsers));
8710 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8711 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8712 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8713 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8714 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8715 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8716 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8717 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8718 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8719 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8720 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8721 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8722 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8723 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8724 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8725 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8726 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8727 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8728 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8729 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8730 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8731 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8732 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8733 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8734 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8735 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8736 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8737 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8738 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8739 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8740 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8741 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8742 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8743 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8744 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8745 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8746 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8748 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8749 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8750 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8751 register_expression_parser(parse_EXPR_UNARY_COMPLEMENT, '~');
8752 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8753 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8754 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8755 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8756 register_expression_parser(parse_sizeof, T_sizeof);
8757 register_expression_parser(parse_alignof, T__Alignof);
8758 register_expression_parser(parse_extension, T___extension__);
8759 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8760 register_expression_parser(parse_delete, T_delete);
8761 register_expression_parser(parse_throw, T_throw);
8765 * Parse a asm statement arguments specification.
8767 static void parse_asm_arguments(asm_argument_t **anchor, bool const is_out)
8769 if (token.kind == T_STRING_LITERAL || token.kind == '[') {
8770 add_anchor_token(',');
8772 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8774 add_anchor_token(')');
8775 add_anchor_token('(');
8776 add_anchor_token(T_STRING_LITERAL);
8779 add_anchor_token(']');
8780 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8781 rem_anchor_token(']');
8785 rem_anchor_token(T_STRING_LITERAL);
8786 argument->constraints = parse_string_literals("asm argument");
8787 rem_anchor_token('(');
8789 expression_t *expression = parse_expression();
8791 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8792 * change size or type representation (e.g. int -> long is ok, but
8793 * int -> float is not) */
8794 if (expression->kind == EXPR_UNARY_CAST) {
8795 type_t *const type = expression->base.type;
8796 type_kind_t const kind = type->kind;
8797 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8800 if (kind == TYPE_ATOMIC) {
8801 atomic_type_kind_t const akind = type->atomic.akind;
8802 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8803 size = get_atomic_type_size(akind);
8805 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8806 size = get_type_size(type_void_ptr);
8810 expression_t *const value = expression->unary.value;
8811 type_t *const value_type = value->base.type;
8812 type_kind_t const value_kind = value_type->kind;
8814 unsigned value_flags;
8815 unsigned value_size;
8816 if (value_kind == TYPE_ATOMIC) {
8817 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8818 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8819 value_size = get_atomic_type_size(value_akind);
8820 } else if (value_kind == TYPE_POINTER) {
8821 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8822 value_size = get_type_size(type_void_ptr);
8827 if (value_flags != flags || value_size != size)
8831 } while (expression->kind == EXPR_UNARY_CAST);
8835 if (!is_lvalue(expression))
8836 errorf(&expression->base.pos,
8837 "asm output argument is not an lvalue");
8839 if (argument->constraints.begin[0] == '=')
8840 determine_lhs_ent(expression, NULL);
8842 mark_vars_read(expression, NULL);
8844 mark_vars_read(expression, NULL);
8846 argument->expression = expression;
8847 rem_anchor_token(')');
8850 set_address_taken(expression, true);
8853 anchor = &argument->next;
8854 } while (accept(','));
8855 rem_anchor_token(',');
8860 * Parse a asm statement clobber specification.
8862 static void parse_asm_clobbers(asm_clobber_t **anchor)
8864 if (token.kind == T_STRING_LITERAL) {
8865 add_anchor_token(',');
8867 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8868 clobber->clobber = parse_string_literals(NULL);
8871 anchor = &clobber->next;
8872 } while (accept(','));
8873 rem_anchor_token(',');
8877 static void parse_asm_labels(asm_label_t **anchor)
8879 if (token.kind == T_IDENTIFIER) {
8880 add_anchor_token(',');
8882 label_t *const label = get_label("while parsing 'asm goto' labels");
8884 asm_label_t *const asm_label = allocate_ast_zero(sizeof(*asm_label));
8885 asm_label->label = label;
8887 *anchor = asm_label;
8888 anchor = &asm_label->next;
8890 } while (accept(','));
8891 rem_anchor_token(',');
8896 * Parse an asm statement.
8898 static statement_t *parse_asm_statement(void)
8900 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8901 asm_statement_t *asm_statement = &statement->asms;
8904 add_anchor_token(')');
8905 add_anchor_token(':');
8906 add_anchor_token(T_STRING_LITERAL);
8908 if (accept(T_volatile))
8909 asm_statement->is_volatile = true;
8911 bool const asm_goto = accept(T_goto);
8914 rem_anchor_token(T_STRING_LITERAL);
8915 asm_statement->asm_text = parse_string_literals("asm statement");
8917 if (accept(':')) parse_asm_arguments(&asm_statement->outputs, true);
8918 if (accept(':')) parse_asm_arguments(&asm_statement->inputs, false);
8919 if (accept(':')) parse_asm_clobbers( &asm_statement->clobbers);
8921 rem_anchor_token(':');
8924 warningf(WARN_OTHER, &statement->base.pos, "assembler statement with labels should be 'asm goto'");
8925 parse_asm_labels(&asm_statement->labels);
8926 if (asm_statement->labels)
8927 errorf(&statement->base.pos, "'asm goto' not supported");
8930 warningf(WARN_OTHER, &statement->base.pos, "'asm goto' without labels");
8933 rem_anchor_token(')');
8937 if (asm_statement->outputs == NULL) {
8938 /* GCC: An 'asm' instruction without any output operands will be treated
8939 * identically to a volatile 'asm' instruction. */
8940 asm_statement->is_volatile = true;
8946 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8948 statement_t *inner_stmt;
8949 switch (token.kind) {
8951 errorf(&label->base.pos, "%s at end of compound statement", label_kind);
8952 inner_stmt = create_error_statement();
8956 if (label->kind == STATEMENT_LABEL) {
8957 /* Eat an empty statement here, to avoid the warning about an empty
8958 * statement after a label. label:; is commonly used to have a label
8959 * before a closing brace. */
8960 inner_stmt = create_empty_statement();
8967 inner_stmt = parse_statement();
8968 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8969 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8970 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8971 errorf(&inner_stmt->base.pos, "declaration after %s", label_kind);
8979 * Parse a case statement.
8981 static statement_t *parse_case_statement(void)
8983 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8984 position_t *const pos = &statement->base.pos;
8987 add_anchor_token(':');
8989 expression_t *expression = parse_expression();
8990 type_t *expression_type = expression->base.type;
8991 type_t *skipped = skip_typeref(expression_type);
8992 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8993 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8994 expression, expression_type);
8997 type_t *type = expression_type;
8998 if (current_switch != NULL) {
8999 type_t *switch_type = current_switch->expression->base.type;
9000 if (is_type_valid(skip_typeref(switch_type))) {
9001 expression = create_implicit_cast(expression, switch_type);
9005 statement->case_label.expression = expression;
9006 expression_classification_t const expr_class = is_constant_expression(expression);
9007 if (expr_class != EXPR_CLASS_CONSTANT) {
9008 if (expr_class != EXPR_CLASS_ERROR) {
9009 errorf(pos, "case label does not reduce to an integer constant");
9011 statement->case_label.is_bad = true;
9013 ir_tarval *val = fold_constant_to_tarval(expression);
9014 statement->case_label.first_case = val;
9015 statement->case_label.last_case = val;
9019 if (accept(T_DOTDOTDOT)) {
9020 expression_t *end_range = parse_expression();
9021 expression_type = expression->base.type;
9022 skipped = skip_typeref(expression_type);
9023 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9024 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9025 expression, expression_type);
9028 end_range = create_implicit_cast(end_range, type);
9029 statement->case_label.end_range = end_range;
9030 expression_classification_t const end_class = is_constant_expression(end_range);
9031 if (end_class != EXPR_CLASS_CONSTANT) {
9032 if (end_class != EXPR_CLASS_ERROR) {
9033 errorf(pos, "case range does not reduce to an integer constant");
9035 statement->case_label.is_bad = true;
9037 ir_tarval *val = fold_constant_to_tarval(end_range);
9038 statement->case_label.last_case = val;
9040 if (tarval_cmp(val, statement->case_label.first_case)
9041 == ir_relation_less) {
9042 statement->case_label.is_empty_range = true;
9043 warningf(WARN_OTHER, pos, "empty range specified");
9049 PUSH_PARENT(statement);
9051 rem_anchor_token(':');
9054 if (current_switch != NULL) {
9055 if (! statement->case_label.is_bad) {
9056 /* Check for duplicate case values */
9057 case_label_statement_t *c = &statement->case_label;
9058 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9059 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9062 if (c->last_case < l->first_case || c->first_case > l->last_case)
9065 errorf(pos, "duplicate case value (previously used %P)",
9070 /* link all cases into the switch statement */
9071 if (current_switch->last_case == NULL) {
9072 current_switch->first_case = &statement->case_label;
9074 current_switch->last_case->next = &statement->case_label;
9076 current_switch->last_case = &statement->case_label;
9078 errorf(pos, "case label not within a switch statement");
9081 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9088 * Parse a default statement.
9090 static statement_t *parse_default_statement(void)
9092 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9096 PUSH_PARENT(statement);
9100 if (current_switch != NULL) {
9101 const case_label_statement_t *def_label = current_switch->default_label;
9102 if (def_label != NULL) {
9103 errorf(&statement->base.pos, "multiple default labels in one switch (previous declared %P)", &def_label->base.pos);
9105 current_switch->default_label = &statement->case_label;
9107 /* link all cases into the switch statement */
9108 if (current_switch->last_case == NULL) {
9109 current_switch->first_case = &statement->case_label;
9111 current_switch->last_case->next = &statement->case_label;
9113 current_switch->last_case = &statement->case_label;
9116 errorf(&statement->base.pos,
9117 "'default' label not within a switch statement");
9120 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9127 * Parse a label statement.
9129 static statement_t *parse_label_statement(void)
9131 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9132 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
9133 statement->label.label = label;
9135 PUSH_PARENT(statement);
9137 /* if statement is already set then the label is defined twice,
9138 * otherwise it was just mentioned in a goto/local label declaration so far
9140 position_t const* const pos = &statement->base.pos;
9141 if (label->statement != NULL) {
9142 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.pos);
9144 label->base.pos = *pos;
9145 label->statement = statement;
9146 label->n_users += 1;
9151 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9152 parse_attributes(NULL); // TODO process attributes
9155 statement->label.statement = parse_label_inner_statement(statement, "label");
9157 /* remember the labels in a list for later checking */
9158 *label_anchor = &statement->label;
9159 label_anchor = &statement->label.next;
9165 static statement_t *parse_inner_statement(void)
9167 statement_t *const stmt = parse_statement();
9168 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9169 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9170 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9171 errorf(&stmt->base.pos, "declaration as inner statement, use {}");
9177 * Parse an expression in parentheses and mark its variables as read.
9179 static expression_t *parse_condition(void)
9181 add_anchor_token(')');
9183 expression_t *const expr = parse_expression();
9184 mark_vars_read(expr, NULL);
9185 rem_anchor_token(')');
9191 * Parse an if statement.
9193 static statement_t *parse_if(void)
9195 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9199 PUSH_PARENT(statement);
9200 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9202 add_anchor_token(T_else);
9204 expression_t *const expr = parse_condition();
9205 statement->ifs.condition = expr;
9206 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9208 semantic_condition(expr, "condition of 'if'-statment");
9210 statement_t *const true_stmt = parse_inner_statement();
9211 statement->ifs.true_statement = true_stmt;
9212 rem_anchor_token(T_else);
9214 if (true_stmt->kind == STATEMENT_EMPTY) {
9215 warningf(WARN_EMPTY_BODY, HERE,
9216 "suggest braces around empty body in an ‘if’ statement");
9219 if (accept(T_else)) {
9220 statement->ifs.false_statement = parse_inner_statement();
9222 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9223 warningf(WARN_EMPTY_BODY, HERE,
9224 "suggest braces around empty body in an ‘if’ statement");
9226 } else if (true_stmt->kind == STATEMENT_IF &&
9227 true_stmt->ifs.false_statement != NULL) {
9228 position_t const *const pos = &true_stmt->base.pos;
9229 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9238 * Check that all enums are handled in a switch.
9240 * @param statement the switch statement to check
9242 static void check_enum_cases(const switch_statement_t *statement)
9244 if (!is_warn_on(WARN_SWITCH_ENUM))
9246 type_t *type = skip_typeref(statement->expression->base.type);
9247 if (! is_type_enum(type))
9249 enum_type_t *enumt = &type->enumt;
9251 /* if we have a default, no warnings */
9252 if (statement->default_label != NULL)
9255 determine_enum_values(enumt);
9257 /* FIXME: calculation of value should be done while parsing */
9258 /* TODO: quadratic algorithm here. Change to an n log n one */
9259 const entity_t *entry = enumt->enume->base.next;
9260 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9261 entry = entry->base.next) {
9262 ir_tarval *value = entry->enum_value.tv;
9264 for (const case_label_statement_t *l = statement->first_case; l != NULL;
9266 if (l->expression == NULL)
9268 if (l->first_case == l->last_case && l->first_case != value)
9270 if ((tarval_cmp(l->first_case, value) & ir_relation_less_equal)
9271 && (tarval_cmp(value, l->last_case) & ir_relation_less_equal)) {
9277 position_t const *const pos = &statement->base.pos;
9278 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9284 * Parse a switch statement.
9286 static statement_t *parse_switch(void)
9288 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9292 PUSH_PARENT(statement);
9293 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9295 expression_t *const expr = parse_condition();
9296 type_t * type = skip_typeref(expr->base.type);
9297 if (is_type_integer(type)) {
9298 type = promote_integer(type);
9299 if (get_akind_rank(get_arithmetic_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9300 warningf(WARN_TRADITIONAL, &expr->base.pos,
9301 "'%T' switch expression not converted to '%T' in ISO C",
9304 } else if (is_type_valid(type)) {
9305 errorf(&expr->base.pos, "switch quantity is not an integer, but '%T'",
9307 type = type_error_type;
9309 statement->switchs.expression = create_implicit_cast(expr, type);
9311 switch_statement_t *rem = current_switch;
9312 current_switch = &statement->switchs;
9313 statement->switchs.body = parse_inner_statement();
9314 current_switch = rem;
9316 if (statement->switchs.default_label == NULL) {
9317 warningf(WARN_SWITCH_DEFAULT, &statement->base.pos, "switch has no default case");
9319 check_enum_cases(&statement->switchs);
9326 static statement_t *parse_loop_body(statement_t *const loop)
9328 statement_t *const rem = current_loop;
9329 current_loop = loop;
9331 statement_t *const body = parse_inner_statement();
9338 * Parse a while statement.
9340 static statement_t *parse_while(void)
9342 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9346 PUSH_PARENT(statement);
9347 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9349 expression_t *const cond = parse_condition();
9350 statement->fors.condition = cond;
9351 /* §6.8.5:2 The controlling expression of an iteration statement shall
9352 * have scalar type. */
9353 semantic_condition(cond, "condition of 'while'-statement");
9355 statement->fors.body = parse_loop_body(statement);
9363 * Parse a do statement.
9365 static statement_t *parse_do(void)
9367 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9371 PUSH_PARENT(statement);
9372 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9374 add_anchor_token(T_while);
9375 statement->do_while.body = parse_loop_body(statement);
9376 rem_anchor_token(T_while);
9379 expression_t *const cond = parse_condition();
9380 statement->do_while.condition = cond;
9381 /* §6.8.5:2 The controlling expression of an iteration statement shall
9382 * have scalar type. */
9383 semantic_condition(cond, "condition of 'do-while'-statement");
9392 * Parse a for statement.
9394 static statement_t *parse_for(void)
9396 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9400 PUSH_PARENT(statement);
9401 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9403 add_anchor_token(')');
9409 } else if (is_declaration_specifier(&token)) {
9410 parse_declaration(record_entity, DECL_FLAGS_NONE);
9412 add_anchor_token(';');
9413 expression_t *const init = parse_expression();
9414 statement->fors.initialisation = init;
9415 mark_vars_read(init, ENT_ANY);
9416 if (!expression_has_effect(init)) {
9417 warningf(WARN_UNUSED_VALUE, &init->base.pos, "initialisation of 'for'-statement has no effect");
9419 rem_anchor_token(';');
9425 if (token.kind != ';') {
9426 add_anchor_token(';');
9427 expression_t *const cond = parse_expression();
9428 statement->fors.condition = cond;
9429 /* §6.8.5:2 The controlling expression of an iteration statement
9430 * shall have scalar type. */
9431 semantic_condition(cond, "condition of 'for'-statement");
9432 mark_vars_read(cond, NULL);
9433 rem_anchor_token(';');
9436 if (token.kind != ')') {
9437 expression_t *const step = parse_expression();
9438 statement->fors.step = step;
9439 mark_vars_read(step, ENT_ANY);
9440 if (!expression_has_effect(step)) {
9441 warningf(WARN_UNUSED_VALUE, &step->base.pos, "step of 'for'-statement has no effect");
9444 rem_anchor_token(')');
9446 statement->fors.body = parse_loop_body(statement);
9454 * Parse a goto statement.
9456 static statement_t *parse_goto(void)
9458 statement_t *statement;
9459 if (GNU_MODE && look_ahead(1)->kind == '*') {
9460 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9464 expression_t *expression = parse_expression();
9465 mark_vars_read(expression, NULL);
9467 /* Argh: although documentation says the expression must be of type void*,
9468 * gcc accepts anything that can be casted into void* without error */
9469 type_t *type = expression->base.type;
9471 if (type != type_error_type) {
9472 if (!is_type_pointer(type) && !is_type_integer(type)) {
9473 errorf(&expression->base.pos, "cannot convert to a pointer type");
9474 } else if (type != type_void_ptr) {
9475 warningf(WARN_OTHER, &expression->base.pos, "type of computed goto expression should be 'void*' not '%T'", type);
9477 expression = create_implicit_cast(expression, type_void_ptr);
9480 statement->computed_goto.expression = expression;
9482 statement = allocate_statement_zero(STATEMENT_GOTO);
9485 label_t *const label = get_label("while parsing goto");
9487 label->n_users += 1;
9489 statement->gotos.label = label;
9491 /* remember the goto's in a list for later checking */
9492 *goto_anchor = &statement->gotos;
9493 goto_anchor = &statement->gotos.next;
9495 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_position)->label;
9504 * Parse a continue statement.
9506 static statement_t *parse_continue(void)
9508 if (current_loop == NULL) {
9509 errorf(HERE, "continue statement not within loop");
9512 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9520 * Parse a break statement.
9522 static statement_t *parse_break(void)
9524 if (current_switch == NULL && current_loop == NULL) {
9525 errorf(HERE, "break statement not within loop or switch");
9528 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9536 * Parse a __leave statement.
9538 static statement_t *parse_leave_statement(void)
9540 if (current_try == NULL) {
9541 errorf(HERE, "__leave statement not within __try");
9544 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9552 * Check if a given entity represents a local variable.
9554 static bool is_local_variable(const entity_t *entity)
9556 if (entity->kind != ENTITY_VARIABLE)
9559 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9560 case STORAGE_CLASS_AUTO:
9561 case STORAGE_CLASS_REGISTER: {
9562 const type_t *type = skip_typeref(entity->declaration.type);
9563 if (is_type_function(type)) {
9575 * Check if a given expression represents a local variable.
9577 static bool expression_is_local_variable(const expression_t *expression)
9579 if (expression->base.kind != EXPR_REFERENCE) {
9582 const entity_t *entity = expression->reference.entity;
9583 return is_local_variable(entity);
9586 static void err_or_warn(position_t const *const pos, char const *const msg)
9588 if (c_mode & _CXX || strict_mode) {
9591 warningf(WARN_OTHER, pos, msg);
9596 * Parse a return statement.
9598 static statement_t *parse_return(void)
9600 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9603 expression_t *return_value = NULL;
9604 if (token.kind != ';') {
9605 return_value = parse_expression();
9606 mark_vars_read(return_value, NULL);
9609 const type_t *const func_type = skip_typeref(current_function->base.type);
9610 assert(is_type_function(func_type));
9611 type_t *const return_type = skip_typeref(func_type->function.return_type);
9613 position_t const *const pos = &statement->base.pos;
9614 if (return_value != NULL) {
9615 type_t *return_value_type = skip_typeref(return_value->base.type);
9617 if (is_type_void(return_type)) {
9618 if (!is_type_void(return_value_type)) {
9619 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9620 /* Only warn in C mode, because GCC does the same */
9621 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9622 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9623 /* Only warn in C mode, because GCC does the same */
9624 err_or_warn(pos, "'return' with expression in function returning 'void'");
9627 assign_error_t error = semantic_assign(return_type, return_value);
9628 report_assign_error(error, return_type, return_value, "'return'",
9631 return_value = create_implicit_cast(return_value, return_type);
9632 /* check for returning address of a local var */
9633 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9634 const expression_t *expression = return_value->unary.value;
9635 if (expression_is_local_variable(expression)) {
9636 warningf(WARN_OTHER, pos, "function returns address of local variable");
9639 } else if (!is_type_void(return_type)) {
9640 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9641 err_or_warn(pos, "'return' without value, in function returning non-void");
9643 statement->returns.value = return_value;
9650 * Parse a declaration statement.
9652 static statement_t *parse_declaration_statement(void)
9654 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9656 entity_t *before = current_scope->last_entity;
9658 parse_external_declaration();
9660 parse_declaration(record_entity, DECL_FLAGS_NONE);
9663 declaration_statement_t *const decl = &statement->declaration;
9664 entity_t *const begin =
9665 before != NULL ? before->base.next : current_scope->entities;
9666 decl->declarations_begin = begin;
9667 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9673 * Parse an expression statement, i.e. expr ';'.
9675 static statement_t *parse_expression_statement(void)
9677 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9679 expression_t *const expr = parse_expression();
9680 statement->expression.expression = expr;
9681 mark_vars_read(expr, ENT_ANY);
9688 * Parse a microsoft __try { } __finally { } or
9689 * __try{ } __except() { }
9691 static statement_t *parse_ms_try_statment(void)
9693 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9696 PUSH_PARENT(statement);
9698 ms_try_statement_t *rem = current_try;
9699 current_try = &statement->ms_try;
9700 statement->ms_try.try_statement = parse_compound_statement(false);
9705 if (accept(T___except)) {
9706 expression_t *const expr = parse_condition();
9707 type_t * type = skip_typeref(expr->base.type);
9708 if (is_type_integer(type)) {
9709 type = promote_integer(type);
9710 } else if (is_type_valid(type)) {
9711 errorf(&expr->base.pos,
9712 "__expect expression is not an integer, but '%T'", type);
9713 type = type_error_type;
9715 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9716 } else if (!accept(T__finally)) {
9717 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9719 statement->ms_try.final_statement = parse_compound_statement(false);
9723 static statement_t *parse_empty_statement(void)
9725 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9726 statement_t *const statement = create_empty_statement();
9731 static statement_t *parse_local_label_declaration(void)
9733 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9737 entity_t *begin = NULL;
9738 entity_t *end = NULL;
9739 entity_t **anchor = &begin;
9740 add_anchor_token(';');
9741 add_anchor_token(',');
9744 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9746 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9747 if (entity != NULL && entity->base.parent_scope == current_scope) {
9748 position_t const *const ppos = &entity->base.pos;
9749 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9751 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9752 entity->base.parent_scope = current_scope;
9755 anchor = &entity->base.next;
9758 environment_push(entity);
9761 } while (accept(','));
9762 rem_anchor_token(',');
9763 rem_anchor_token(';');
9765 statement->declaration.declarations_begin = begin;
9766 statement->declaration.declarations_end = end;
9770 static void parse_namespace_definition(void)
9774 entity_t *entity = NULL;
9775 symbol_t *symbol = NULL;
9777 if (token.kind == T_IDENTIFIER) {
9778 symbol = token.base.symbol;
9779 entity = get_entity(symbol, NAMESPACE_NORMAL);
9780 if (entity && entity->kind != ENTITY_NAMESPACE) {
9782 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9783 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9789 if (entity == NULL) {
9790 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9791 entity->base.parent_scope = current_scope;
9794 if (token.kind == '=') {
9795 /* TODO: parse namespace alias */
9796 panic("namespace alias definition not supported yet");
9799 environment_push(entity);
9800 append_entity(current_scope, entity);
9802 PUSH_SCOPE(&entity->namespacee.members);
9803 PUSH_CURRENT_ENTITY(entity);
9805 add_anchor_token('}');
9808 rem_anchor_token('}');
9811 POP_CURRENT_ENTITY();
9816 * Parse a statement.
9817 * There's also parse_statement() which additionally checks for
9818 * "statement has no effect" warnings
9820 static statement_t *intern_parse_statement(void)
9822 /* declaration or statement */
9823 statement_t *statement;
9824 switch (token.kind) {
9825 case T_IDENTIFIER: {
9826 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9827 if (la1_type == ':') {
9828 statement = parse_label_statement();
9829 } else if (is_typedef_symbol(token.base.symbol)) {
9830 statement = parse_declaration_statement();
9832 /* it's an identifier, the grammar says this must be an
9833 * expression statement. However it is common that users mistype
9834 * declaration types, so we guess a bit here to improve robustness
9835 * for incorrect programs */
9839 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9841 statement = parse_expression_statement();
9845 statement = parse_declaration_statement();
9853 case T___extension__: {
9854 /* This can be a prefix to a declaration or an expression statement.
9855 * We simply eat it now and parse the rest with tail recursion. */
9857 statement = intern_parse_statement();
9863 statement = parse_declaration_statement();
9867 statement = parse_local_label_declaration();
9870 case ';': statement = parse_empty_statement(); break;
9871 case '{': statement = parse_compound_statement(false); break;
9872 case T___leave: statement = parse_leave_statement(); break;
9873 case T___try: statement = parse_ms_try_statment(); break;
9874 case T_asm: statement = parse_asm_statement(); break;
9875 case T_break: statement = parse_break(); break;
9876 case T_case: statement = parse_case_statement(); break;
9877 case T_continue: statement = parse_continue(); break;
9878 case T_default: statement = parse_default_statement(); break;
9879 case T_do: statement = parse_do(); break;
9880 case T_for: statement = parse_for(); break;
9881 case T_goto: statement = parse_goto(); break;
9882 case T_if: statement = parse_if(); break;
9883 case T_return: statement = parse_return(); break;
9884 case T_switch: statement = parse_switch(); break;
9885 case T_while: statement = parse_while(); break;
9888 statement = parse_expression_statement();
9892 errorf(HERE, "unexpected token %K while parsing statement", &token);
9893 statement = create_error_statement();
9902 * parse a statement and emits "statement has no effect" warning if needed
9903 * (This is really a wrapper around intern_parse_statement with check for 1
9904 * single warning. It is needed, because for statement expressions we have
9905 * to avoid the warning on the last statement)
9907 static statement_t *parse_statement(void)
9909 statement_t *statement = intern_parse_statement();
9911 if (statement->kind == STATEMENT_EXPRESSION) {
9912 expression_t *expression = statement->expression.expression;
9913 if (!expression_has_effect(expression)) {
9914 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
9915 "statement has no effect");
9923 * Parse a compound statement.
9925 static statement_t *parse_compound_statement(bool inside_expression_statement)
9927 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9929 PUSH_PARENT(statement);
9930 PUSH_SCOPE(&statement->compound.scope);
9933 add_anchor_token('}');
9934 /* tokens, which can start a statement */
9935 /* TODO MS, __builtin_FOO */
9936 add_anchor_token('!');
9937 add_anchor_token('&');
9938 add_anchor_token('(');
9939 add_anchor_token('*');
9940 add_anchor_token('+');
9941 add_anchor_token('-');
9942 add_anchor_token(';');
9943 add_anchor_token('{');
9944 add_anchor_token('~');
9945 add_anchor_token(T_CHARACTER_CONSTANT);
9946 add_anchor_token(T_COLONCOLON);
9947 add_anchor_token(T_IDENTIFIER);
9948 add_anchor_token(T_MINUSMINUS);
9949 add_anchor_token(T_NUMBER);
9950 add_anchor_token(T_PLUSPLUS);
9951 add_anchor_token(T_STRING_LITERAL);
9952 add_anchor_token(T__Alignof);
9953 add_anchor_token(T__Bool);
9954 add_anchor_token(T__Complex);
9955 add_anchor_token(T__Imaginary);
9956 add_anchor_token(T__Thread_local);
9957 add_anchor_token(T___PRETTY_FUNCTION__);
9958 add_anchor_token(T___attribute__);
9959 add_anchor_token(T___builtin_va_start);
9960 add_anchor_token(T___extension__);
9961 add_anchor_token(T___func__);
9962 add_anchor_token(T___imag__);
9963 add_anchor_token(T___label__);
9964 add_anchor_token(T___real__);
9965 add_anchor_token(T_asm);
9966 add_anchor_token(T_auto);
9967 add_anchor_token(T_bool);
9968 add_anchor_token(T_break);
9969 add_anchor_token(T_case);
9970 add_anchor_token(T_char);
9971 add_anchor_token(T_class);
9972 add_anchor_token(T_const);
9973 add_anchor_token(T_const_cast);
9974 add_anchor_token(T_continue);
9975 add_anchor_token(T_default);
9976 add_anchor_token(T_delete);
9977 add_anchor_token(T_double);
9978 add_anchor_token(T_do);
9979 add_anchor_token(T_dynamic_cast);
9980 add_anchor_token(T_enum);
9981 add_anchor_token(T_extern);
9982 add_anchor_token(T_false);
9983 add_anchor_token(T_float);
9984 add_anchor_token(T_for);
9985 add_anchor_token(T_goto);
9986 add_anchor_token(T_if);
9987 add_anchor_token(T_inline);
9988 add_anchor_token(T_int);
9989 add_anchor_token(T_long);
9990 add_anchor_token(T_new);
9991 add_anchor_token(T_operator);
9992 add_anchor_token(T_register);
9993 add_anchor_token(T_reinterpret_cast);
9994 add_anchor_token(T_restrict);
9995 add_anchor_token(T_return);
9996 add_anchor_token(T_short);
9997 add_anchor_token(T_signed);
9998 add_anchor_token(T_sizeof);
9999 add_anchor_token(T_static);
10000 add_anchor_token(T_static_cast);
10001 add_anchor_token(T_struct);
10002 add_anchor_token(T_switch);
10003 add_anchor_token(T_template);
10004 add_anchor_token(T_this);
10005 add_anchor_token(T_throw);
10006 add_anchor_token(T_true);
10007 add_anchor_token(T_try);
10008 add_anchor_token(T_typedef);
10009 add_anchor_token(T_typeid);
10010 add_anchor_token(T_typename);
10011 add_anchor_token(T_typeof);
10012 add_anchor_token(T_union);
10013 add_anchor_token(T_unsigned);
10014 add_anchor_token(T_using);
10015 add_anchor_token(T_void);
10016 add_anchor_token(T_volatile);
10017 add_anchor_token(T_wchar_t);
10018 add_anchor_token(T_while);
10020 statement_t **anchor = &statement->compound.statements;
10021 bool only_decls_so_far = true;
10022 while (token.kind != '}' && token.kind != T_EOF) {
10023 statement_t *sub_statement = intern_parse_statement();
10024 if (sub_statement->kind == STATEMENT_ERROR) {
10028 if (sub_statement->kind != STATEMENT_DECLARATION) {
10029 only_decls_so_far = false;
10030 } else if (!only_decls_so_far) {
10031 position_t const *const pos = &sub_statement->base.pos;
10032 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10035 *anchor = sub_statement;
10036 anchor = &sub_statement->base.next;
10040 /* look over all statements again to produce no effect warnings */
10041 if (is_warn_on(WARN_UNUSED_VALUE)) {
10042 statement_t *sub_statement = statement->compound.statements;
10043 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10044 if (sub_statement->kind != STATEMENT_EXPRESSION)
10046 /* don't emit a warning for the last expression in an expression
10047 * statement as it has always an effect */
10048 if (inside_expression_statement && sub_statement->base.next == NULL)
10051 expression_t *expression = sub_statement->expression.expression;
10052 if (!expression_has_effect(expression)) {
10053 warningf(WARN_UNUSED_VALUE, &expression->base.pos,
10054 "statement has no effect");
10059 rem_anchor_token(T_while);
10060 rem_anchor_token(T_wchar_t);
10061 rem_anchor_token(T_volatile);
10062 rem_anchor_token(T_void);
10063 rem_anchor_token(T_using);
10064 rem_anchor_token(T_unsigned);
10065 rem_anchor_token(T_union);
10066 rem_anchor_token(T_typeof);
10067 rem_anchor_token(T_typename);
10068 rem_anchor_token(T_typeid);
10069 rem_anchor_token(T_typedef);
10070 rem_anchor_token(T_try);
10071 rem_anchor_token(T_true);
10072 rem_anchor_token(T_throw);
10073 rem_anchor_token(T_this);
10074 rem_anchor_token(T_template);
10075 rem_anchor_token(T_switch);
10076 rem_anchor_token(T_struct);
10077 rem_anchor_token(T_static_cast);
10078 rem_anchor_token(T_static);
10079 rem_anchor_token(T_sizeof);
10080 rem_anchor_token(T_signed);
10081 rem_anchor_token(T_short);
10082 rem_anchor_token(T_return);
10083 rem_anchor_token(T_restrict);
10084 rem_anchor_token(T_reinterpret_cast);
10085 rem_anchor_token(T_register);
10086 rem_anchor_token(T_operator);
10087 rem_anchor_token(T_new);
10088 rem_anchor_token(T_long);
10089 rem_anchor_token(T_int);
10090 rem_anchor_token(T_inline);
10091 rem_anchor_token(T_if);
10092 rem_anchor_token(T_goto);
10093 rem_anchor_token(T_for);
10094 rem_anchor_token(T_float);
10095 rem_anchor_token(T_false);
10096 rem_anchor_token(T_extern);
10097 rem_anchor_token(T_enum);
10098 rem_anchor_token(T_dynamic_cast);
10099 rem_anchor_token(T_do);
10100 rem_anchor_token(T_double);
10101 rem_anchor_token(T_delete);
10102 rem_anchor_token(T_default);
10103 rem_anchor_token(T_continue);
10104 rem_anchor_token(T_const_cast);
10105 rem_anchor_token(T_const);
10106 rem_anchor_token(T_class);
10107 rem_anchor_token(T_char);
10108 rem_anchor_token(T_case);
10109 rem_anchor_token(T_break);
10110 rem_anchor_token(T_bool);
10111 rem_anchor_token(T_auto);
10112 rem_anchor_token(T_asm);
10113 rem_anchor_token(T___real__);
10114 rem_anchor_token(T___label__);
10115 rem_anchor_token(T___imag__);
10116 rem_anchor_token(T___func__);
10117 rem_anchor_token(T___extension__);
10118 rem_anchor_token(T___builtin_va_start);
10119 rem_anchor_token(T___attribute__);
10120 rem_anchor_token(T___PRETTY_FUNCTION__);
10121 rem_anchor_token(T__Thread_local);
10122 rem_anchor_token(T__Imaginary);
10123 rem_anchor_token(T__Complex);
10124 rem_anchor_token(T__Bool);
10125 rem_anchor_token(T__Alignof);
10126 rem_anchor_token(T_STRING_LITERAL);
10127 rem_anchor_token(T_PLUSPLUS);
10128 rem_anchor_token(T_NUMBER);
10129 rem_anchor_token(T_MINUSMINUS);
10130 rem_anchor_token(T_IDENTIFIER);
10131 rem_anchor_token(T_COLONCOLON);
10132 rem_anchor_token(T_CHARACTER_CONSTANT);
10133 rem_anchor_token('~');
10134 rem_anchor_token('{');
10135 rem_anchor_token(';');
10136 rem_anchor_token('-');
10137 rem_anchor_token('+');
10138 rem_anchor_token('*');
10139 rem_anchor_token('(');
10140 rem_anchor_token('&');
10141 rem_anchor_token('!');
10142 rem_anchor_token('}');
10150 * Check for unused global static functions and variables
10152 static void check_unused_globals(void)
10154 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10157 for (const entity_t *entity = file_scope->entities; entity != NULL;
10158 entity = entity->base.next) {
10159 if (!is_declaration(entity))
10162 const declaration_t *declaration = &entity->declaration;
10163 if (declaration->used ||
10164 declaration->modifiers & DM_UNUSED ||
10165 declaration->modifiers & DM_USED ||
10166 declaration->storage_class != STORAGE_CLASS_STATIC)
10171 if (entity->kind == ENTITY_FUNCTION) {
10172 /* inhibit warning for static inline functions */
10173 if (entity->function.is_inline)
10176 why = WARN_UNUSED_FUNCTION;
10177 s = entity->function.body != NULL ? "defined" : "declared";
10179 why = WARN_UNUSED_VARIABLE;
10183 warningf(why, &declaration->base.pos, "'%#N' %s but not used", entity, s);
10187 static void parse_global_asm(void)
10189 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10192 add_anchor_token(';');
10193 add_anchor_token(')');
10194 add_anchor_token(T_STRING_LITERAL);
10197 rem_anchor_token(T_STRING_LITERAL);
10198 statement->asms.asm_text = parse_string_literals("global asm");
10199 statement->base.next = unit->global_asm;
10200 unit->global_asm = statement;
10202 rem_anchor_token(')');
10204 rem_anchor_token(';');
10208 static void parse_linkage_specification(void)
10212 position_t const pos = *HERE;
10213 char const *const linkage = parse_string_literals(NULL).begin;
10215 linkage_kind_t old_linkage = current_linkage;
10216 linkage_kind_t new_linkage;
10217 if (streq(linkage, "C")) {
10218 new_linkage = LINKAGE_C;
10219 } else if (streq(linkage, "C++")) {
10220 new_linkage = LINKAGE_CXX;
10222 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10223 new_linkage = LINKAGE_C;
10225 current_linkage = new_linkage;
10234 assert(current_linkage == new_linkage);
10235 current_linkage = old_linkage;
10238 static void parse_external(void)
10240 switch (token.kind) {
10242 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10243 parse_linkage_specification();
10245 DECLARATION_START_NO_EXTERN
10247 case T___extension__:
10248 /* tokens below are for implicit int */
10249 case '&': /* & x; -> int& x; (and error later, because C++ has no
10251 case '*': /* * x; -> int* x; */
10252 case '(': /* (x); -> int (x); */
10254 parse_external_declaration();
10260 parse_global_asm();
10264 parse_namespace_definition();
10268 if (!strict_mode) {
10269 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10276 errorf(HERE, "stray %K outside of function", &token);
10277 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10278 eat_until_matching_token(token.kind);
10284 static void parse_externals(void)
10286 add_anchor_token('}');
10287 add_anchor_token(T_EOF);
10290 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10291 unsigned short token_anchor_copy[T_LAST_TOKEN];
10292 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10295 while (token.kind != T_EOF && token.kind != '}') {
10297 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10298 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10300 /* the anchor set and its copy differs */
10301 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10304 if (in_gcc_extension) {
10305 /* an gcc extension scope was not closed */
10306 internal_errorf(HERE, "Leaked __extension__");
10313 rem_anchor_token(T_EOF);
10314 rem_anchor_token('}');
10318 * Parse a translation unit.
10320 static void parse_translation_unit(void)
10322 add_anchor_token(T_EOF);
10327 if (token.kind == T_EOF)
10330 errorf(HERE, "stray %K outside of function", &token);
10331 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10332 eat_until_matching_token(token.kind);
10337 void set_default_visibility(elf_visibility_tag_t visibility)
10339 default_visibility = visibility;
10345 * @return the translation unit or NULL if errors occurred.
10347 void start_parsing(void)
10349 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10350 label_stack = NEW_ARR_F(stack_entry_t, 0);
10352 print_to_file(stderr);
10354 assert(unit == NULL);
10355 unit = allocate_ast_zero(sizeof(unit[0]));
10357 assert(file_scope == NULL);
10358 file_scope = &unit->scope;
10360 assert(current_scope == NULL);
10361 scope_push(&unit->scope);
10363 create_gnu_builtins();
10365 create_microsoft_intrinsics();
10368 translation_unit_t *finish_parsing(void)
10370 assert(current_scope == &unit->scope);
10373 assert(file_scope == &unit->scope);
10374 check_unused_globals();
10377 DEL_ARR_F(environment_stack);
10378 DEL_ARR_F(label_stack);
10380 translation_unit_t *result = unit;
10385 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10386 * are given length one. */
10387 static void complete_incomplete_arrays(void)
10389 size_t n = ARR_LEN(incomplete_arrays);
10390 for (size_t i = 0; i != n; ++i) {
10391 declaration_t *const decl = incomplete_arrays[i];
10392 type_t *const type = skip_typeref(decl->type);
10394 if (!is_type_incomplete(type))
10397 position_t const *const pos = &decl->base.pos;
10398 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10400 type_t *const new_type = duplicate_type(type);
10401 new_type->array.size_constant = true;
10402 new_type->array.has_implicit_size = true;
10403 new_type->array.size = 1;
10405 type_t *const result = identify_new_type(new_type);
10407 decl->type = result;
10411 static void prepare_main_collect2(entity_t *const entity)
10413 PUSH_SCOPE(&entity->function.body->compound.scope);
10415 // create call to __main
10416 symbol_t *symbol = symbol_table_insert("__main");
10417 entity_t *subsubmain_ent
10418 = create_implicit_function(symbol, &builtin_position);
10420 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10421 type_t *ftype = subsubmain_ent->declaration.type;
10422 ref->base.pos = builtin_position;
10423 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10424 ref->reference.entity = subsubmain_ent;
10426 expression_t *call = allocate_expression_zero(EXPR_CALL);
10427 call->base.pos = builtin_position;
10428 call->base.type = type_void;
10429 call->call.function = ref;
10431 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10432 expr_statement->base.pos = builtin_position;
10433 expr_statement->expression.expression = call;
10435 statement_t *const body = entity->function.body;
10436 assert(body->kind == STATEMENT_COMPOUND);
10437 compound_statement_t *compounds = &body->compound;
10439 expr_statement->base.next = compounds->statements;
10440 compounds->statements = expr_statement;
10447 lookahead_bufpos = 0;
10448 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10451 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10452 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10453 parse_translation_unit();
10454 complete_incomplete_arrays();
10455 DEL_ARR_F(incomplete_arrays);
10456 incomplete_arrays = NULL;
10460 * Initialize the parser.
10462 void init_parser(void)
10464 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10466 init_expression_parsers();
10467 obstack_init(&temp_obst);
10471 * Terminate the parser.
10473 void exit_parser(void)
10475 obstack_free(&temp_obst, NULL);